Simple Terminal from SuckLess
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4080 lines
90 KiB

Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
11 years ago
11 years ago
11 years ago
13 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
10 years ago
14 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
11 years ago
14 years ago
13 years ago
10 years ago
10 years ago
10 years ago
14 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
14 years ago
14 years ago
13 years ago
10 years ago
14 years ago
14 years ago
13 years ago
13 years ago
11 years ago
14 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
11 years ago
13 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
Clean up xdraws and optimize glyph drawing with non-unit kerning values I have another patch here for review that optimizes the performance of glyph drawing, primarily when using non-unit kerning values, and fixes a few other minor issues. It's dependent on the earlier patch from me that stores unicode codepoints in a Rune type, typedef'd to uint_least32_t. This patch is a pretty big change to xdraws so your scrutiny is appreciated. First, some performance numbers. I used Yu-Jie Lin termfps.sh shell script to benchmark before and after, and you can find it in the attachments. On my Kaveri A10 7850k machine, I get the following results: Before Patch ============ 1) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.553 Frames/second: 64.352 Chars /second: 1,458,159 2) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 159.286 Frames/second: 0.627 Chars /second: 10,953 After Patch =========== 3) Font: "Liberation Mono:pixelsize=12:antialias=false:autohint=false" cwscale: 1.0, chscale: 1.0 For 273x83 100 frames. Elapsed time : 1.544 Frames/second: 64.728 Chars /second: 1,466,690 4) Font: "Inconsolata:pixelsize=14:antialias=true:autohint=true" cwscale: 1.001, chscale: 1.001 For 239x73 100 frames. Elapsed time : 1.955 Frames/second: 51.146 Chars /second: 892,361 As you can see, while the improvements for fonts with unit-kerning is marginal, there's a huge ~81x performance increase with the patch when using kerning values other than 1.0. So what does the patch do? The `xdraws' function would render each glyph one at a time if non-unit kerning values were configured, and this was the primary cause of the slow down. Xft provides a handful of functions which allow you to render multiple characters or glyphs at time, each with a unique <x,y> position, so it was simply a matter of massaging the data into a format that would allow us to use one of these functions. I've split `xdraws' up into two functions. In the first pass with `xmakeglyphfontspecs' it will iterate over all of the glyphs in a given row and it will build up an array of corresponding XftGlyphFontSpec records. Much of the old logic for resolving fonts for glyphs using Xft and fontconfig went into this function. The second pass is done with `xrenderglyphfontspecs' which contains the old logic for determining colors, clearing the background, and finally rendering the array of XftGlyphFontSpec records. There's a couple of other things that have been improved by this patch. For instance, the UTF-32 codepoints in the Line's were being re-encoded back into UTF-8 strings to be passed to `xdraws' which in turn would then decode back to UTF-32 to verify that the Font contained a matching glyph for the code point. Next, the UTF-8 string was being passed to `XftDrawStringUtf8' which internally mallocs a scratch buffer and decodes back to UTF-32 and does the lookup of the glyphs all over again. This patch gets rid of all of this redundant round-trip encoding and decoding of characters to be rendered and only looks up the glyph index once (per font) during the font resolution phase. So this is probably what's responsible for the marginal improvements seen when kerning values are kept to 1.0. I imagine there are other performance improvements here too, not seen in the above benchmarks, if the user has lots of non-ASCII code plane characters on the screen, or several different fonts are being utilized during screen redraw. Anyway, if you see any problems, please let me know and I can fix them.
9 years ago
14 years ago
14 years ago
  1. /* See LICENSE for license details. */
  2. #include <ctype.h>
  3. #include <errno.h>
  4. #include <fcntl.h>
  5. #include <limits.h>
  6. #include <locale.h>
  7. #include <pwd.h>
  8. #include <stdarg.h>
  9. #include <stdbool.h>
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <signal.h>
  14. #include <stdint.h>
  15. #include <sys/ioctl.h>
  16. #include <sys/select.h>
  17. #include <sys/stat.h>
  18. #include <sys/time.h>
  19. #include <sys/types.h>
  20. #include <sys/wait.h>
  21. #include <time.h>
  22. #include <unistd.h>
  23. #include <libgen.h>
  24. #include <X11/Xatom.h>
  25. #include <X11/Xlib.h>
  26. #include <X11/Xutil.h>
  27. #include <X11/cursorfont.h>
  28. #include <X11/keysym.h>
  29. #include <X11/Xft/Xft.h>
  30. #include <X11/XKBlib.h>
  31. #include <fontconfig/fontconfig.h>
  32. #include <wchar.h>
  33. #include "arg.h"
  34. char *argv0;
  35. #define Glyph Glyph_
  36. #define Font Font_
  37. #if defined(__linux)
  38. #include <pty.h>
  39. #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  40. #include <util.h>
  41. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  42. #include <libutil.h>
  43. #endif
  44. /* XEMBED messages */
  45. #define XEMBED_FOCUS_IN 4
  46. #define XEMBED_FOCUS_OUT 5
  47. /* Arbitrary sizes */
  48. #define UTF_INVALID 0xFFFD
  49. #define UTF_SIZ 4
  50. #define ESC_BUF_SIZ (128*UTF_SIZ)
  51. #define ESC_ARG_SIZ 16
  52. #define STR_BUF_SIZ ESC_BUF_SIZ
  53. #define STR_ARG_SIZ ESC_ARG_SIZ
  54. #define XK_ANY_MOD UINT_MAX
  55. #define XK_NO_MOD 0
  56. #define XK_SWITCH_MOD (1<<13)
  57. /* macros */
  58. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  59. #define MAX(a, b) ((a) < (b) ? (b) : (a))
  60. #define LEN(a) (sizeof(a) / sizeof(a)[0])
  61. #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
  62. #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
  63. #define ISCONTROLC0(c) (BETWEEN(c, 0, 0x1f) || (c) == '\177')
  64. #define ISCONTROLC1(c) (BETWEEN(c, 0x80, 0x9f))
  65. #define ISCONTROL(c) (ISCONTROLC0(c) || ISCONTROLC1(c))
  66. #define ISDELIM(u) (utf8strchr(worddelimiters, u) != NULL)
  67. #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
  68. #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
  69. #define IS_SET(flag) ((term.mode & (flag)) != 0)
  70. #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_nsec-t2.tv_nsec)/1E6)
  71. #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
  72. #define TRUECOLOR(r,g,b) (1 << 24 | (r) << 16 | (g) << 8 | (b))
  73. #define IS_TRUECOL(x) (1 << 24 & (x))
  74. #define TRUERED(x) (((x) & 0xff0000) >> 8)
  75. #define TRUEGREEN(x) (((x) & 0xff00))
  76. #define TRUEBLUE(x) (((x) & 0xff) << 8)
  77. enum glyph_attribute {
  78. ATTR_NULL = 0,
  79. ATTR_BOLD = 1 << 0,
  80. ATTR_FAINT = 1 << 1,
  81. ATTR_ITALIC = 1 << 2,
  82. ATTR_UNDERLINE = 1 << 3,
  83. ATTR_BLINK = 1 << 4,
  84. ATTR_REVERSE = 1 << 5,
  85. ATTR_INVISIBLE = 1 << 6,
  86. ATTR_STRUCK = 1 << 7,
  87. ATTR_WRAP = 1 << 8,
  88. ATTR_WIDE = 1 << 9,
  89. ATTR_WDUMMY = 1 << 10,
  90. ATTR_BOLD_FAINT = ATTR_BOLD | ATTR_FAINT,
  91. };
  92. enum cursor_movement {
  93. CURSOR_SAVE,
  94. CURSOR_LOAD
  95. };
  96. enum cursor_state {
  97. CURSOR_DEFAULT = 0,
  98. CURSOR_WRAPNEXT = 1,
  99. CURSOR_ORIGIN = 2
  100. };
  101. enum term_mode {
  102. MODE_WRAP = 1 << 0,
  103. MODE_INSERT = 1 << 1,
  104. MODE_APPKEYPAD = 1 << 2,
  105. MODE_ALTSCREEN = 1 << 3,
  106. MODE_CRLF = 1 << 4,
  107. MODE_MOUSEBTN = 1 << 5,
  108. MODE_MOUSEMOTION = 1 << 6,
  109. MODE_REVERSE = 1 << 7,
  110. MODE_KBDLOCK = 1 << 8,
  111. MODE_HIDE = 1 << 9,
  112. MODE_ECHO = 1 << 10,
  113. MODE_APPCURSOR = 1 << 11,
  114. MODE_MOUSESGR = 1 << 12,
  115. MODE_8BIT = 1 << 13,
  116. MODE_BLINK = 1 << 14,
  117. MODE_FBLINK = 1 << 15,
  118. MODE_FOCUS = 1 << 16,
  119. MODE_MOUSEX10 = 1 << 17,
  120. MODE_MOUSEMANY = 1 << 18,
  121. MODE_BRCKTPASTE = 1 << 19,
  122. MODE_PRINT = 1 << 20,
  123. MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
  124. |MODE_MOUSEMANY,
  125. };
  126. enum charset {
  127. CS_GRAPHIC0,
  128. CS_GRAPHIC1,
  129. CS_UK,
  130. CS_USA,
  131. CS_MULTI,
  132. CS_GER,
  133. CS_FIN
  134. };
  135. enum escape_state {
  136. ESC_START = 1,
  137. ESC_CSI = 2,
  138. ESC_STR = 4, /* DCS, OSC, PM, APC */
  139. ESC_ALTCHARSET = 8,
  140. ESC_STR_END = 16, /* a final string was encountered */
  141. ESC_TEST = 32, /* Enter in test mode */
  142. };
  143. enum window_state {
  144. WIN_VISIBLE = 1,
  145. WIN_FOCUSED = 2
  146. };
  147. enum selection_mode {
  148. SEL_IDLE = 0,
  149. SEL_EMPTY = 1,
  150. SEL_READY = 2
  151. };
  152. enum selection_type {
  153. SEL_REGULAR = 1,
  154. SEL_RECTANGULAR = 2
  155. };
  156. enum selection_snap {
  157. SNAP_WORD = 1,
  158. SNAP_LINE = 2
  159. };
  160. typedef unsigned char uchar;
  161. typedef unsigned int uint;
  162. typedef unsigned long ulong;
  163. typedef unsigned short ushort;
  164. typedef uint_least32_t Rune;
  165. typedef XftDraw *Draw;
  166. typedef XftColor Color;
  167. typedef struct {
  168. Rune u; /* character code */
  169. ushort mode; /* attribute flags */
  170. uint32_t fg; /* foreground */
  171. uint32_t bg; /* background */
  172. } Glyph;
  173. typedef Glyph *Line;
  174. typedef struct {
  175. Glyph attr; /* current char attributes */
  176. int x;
  177. int y;
  178. char state;
  179. } TCursor;
  180. /* CSI Escape sequence structs */
  181. /* ESC '[' [[ [<priv>] <arg> [;]] <mode> [<mode>]] */
  182. typedef struct {
  183. char buf[ESC_BUF_SIZ]; /* raw string */
  184. int len; /* raw string length */
  185. char priv;
  186. int arg[ESC_ARG_SIZ];
  187. int narg; /* nb of args */
  188. char mode[2];
  189. } CSIEscape;
  190. /* STR Escape sequence structs */
  191. /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
  192. typedef struct {
  193. char type; /* ESC type ... */
  194. char buf[STR_BUF_SIZ]; /* raw string */
  195. int len; /* raw string length */
  196. char *args[STR_ARG_SIZ];
  197. int narg; /* nb of args */
  198. } STREscape;
  199. /* Internal representation of the screen */
  200. typedef struct {
  201. int row; /* nb row */
  202. int col; /* nb col */
  203. Line *line; /* screen */
  204. Line *alt; /* alternate screen */
  205. bool *dirty; /* dirtyness of lines */
  206. XftGlyphFontSpec *specbuf; /* font spec buffer used for rendering */
  207. TCursor c; /* cursor */
  208. int top; /* top scroll limit */
  209. int bot; /* bottom scroll limit */
  210. int mode; /* terminal mode flags */
  211. int esc; /* escape state flags */
  212. char trantbl[4]; /* charset table translation */
  213. int charset; /* current charset */
  214. int icharset; /* selected charset for sequence */
  215. bool numlock; /* lock numbers in keyboard */
  216. bool *tabs;
  217. } Term;
  218. /* Purely graphic info */
  219. typedef struct {
  220. Display *dpy;
  221. Colormap cmap;
  222. Window win;
  223. Drawable buf;
  224. Atom xembed, wmdeletewin, netwmname, netwmpid;
  225. XIM xim;
  226. XIC xic;
  227. Draw draw;
  228. Visual *vis;
  229. XSetWindowAttributes attrs;
  230. int scr;
  231. bool isfixed; /* is fixed geometry? */
  232. int l, t; /* left and top offset */
  233. int gm; /* geometry mask */
  234. int tw, th; /* tty width and height */
  235. int w, h; /* window width and height */
  236. int ch; /* char height */
  237. int cw; /* char width */
  238. char state; /* focus, redraw, visible */
  239. int cursor; /* cursor style */
  240. } XWindow;
  241. typedef struct {
  242. uint b;
  243. uint mask;
  244. char *s;
  245. } Mousekey;
  246. typedef struct {
  247. KeySym k;
  248. uint mask;
  249. char *s;
  250. /* three valued logic variables: 0 indifferent, 1 on, -1 off */
  251. signed char appkey; /* application keypad */
  252. signed char appcursor; /* application cursor */
  253. signed char crlf; /* crlf mode */
  254. } Key;
  255. typedef struct {
  256. int mode;
  257. int type;
  258. int snap;
  259. /*
  260. * Selection variables:
  261. * nb normalized coordinates of the beginning of the selection
  262. * ne normalized coordinates of the end of the selection
  263. * ob original coordinates of the beginning of the selection
  264. * oe original coordinates of the end of the selection
  265. */
  266. struct {
  267. int x, y;
  268. } nb, ne, ob, oe;
  269. char *primary, *clipboard;
  270. Atom xtarget;
  271. bool alt;
  272. struct timespec tclick1;
  273. struct timespec tclick2;
  274. } Selection;
  275. typedef union {
  276. int i;
  277. uint ui;
  278. float f;
  279. const void *v;
  280. } Arg;
  281. typedef struct {
  282. uint mod;
  283. KeySym keysym;
  284. void (*func)(const Arg *);
  285. const Arg arg;
  286. } Shortcut;
  287. /* function definitions used in config.h */
  288. static void clipcopy(const Arg *);
  289. static void clippaste(const Arg *);
  290. static void numlock(const Arg *);
  291. static void selpaste(const Arg *);
  292. static void xzoom(const Arg *);
  293. static void xzoomabs(const Arg *);
  294. static void xzoomreset(const Arg *);
  295. static void printsel(const Arg *);
  296. static void printscreen(const Arg *) ;
  297. static void toggleprinter(const Arg *);
  298. /* Config.h for applying patches and the configuration. */
  299. #include "config.h"
  300. /* Font structure */
  301. typedef struct {
  302. int height;
  303. int width;
  304. int ascent;
  305. int descent;
  306. short lbearing;
  307. short rbearing;
  308. XftFont *match;
  309. FcFontSet *set;
  310. FcPattern *pattern;
  311. } Font;
  312. /* Drawing Context */
  313. typedef struct {
  314. Color col[MAX(LEN(colorname), 256)];
  315. Font font, bfont, ifont, ibfont;
  316. GC gc;
  317. } DC;
  318. static void die(const char *, ...);
  319. static void draw(void);
  320. static void redraw(void);
  321. static void drawregion(int, int, int, int);
  322. static void execsh(void);
  323. static void stty(void);
  324. static void sigchld(int);
  325. static void run(void);
  326. static void csidump(void);
  327. static void csihandle(void);
  328. static void csiparse(void);
  329. static void csireset(void);
  330. static int eschandle(uchar);
  331. static void strdump(void);
  332. static void strhandle(void);
  333. static void strparse(void);
  334. static void strreset(void);
  335. static int tattrset(int);
  336. static void tprinter(char *, size_t);
  337. static void tdumpsel(void);
  338. static void tdumpline(int);
  339. static void tdump(void);
  340. static void tclearregion(int, int, int, int);
  341. static void tcursor(int);
  342. static void tdeletechar(int);
  343. static void tdeleteline(int);
  344. static void tinsertblank(int);
  345. static void tinsertblankline(int);
  346. static int tlinelen(int);
  347. static void tmoveto(int, int);
  348. static void tmoveato(int, int);
  349. static void tnew(int, int);
  350. static void tnewline(int);
  351. static void tputtab(int);
  352. static void tputc(Rune);
  353. static void treset(void);
  354. static void tresize(int, int);
  355. static void tscrollup(int, int);
  356. static void tscrolldown(int, int);
  357. static void tsetattr(int *, int);
  358. static void tsetchar(Rune, Glyph *, int, int);
  359. static void tsetscroll(int, int);
  360. static void tswapscreen(void);
  361. static void tsetdirt(int, int);
  362. static void tsetdirtattr(int);
  363. static void tsetmode(bool, bool, int *, int);
  364. static void tfulldirt(void);
  365. static void techo(Rune);
  366. static void tcontrolcode(uchar );
  367. static void tdectest(char );
  368. static int32_t tdefcolor(int *, int *, int);
  369. static void tdeftran(char);
  370. static inline bool match(uint, uint);
  371. static void ttynew(void);
  372. static void ttyread(void);
  373. static void ttyresize(void);
  374. static void ttysend(char *, size_t);
  375. static void ttywrite(const char *, size_t);
  376. static void tstrsequence(uchar);
  377. static inline ushort sixd_to_16bit(int);
  378. static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
  379. static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
  380. static void xdrawglyph(Glyph, int, int);
  381. static void xhints(void);
  382. static void xclear(int, int, int, int);
  383. static void xdrawcursor(void);
  384. static void xinit(void);
  385. static void xloadcols(void);
  386. static int xsetcolorname(int, const char *);
  387. static int xgeommasktogravity(int);
  388. static int xloadfont(Font *, FcPattern *);
  389. static void xloadfonts(char *, double);
  390. static void xsettitle(char *);
  391. static void xresettitle(void);
  392. static void xsetpointermotion(int);
  393. static void xseturgency(int);
  394. static void xsetsel(char *, Time);
  395. static void xtermclear(int, int, int, int);
  396. static void xunloadfont(Font *);
  397. static void xunloadfonts(void);
  398. static void xresize(int, int);
  399. static void expose(XEvent *);
  400. static void visibility(XEvent *);
  401. static void unmap(XEvent *);
  402. static char *kmap(KeySym, uint);
  403. static void kpress(XEvent *);
  404. static void cmessage(XEvent *);
  405. static void cresize(int, int);
  406. static void resize(XEvent *);
  407. static void focus(XEvent *);
  408. static void brelease(XEvent *);
  409. static void bpress(XEvent *);
  410. static void bmotion(XEvent *);
  411. static void selnotify(XEvent *);
  412. static void selclear(XEvent *);
  413. static void selrequest(XEvent *);
  414. static void selinit(void);
  415. static void selnormalize(void);
  416. static inline bool selected(int, int);
  417. static char *getsel(void);
  418. static void selcopy(Time);
  419. static void selscroll(int, int);
  420. static void selsnap(int *, int *, int);
  421. static int x2col(int);
  422. static int y2row(int);
  423. static void getbuttoninfo(XEvent *);
  424. static void mousereport(XEvent *);
  425. static size_t utf8decode(char *, Rune *, size_t);
  426. static Rune utf8decodebyte(char, size_t *);
  427. static size_t utf8encode(Rune, char *);
  428. static char utf8encodebyte(Rune, size_t);
  429. static char *utf8strchr(char *s, Rune u);
  430. static size_t utf8validate(Rune *, size_t);
  431. static ssize_t xwrite(int, const char *, size_t);
  432. static void *xmalloc(size_t);
  433. static void *xrealloc(void *, size_t);
  434. static char *xstrdup(char *);
  435. static void usage(void);
  436. static void (*handler[LASTEvent])(XEvent *) = {
  437. [KeyPress] = kpress,
  438. [ClientMessage] = cmessage,
  439. [ConfigureNotify] = resize,
  440. [VisibilityNotify] = visibility,
  441. [UnmapNotify] = unmap,
  442. [Expose] = expose,
  443. [FocusIn] = focus,
  444. [FocusOut] = focus,
  445. [MotionNotify] = bmotion,
  446. [ButtonPress] = bpress,
  447. [ButtonRelease] = brelease,
  448. /*
  449. * Uncomment if you want the selection to disappear when you select something
  450. * different in another window.
  451. */
  452. /* [SelectionClear] = selclear, */
  453. [SelectionNotify] = selnotify,
  454. [SelectionRequest] = selrequest,
  455. };
  456. /* Globals */
  457. static DC dc;
  458. static XWindow xw;
  459. static Term term;
  460. static CSIEscape csiescseq;
  461. static STREscape strescseq;
  462. static int cmdfd;
  463. static pid_t pid;
  464. static Selection sel;
  465. static int iofd = 1;
  466. static char **opt_cmd = NULL;
  467. static char *opt_io = NULL;
  468. static char *opt_title = NULL;
  469. static char *opt_embed = NULL;
  470. static char *opt_class = NULL;
  471. static char *opt_font = NULL;
  472. static char *opt_line = NULL;
  473. static int oldbutton = 3; /* button event on startup: 3 = release */
  474. static char *usedfont = NULL;
  475. static double usedfontsize = 0;
  476. static double defaultfontsize = 0;
  477. static uchar utfbyte[UTF_SIZ + 1] = {0x80, 0, 0xC0, 0xE0, 0xF0};
  478. static uchar utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
  479. static Rune utfmin[UTF_SIZ + 1] = { 0, 0, 0x80, 0x800, 0x10000};
  480. static Rune utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
  481. /* Font Ring Cache */
  482. enum {
  483. FRC_NORMAL,
  484. FRC_ITALIC,
  485. FRC_BOLD,
  486. FRC_ITALICBOLD
  487. };
  488. typedef struct {
  489. XftFont *font;
  490. int flags;
  491. Rune unicodep;
  492. } Fontcache;
  493. /* Fontcache is an array now. A new font will be appended to the array. */
  494. static Fontcache frc[16];
  495. static int frclen = 0;
  496. ssize_t
  497. xwrite(int fd, const char *s, size_t len) {
  498. size_t aux = len;
  499. while(len > 0) {
  500. ssize_t r = write(fd, s, len);
  501. if(r < 0)
  502. return r;
  503. len -= r;
  504. s += r;
  505. }
  506. return aux;
  507. }
  508. void *
  509. xmalloc(size_t len) {
  510. void *p = malloc(len);
  511. if(!p)
  512. die("Out of memory\n");
  513. return p;
  514. }
  515. void *
  516. xrealloc(void *p, size_t len) {
  517. if((p = realloc(p, len)) == NULL)
  518. die("Out of memory\n");
  519. return p;
  520. }
  521. char *
  522. xstrdup(char *s) {
  523. if((s = strdup(s)) == NULL)
  524. die("Out of memory\n");
  525. return s;
  526. }
  527. size_t
  528. utf8decode(char *c, Rune *u, size_t clen) {
  529. size_t i, j, len, type;
  530. Rune udecoded;
  531. *u = UTF_INVALID;
  532. if(!clen)
  533. return 0;
  534. udecoded = utf8decodebyte(c[0], &len);
  535. if(!BETWEEN(len, 1, UTF_SIZ))
  536. return 1;
  537. for(i = 1, j = 1; i < clen && j < len; ++i, ++j) {
  538. udecoded = (udecoded << 6) | utf8decodebyte(c[i], &type);
  539. if(type != 0)
  540. return j;
  541. }
  542. if(j < len)
  543. return 0;
  544. *u = udecoded;
  545. utf8validate(u, len);
  546. return len;
  547. }
  548. Rune
  549. utf8decodebyte(char c, size_t *i) {
  550. for(*i = 0; *i < LEN(utfmask); ++(*i))
  551. if(((uchar)c & utfmask[*i]) == utfbyte[*i])
  552. return (uchar)c & ~utfmask[*i];
  553. return 0;
  554. }
  555. size_t
  556. utf8encode(Rune u, char *c) {
  557. size_t len, i;
  558. len = utf8validate(&u, 0);
  559. if(len > UTF_SIZ)
  560. return 0;
  561. for(i = len - 1; i != 0; --i) {
  562. c[i] = utf8encodebyte(u, 0);
  563. u >>= 6;
  564. }
  565. c[0] = utf8encodebyte(u, len);
  566. return len;
  567. }
  568. char
  569. utf8encodebyte(Rune u, size_t i) {
  570. return utfbyte[i] | (u & ~utfmask[i]);
  571. }
  572. char *
  573. utf8strchr(char *s, Rune u) {
  574. Rune r;
  575. size_t i, j, len;
  576. len = strlen(s);
  577. for(i = 0, j = 0; i < len; i += j) {
  578. if(!(j = utf8decode(&s[i], &r, len - i)))
  579. break;
  580. if(r == u)
  581. return &(s[i]);
  582. }
  583. return NULL;
  584. }
  585. size_t
  586. utf8validate(Rune *u, size_t i) {
  587. if(!BETWEEN(*u, utfmin[i], utfmax[i]) || BETWEEN(*u, 0xD800, 0xDFFF))
  588. *u = UTF_INVALID;
  589. for(i = 1; *u > utfmax[i]; ++i)
  590. ;
  591. return i;
  592. }
  593. void
  594. selinit(void) {
  595. memset(&sel.tclick1, 0, sizeof(sel.tclick1));
  596. memset(&sel.tclick2, 0, sizeof(sel.tclick2));
  597. sel.mode = SEL_IDLE;
  598. sel.ob.x = -1;
  599. sel.primary = NULL;
  600. sel.clipboard = NULL;
  601. sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
  602. if(sel.xtarget == None)
  603. sel.xtarget = XA_STRING;
  604. }
  605. int
  606. x2col(int x) {
  607. x -= borderpx;
  608. x /= xw.cw;
  609. return LIMIT(x, 0, term.col-1);
  610. }
  611. int
  612. y2row(int y) {
  613. y -= borderpx;
  614. y /= xw.ch;
  615. return LIMIT(y, 0, term.row-1);
  616. }
  617. int
  618. tlinelen(int y) {
  619. int i = term.col;
  620. if(term.line[y][i - 1].mode & ATTR_WRAP)
  621. return i;
  622. while(i > 0 && term.line[y][i - 1].u == ' ')
  623. --i;
  624. return i;
  625. }
  626. void
  627. selnormalize(void) {
  628. int i;
  629. if(sel.type == SEL_REGULAR && sel.ob.y != sel.oe.y) {
  630. sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
  631. sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
  632. } else {
  633. sel.nb.x = MIN(sel.ob.x, sel.oe.x);
  634. sel.ne.x = MAX(sel.ob.x, sel.oe.x);
  635. }
  636. sel.nb.y = MIN(sel.ob.y, sel.oe.y);
  637. sel.ne.y = MAX(sel.ob.y, sel.oe.y);
  638. selsnap(&sel.nb.x, &sel.nb.y, -1);
  639. selsnap(&sel.ne.x, &sel.ne.y, +1);
  640. /* expand selection over line breaks */
  641. if (sel.type == SEL_RECTANGULAR)
  642. return;
  643. i = tlinelen(sel.nb.y);
  644. if (i < sel.nb.x)
  645. sel.nb.x = i;
  646. if (tlinelen(sel.ne.y) <= sel.ne.x)
  647. sel.ne.x = term.col - 1;
  648. }
  649. bool
  650. selected(int x, int y) {
  651. if(sel.mode == SEL_EMPTY)
  652. return false;
  653. if(sel.type == SEL_RECTANGULAR)
  654. return BETWEEN(y, sel.nb.y, sel.ne.y)
  655. && BETWEEN(x, sel.nb.x, sel.ne.x);
  656. return BETWEEN(y, sel.nb.y, sel.ne.y)
  657. && (y != sel.nb.y || x >= sel.nb.x)
  658. && (y != sel.ne.y || x <= sel.ne.x);
  659. }
  660. void
  661. selsnap(int *x, int *y, int direction) {
  662. int newx, newy, xt, yt;
  663. bool delim, prevdelim;
  664. Glyph *gp, *prevgp;
  665. switch(sel.snap) {
  666. case SNAP_WORD:
  667. /*
  668. * Snap around if the word wraps around at the end or
  669. * beginning of a line.
  670. */
  671. prevgp = &term.line[*y][*x];
  672. prevdelim = ISDELIM(prevgp->u);
  673. for(;;) {
  674. newx = *x + direction;
  675. newy = *y;
  676. if(!BETWEEN(newx, 0, term.col - 1)) {
  677. newy += direction;
  678. newx = (newx + term.col) % term.col;
  679. if (!BETWEEN(newy, 0, term.row - 1))
  680. break;
  681. if(direction > 0)
  682. yt = *y, xt = *x;
  683. else
  684. yt = newy, xt = newx;
  685. if(!(term.line[yt][xt].mode & ATTR_WRAP))
  686. break;
  687. }
  688. if (newx >= tlinelen(newy))
  689. break;
  690. gp = &term.line[newy][newx];
  691. delim = ISDELIM(gp->u);
  692. if(!(gp->mode & ATTR_WDUMMY) && (delim != prevdelim
  693. || (delim && gp->u != prevgp->u)))
  694. break;
  695. *x = newx;
  696. *y = newy;
  697. prevgp = gp;
  698. prevdelim = delim;
  699. }
  700. break;
  701. case SNAP_LINE:
  702. /*
  703. * Snap around if the the previous line or the current one
  704. * has set ATTR_WRAP at its end. Then the whole next or
  705. * previous line will be selected.
  706. */
  707. *x = (direction < 0) ? 0 : term.col - 1;
  708. if(direction < 0) {
  709. for(; *y > 0; *y += direction) {
  710. if(!(term.line[*y-1][term.col-1].mode
  711. & ATTR_WRAP)) {
  712. break;
  713. }
  714. }
  715. } else if(direction > 0) {
  716. for(; *y < term.row-1; *y += direction) {
  717. if(!(term.line[*y][term.col-1].mode
  718. & ATTR_WRAP)) {
  719. break;
  720. }
  721. }
  722. }
  723. break;
  724. }
  725. }
  726. void
  727. getbuttoninfo(XEvent *e) {
  728. int type;
  729. uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
  730. sel.alt = IS_SET(MODE_ALTSCREEN);
  731. sel.oe.x = x2col(e->xbutton.x);
  732. sel.oe.y = y2row(e->xbutton.y);
  733. selnormalize();
  734. sel.type = SEL_REGULAR;
  735. for(type = 1; type < LEN(selmasks); ++type) {
  736. if(match(selmasks[type], state)) {
  737. sel.type = type;
  738. break;
  739. }
  740. }
  741. }
  742. void
  743. mousereport(XEvent *e) {
  744. int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
  745. button = e->xbutton.button, state = e->xbutton.state,
  746. len;
  747. char buf[40];
  748. static int ox, oy;
  749. /* from urxvt */
  750. if(e->xbutton.type == MotionNotify) {
  751. if(x == ox && y == oy)
  752. return;
  753. if(!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
  754. return;
  755. /* MOUSE_MOTION: no reporting if no button is pressed */
  756. if(IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
  757. return;
  758. button = oldbutton + 32;
  759. ox = x;
  760. oy = y;
  761. } else {
  762. if(!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
  763. button = 3;
  764. } else {
  765. button -= Button1;
  766. if(button >= 3)
  767. button += 64 - 3;
  768. }
  769. if(e->xbutton.type == ButtonPress) {
  770. oldbutton = button;
  771. ox = x;
  772. oy = y;
  773. } else if(e->xbutton.type == ButtonRelease) {
  774. oldbutton = 3;
  775. /* MODE_MOUSEX10: no button release reporting */
  776. if(IS_SET(MODE_MOUSEX10))
  777. return;
  778. if (button == 64 || button == 65)
  779. return;
  780. }
  781. }
  782. if(!IS_SET(MODE_MOUSEX10)) {
  783. button += ((state & ShiftMask ) ? 4 : 0)
  784. + ((state & Mod4Mask ) ? 8 : 0)
  785. + ((state & ControlMask) ? 16 : 0);
  786. }
  787. if(IS_SET(MODE_MOUSESGR)) {
  788. len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
  789. button, x+1, y+1,
  790. e->xbutton.type == ButtonRelease ? 'm' : 'M');
  791. } else if(x < 223 && y < 223) {
  792. len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
  793. 32+button, 32+x+1, 32+y+1);
  794. } else {
  795. return;
  796. }
  797. ttywrite(buf, len);
  798. }
  799. void
  800. bpress(XEvent *e) {
  801. struct timespec now;
  802. Mousekey *mk;
  803. if(IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
  804. mousereport(e);
  805. return;
  806. }
  807. for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
  808. if(e->xbutton.button == mk->b
  809. && match(mk->mask, e->xbutton.state)) {
  810. ttysend(mk->s, strlen(mk->s));
  811. return;
  812. }
  813. }
  814. if(e->xbutton.button == Button1) {
  815. clock_gettime(CLOCK_MONOTONIC, &now);
  816. /* Clear previous selection, logically and visually. */
  817. selclear(NULL);
  818. sel.mode = SEL_EMPTY;
  819. sel.type = SEL_REGULAR;
  820. sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
  821. sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
  822. /*
  823. * If the user clicks below predefined timeouts specific
  824. * snapping behaviour is exposed.
  825. */
  826. if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
  827. sel.snap = SNAP_LINE;
  828. } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
  829. sel.snap = SNAP_WORD;
  830. } else {
  831. sel.snap = 0;
  832. }
  833. selnormalize();
  834. if(sel.snap != 0)
  835. sel.mode = SEL_READY;
  836. tsetdirt(sel.nb.y, sel.ne.y);
  837. sel.tclick2 = sel.tclick1;
  838. sel.tclick1 = now;
  839. }
  840. }
  841. char *
  842. getsel(void) {
  843. char *str, *ptr;
  844. int y, bufsize, lastx, linelen;
  845. Glyph *gp, *last;
  846. if(sel.ob.x == -1)
  847. return NULL;
  848. bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
  849. ptr = str = xmalloc(bufsize);
  850. /* append every set & selected glyph to the selection */
  851. for(y = sel.nb.y; y <= sel.ne.y; y++) {
  852. linelen = tlinelen(y);
  853. if(sel.type == SEL_RECTANGULAR) {
  854. gp = &term.line[y][sel.nb.x];
  855. lastx = sel.ne.x;
  856. } else {
  857. gp = &term.line[y][sel.nb.y == y ? sel.nb.x : 0];
  858. lastx = (sel.ne.y == y) ? sel.ne.x : term.col-1;
  859. }
  860. last = &term.line[y][MIN(lastx, linelen-1)];
  861. while(last >= gp && last->u == ' ')
  862. --last;
  863. for( ; gp <= last; ++gp) {
  864. if(gp->mode & ATTR_WDUMMY)
  865. continue;
  866. ptr += utf8encode(gp->u, ptr);
  867. }
  868. /*
  869. * Copy and pasting of line endings is inconsistent
  870. * in the inconsistent terminal and GUI world.
  871. * The best solution seems like to produce '\n' when
  872. * something is copied from st and convert '\n' to
  873. * '\r', when something to be pasted is received by
  874. * st.
  875. * FIXME: Fix the computer world.
  876. */
  877. if((y < sel.ne.y || lastx >= linelen) && !(last->mode & ATTR_WRAP))
  878. *ptr++ = '\n';
  879. }
  880. *ptr = 0;
  881. return str;
  882. }
  883. void
  884. selcopy(Time t) {
  885. xsetsel(getsel(), t);
  886. }
  887. void
  888. selnotify(XEvent *e) {
  889. ulong nitems, ofs, rem;
  890. int format;
  891. uchar *data, *last, *repl;
  892. Atom type;
  893. XSelectionEvent *xsev;
  894. ofs = 0;
  895. xsev = &e->xselection;
  896. if (xsev->property == None)
  897. return;
  898. do {
  899. if(XGetWindowProperty(xw.dpy, xw.win, xsev->property, ofs,
  900. BUFSIZ/4, False, AnyPropertyType,
  901. &type, &format, &nitems, &rem,
  902. &data)) {
  903. fprintf(stderr, "Clipboard allocation failed\n");
  904. return;
  905. }
  906. /*
  907. * As seen in getsel:
  908. * Line endings are inconsistent in the terminal and GUI world
  909. * copy and pasting. When receiving some selection data,
  910. * replace all '\n' with '\r'.
  911. * FIXME: Fix the computer world.
  912. */
  913. repl = data;
  914. last = data + nitems * format / 8;
  915. while((repl = memchr(repl, '\n', last - repl))) {
  916. *repl++ = '\r';
  917. }
  918. if(IS_SET(MODE_BRCKTPASTE))
  919. ttywrite("\033[200~", 6);
  920. ttysend((char *)data, nitems * format / 8);
  921. if(IS_SET(MODE_BRCKTPASTE))
  922. ttywrite("\033[201~", 6);
  923. XFree(data);
  924. /* number of 32-bit chunks returned */
  925. ofs += nitems * format / 32;
  926. } while(rem > 0);
  927. }
  928. void
  929. selpaste(const Arg *dummy) {
  930. XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
  931. xw.win, CurrentTime);
  932. }
  933. void
  934. clipcopy(const Arg *dummy) {
  935. Atom clipboard;
  936. if(sel.clipboard != NULL)
  937. free(sel.clipboard);
  938. if(sel.primary != NULL) {
  939. sel.clipboard = xstrdup(sel.primary);
  940. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  941. XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
  942. }
  943. }
  944. void
  945. clippaste(const Arg *dummy) {
  946. Atom clipboard;
  947. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  948. XConvertSelection(xw.dpy, clipboard, sel.xtarget, clipboard,
  949. xw.win, CurrentTime);
  950. }
  951. void
  952. selclear(XEvent *e) {
  953. if(sel.ob.x == -1)
  954. return;
  955. sel.mode = SEL_IDLE;
  956. sel.ob.x = -1;
  957. tsetdirt(sel.nb.y, sel.ne.y);
  958. }
  959. void
  960. selrequest(XEvent *e) {
  961. XSelectionRequestEvent *xsre;
  962. XSelectionEvent xev;
  963. Atom xa_targets, string, clipboard;
  964. char *seltext;
  965. xsre = (XSelectionRequestEvent *) e;
  966. xev.type = SelectionNotify;
  967. xev.requestor = xsre->requestor;
  968. xev.selection = xsre->selection;
  969. xev.target = xsre->target;
  970. xev.time = xsre->time;
  971. if (xsre->property == None)
  972. xsre->property = xsre->target;
  973. /* reject */
  974. xev.property = None;
  975. xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
  976. if(xsre->target == xa_targets) {
  977. /* respond with the supported type */
  978. string = sel.xtarget;
  979. XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  980. XA_ATOM, 32, PropModeReplace,
  981. (uchar *) &string, 1);
  982. xev.property = xsre->property;
  983. } else if(xsre->target == sel.xtarget || xsre->target == XA_STRING) {
  984. /*
  985. * xith XA_STRING non ascii characters may be incorrect in the
  986. * requestor. It is not our problem, use utf8.
  987. */
  988. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  989. if(xsre->selection == XA_PRIMARY) {
  990. seltext = sel.primary;
  991. } else if(xsre->selection == clipboard) {
  992. seltext = sel.clipboard;
  993. } else {
  994. fprintf(stderr,
  995. "Unhandled clipboard selection 0x%lx\n",
  996. xsre->selection);
  997. return;
  998. }
  999. if(seltext != NULL) {
  1000. XChangeProperty(xsre->display, xsre->requestor,
  1001. xsre->property, xsre->target,
  1002. 8, PropModeReplace,
  1003. (uchar *)seltext, strlen(seltext));
  1004. xev.property = xsre->property;
  1005. }
  1006. }
  1007. /* all done, send a notification to the listener */
  1008. if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
  1009. fprintf(stderr, "Error sending SelectionNotify event\n");
  1010. }
  1011. void
  1012. xsetsel(char *str, Time t) {
  1013. free(sel.primary);
  1014. sel.primary = str;
  1015. XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
  1016. if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
  1017. selclear(0);
  1018. }
  1019. void
  1020. brelease(XEvent *e) {
  1021. if(IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
  1022. mousereport(e);
  1023. return;
  1024. }
  1025. if(e->xbutton.button == Button2) {
  1026. selpaste(NULL);
  1027. } else if(e->xbutton.button == Button1) {
  1028. if(sel.mode == SEL_READY) {
  1029. getbuttoninfo(e);
  1030. selcopy(e->xbutton.time);
  1031. } else
  1032. selclear(NULL);
  1033. sel.mode = SEL_IDLE;
  1034. tsetdirt(sel.nb.y, sel.ne.y);
  1035. }
  1036. }
  1037. void
  1038. bmotion(XEvent *e) {
  1039. int oldey, oldex, oldsby, oldsey;
  1040. if(IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
  1041. mousereport(e);
  1042. return;
  1043. }
  1044. if(!sel.mode)
  1045. return;
  1046. sel.mode = SEL_READY;
  1047. oldey = sel.oe.y;
  1048. oldex = sel.oe.x;
  1049. oldsby = sel.nb.y;
  1050. oldsey = sel.ne.y;
  1051. getbuttoninfo(e);
  1052. if(oldey != sel.oe.y || oldex != sel.oe.x)
  1053. tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
  1054. }
  1055. void
  1056. die(const char *errstr, ...) {
  1057. va_list ap;
  1058. va_start(ap, errstr);
  1059. vfprintf(stderr, errstr, ap);
  1060. va_end(ap);
  1061. exit(1);
  1062. }
  1063. void
  1064. execsh(void) {
  1065. char **args, *sh, *prog;
  1066. const struct passwd *pw;
  1067. char buf[sizeof(long) * 8 + 1];
  1068. errno = 0;
  1069. if((pw = getpwuid(getuid())) == NULL) {
  1070. if(errno)
  1071. die("getpwuid:%s\n", strerror(errno));
  1072. else
  1073. die("who are you?\n");
  1074. }
  1075. if (!(sh = getenv("SHELL"))) {
  1076. sh = (pw->pw_shell[0]) ? pw->pw_shell : shell;
  1077. }
  1078. if(opt_cmd)
  1079. prog = opt_cmd[0];
  1080. else if(utmp)
  1081. prog = utmp;
  1082. else
  1083. prog = sh;
  1084. args = (opt_cmd) ? opt_cmd : (char *[]) {prog, NULL};
  1085. snprintf(buf, sizeof(buf), "%lu", xw.win);
  1086. unsetenv("COLUMNS");
  1087. unsetenv("LINES");
  1088. unsetenv("TERMCAP");
  1089. setenv("LOGNAME", pw->pw_name, 1);
  1090. setenv("USER", pw->pw_name, 1);
  1091. setenv("SHELL", sh, 1);
  1092. setenv("HOME", pw->pw_dir, 1);
  1093. setenv("TERM", termname, 1);
  1094. setenv("WINDOWID", buf, 1);
  1095. signal(SIGCHLD, SIG_DFL);
  1096. signal(SIGHUP, SIG_DFL);
  1097. signal(SIGINT, SIG_DFL);
  1098. signal(SIGQUIT, SIG_DFL);
  1099. signal(SIGTERM, SIG_DFL);
  1100. signal(SIGALRM, SIG_DFL);
  1101. execvp(prog, args);
  1102. _exit(1);
  1103. }
  1104. void
  1105. sigchld(int a) {
  1106. int stat;
  1107. pid_t p;
  1108. if((p = waitpid(pid, &stat, WNOHANG)) < 0)
  1109. die("Waiting for pid %hd failed: %s\n", pid, strerror(errno));
  1110. if(pid != p)
  1111. return;
  1112. if (!WIFEXITED(stat) || WEXITSTATUS(stat))
  1113. die("child finished with error '%d'\n", stat);
  1114. exit(0);
  1115. }
  1116. void
  1117. stty(void)
  1118. {
  1119. char cmd[_POSIX_ARG_MAX], **p, *q, *s;
  1120. size_t n, siz;
  1121. if((n = strlen(stty_args)) > sizeof(cmd)-1)
  1122. die("incorrect stty parameters\n");
  1123. memcpy(cmd, stty_args, n);
  1124. q = cmd + n;
  1125. siz = sizeof(cmd) - n;
  1126. for(p = opt_cmd; p && (s = *p); ++p) {
  1127. if((n = strlen(s)) > siz-1)
  1128. die("stty parameter length too long\n");
  1129. *q++ = ' ';
  1130. q = memcpy(q, s, n);
  1131. q += n;
  1132. siz-= n + 1;
  1133. }
  1134. *q = '\0';
  1135. if (system(cmd) != 0)
  1136. perror("Couldn't call stty");
  1137. }
  1138. void
  1139. ttynew(void) {
  1140. int m, s;
  1141. struct winsize w = {term.row, term.col, 0, 0};
  1142. if(opt_io) {
  1143. term.mode |= MODE_PRINT;
  1144. iofd = (!strcmp(opt_io, "-")) ?
  1145. 1 : open(opt_io, O_WRONLY | O_CREAT, 0666);
  1146. if(iofd < 0) {
  1147. fprintf(stderr, "Error opening %s:%s\n",
  1148. opt_io, strerror(errno));
  1149. }
  1150. }
  1151. if (opt_line) {
  1152. if((cmdfd = open(opt_line, O_RDWR)) < 0)
  1153. die("open line failed: %s\n", strerror(errno));
  1154. close(0);
  1155. dup(cmdfd);
  1156. stty();
  1157. return;
  1158. }
  1159. /* seems to work fine on linux, openbsd and freebsd */
  1160. if(openpty(&m, &s, NULL, NULL, &w) < 0)
  1161. die("openpty failed: %s\n", strerror(errno));
  1162. switch(pid = fork()) {
  1163. case -1:
  1164. die("fork failed\n");
  1165. break;
  1166. case 0:
  1167. close(iofd);
  1168. setsid(); /* create a new process group */
  1169. dup2(s, 0);
  1170. dup2(s, 1);
  1171. dup2(s, 2);
  1172. if(ioctl(s, TIOCSCTTY, NULL) < 0)
  1173. die("ioctl TIOCSCTTY failed: %s\n", strerror(errno));
  1174. close(s);
  1175. close(m);
  1176. execsh();
  1177. break;
  1178. default:
  1179. close(s);
  1180. cmdfd = m;
  1181. signal(SIGCHLD, sigchld);
  1182. break;
  1183. }
  1184. }
  1185. void
  1186. ttyread(void) {
  1187. static char buf[BUFSIZ];
  1188. static int buflen = 0;
  1189. char *ptr;
  1190. int charsize; /* size of utf8 char in bytes */
  1191. Rune unicodep;
  1192. int ret;
  1193. /* append read bytes to unprocessed bytes */
  1194. if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
  1195. die("Couldn't read from shell: %s\n", strerror(errno));
  1196. /* process every complete utf8 char */
  1197. buflen += ret;
  1198. ptr = buf;
  1199. while((charsize = utf8decode(ptr, &unicodep, buflen))) {
  1200. tputc(unicodep);
  1201. ptr += charsize;
  1202. buflen -= charsize;
  1203. }
  1204. /* keep any uncomplete utf8 char for the next call */
  1205. memmove(buf, ptr, buflen);
  1206. }
  1207. void
  1208. ttywrite(const char *s, size_t n) {
  1209. if(xwrite(cmdfd, s, n) == -1)
  1210. die("write error on tty: %s\n", strerror(errno));
  1211. }
  1212. void
  1213. ttysend(char *s, size_t n) {
  1214. int len;
  1215. Rune u;
  1216. ttywrite(s, n);
  1217. if(IS_SET(MODE_ECHO))
  1218. while((len = utf8decode(s, &u, n)) > 0) {
  1219. techo(u);
  1220. n -= len;
  1221. s += len;
  1222. }
  1223. }
  1224. void
  1225. ttyresize(void) {
  1226. struct winsize w;
  1227. w.ws_row = term.row;
  1228. w.ws_col = term.col;
  1229. w.ws_xpixel = xw.tw;
  1230. w.ws_ypixel = xw.th;
  1231. if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
  1232. fprintf(stderr, "Couldn't set window size: %s\n", strerror(errno));
  1233. }
  1234. int
  1235. tattrset(int attr) {
  1236. int i, j;
  1237. for(i = 0; i < term.row-1; i++) {
  1238. for(j = 0; j < term.col-1; j++) {
  1239. if(term.line[i][j].mode & attr)
  1240. return 1;
  1241. }
  1242. }
  1243. return 0;
  1244. }
  1245. void
  1246. tsetdirt(int top, int bot) {
  1247. int i;
  1248. LIMIT(top, 0, term.row-1);
  1249. LIMIT(bot, 0, term.row-1);
  1250. for(i = top; i <= bot; i++)
  1251. term.dirty[i] = 1;
  1252. }
  1253. void
  1254. tsetdirtattr(int attr) {
  1255. int i, j;
  1256. for(i = 0; i < term.row-1; i++) {
  1257. for(j = 0; j < term.col-1; j++) {
  1258. if(term.line[i][j].mode & attr) {
  1259. tsetdirt(i, i);
  1260. break;
  1261. }
  1262. }
  1263. }
  1264. }
  1265. void
  1266. tfulldirt(void) {
  1267. tsetdirt(0, term.row-1);
  1268. }
  1269. void
  1270. tcursor(int mode) {
  1271. static TCursor c[2];
  1272. bool alt = IS_SET(MODE_ALTSCREEN);
  1273. if(mode == CURSOR_SAVE) {
  1274. c[alt] = term.c;
  1275. } else if(mode == CURSOR_LOAD) {
  1276. term.c = c[alt];
  1277. tmoveto(c[alt].x, c[alt].y);
  1278. }
  1279. }
  1280. void
  1281. treset(void) {
  1282. uint i;
  1283. term.c = (TCursor){{
  1284. .mode = ATTR_NULL,
  1285. .fg = defaultfg,
  1286. .bg = defaultbg
  1287. }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
  1288. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  1289. for(i = tabspaces; i < term.col; i += tabspaces)
  1290. term.tabs[i] = 1;
  1291. term.top = 0;
  1292. term.bot = term.row - 1;
  1293. term.mode = MODE_WRAP;
  1294. memset(term.trantbl, CS_USA, sizeof(term.trantbl));
  1295. term.charset = 0;
  1296. for(i = 0; i < 2; i++) {
  1297. tmoveto(0, 0);
  1298. tcursor(CURSOR_SAVE);
  1299. tclearregion(0, 0, term.col-1, term.row-1);
  1300. tswapscreen();
  1301. }
  1302. }
  1303. void
  1304. tnew(int col, int row) {
  1305. term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
  1306. tresize(col, row);
  1307. term.numlock = 1;
  1308. treset();
  1309. }
  1310. void
  1311. tswapscreen(void) {
  1312. Line *tmp = term.line;
  1313. term.line = term.alt;
  1314. term.alt = tmp;
  1315. term.mode ^= MODE_ALTSCREEN;
  1316. tfulldirt();
  1317. }
  1318. void
  1319. tscrolldown(int orig, int n) {
  1320. int i;
  1321. Line temp;
  1322. LIMIT(n, 0, term.bot-orig+1);
  1323. tsetdirt(orig, term.bot-n);
  1324. tclearregion(0, term.bot-n+1, term.col-1, term.bot);
  1325. for(i = term.bot; i >= orig+n; i--) {
  1326. temp = term.line[i];
  1327. term.line[i] = term.line[i-n];
  1328. term.line[i-n] = temp;
  1329. }
  1330. selscroll(orig, n);
  1331. }
  1332. void
  1333. tscrollup(int orig, int n) {
  1334. int i;
  1335. Line temp;
  1336. LIMIT(n, 0, term.bot-orig+1);
  1337. tclearregion(0, orig, term.col-1, orig+n-1);
  1338. tsetdirt(orig+n, term.bot);
  1339. for(i = orig; i <= term.bot-n; i++) {
  1340. temp = term.line[i];
  1341. term.line[i] = term.line[i+n];
  1342. term.line[i+n] = temp;
  1343. }
  1344. selscroll(orig, -n);
  1345. }
  1346. void
  1347. selscroll(int orig, int n) {
  1348. if(sel.ob.x == -1)
  1349. return;
  1350. if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
  1351. if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
  1352. selclear(NULL);
  1353. return;
  1354. }
  1355. if(sel.type == SEL_RECTANGULAR) {
  1356. if(sel.ob.y < term.top)
  1357. sel.ob.y = term.top;
  1358. if(sel.oe.y > term.bot)
  1359. sel.oe.y = term.bot;
  1360. } else {
  1361. if(sel.ob.y < term.top) {
  1362. sel.ob.y = term.top;
  1363. sel.ob.x = 0;
  1364. }
  1365. if(sel.oe.y > term.bot) {
  1366. sel.oe.y = term.bot;
  1367. sel.oe.x = term.col;
  1368. }
  1369. }
  1370. selnormalize();
  1371. }
  1372. }
  1373. void
  1374. tnewline(int first_col) {
  1375. int y = term.c.y;
  1376. if(y == term.bot) {
  1377. tscrollup(term.top, 1);
  1378. } else {
  1379. y++;
  1380. }
  1381. tmoveto(first_col ? 0 : term.c.x, y);
  1382. }
  1383. void
  1384. csiparse(void) {
  1385. char *p = csiescseq.buf, *np;
  1386. long int v;
  1387. csiescseq.narg = 0;
  1388. if(*p == '?') {
  1389. csiescseq.priv = 1;
  1390. p++;
  1391. }
  1392. csiescseq.buf[csiescseq.len] = '\0';
  1393. while(p < csiescseq.buf+csiescseq.len) {
  1394. np = NULL;
  1395. v = strtol(p, &np, 10);
  1396. if(np == p)
  1397. v = 0;
  1398. if(v == LONG_MAX || v == LONG_MIN)
  1399. v = -1;
  1400. csiescseq.arg[csiescseq.narg++] = v;
  1401. p = np;
  1402. if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
  1403. break;
  1404. p++;
  1405. }
  1406. csiescseq.mode[0] = *p++;
  1407. csiescseq.mode[1] = (p < csiescseq.buf+csiescseq.len) ? *p : '\0';
  1408. }
  1409. /* for absolute user moves, when decom is set */
  1410. void
  1411. tmoveato(int x, int y) {
  1412. tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
  1413. }
  1414. void
  1415. tmoveto(int x, int y) {
  1416. int miny, maxy;
  1417. if(term.c.state & CURSOR_ORIGIN) {
  1418. miny = term.top;
  1419. maxy = term.bot;
  1420. } else {
  1421. miny = 0;
  1422. maxy = term.row - 1;
  1423. }
  1424. term.c.state &= ~CURSOR_WRAPNEXT;
  1425. term.c.x = LIMIT(x, 0, term.col-1);
  1426. term.c.y = LIMIT(y, miny, maxy);
  1427. }
  1428. void
  1429. tsetchar(Rune u, Glyph *attr, int x, int y) {
  1430. static char *vt100_0[62] = { /* 0x41 - 0x7e */
  1431. "", "", "", "", "", "", "", /* A - G */
  1432. 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
  1433. 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
  1434. 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
  1435. "", "", "", "", "", "", "°", "±", /* ` - g */
  1436. "", "", "", "", "", "", "", "", /* h - o */
  1437. "", "", "", "", "", "", "", "", /* p - w */
  1438. "", "", "", "π", "", "£", "·", /* x - ~ */
  1439. };
  1440. /*
  1441. * The table is proudly stolen from rxvt.
  1442. */
  1443. if(term.trantbl[term.charset] == CS_GRAPHIC0 &&
  1444. BETWEEN(u, 0x41, 0x7e) && vt100_0[u - 0x41])
  1445. utf8decode(vt100_0[u - 0x41], &u, UTF_SIZ);
  1446. if(term.line[y][x].mode & ATTR_WIDE) {
  1447. if(x+1 < term.col) {
  1448. term.line[y][x+1].u = ' ';
  1449. term.line[y][x+1].mode &= ~ATTR_WDUMMY;
  1450. }
  1451. } else if(term.line[y][x].mode & ATTR_WDUMMY) {
  1452. term.line[y][x-1].u = ' ';
  1453. term.line[y][x-1].mode &= ~ATTR_WIDE;
  1454. }
  1455. term.dirty[y] = 1;
  1456. term.line[y][x] = *attr;
  1457. term.line[y][x].u = u;
  1458. }
  1459. void
  1460. tclearregion(int x1, int y1, int x2, int y2) {
  1461. int x, y, temp;
  1462. Glyph *gp;
  1463. if(x1 > x2)
  1464. temp = x1, x1 = x2, x2 = temp;
  1465. if(y1 > y2)
  1466. temp = y1, y1 = y2, y2 = temp;
  1467. LIMIT(x1, 0, term.col-1);
  1468. LIMIT(x2, 0, term.col-1);
  1469. LIMIT(y1, 0, term.row-1);
  1470. LIMIT(y2, 0, term.row-1);
  1471. for(y = y1; y <= y2; y++) {
  1472. term.dirty[y] = 1;
  1473. for(x = x1; x <= x2; x++) {
  1474. gp = &term.line[y][x];
  1475. if(selected(x, y))
  1476. selclear(NULL);
  1477. gp->fg = term.c.attr.fg;
  1478. gp->bg = term.c.attr.bg;
  1479. gp->mode = 0;
  1480. gp->u = ' ';
  1481. }
  1482. }
  1483. }
  1484. void
  1485. tdeletechar(int n) {
  1486. int dst, src, size;
  1487. Glyph *line;
  1488. LIMIT(n, 0, term.col - term.c.x);
  1489. dst = term.c.x;
  1490. src = term.c.x + n;
  1491. size = term.col - src;
  1492. line = term.line[term.c.y];
  1493. memmove(&line[dst], &line[src], size * sizeof(Glyph));
  1494. tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
  1495. }
  1496. void
  1497. tinsertblank(int n) {
  1498. int dst, src, size;
  1499. Glyph *line;
  1500. LIMIT(n, 0, term.col - term.c.x);
  1501. dst = term.c.x + n;
  1502. src = term.c.x;
  1503. size = term.col - dst;
  1504. line = term.line[term.c.y];
  1505. memmove(&line[dst], &line[src], size * sizeof(Glyph));
  1506. tclearregion(src, term.c.y, dst - 1, term.c.y);
  1507. }
  1508. void
  1509. tinsertblankline(int n) {
  1510. if(BETWEEN(term.c.y, term.top, term.bot))
  1511. tscrolldown(term.c.y, n);
  1512. }
  1513. void
  1514. tdeleteline(int n) {
  1515. if(BETWEEN(term.c.y, term.top, term.bot))
  1516. tscrollup(term.c.y, n);
  1517. }
  1518. int32_t
  1519. tdefcolor(int *attr, int *npar, int l) {
  1520. int32_t idx = -1;
  1521. uint r, g, b;
  1522. switch (attr[*npar + 1]) {
  1523. case 2: /* direct color in RGB space */
  1524. if (*npar + 4 >= l) {
  1525. fprintf(stderr,
  1526. "erresc(38): Incorrect number of parameters (%d)\n",
  1527. *npar);
  1528. break;
  1529. }
  1530. r = attr[*npar + 2];
  1531. g = attr[*npar + 3];
  1532. b = attr[*npar + 4];
  1533. *npar += 4;
  1534. if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
  1535. fprintf(stderr, "erresc: bad rgb color (%u,%u,%u)\n",
  1536. r, g, b);
  1537. else
  1538. idx = TRUECOLOR(r, g, b);
  1539. break;
  1540. case 5: /* indexed color */
  1541. if (*npar + 2 >= l) {
  1542. fprintf(stderr,
  1543. "erresc(38): Incorrect number of parameters (%d)\n",
  1544. *npar);
  1545. break;
  1546. }
  1547. *npar += 2;
  1548. if(!BETWEEN(attr[*npar], 0, 255))
  1549. fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
  1550. else
  1551. idx = attr[*npar];
  1552. break;
  1553. case 0: /* implemented defined (only foreground) */
  1554. case 1: /* transparent */
  1555. case 3: /* direct color in CMY space */
  1556. case 4: /* direct color in CMYK space */
  1557. default:
  1558. fprintf(stderr,
  1559. "erresc(38): gfx attr %d unknown\n", attr[*npar]);
  1560. break;
  1561. }
  1562. return idx;
  1563. }
  1564. void
  1565. tsetattr(int *attr, int l) {
  1566. int i;
  1567. int32_t idx;
  1568. for(i = 0; i < l; i++) {
  1569. switch(attr[i]) {
  1570. case 0:
  1571. term.c.attr.mode &= ~(
  1572. ATTR_BOLD |
  1573. ATTR_FAINT |
  1574. ATTR_ITALIC |
  1575. ATTR_UNDERLINE |
  1576. ATTR_BLINK |
  1577. ATTR_REVERSE |
  1578. ATTR_INVISIBLE |
  1579. ATTR_STRUCK );
  1580. term.c.attr.fg = defaultfg;
  1581. term.c.attr.bg = defaultbg;
  1582. break;
  1583. case 1:
  1584. term.c.attr.mode |= ATTR_BOLD;
  1585. break;
  1586. case 2:
  1587. term.c.attr.mode |= ATTR_FAINT;
  1588. break;
  1589. case 3:
  1590. term.c.attr.mode |= ATTR_ITALIC;
  1591. break;
  1592. case 4:
  1593. term.c.attr.mode |= ATTR_UNDERLINE;
  1594. break;
  1595. case 5: /* slow blink */
  1596. /* FALLTHROUGH */
  1597. case 6: /* rapid blink */
  1598. term.c.attr.mode |= ATTR_BLINK;
  1599. break;
  1600. case 7:
  1601. term.c.attr.mode |= ATTR_REVERSE;
  1602. break;
  1603. case 8:
  1604. term.c.attr.mode |= ATTR_INVISIBLE;
  1605. break;
  1606. case 9:
  1607. term.c.attr.mode |= ATTR_STRUCK;
  1608. break;
  1609. case 22:
  1610. term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT);
  1611. break;
  1612. case 23:
  1613. term.c.attr.mode &= ~ATTR_ITALIC;
  1614. break;
  1615. case 24:
  1616. term.c.attr.mode &= ~ATTR_UNDERLINE;
  1617. break;
  1618. case 25:
  1619. term.c.attr.mode &= ~ATTR_BLINK;
  1620. break;
  1621. case 27:
  1622. term.c.attr.mode &= ~ATTR_REVERSE;
  1623. break;
  1624. case 28:
  1625. term.c.attr.mode &= ~ATTR_INVISIBLE;
  1626. break;
  1627. case 29:
  1628. term.c.attr.mode &= ~ATTR_STRUCK;
  1629. break;
  1630. case 38:
  1631. if ((idx = tdefcolor(attr, &i, l)) >= 0)
  1632. term.c.attr.fg = idx;
  1633. break;
  1634. case 39:
  1635. term.c.attr.fg = defaultfg;
  1636. break;
  1637. case 48:
  1638. if ((idx = tdefcolor(attr, &i, l)) >= 0)
  1639. term.c.attr.bg = idx;
  1640. break;
  1641. case 49:
  1642. term.c.attr.bg = defaultbg;
  1643. break;
  1644. default:
  1645. if(BETWEEN(attr[i], 30, 37)) {
  1646. term.c.attr.fg = attr[i] - 30;
  1647. } else if(BETWEEN(attr[i], 40, 47)) {
  1648. term.c.attr.bg = attr[i] - 40;
  1649. } else if(BETWEEN(attr[i], 90, 97)) {
  1650. term.c.attr.fg = attr[i] - 90 + 8;
  1651. } else if(BETWEEN(attr[i], 100, 107)) {
  1652. term.c.attr.bg = attr[i] - 100 + 8;
  1653. } else {
  1654. fprintf(stderr,
  1655. "erresc(default): gfx attr %d unknown\n",
  1656. attr[i]), csidump();
  1657. }
  1658. break;
  1659. }
  1660. }
  1661. }
  1662. void
  1663. tsetscroll(int t, int b) {
  1664. int temp;
  1665. LIMIT(t, 0, term.row-1);
  1666. LIMIT(b, 0, term.row-1);
  1667. if(t > b) {
  1668. temp = t;
  1669. t = b;
  1670. b = temp;
  1671. }
  1672. term.top = t;
  1673. term.bot = b;
  1674. }
  1675. void
  1676. tsetmode(bool priv, bool set, int *args, int narg) {
  1677. int *lim, mode;
  1678. bool alt;
  1679. for(lim = args + narg; args < lim; ++args) {
  1680. if(priv) {
  1681. switch(*args) {
  1682. case 1: /* DECCKM -- Cursor key */
  1683. MODBIT(term.mode, set, MODE_APPCURSOR);
  1684. break;
  1685. case 5: /* DECSCNM -- Reverse video */
  1686. mode = term.mode;
  1687. MODBIT(term.mode, set, MODE_REVERSE);
  1688. if(mode != term.mode)
  1689. redraw();
  1690. break;
  1691. case 6: /* DECOM -- Origin */
  1692. MODBIT(term.c.state, set, CURSOR_ORIGIN);
  1693. tmoveato(0, 0);
  1694. break;
  1695. case 7: /* DECAWM -- Auto wrap */
  1696. MODBIT(term.mode, set, MODE_WRAP);
  1697. break;
  1698. case 0: /* Error (IGNORED) */
  1699. case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
  1700. case 3: /* DECCOLM -- Column (IGNORED) */
  1701. case 4: /* DECSCLM -- Scroll (IGNORED) */
  1702. case 8: /* DECARM -- Auto repeat (IGNORED) */
  1703. case 18: /* DECPFF -- Printer feed (IGNORED) */
  1704. case 19: /* DECPEX -- Printer extent (IGNORED) */
  1705. case 42: /* DECNRCM -- National characters (IGNORED) */
  1706. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  1707. break;
  1708. case 25: /* DECTCEM -- Text Cursor Enable Mode */
  1709. MODBIT(term.mode, !set, MODE_HIDE);
  1710. break;
  1711. case 9: /* X10 mouse compatibility mode */
  1712. xsetpointermotion(0);
  1713. MODBIT(term.mode, 0, MODE_MOUSE);
  1714. MODBIT(term.mode, set, MODE_MOUSEX10);
  1715. break;
  1716. case 1000: /* 1000: report button press */
  1717. xsetpointermotion(0);
  1718. MODBIT(term.mode, 0, MODE_MOUSE);
  1719. MODBIT(term.mode, set, MODE_MOUSEBTN);
  1720. break;
  1721. case 1002: /* 1002: report motion on button press */
  1722. xsetpointermotion(0);
  1723. MODBIT(term.mode, 0, MODE_MOUSE);
  1724. MODBIT(term.mode, set, MODE_MOUSEMOTION);
  1725. break;
  1726. case 1003: /* 1003: enable all mouse motions */
  1727. xsetpointermotion(set);
  1728. MODBIT(term.mode, 0, MODE_MOUSE);
  1729. MODBIT(term.mode, set, MODE_MOUSEMANY);
  1730. break;
  1731. case 1004: /* 1004: send focus events to tty */
  1732. MODBIT(term.mode, set, MODE_FOCUS);
  1733. break;
  1734. case 1006: /* 1006: extended reporting mode */
  1735. MODBIT(term.mode, set, MODE_MOUSESGR);
  1736. break;
  1737. case 1034:
  1738. MODBIT(term.mode, set, MODE_8BIT);
  1739. break;
  1740. case 1049: /* swap screen & set/restore cursor as xterm */
  1741. if (!allowaltscreen)
  1742. break;
  1743. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1744. /* FALLTHROUGH */
  1745. case 47: /* swap screen */
  1746. case 1047:
  1747. if (!allowaltscreen)
  1748. break;
  1749. alt = IS_SET(MODE_ALTSCREEN);
  1750. if(alt) {
  1751. tclearregion(0, 0, term.col-1,
  1752. term.row-1);
  1753. }
  1754. if(set ^ alt) /* set is always 1 or 0 */
  1755. tswapscreen();
  1756. if(*args != 1049)
  1757. break;
  1758. /* FALLTHROUGH */
  1759. case 1048:
  1760. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1761. break;
  1762. case 2004: /* 2004: bracketed paste mode */
  1763. MODBIT(term.mode, set, MODE_BRCKTPASTE);
  1764. break;
  1765. /* Not implemented mouse modes. See comments there. */
  1766. case 1001: /* mouse highlight mode; can hang the
  1767. terminal by design when implemented. */
  1768. case 1005: /* UTF-8 mouse mode; will confuse
  1769. applications not supporting UTF-8
  1770. and luit. */
  1771. case 1015: /* urxvt mangled mouse mode; incompatible
  1772. and can be mistaken for other control
  1773. codes. */
  1774. default:
  1775. fprintf(stderr,
  1776. "erresc: unknown private set/reset mode %d\n",
  1777. *args);
  1778. break;
  1779. }
  1780. } else {
  1781. switch(*args) {
  1782. case 0: /* Error (IGNORED) */
  1783. break;
  1784. case 2: /* KAM -- keyboard action */
  1785. MODBIT(term.mode, set, MODE_KBDLOCK);
  1786. break;
  1787. case 4: /* IRM -- Insertion-replacement */
  1788. MODBIT(term.mode, set, MODE_INSERT);
  1789. break;
  1790. case 12: /* SRM -- Send/Receive */
  1791. MODBIT(term.mode, !set, MODE_ECHO);
  1792. break;
  1793. case 20: /* LNM -- Linefeed/new line */
  1794. MODBIT(term.mode, set, MODE_CRLF);
  1795. break;
  1796. default:
  1797. fprintf(stderr,
  1798. "erresc: unknown set/reset mode %d\n",
  1799. *args);
  1800. break;
  1801. }
  1802. }
  1803. }
  1804. }
  1805. void
  1806. csihandle(void) {
  1807. char buf[40];
  1808. int len;
  1809. switch(csiescseq.mode[0]) {
  1810. default:
  1811. unknown:
  1812. fprintf(stderr, "erresc: unknown csi ");
  1813. csidump();
  1814. /* die(""); */
  1815. break;
  1816. case '@': /* ICH -- Insert <n> blank char */
  1817. DEFAULT(csiescseq.arg[0], 1);
  1818. tinsertblank(csiescseq.arg[0]);
  1819. break;
  1820. case 'A': /* CUU -- Cursor <n> Up */
  1821. DEFAULT(csiescseq.arg[0], 1);
  1822. tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
  1823. break;
  1824. case 'B': /* CUD -- Cursor <n> Down */
  1825. case 'e': /* VPR --Cursor <n> Down */
  1826. DEFAULT(csiescseq.arg[0], 1);
  1827. tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
  1828. break;
  1829. case 'i': /* MC -- Media Copy */
  1830. switch(csiescseq.arg[0]) {
  1831. case 0:
  1832. tdump();
  1833. break;
  1834. case 1:
  1835. tdumpline(term.c.y);
  1836. break;
  1837. case 2:
  1838. tdumpsel();
  1839. break;
  1840. case 4:
  1841. term.mode &= ~MODE_PRINT;
  1842. break;
  1843. case 5:
  1844. term.mode |= MODE_PRINT;
  1845. break;
  1846. }
  1847. break;
  1848. case 'c': /* DA -- Device Attributes */
  1849. if(csiescseq.arg[0] == 0)
  1850. ttywrite(vtiden, sizeof(vtiden) - 1);
  1851. break;
  1852. case 'C': /* CUF -- Cursor <n> Forward */
  1853. case 'a': /* HPR -- Cursor <n> Forward */
  1854. DEFAULT(csiescseq.arg[0], 1);
  1855. tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
  1856. break;
  1857. case 'D': /* CUB -- Cursor <n> Backward */
  1858. DEFAULT(csiescseq.arg[0], 1);
  1859. tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
  1860. break;
  1861. case 'E': /* CNL -- Cursor <n> Down and first col */
  1862. DEFAULT(csiescseq.arg[0], 1);
  1863. tmoveto(0, term.c.y+csiescseq.arg[0]);
  1864. break;
  1865. case 'F': /* CPL -- Cursor <n> Up and first col */
  1866. DEFAULT(csiescseq.arg[0], 1);
  1867. tmoveto(0, term.c.y-csiescseq.arg[0]);
  1868. break;
  1869. case 'g': /* TBC -- Tabulation clear */
  1870. switch(csiescseq.arg[0]) {
  1871. case 0: /* clear current tab stop */
  1872. term.tabs[term.c.x] = 0;
  1873. break;
  1874. case 3: /* clear all the tabs */
  1875. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  1876. break;
  1877. default:
  1878. goto unknown;
  1879. }
  1880. break;
  1881. case 'G': /* CHA -- Move to <col> */
  1882. case '`': /* HPA */
  1883. DEFAULT(csiescseq.arg[0], 1);
  1884. tmoveto(csiescseq.arg[0]-1, term.c.y);
  1885. break;
  1886. case 'H': /* CUP -- Move to <row> <col> */
  1887. case 'f': /* HVP */
  1888. DEFAULT(csiescseq.arg[0], 1);
  1889. DEFAULT(csiescseq.arg[1], 1);
  1890. tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
  1891. break;
  1892. case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
  1893. DEFAULT(csiescseq.arg[0], 1);
  1894. tputtab(csiescseq.arg[0]);
  1895. break;
  1896. case 'J': /* ED -- Clear screen */
  1897. selclear(NULL);
  1898. switch(csiescseq.arg[0]) {
  1899. case 0: /* below */
  1900. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1901. if(term.c.y < term.row-1) {
  1902. tclearregion(0, term.c.y+1, term.col-1,
  1903. term.row-1);
  1904. }
  1905. break;
  1906. case 1: /* above */
  1907. if(term.c.y > 1)
  1908. tclearregion(0, 0, term.col-1, term.c.y-1);
  1909. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1910. break;
  1911. case 2: /* all */
  1912. tclearregion(0, 0, term.col-1, term.row-1);
  1913. break;
  1914. default:
  1915. goto unknown;
  1916. }
  1917. break;
  1918. case 'K': /* EL -- Clear line */
  1919. switch(csiescseq.arg[0]) {
  1920. case 0: /* right */
  1921. tclearregion(term.c.x, term.c.y, term.col-1,
  1922. term.c.y);
  1923. break;
  1924. case 1: /* left */
  1925. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1926. break;
  1927. case 2: /* all */
  1928. tclearregion(0, term.c.y, term.col-1, term.c.y);
  1929. break;
  1930. }
  1931. break;
  1932. case 'S': /* SU -- Scroll <n> line up */
  1933. DEFAULT(csiescseq.arg[0], 1);
  1934. tscrollup(term.top, csiescseq.arg[0]);
  1935. break;
  1936. case 'T': /* SD -- Scroll <n> line down */
  1937. DEFAULT(csiescseq.arg[0], 1);
  1938. tscrolldown(term.top, csiescseq.arg[0]);
  1939. break;
  1940. case 'L': /* IL -- Insert <n> blank lines */
  1941. DEFAULT(csiescseq.arg[0], 1);
  1942. tinsertblankline(csiescseq.arg[0]);
  1943. break;
  1944. case 'l': /* RM -- Reset Mode */
  1945. tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
  1946. break;
  1947. case 'M': /* DL -- Delete <n> lines */
  1948. DEFAULT(csiescseq.arg[0], 1);
  1949. tdeleteline(csiescseq.arg[0]);
  1950. break;
  1951. case 'X': /* ECH -- Erase <n> char */
  1952. DEFAULT(csiescseq.arg[0], 1);
  1953. tclearregion(term.c.x, term.c.y,
  1954. term.c.x + csiescseq.arg[0] - 1, term.c.y);
  1955. break;
  1956. case 'P': /* DCH -- Delete <n> char */
  1957. DEFAULT(csiescseq.arg[0], 1);
  1958. tdeletechar(csiescseq.arg[0]);
  1959. break;
  1960. case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
  1961. DEFAULT(csiescseq.arg[0], 1);
  1962. tputtab(-csiescseq.arg[0]);
  1963. break;
  1964. case 'd': /* VPA -- Move to <row> */
  1965. DEFAULT(csiescseq.arg[0], 1);
  1966. tmoveato(term.c.x, csiescseq.arg[0]-1);
  1967. break;
  1968. case 'h': /* SM -- Set terminal mode */
  1969. tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
  1970. break;
  1971. case 'm': /* SGR -- Terminal attribute (color) */
  1972. tsetattr(csiescseq.arg, csiescseq.narg);
  1973. break;
  1974. case 'n': /* DSR – Device Status Report (cursor position) */
  1975. if (csiescseq.arg[0] == 6) {
  1976. len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
  1977. term.c.y+1, term.c.x+1);
  1978. ttywrite(buf, len);
  1979. }
  1980. break;
  1981. case 'r': /* DECSTBM -- Set Scrolling Region */
  1982. if(csiescseq.priv) {
  1983. goto unknown;
  1984. } else {
  1985. DEFAULT(csiescseq.arg[0], 1);
  1986. DEFAULT(csiescseq.arg[1], term.row);
  1987. tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
  1988. tmoveato(0, 0);
  1989. }
  1990. break;
  1991. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  1992. tcursor(CURSOR_SAVE);
  1993. break;
  1994. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  1995. tcursor(CURSOR_LOAD);
  1996. break;
  1997. case ' ':
  1998. switch (csiescseq.mode[1]) {
  1999. case 'q': /* DECSCUSR -- Set Cursor Style */
  2000. DEFAULT(csiescseq.arg[0], 1);
  2001. if (!BETWEEN(csiescseq.arg[0], 0, 6)) {
  2002. goto unknown;
  2003. }
  2004. xw.cursor = csiescseq.arg[0];
  2005. break;
  2006. default:
  2007. goto unknown;
  2008. }
  2009. break;
  2010. }
  2011. }
  2012. void
  2013. csidump(void) {
  2014. int i;
  2015. uint c;
  2016. printf("ESC[");
  2017. for(i = 0; i < csiescseq.len; i++) {
  2018. c = csiescseq.buf[i] & 0xff;
  2019. if(isprint(c)) {
  2020. putchar(c);
  2021. } else if(c == '\n') {
  2022. printf("(\\n)");
  2023. } else if(c == '\r') {
  2024. printf("(\\r)");
  2025. } else if(c == 0x1b) {
  2026. printf("(\\e)");
  2027. } else {
  2028. printf("(%02x)", c);
  2029. }
  2030. }
  2031. putchar('\n');
  2032. }
  2033. void
  2034. csireset(void) {
  2035. memset(&csiescseq, 0, sizeof(csiescseq));
  2036. }
  2037. void
  2038. strhandle(void) {
  2039. char *p = NULL;
  2040. int j, narg, par;
  2041. term.esc &= ~(ESC_STR_END|ESC_STR);
  2042. strparse();
  2043. par = (narg = strescseq.narg) ? atoi(strescseq.args[0]) : 0;
  2044. switch(strescseq.type) {
  2045. case ']': /* OSC -- Operating System Command */
  2046. switch(par) {
  2047. case 0:
  2048. case 1:
  2049. case 2:
  2050. if(narg > 1)
  2051. xsettitle(strescseq.args[1]);
  2052. return;
  2053. case 4: /* color set */
  2054. if(narg < 3)
  2055. break;
  2056. p = strescseq.args[2];
  2057. /* FALLTHROUGH */
  2058. case 104: /* color reset, here p = NULL */
  2059. j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
  2060. if(xsetcolorname(j, p)) {
  2061. fprintf(stderr, "erresc: invalid color %s\n", p);
  2062. } else {
  2063. /*
  2064. * TODO if defaultbg color is changed, borders
  2065. * are dirty
  2066. */
  2067. redraw();
  2068. }
  2069. return;
  2070. }
  2071. break;
  2072. case 'k': /* old title set compatibility */
  2073. xsettitle(strescseq.args[0]);
  2074. return;
  2075. case 'P': /* DCS -- Device Control String */
  2076. case '_': /* APC -- Application Program Command */
  2077. case '^': /* PM -- Privacy Message */
  2078. return;
  2079. }
  2080. fprintf(stderr, "erresc: unknown str ");
  2081. strdump();
  2082. }
  2083. void
  2084. strparse(void) {
  2085. int c;
  2086. char *p = strescseq.buf;
  2087. strescseq.narg = 0;
  2088. strescseq.buf[strescseq.len] = '\0';
  2089. if(*p == '\0')
  2090. return;
  2091. while(strescseq.narg < STR_ARG_SIZ) {
  2092. strescseq.args[strescseq.narg++] = p;
  2093. while((c = *p) != ';' && c != '\0')
  2094. ++p;
  2095. if(c == '\0')
  2096. return;
  2097. *p++ = '\0';
  2098. }
  2099. }
  2100. void
  2101. strdump(void) {
  2102. int i;
  2103. uint c;
  2104. printf("ESC%c", strescseq.type);
  2105. for(i = 0; i < strescseq.len; i++) {
  2106. c = strescseq.buf[i] & 0xff;
  2107. if(c == '\0') {
  2108. return;
  2109. } else if(isprint(c)) {
  2110. putchar(c);
  2111. } else if(c == '\n') {
  2112. printf("(\\n)");
  2113. } else if(c == '\r') {
  2114. printf("(\\r)");
  2115. } else if(c == 0x1b) {
  2116. printf("(\\e)");
  2117. } else {
  2118. printf("(%02x)", c);
  2119. }
  2120. }
  2121. printf("ESC\\\n");
  2122. }
  2123. void
  2124. strreset(void) {
  2125. memset(&strescseq, 0, sizeof(strescseq));
  2126. }
  2127. void
  2128. tprinter(char *s, size_t len) {
  2129. if(iofd != -1 && xwrite(iofd, s, len) < 0) {
  2130. fprintf(stderr, "Error writing in %s:%s\n",
  2131. opt_io, strerror(errno));
  2132. close(iofd);
  2133. iofd = -1;
  2134. }
  2135. }
  2136. void
  2137. toggleprinter(const Arg *arg) {
  2138. term.mode ^= MODE_PRINT;
  2139. }
  2140. void
  2141. printscreen(const Arg *arg) {
  2142. tdump();
  2143. }
  2144. void
  2145. printsel(const Arg *arg) {
  2146. tdumpsel();
  2147. }
  2148. void
  2149. tdumpsel(void) {
  2150. char *ptr;
  2151. if((ptr = getsel())) {
  2152. tprinter(ptr, strlen(ptr));
  2153. free(ptr);
  2154. }
  2155. }
  2156. void
  2157. tdumpline(int n) {
  2158. char buf[UTF_SIZ];
  2159. Glyph *bp, *end;
  2160. bp = &term.line[n][0];
  2161. end = &bp[MIN(tlinelen(n), term.col) - 1];
  2162. if(bp != end || bp->u != ' ') {
  2163. for( ;bp <= end; ++bp)
  2164. tprinter(buf, utf8encode(bp->u, buf));
  2165. }
  2166. tprinter("\n", 1);
  2167. }
  2168. void
  2169. tdump(void) {
  2170. int i;
  2171. for(i = 0; i < term.row; ++i)
  2172. tdumpline(i);
  2173. }
  2174. void
  2175. tputtab(int n) {
  2176. uint x = term.c.x;
  2177. if(n > 0) {
  2178. while(x < term.col && n--)
  2179. for(++x; x < term.col && !term.tabs[x]; ++x)
  2180. /* nothing */ ;
  2181. } else if(n < 0) {
  2182. while(x > 0 && n++)
  2183. for(--x; x > 0 && !term.tabs[x]; --x)
  2184. /* nothing */ ;
  2185. }
  2186. term.c.x = LIMIT(x, 0, term.col-1);
  2187. }
  2188. void
  2189. techo(Rune u) {
  2190. if(ISCONTROL(u)) { /* control code */
  2191. if(u & 0x80) {
  2192. u &= 0x7f;
  2193. tputc('^');
  2194. tputc('[');
  2195. } else if(u != '\n' && u != '\r' && u != '\t') {
  2196. u ^= 0x40;
  2197. tputc('^');
  2198. }
  2199. }
  2200. tputc(u);
  2201. }
  2202. void
  2203. tdeftran(char ascii) {
  2204. static char cs[] = "0B";
  2205. static int vcs[] = {CS_GRAPHIC0, CS_USA};
  2206. char *p;
  2207. if((p = strchr(cs, ascii)) == NULL) {
  2208. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  2209. } else {
  2210. term.trantbl[term.icharset] = vcs[p - cs];
  2211. }
  2212. }
  2213. void
  2214. tdectest(char c) {
  2215. int x, y;
  2216. if(c == '8') { /* DEC screen alignment test. */
  2217. for(x = 0; x < term.col; ++x) {
  2218. for(y = 0; y < term.row; ++y)
  2219. tsetchar('E', &term.c.attr, x, y);
  2220. }
  2221. }
  2222. }
  2223. void
  2224. tstrsequence(uchar c) {
  2225. switch (c) {
  2226. case 0x90: /* DCS -- Device Control String */
  2227. c = 'P';
  2228. break;
  2229. case 0x9f: /* APC -- Application Program Command */
  2230. c = '_';
  2231. break;
  2232. case 0x9e: /* PM -- Privacy Message */
  2233. c = '^';
  2234. break;
  2235. case 0x9d: /* OSC -- Operating System Command */
  2236. c = ']';
  2237. break;
  2238. }
  2239. strreset();
  2240. strescseq.type = c;
  2241. term.esc |= ESC_STR;
  2242. }
  2243. void
  2244. tcontrolcode(uchar ascii) {
  2245. switch(ascii) {
  2246. case '\t': /* HT */
  2247. tputtab(1);
  2248. return;
  2249. case '\b': /* BS */
  2250. tmoveto(term.c.x-1, term.c.y);
  2251. return;
  2252. case '\r': /* CR */
  2253. tmoveto(0, term.c.y);
  2254. return;
  2255. case '\f': /* LF */
  2256. case '\v': /* VT */
  2257. case '\n': /* LF */
  2258. /* go to first col if the mode is set */
  2259. tnewline(IS_SET(MODE_CRLF));
  2260. return;
  2261. case '\a': /* BEL */
  2262. if(term.esc & ESC_STR_END) {
  2263. /* backwards compatibility to xterm */
  2264. strhandle();
  2265. } else {
  2266. if(!(xw.state & WIN_FOCUSED))
  2267. xseturgency(1);
  2268. if (bellvolume)
  2269. XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
  2270. }
  2271. break;
  2272. case '\033': /* ESC */
  2273. csireset();
  2274. term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
  2275. term.esc |= ESC_START;
  2276. return;
  2277. case '\016': /* SO (LS1 -- Locking shift 1) */
  2278. case '\017': /* SI (LS0 -- Locking shift 0) */
  2279. term.charset = 1 - (ascii - '\016');
  2280. return;
  2281. case '\032': /* SUB */
  2282. tsetchar('?', &term.c.attr, term.c.x, term.c.y);
  2283. case '\030': /* CAN */
  2284. csireset();
  2285. break;
  2286. case '\005': /* ENQ (IGNORED) */
  2287. case '\000': /* NUL (IGNORED) */
  2288. case '\021': /* XON (IGNORED) */
  2289. case '\023': /* XOFF (IGNORED) */
  2290. case 0177: /* DEL (IGNORED) */
  2291. return;
  2292. case 0x84: /* TODO: IND */
  2293. break;
  2294. case 0x85: /* NEL -- Next line */
  2295. tnewline(1); /* always go to first col */
  2296. break;
  2297. case 0x88: /* HTS -- Horizontal tab stop */
  2298. term.tabs[term.c.x] = 1;
  2299. break;
  2300. case 0x8d: /* TODO: RI */
  2301. case 0x8e: /* TODO: SS2 */
  2302. case 0x8f: /* TODO: SS3 */
  2303. case 0x98: /* TODO: SOS */
  2304. break;
  2305. case 0x9a: /* DECID -- Identify Terminal */
  2306. ttywrite(vtiden, sizeof(vtiden) - 1);
  2307. break;
  2308. case 0x9b: /* TODO: CSI */
  2309. case 0x9c: /* TODO: ST */
  2310. break;
  2311. case 0x90: /* DCS -- Device Control String */
  2312. case 0x9f: /* APC -- Application Program Command */
  2313. case 0x9e: /* PM -- Privacy Message */
  2314. case 0x9d: /* OSC -- Operating System Command */
  2315. tstrsequence(ascii);
  2316. return;
  2317. }
  2318. /* only CAN, SUB, \a and C1 chars interrupt a sequence */
  2319. term.esc &= ~(ESC_STR_END|ESC_STR);
  2320. }
  2321. /*
  2322. * returns 1 when the sequence is finished and it hasn't to read
  2323. * more characters for this sequence, otherwise 0
  2324. */
  2325. int
  2326. eschandle(uchar ascii) {
  2327. switch(ascii) {
  2328. case '[':
  2329. term.esc |= ESC_CSI;
  2330. return 0;
  2331. case '#':
  2332. term.esc |= ESC_TEST;
  2333. return 0;
  2334. case 'P': /* DCS -- Device Control String */
  2335. case '_': /* APC -- Application Program Command */
  2336. case '^': /* PM -- Privacy Message */
  2337. case ']': /* OSC -- Operating System Command */
  2338. case 'k': /* old title set compatibility */
  2339. tstrsequence(ascii);
  2340. return 0;
  2341. case 'n': /* LS2 -- Locking shift 2 */
  2342. case 'o': /* LS3 -- Locking shift 3 */
  2343. term.charset = 2 + (ascii - 'n');
  2344. break;
  2345. case '(': /* GZD4 -- set primary charset G0 */
  2346. case ')': /* G1D4 -- set secondary charset G1 */
  2347. case '*': /* G2D4 -- set tertiary charset G2 */
  2348. case '+': /* G3D4 -- set quaternary charset G3 */
  2349. term.icharset = ascii - '(';
  2350. term.esc |= ESC_ALTCHARSET;
  2351. return 0;
  2352. case 'D': /* IND -- Linefeed */
  2353. if(term.c.y == term.bot) {
  2354. tscrollup(term.top, 1);
  2355. } else {
  2356. tmoveto(term.c.x, term.c.y+1);
  2357. }
  2358. break;
  2359. case 'E': /* NEL -- Next line */
  2360. tnewline(1); /* always go to first col */
  2361. break;
  2362. case 'H': /* HTS -- Horizontal tab stop */
  2363. term.tabs[term.c.x] = 1;
  2364. break;
  2365. case 'M': /* RI -- Reverse index */
  2366. if(term.c.y == term.top) {
  2367. tscrolldown(term.top, 1);
  2368. } else {
  2369. tmoveto(term.c.x, term.c.y-1);
  2370. }
  2371. break;
  2372. case 'Z': /* DECID -- Identify Terminal */
  2373. ttywrite(vtiden, sizeof(vtiden) - 1);
  2374. break;
  2375. case 'c': /* RIS -- Reset to inital state */
  2376. treset();
  2377. xresettitle();
  2378. xloadcols();
  2379. break;
  2380. case '=': /* DECPAM -- Application keypad */
  2381. term.mode |= MODE_APPKEYPAD;
  2382. break;
  2383. case '>': /* DECPNM -- Normal keypad */
  2384. term.mode &= ~MODE_APPKEYPAD;
  2385. break;
  2386. case '7': /* DECSC -- Save Cursor */
  2387. tcursor(CURSOR_SAVE);
  2388. break;
  2389. case '8': /* DECRC -- Restore Cursor */
  2390. tcursor(CURSOR_LOAD);
  2391. break;
  2392. case '\\': /* ST -- String Terminator */
  2393. if(term.esc & ESC_STR_END)
  2394. strhandle();
  2395. break;
  2396. default:
  2397. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  2398. (uchar) ascii, isprint(ascii)? ascii:'.');
  2399. break;
  2400. }
  2401. return 1;
  2402. }
  2403. void
  2404. tputc(Rune u) {
  2405. char c[UTF_SIZ];
  2406. bool control;
  2407. int width, len;
  2408. Glyph *gp;
  2409. len = utf8encode(u, c);
  2410. if((width = wcwidth(u)) == -1) {
  2411. memcpy(c, "\357\277\275", 4); /* UTF_INVALID */
  2412. width = 1;
  2413. }
  2414. if(IS_SET(MODE_PRINT))
  2415. tprinter(c, len);
  2416. control = ISCONTROL(u);
  2417. /*
  2418. * STR sequence must be checked before anything else
  2419. * because it uses all following characters until it
  2420. * receives a ESC, a SUB, a ST or any other C1 control
  2421. * character.
  2422. */
  2423. if(term.esc & ESC_STR) {
  2424. if(u == '\a' || u == 030 || u == 032 || u == 033 ||
  2425. ISCONTROLC1(u)) {
  2426. term.esc &= ~(ESC_START|ESC_STR);
  2427. term.esc |= ESC_STR_END;
  2428. } else if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
  2429. memmove(&strescseq.buf[strescseq.len], c, len);
  2430. strescseq.len += len;
  2431. return;
  2432. } else {
  2433. /*
  2434. * Here is a bug in terminals. If the user never sends
  2435. * some code to stop the str or esc command, then st
  2436. * will stop responding. But this is better than
  2437. * silently failing with unknown characters. At least
  2438. * then users will report back.
  2439. *
  2440. * In the case users ever get fixed, here is the code:
  2441. */
  2442. /*
  2443. * term.esc = 0;
  2444. * strhandle();
  2445. */
  2446. return;
  2447. }
  2448. }
  2449. /*
  2450. * Actions of control codes must be performed as soon they arrive
  2451. * because they can be embedded inside a control sequence, and
  2452. * they must not cause conflicts with sequences.
  2453. */
  2454. if(control) {
  2455. tcontrolcode(u);
  2456. /*
  2457. * control codes are not shown ever
  2458. */
  2459. return;
  2460. } else if(term.esc & ESC_START) {
  2461. if(term.esc & ESC_CSI) {
  2462. csiescseq.buf[csiescseq.len++] = u;
  2463. if(BETWEEN(u, 0x40, 0x7E)
  2464. || csiescseq.len >= \
  2465. sizeof(csiescseq.buf)-1) {
  2466. term.esc = 0;
  2467. csiparse();
  2468. csihandle();
  2469. }
  2470. return;
  2471. } else if(term.esc & ESC_ALTCHARSET) {
  2472. tdeftran(u);
  2473. } else if(term.esc & ESC_TEST) {
  2474. tdectest(u);
  2475. } else {
  2476. if (!eschandle(u))
  2477. return;
  2478. /* sequence already finished */
  2479. }
  2480. term.esc = 0;
  2481. /*
  2482. * All characters which form part of a sequence are not
  2483. * printed
  2484. */
  2485. return;
  2486. }
  2487. if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
  2488. selclear(NULL);
  2489. gp = &term.line[term.c.y][term.c.x];
  2490. if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
  2491. gp->mode |= ATTR_WRAP;
  2492. tnewline(1);
  2493. gp = &term.line[term.c.y][term.c.x];
  2494. }
  2495. if(IS_SET(MODE_INSERT) && term.c.x+width < term.col)
  2496. memmove(gp+width, gp, (term.col - term.c.x - width) * sizeof(Glyph));
  2497. if(term.c.x+width > term.col) {
  2498. tnewline(1);
  2499. gp = &term.line[term.c.y][term.c.x];
  2500. }
  2501. tsetchar(u, &term.c.attr, term.c.x, term.c.y);
  2502. if(width == 2) {
  2503. gp->mode |= ATTR_WIDE;
  2504. if(term.c.x+1 < term.col) {
  2505. gp[1].u = '\0';
  2506. gp[1].mode = ATTR_WDUMMY;
  2507. }
  2508. }
  2509. if(term.c.x+width < term.col) {
  2510. tmoveto(term.c.x+width, term.c.y);
  2511. } else {
  2512. term.c.state |= CURSOR_WRAPNEXT;
  2513. }
  2514. }
  2515. void
  2516. tresize(int col, int row) {
  2517. int i;
  2518. int minrow = MIN(row, term.row);
  2519. int mincol = MIN(col, term.col);
  2520. bool *bp;
  2521. TCursor c;
  2522. if(col < 1 || row < 1) {
  2523. fprintf(stderr,
  2524. "tresize: error resizing to %dx%d\n", col, row);
  2525. return;
  2526. }
  2527. /*
  2528. * slide screen to keep cursor where we expect it -
  2529. * tscrollup would work here, but we can optimize to
  2530. * memmove because we're freeing the earlier lines
  2531. */
  2532. for(i = 0; i <= term.c.y - row; i++) {
  2533. free(term.line[i]);
  2534. free(term.alt[i]);
  2535. }
  2536. /* ensure that both src and dst are not NULL */
  2537. if (i > 0) {
  2538. memmove(term.line, term.line + i, row * sizeof(Line));
  2539. memmove(term.alt, term.alt + i, row * sizeof(Line));
  2540. }
  2541. for(i += row; i < term.row; i++) {
  2542. free(term.line[i]);
  2543. free(term.alt[i]);
  2544. }
  2545. /* resize to new width */
  2546. term.specbuf = xrealloc(term.specbuf, col * sizeof(XftGlyphFontSpec));
  2547. /* resize to new height */
  2548. term.line = xrealloc(term.line, row * sizeof(Line));
  2549. term.alt = xrealloc(term.alt, row * sizeof(Line));
  2550. term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
  2551. term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
  2552. /* resize each row to new width, zero-pad if needed */
  2553. for(i = 0; i < minrow; i++) {
  2554. term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
  2555. term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
  2556. }
  2557. /* allocate any new rows */
  2558. for(/* i == minrow */; i < row; i++) {
  2559. term.line[i] = xmalloc(col * sizeof(Glyph));
  2560. term.alt[i] = xmalloc(col * sizeof(Glyph));
  2561. }
  2562. if(col > term.col) {
  2563. bp = term.tabs + term.col;
  2564. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  2565. while(--bp > term.tabs && !*bp)
  2566. /* nothing */ ;
  2567. for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
  2568. *bp = 1;
  2569. }
  2570. /* update terminal size */
  2571. term.col = col;
  2572. term.row = row;
  2573. /* reset scrolling region */
  2574. tsetscroll(0, row-1);
  2575. /* make use of the LIMIT in tmoveto */
  2576. tmoveto(term.c.x, term.c.y);
  2577. /* Clearing both screens (it makes dirty all lines) */
  2578. c = term.c;
  2579. for(i = 0; i < 2; i++) {
  2580. if(mincol < col && 0 < minrow) {
  2581. tclearregion(mincol, 0, col - 1, minrow - 1);
  2582. }
  2583. if(0 < col && minrow < row) {
  2584. tclearregion(0, minrow, col - 1, row - 1);
  2585. }
  2586. tswapscreen();
  2587. tcursor(CURSOR_LOAD);
  2588. }
  2589. term.c = c;
  2590. }
  2591. void
  2592. xresize(int col, int row) {
  2593. xw.tw = MAX(1, col * xw.cw);
  2594. xw.th = MAX(1, row * xw.ch);
  2595. XFreePixmap(xw.dpy, xw.buf);
  2596. xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
  2597. DefaultDepth(xw.dpy, xw.scr));
  2598. XftDrawChange(xw.draw, xw.buf);
  2599. xclear(0, 0, xw.w, xw.h);
  2600. }
  2601. ushort
  2602. sixd_to_16bit(int x) {
  2603. return x == 0 ? 0 : 0x3737 + 0x2828 * x;
  2604. }
  2605. bool
  2606. xloadcolor(int i, const char *name, Color *ncolor) {
  2607. XRenderColor color = { .alpha = 0xffff };
  2608. if(!name) {
  2609. if(BETWEEN(i, 16, 255)) { /* 256 color */
  2610. if(i < 6*6*6+16) { /* same colors as xterm */
  2611. color.red = sixd_to_16bit( ((i-16)/36)%6 );
  2612. color.green = sixd_to_16bit( ((i-16)/6) %6 );
  2613. color.blue = sixd_to_16bit( ((i-16)/1) %6 );
  2614. } else { /* greyscale */
  2615. color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
  2616. color.green = color.blue = color.red;
  2617. }
  2618. return XftColorAllocValue(xw.dpy, xw.vis,
  2619. xw.cmap, &color, ncolor);
  2620. } else
  2621. name = colorname[i];
  2622. }
  2623. return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
  2624. }
  2625. void
  2626. xloadcols(void) {
  2627. int i;
  2628. static bool loaded;
  2629. Color *cp;
  2630. if(loaded) {
  2631. for (cp = dc.col; cp < &dc.col[LEN(dc.col)]; ++cp)
  2632. XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
  2633. }
  2634. for(i = 0; i < LEN(dc.col); i++)
  2635. if(!xloadcolor(i, NULL, &dc.col[i])) {
  2636. if(colorname[i])
  2637. die("Could not allocate color '%s'\n", colorname[i]);
  2638. else
  2639. die("Could not allocate color %d\n", i);
  2640. }
  2641. loaded = true;
  2642. }
  2643. int
  2644. xsetcolorname(int x, const char *name) {
  2645. Color ncolor;
  2646. if(!BETWEEN(x, 0, LEN(dc.col)))
  2647. return 1;
  2648. if(!xloadcolor(x, name, &ncolor))
  2649. return 1;
  2650. XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
  2651. dc.col[x] = ncolor;
  2652. return 0;
  2653. }
  2654. void
  2655. xtermclear(int col1, int row1, int col2, int row2) {
  2656. XftDrawRect(xw.draw,
  2657. &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
  2658. borderpx + col1 * xw.cw,
  2659. borderpx + row1 * xw.ch,
  2660. (col2-col1+1) * xw.cw,
  2661. (row2-row1+1) * xw.ch);
  2662. }
  2663. /*
  2664. * Absolute coordinates.
  2665. */
  2666. void
  2667. xclear(int x1, int y1, int x2, int y2) {
  2668. XftDrawRect(xw.draw,
  2669. &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
  2670. x1, y1, x2-x1, y2-y1);
  2671. }
  2672. void
  2673. xhints(void) {
  2674. XClassHint class = {opt_class ? opt_class : termname, termname};
  2675. XWMHints wm = {.flags = InputHint, .input = 1};
  2676. XSizeHints *sizeh = NULL;
  2677. sizeh = XAllocSizeHints();
  2678. sizeh->flags = PSize | PResizeInc | PBaseSize;
  2679. sizeh->height = xw.h;
  2680. sizeh->width = xw.w;
  2681. sizeh->height_inc = xw.ch;
  2682. sizeh->width_inc = xw.cw;
  2683. sizeh->base_height = 2 * borderpx;
  2684. sizeh->base_width = 2 * borderpx;
  2685. if(xw.isfixed == True) {
  2686. sizeh->flags |= PMaxSize | PMinSize;
  2687. sizeh->min_width = sizeh->max_width = xw.w;
  2688. sizeh->min_height = sizeh->max_height = xw.h;
  2689. }
  2690. if(xw.gm & (XValue|YValue)) {
  2691. sizeh->flags |= USPosition | PWinGravity;
  2692. sizeh->x = xw.l;
  2693. sizeh->y = xw.t;
  2694. sizeh->win_gravity = xgeommasktogravity(xw.gm);
  2695. }
  2696. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
  2697. &class);
  2698. XFree(sizeh);
  2699. }
  2700. int
  2701. xgeommasktogravity(int mask) {
  2702. switch(mask & (XNegative|YNegative)) {
  2703. case 0:
  2704. return NorthWestGravity;
  2705. case XNegative:
  2706. return NorthEastGravity;
  2707. case YNegative:
  2708. return SouthWestGravity;
  2709. }
  2710. return SouthEastGravity;
  2711. }
  2712. int
  2713. xloadfont(Font *f, FcPattern *pattern) {
  2714. FcPattern *match;
  2715. FcResult result;
  2716. match = FcFontMatch(NULL, pattern, &result);
  2717. if(!match)
  2718. return 1;
  2719. if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
  2720. FcPatternDestroy(match);
  2721. return 1;
  2722. }
  2723. f->set = NULL;
  2724. f->pattern = FcPatternDuplicate(pattern);
  2725. f->ascent = f->match->ascent;
  2726. f->descent = f->match->descent;
  2727. f->lbearing = 0;
  2728. f->rbearing = f->match->max_advance_width;
  2729. f->height = f->ascent + f->descent;
  2730. f->width = f->lbearing + f->rbearing;
  2731. return 0;
  2732. }
  2733. void
  2734. xloadfonts(char *fontstr, double fontsize) {
  2735. FcPattern *pattern;
  2736. double fontval;
  2737. float ceilf(float);
  2738. if(fontstr[0] == '-') {
  2739. pattern = XftXlfdParse(fontstr, False, False);
  2740. } else {
  2741. pattern = FcNameParse((FcChar8 *)fontstr);
  2742. }
  2743. if(!pattern)
  2744. die("st: can't open font %s\n", fontstr);
  2745. if(fontsize > 1) {
  2746. FcPatternDel(pattern, FC_PIXEL_SIZE);
  2747. FcPatternDel(pattern, FC_SIZE);
  2748. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
  2749. usedfontsize = fontsize;
  2750. } else {
  2751. if(FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
  2752. FcResultMatch) {
  2753. usedfontsize = fontval;
  2754. } else if(FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
  2755. FcResultMatch) {
  2756. usedfontsize = -1;
  2757. } else {
  2758. /*
  2759. * Default font size is 12, if none given. This is to
  2760. * have a known usedfontsize value.
  2761. */
  2762. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
  2763. usedfontsize = 12;
  2764. }
  2765. defaultfontsize = usedfontsize;
  2766. }
  2767. FcConfigSubstitute(0, pattern, FcMatchPattern);
  2768. FcDefaultSubstitute(pattern);
  2769. if(xloadfont(&dc.font, pattern))
  2770. die("st: can't open font %s\n", fontstr);
  2771. if(usedfontsize < 0) {
  2772. FcPatternGetDouble(dc.font.match->pattern,
  2773. FC_PIXEL_SIZE, 0, &fontval);
  2774. usedfontsize = fontval;
  2775. if(fontsize == 0)
  2776. defaultfontsize = fontval;
  2777. }
  2778. /* Setting character width and height. */
  2779. xw.cw = ceilf(dc.font.width * cwscale);
  2780. xw.ch = ceilf(dc.font.height * chscale);
  2781. FcPatternDel(pattern, FC_SLANT);
  2782. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
  2783. if(xloadfont(&dc.ifont, pattern))
  2784. die("st: can't open font %s\n", fontstr);
  2785. FcPatternDel(pattern, FC_WEIGHT);
  2786. FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
  2787. if(xloadfont(&dc.ibfont, pattern))
  2788. die("st: can't open font %s\n", fontstr);
  2789. FcPatternDel(pattern, FC_SLANT);
  2790. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
  2791. if(xloadfont(&dc.bfont, pattern))
  2792. die("st: can't open font %s\n", fontstr);
  2793. FcPatternDestroy(pattern);
  2794. }
  2795. void
  2796. xunloadfont(Font *f) {
  2797. XftFontClose(xw.dpy, f->match);
  2798. FcPatternDestroy(f->pattern);
  2799. if(f->set)
  2800. FcFontSetDestroy(f->set);
  2801. }
  2802. void
  2803. xunloadfonts(void) {
  2804. /* Free the loaded fonts in the font cache. */
  2805. while(frclen > 0)
  2806. XftFontClose(xw.dpy, frc[--frclen].font);
  2807. xunloadfont(&dc.font);
  2808. xunloadfont(&dc.bfont);
  2809. xunloadfont(&dc.ifont);
  2810. xunloadfont(&dc.ibfont);
  2811. }
  2812. void
  2813. xzoom(const Arg *arg) {
  2814. Arg larg;
  2815. larg.f = usedfontsize + arg->f;
  2816. xzoomabs(&larg);
  2817. }
  2818. void
  2819. xzoomabs(const Arg *arg) {
  2820. xunloadfonts();
  2821. xloadfonts(usedfont, arg->f);
  2822. cresize(0, 0);
  2823. redraw();
  2824. xhints();
  2825. }
  2826. void
  2827. xzoomreset(const Arg *arg) {
  2828. Arg larg;
  2829. if(defaultfontsize > 0) {
  2830. larg.f = defaultfontsize;
  2831. xzoomabs(&larg);
  2832. }
  2833. }
  2834. void
  2835. xinit(void) {
  2836. XGCValues gcvalues;
  2837. Cursor cursor;
  2838. Window parent;
  2839. pid_t thispid = getpid();
  2840. if(!(xw.dpy = XOpenDisplay(NULL)))
  2841. die("Can't open display\n");
  2842. xw.scr = XDefaultScreen(xw.dpy);
  2843. xw.vis = XDefaultVisual(xw.dpy, xw.scr);
  2844. /* font */
  2845. if(!FcInit())
  2846. die("Could not init fontconfig.\n");
  2847. usedfont = (opt_font == NULL)? font : opt_font;
  2848. xloadfonts(usedfont, 0);
  2849. /* colors */
  2850. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  2851. xloadcols();
  2852. /* adjust fixed window geometry */
  2853. xw.w = 2 * borderpx + term.col * xw.cw;
  2854. xw.h = 2 * borderpx + term.row * xw.ch;
  2855. if(xw.gm & XNegative)
  2856. xw.l += DisplayWidth(xw.dpy, xw.scr) - xw.w - 2;
  2857. if(xw.gm & YNegative)
  2858. xw.t += DisplayWidth(xw.dpy, xw.scr) - xw.h - 2;
  2859. /* Events */
  2860. xw.attrs.background_pixel = dc.col[defaultbg].pixel;
  2861. xw.attrs.border_pixel = dc.col[defaultbg].pixel;
  2862. xw.attrs.bit_gravity = NorthWestGravity;
  2863. xw.attrs.event_mask = FocusChangeMask | KeyPressMask
  2864. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  2865. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  2866. xw.attrs.colormap = xw.cmap;
  2867. if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
  2868. parent = XRootWindow(xw.dpy, xw.scr);
  2869. xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
  2870. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  2871. xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
  2872. | CWEventMask | CWColormap, &xw.attrs);
  2873. memset(&gcvalues, 0, sizeof(gcvalues));
  2874. gcvalues.graphics_exposures = False;
  2875. dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
  2876. &gcvalues);
  2877. xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
  2878. DefaultDepth(xw.dpy, xw.scr));
  2879. XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
  2880. XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
  2881. /* Xft rendering context */
  2882. xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
  2883. /* input methods */
  2884. if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  2885. XSetLocaleModifiers("@im=local");
  2886. if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  2887. XSetLocaleModifiers("@im=");
  2888. if((xw.xim = XOpenIM(xw.dpy,
  2889. NULL, NULL, NULL)) == NULL) {
  2890. die("XOpenIM failed. Could not open input"
  2891. " device.\n");
  2892. }
  2893. }
  2894. }
  2895. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  2896. | XIMStatusNothing, XNClientWindow, xw.win,
  2897. XNFocusWindow, xw.win, NULL);
  2898. if(xw.xic == NULL)
  2899. die("XCreateIC failed. Could not obtain input method.\n");
  2900. /* white cursor, black outline */
  2901. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  2902. XDefineCursor(xw.dpy, xw.win, cursor);
  2903. XRecolorCursor(xw.dpy, cursor,
  2904. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  2905. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  2906. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  2907. xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
  2908. xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
  2909. XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
  2910. xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
  2911. XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
  2912. PropModeReplace, (uchar *)&thispid, 1);
  2913. xresettitle();
  2914. XMapWindow(xw.dpy, xw.win);
  2915. xhints();
  2916. XSync(xw.dpy, False);
  2917. }
  2918. int
  2919. xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
  2920. {
  2921. float winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch, xp, yp;
  2922. ushort mode, prevmode = USHRT_MAX;
  2923. Font *font = &dc.font;
  2924. int frcflags = FRC_NORMAL;
  2925. float runewidth = xw.cw;
  2926. Rune rune;
  2927. FT_UInt glyphidx;
  2928. FcResult fcres;
  2929. FcPattern *fcpattern, *fontpattern;
  2930. FcFontSet *fcsets[] = { NULL };
  2931. FcCharSet *fccharset;
  2932. int i, f, numspecs = 0;
  2933. for(i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
  2934. /* Fetch rune and mode for current glyph. */
  2935. rune = glyphs[i].u;
  2936. mode = glyphs[i].mode;
  2937. /* Skip dummy wide-character spacing. */
  2938. if(mode == ATTR_WDUMMY)
  2939. continue;
  2940. /* Determine font for glyph if different from previous glyph. */
  2941. if(prevmode != mode) {
  2942. prevmode = mode;
  2943. font = &dc.font;
  2944. frcflags = FRC_NORMAL;
  2945. runewidth = xw.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
  2946. if((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
  2947. font = &dc.ibfont;
  2948. frcflags = FRC_ITALICBOLD;
  2949. } else if(mode & ATTR_ITALIC) {
  2950. font = &dc.ifont;
  2951. frcflags = FRC_ITALIC;
  2952. } else if(mode & ATTR_BOLD) {
  2953. font = &dc.bfont;
  2954. frcflags = FRC_BOLD;
  2955. }
  2956. yp = winy + font->ascent;
  2957. }
  2958. /* Lookup character index with default font. */
  2959. glyphidx = XftCharIndex(xw.dpy, font->match, rune);
  2960. if(glyphidx) {
  2961. specs[numspecs].font = font->match;
  2962. specs[numspecs].glyph = glyphidx;
  2963. specs[numspecs].x = (short)xp;
  2964. specs[numspecs].y = (short)yp;
  2965. xp += runewidth;
  2966. numspecs++;
  2967. continue;
  2968. }
  2969. /* Fallback on font cache, search the font cache for match. */
  2970. for(f = 0; f < frclen; f++) {
  2971. glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
  2972. /* Everything correct. */
  2973. if(glyphidx && frc[f].flags == frcflags)
  2974. break;
  2975. /* We got a default font for a not found glyph. */
  2976. if(!glyphidx && frc[f].flags == frcflags
  2977. && frc[f].unicodep == rune) {
  2978. break;
  2979. }
  2980. }
  2981. /* Nothing was found. Use fontconfig to find matching font. */
  2982. if(f >= frclen) {
  2983. if(!font->set)
  2984. font->set = FcFontSort(0, font->pattern,
  2985. FcTrue, 0, &fcres);
  2986. fcsets[0] = font->set;
  2987. /*
  2988. * Nothing was found in the cache. Now use
  2989. * some dozen of Fontconfig calls to get the
  2990. * font for one single character.
  2991. *
  2992. * Xft and fontconfig are design failures.
  2993. */
  2994. fcpattern = FcPatternDuplicate(font->pattern);
  2995. fccharset = FcCharSetCreate();
  2996. FcCharSetAddChar(fccharset, rune);
  2997. FcPatternAddCharSet(fcpattern, FC_CHARSET,
  2998. fccharset);
  2999. FcPatternAddBool(fcpattern, FC_SCALABLE,
  3000. FcTrue);
  3001. FcConfigSubstitute(0, fcpattern,
  3002. FcMatchPattern);
  3003. FcDefaultSubstitute(fcpattern);
  3004. fontpattern = FcFontSetMatch(0, fcsets, 1,
  3005. fcpattern, &fcres);
  3006. /*
  3007. * Overwrite or create the new cache entry.
  3008. */
  3009. if(frclen >= LEN(frc)) {
  3010. frclen = LEN(frc) - 1;
  3011. XftFontClose(xw.dpy, frc[frclen].font);
  3012. frc[frclen].unicodep = 0;
  3013. }
  3014. frc[frclen].font = XftFontOpenPattern(xw.dpy,
  3015. fontpattern);
  3016. frc[frclen].flags = frcflags;
  3017. frc[frclen].unicodep = rune;
  3018. glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
  3019. f = frclen;
  3020. frclen++;
  3021. FcPatternDestroy(fcpattern);
  3022. FcCharSetDestroy(fccharset);
  3023. }
  3024. specs[numspecs].font = frc[f].font;
  3025. specs[numspecs].glyph = glyphidx;
  3026. specs[numspecs].x = (short)xp;
  3027. specs[numspecs].y = (short)(winy + frc[f].font->ascent);
  3028. xp += runewidth;
  3029. numspecs++;
  3030. }
  3031. return numspecs;
  3032. }
  3033. void
  3034. xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y) {
  3035. int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
  3036. int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
  3037. width = charlen * xw.cw;
  3038. Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
  3039. XRenderColor colfg, colbg;
  3040. XRectangle r;
  3041. /* Determine foreground and background colors based on mode. */
  3042. if(base.fg == defaultfg) {
  3043. if(base.mode & ATTR_ITALIC)
  3044. base.fg = defaultitalic;
  3045. else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD))
  3046. base.fg = defaultitalic;
  3047. else if(base.mode & ATTR_UNDERLINE)
  3048. base.fg = defaultunderline;
  3049. }
  3050. if(IS_TRUECOL(base.fg)) {
  3051. colfg.alpha = 0xffff;
  3052. colfg.red = TRUERED(base.fg);
  3053. colfg.green = TRUEGREEN(base.fg);
  3054. colfg.blue = TRUEBLUE(base.fg);
  3055. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
  3056. fg = &truefg;
  3057. } else {
  3058. fg = &dc.col[base.fg];
  3059. }
  3060. if(IS_TRUECOL(base.bg)) {
  3061. colbg.alpha = 0xffff;
  3062. colbg.green = TRUEGREEN(base.bg);
  3063. colbg.red = TRUERED(base.bg);
  3064. colbg.blue = TRUEBLUE(base.bg);
  3065. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
  3066. bg = &truebg;
  3067. } else {
  3068. bg = &dc.col[base.bg];
  3069. }
  3070. /* Change basic system colors [0-7] to bright system colors [8-15] */
  3071. if((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
  3072. fg = &dc.col[base.fg + 8];
  3073. if(IS_SET(MODE_REVERSE)) {
  3074. if(fg == &dc.col[defaultfg]) {
  3075. fg = &dc.col[defaultbg];
  3076. } else {
  3077. colfg.red = ~fg->color.red;
  3078. colfg.green = ~fg->color.green;
  3079. colfg.blue = ~fg->color.blue;
  3080. colfg.alpha = fg->color.alpha;
  3081. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
  3082. &revfg);
  3083. fg = &revfg;
  3084. }
  3085. if(bg == &dc.col[defaultbg]) {
  3086. bg = &dc.col[defaultfg];
  3087. } else {
  3088. colbg.red = ~bg->color.red;
  3089. colbg.green = ~bg->color.green;
  3090. colbg.blue = ~bg->color.blue;
  3091. colbg.alpha = bg->color.alpha;
  3092. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
  3093. &revbg);
  3094. bg = &revbg;
  3095. }
  3096. }
  3097. if(base.mode & ATTR_REVERSE) {
  3098. temp = fg;
  3099. fg = bg;
  3100. bg = temp;
  3101. }
  3102. if((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
  3103. colfg.red = fg->color.red / 2;
  3104. colfg.green = fg->color.green / 2;
  3105. colfg.blue = fg->color.blue / 2;
  3106. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
  3107. fg = &revfg;
  3108. }
  3109. if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
  3110. fg = bg;
  3111. if(base.mode & ATTR_INVISIBLE)
  3112. fg = bg;
  3113. /* Intelligent cleaning up of the borders. */
  3114. if(x == 0) {
  3115. xclear(0, (y == 0)? 0 : winy, borderpx,
  3116. winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
  3117. }
  3118. if(x + charlen >= term.col) {
  3119. xclear(winx + width, (y == 0)? 0 : winy, xw.w,
  3120. ((y >= term.row-1)? xw.h : (winy + xw.ch)));
  3121. }
  3122. if(y == 0)
  3123. xclear(winx, 0, winx + width, borderpx);
  3124. if(y == term.row-1)
  3125. xclear(winx, winy + xw.ch, winx + width, xw.h);
  3126. /* Clean up the region we want to draw to. */
  3127. XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
  3128. /* Set the clip region because Xft is sometimes dirty. */
  3129. r.x = 0;
  3130. r.y = 0;
  3131. r.height = xw.ch;
  3132. r.width = width;
  3133. XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
  3134. /* Render the glyphs. */
  3135. XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
  3136. /* Render underline and strikethrough. */
  3137. if(base.mode & ATTR_UNDERLINE) {
  3138. XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
  3139. width, 1);
  3140. }
  3141. if(base.mode & ATTR_STRUCK) {
  3142. XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
  3143. width, 1);
  3144. }
  3145. /* Reset clip to none. */
  3146. XftDrawSetClip(xw.draw, 0);
  3147. }
  3148. void
  3149. xdrawglyph(Glyph g, int x, int y) {
  3150. int numspecs;
  3151. XftGlyphFontSpec spec;
  3152. numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
  3153. xdrawglyphfontspecs(&spec, g, numspecs, x, y);
  3154. }
  3155. void
  3156. xdrawcursor(void) {
  3157. static int oldx = 0, oldy = 0;
  3158. int curx;
  3159. Glyph g = {' ', ATTR_NULL, defaultbg, defaultcs};
  3160. LIMIT(oldx, 0, term.col-1);
  3161. LIMIT(oldy, 0, term.row-1);
  3162. curx = term.c.x;
  3163. /* adjust position if in dummy */
  3164. if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
  3165. oldx--;
  3166. if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
  3167. curx--;
  3168. g.u = term.line[term.c.y][term.c.x].u;
  3169. /* remove the old cursor */
  3170. xdrawglyph(term.line[oldy][oldx], oldx, oldy);
  3171. if(IS_SET(MODE_HIDE))
  3172. return;
  3173. /* draw the new one */
  3174. if(xw.state & WIN_FOCUSED) {
  3175. switch (xw.cursor) {
  3176. case 0: /* Blinking Block */
  3177. case 1: /* Blinking Block (Default) */
  3178. case 2: /* Steady Block */
  3179. if(IS_SET(MODE_REVERSE)) {
  3180. g.mode |= ATTR_REVERSE;
  3181. g.fg = defaultcs;
  3182. g.bg = defaultfg;
  3183. }
  3184. g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
  3185. xdrawglyph(g, term.c.x, term.c.y);
  3186. break;
  3187. case 3: /* Blinking Underline */
  3188. case 4: /* Steady Underline */
  3189. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3190. borderpx + curx * xw.cw,
  3191. borderpx + (term.c.y + 1) * xw.ch - cursorthickness,
  3192. xw.cw, cursorthickness);
  3193. break;
  3194. case 5: /* Blinking bar */
  3195. case 6: /* Steady bar */
  3196. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3197. borderpx + curx * xw.cw,
  3198. borderpx + term.c.y * xw.ch,
  3199. cursorthickness, xw.ch);
  3200. break;
  3201. }
  3202. } else {
  3203. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3204. borderpx + curx * xw.cw,
  3205. borderpx + term.c.y * xw.ch,
  3206. xw.cw - 1, 1);
  3207. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3208. borderpx + curx * xw.cw,
  3209. borderpx + term.c.y * xw.ch,
  3210. 1, xw.ch - 1);
  3211. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3212. borderpx + (curx + 1) * xw.cw - 1,
  3213. borderpx + term.c.y * xw.ch,
  3214. 1, xw.ch - 1);
  3215. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3216. borderpx + curx * xw.cw,
  3217. borderpx + (term.c.y + 1) * xw.ch - 1,
  3218. xw.cw, 1);
  3219. }
  3220. oldx = curx, oldy = term.c.y;
  3221. }
  3222. void
  3223. xsettitle(char *p) {
  3224. XTextProperty prop;
  3225. Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
  3226. &prop);
  3227. XSetWMName(xw.dpy, xw.win, &prop);
  3228. XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
  3229. XFree(prop.value);
  3230. }
  3231. void
  3232. xresettitle(void) {
  3233. xsettitle(opt_title ? opt_title : "st");
  3234. }
  3235. void
  3236. redraw(void) {
  3237. tfulldirt();
  3238. draw();
  3239. }
  3240. void
  3241. draw(void) {
  3242. drawregion(0, 0, term.col, term.row);
  3243. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
  3244. xw.h, 0, 0);
  3245. XSetForeground(xw.dpy, dc.gc,
  3246. dc.col[IS_SET(MODE_REVERSE)?
  3247. defaultfg : defaultbg].pixel);
  3248. }
  3249. void
  3250. drawregion(int x1, int y1, int x2, int y2) {
  3251. int i, x, y, ox, numspecs;
  3252. Glyph base, new;
  3253. XftGlyphFontSpec* specs;
  3254. bool ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
  3255. if(!(xw.state & WIN_VISIBLE))
  3256. return;
  3257. for(y = y1; y < y2; y++) {
  3258. if(!term.dirty[y])
  3259. continue;
  3260. xtermclear(0, y, term.col, y);
  3261. term.dirty[y] = 0;
  3262. specs = term.specbuf;
  3263. numspecs = xmakeglyphfontspecs(specs, &term.line[y][x1], x2 - x1, x1, y);
  3264. i = ox = 0;
  3265. for(x = x1; x < x2 && i < numspecs; x++) {
  3266. new = term.line[y][x];
  3267. if(new.mode == ATTR_WDUMMY)
  3268. continue;
  3269. if(ena_sel && selected(x, y))
  3270. new.mode ^= ATTR_REVERSE;
  3271. if(i > 0 && ATTRCMP(base, new)) {
  3272. xdrawglyphfontspecs(specs, base, i, ox, y);
  3273. specs += i;
  3274. numspecs -= i;
  3275. i = 0;
  3276. }
  3277. if(i == 0) {
  3278. ox = x;
  3279. base = new;
  3280. }
  3281. i++;
  3282. }
  3283. if(i > 0)
  3284. xdrawglyphfontspecs(specs, base, i, ox, y);
  3285. }
  3286. xdrawcursor();
  3287. }
  3288. void
  3289. expose(XEvent *ev) {
  3290. redraw();
  3291. }
  3292. void
  3293. visibility(XEvent *ev) {
  3294. XVisibilityEvent *e = &ev->xvisibility;
  3295. MODBIT(xw.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
  3296. }
  3297. void
  3298. unmap(XEvent *ev) {
  3299. xw.state &= ~WIN_VISIBLE;
  3300. }
  3301. void
  3302. xsetpointermotion(int set) {
  3303. MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
  3304. XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
  3305. }
  3306. void
  3307. xseturgency(int add) {
  3308. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  3309. MODBIT(h->flags, add, XUrgencyHint);
  3310. XSetWMHints(xw.dpy, xw.win, h);
  3311. XFree(h);
  3312. }
  3313. void
  3314. focus(XEvent *ev) {
  3315. XFocusChangeEvent *e = &ev->xfocus;
  3316. if(e->mode == NotifyGrab)
  3317. return;
  3318. if(ev->type == FocusIn) {
  3319. XSetICFocus(xw.xic);
  3320. xw.state |= WIN_FOCUSED;
  3321. xseturgency(0);
  3322. if(IS_SET(MODE_FOCUS))
  3323. ttywrite("\033[I", 3);
  3324. } else {
  3325. XUnsetICFocus(xw.xic);
  3326. xw.state &= ~WIN_FOCUSED;
  3327. if(IS_SET(MODE_FOCUS))
  3328. ttywrite("\033[O", 3);
  3329. }
  3330. }
  3331. bool
  3332. match(uint mask, uint state) {
  3333. return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
  3334. }
  3335. void
  3336. numlock(const Arg *dummy) {
  3337. term.numlock ^= 1;
  3338. }
  3339. char*
  3340. kmap(KeySym k, uint state) {
  3341. Key *kp;
  3342. int i;
  3343. /* Check for mapped keys out of X11 function keys. */
  3344. for(i = 0; i < LEN(mappedkeys); i++) {
  3345. if(mappedkeys[i] == k)
  3346. break;
  3347. }
  3348. if(i == LEN(mappedkeys)) {
  3349. if((k & 0xFFFF) < 0xFD00)
  3350. return NULL;
  3351. }
  3352. for(kp = key; kp < key + LEN(key); kp++) {
  3353. if(kp->k != k)
  3354. continue;
  3355. if(!match(kp->mask, state))
  3356. continue;
  3357. if(IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
  3358. continue;
  3359. if(term.numlock && kp->appkey == 2)
  3360. continue;
  3361. if(IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
  3362. continue;
  3363. if(IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
  3364. continue;
  3365. return kp->s;
  3366. }
  3367. return NULL;
  3368. }
  3369. void
  3370. kpress(XEvent *ev) {
  3371. XKeyEvent *e = &ev->xkey;
  3372. KeySym ksym;
  3373. char buf[32], *customkey;
  3374. int len;
  3375. Rune c;
  3376. Status status;
  3377. Shortcut *bp;
  3378. if(IS_SET(MODE_KBDLOCK))
  3379. return;
  3380. len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
  3381. /* 1. shortcuts */
  3382. for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
  3383. if(ksym == bp->keysym && match(bp->mod, e->state)) {
  3384. bp->func(&(bp->arg));
  3385. return;
  3386. }
  3387. }
  3388. /* 2. custom keys from config.h */
  3389. if((customkey = kmap(ksym, e->state))) {
  3390. ttysend(customkey, strlen(customkey));
  3391. return;
  3392. }
  3393. /* 3. composed string from input method */
  3394. if(len == 0)
  3395. return;
  3396. if(len == 1 && e->state & Mod1Mask) {
  3397. if(IS_SET(MODE_8BIT)) {
  3398. if(*buf < 0177) {
  3399. c = *buf | 0x80;
  3400. len = utf8encode(c, buf);
  3401. }
  3402. } else {
  3403. buf[1] = buf[0];
  3404. buf[0] = '\033';
  3405. len = 2;
  3406. }
  3407. }
  3408. ttysend(buf, len);
  3409. }
  3410. void
  3411. cmessage(XEvent *e) {
  3412. /*
  3413. * See xembed specs
  3414. * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
  3415. */
  3416. if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  3417. if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  3418. xw.state |= WIN_FOCUSED;
  3419. xseturgency(0);
  3420. } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  3421. xw.state &= ~WIN_FOCUSED;
  3422. }
  3423. } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
  3424. /* Send SIGHUP to shell */
  3425. kill(pid, SIGHUP);
  3426. exit(0);
  3427. }
  3428. }
  3429. void
  3430. cresize(int width, int height) {
  3431. int col, row;
  3432. if(width != 0)
  3433. xw.w = width;
  3434. if(height != 0)
  3435. xw.h = height;
  3436. col = (xw.w - 2 * borderpx) / xw.cw;
  3437. row = (xw.h - 2 * borderpx) / xw.ch;
  3438. tresize(col, row);
  3439. xresize(col, row);
  3440. ttyresize();
  3441. }
  3442. void
  3443. resize(XEvent *e) {
  3444. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  3445. return;
  3446. cresize(e->xconfigure.width, e->xconfigure.height);
  3447. }
  3448. void
  3449. run(void) {
  3450. XEvent ev;
  3451. int w = xw.w, h = xw.h;
  3452. fd_set rfd;
  3453. int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
  3454. struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
  3455. long deltatime;
  3456. /* Waiting for window mapping */
  3457. do {
  3458. XNextEvent(xw.dpy, &ev);
  3459. /*
  3460. * XFilterEvent is required to be called after you using XOpenIM,
  3461. * this is not unnecessary.It does not only filter the key event,
  3462. * but some clientmessage for input method as well.
  3463. */
  3464. if(XFilterEvent(&ev, None))
  3465. continue;
  3466. if(ev.type == ConfigureNotify) {
  3467. w = ev.xconfigure.width;
  3468. h = ev.xconfigure.height;
  3469. }
  3470. } while(ev.type != MapNotify);
  3471. ttynew();
  3472. cresize(w, h);
  3473. clock_gettime(CLOCK_MONOTONIC, &last);
  3474. lastblink = last;
  3475. for(xev = actionfps;;) {
  3476. FD_ZERO(&rfd);
  3477. FD_SET(cmdfd, &rfd);
  3478. FD_SET(xfd, &rfd);
  3479. if(pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
  3480. if(errno == EINTR)
  3481. continue;
  3482. die("select failed: %s\n", strerror(errno));
  3483. }
  3484. if(FD_ISSET(cmdfd, &rfd)) {
  3485. ttyread();
  3486. if(blinktimeout) {
  3487. blinkset = tattrset(ATTR_BLINK);
  3488. if(!blinkset)
  3489. MODBIT(term.mode, 0, MODE_BLINK);
  3490. }
  3491. }
  3492. if(FD_ISSET(xfd, &rfd))
  3493. xev = actionfps;
  3494. clock_gettime(CLOCK_MONOTONIC, &now);
  3495. drawtimeout.tv_sec = 0;
  3496. drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
  3497. tv = &drawtimeout;
  3498. dodraw = 0;
  3499. if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
  3500. tsetdirtattr(ATTR_BLINK);
  3501. term.mode ^= MODE_BLINK;
  3502. lastblink = now;
  3503. dodraw = 1;
  3504. }
  3505. deltatime = TIMEDIFF(now, last);
  3506. if(deltatime > 1000 / (xev ? xfps : actionfps)) {
  3507. dodraw = 1;
  3508. last = now;
  3509. }
  3510. if(dodraw) {
  3511. while(XPending(xw.dpy)) {
  3512. XNextEvent(xw.dpy, &ev);
  3513. if(XFilterEvent(&ev, None))
  3514. continue;
  3515. if(handler[ev.type])
  3516. (handler[ev.type])(&ev);
  3517. }
  3518. draw();
  3519. XFlush(xw.dpy);
  3520. if(xev && !FD_ISSET(xfd, &rfd))
  3521. xev--;
  3522. if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
  3523. if(blinkset) {
  3524. if(TIMEDIFF(now, lastblink) \
  3525. > blinktimeout) {
  3526. drawtimeout.tv_nsec = 1000;
  3527. } else {
  3528. drawtimeout.tv_nsec = (1E6 * \
  3529. (blinktimeout - \
  3530. TIMEDIFF(now,
  3531. lastblink)));
  3532. }
  3533. drawtimeout.tv_sec = \
  3534. drawtimeout.tv_nsec / 1E9;
  3535. drawtimeout.tv_nsec %= (long)1E9;
  3536. } else {
  3537. tv = NULL;
  3538. }
  3539. }
  3540. }
  3541. }
  3542. }
  3543. void
  3544. usage(void) {
  3545. die("%s " VERSION " (c) 2010-2015 st engineers\n"
  3546. "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]\n"
  3547. " [-i] [-t title] [-w windowid] [-e command ...] [command ...]\n"
  3548. " st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]\n"
  3549. " [-i] [-t title] [-w windowid] [-l line] [stty_args ...]\n",
  3550. argv0);
  3551. }
  3552. int
  3553. main(int argc, char *argv[]) {
  3554. uint cols = 80, rows = 24;
  3555. xw.l = xw.t = 0;
  3556. xw.isfixed = False;
  3557. xw.cursor = 0;
  3558. ARGBEGIN {
  3559. case 'a':
  3560. allowaltscreen = false;
  3561. break;
  3562. case 'c':
  3563. opt_class = EARGF(usage());
  3564. break;
  3565. case 'e':
  3566. if(argc > 0)
  3567. --argc, ++argv;
  3568. goto run;
  3569. case 'f':
  3570. opt_font = EARGF(usage());
  3571. break;
  3572. case 'g':
  3573. xw.gm = XParseGeometry(EARGF(usage()),
  3574. &xw.l, &xw.t, &cols, &rows);
  3575. break;
  3576. case 'i':
  3577. xw.isfixed = True;
  3578. break;
  3579. case 'o':
  3580. opt_io = EARGF(usage());
  3581. break;
  3582. case 'l':
  3583. opt_line = EARGF(usage());
  3584. break;
  3585. case 't':
  3586. opt_title = EARGF(usage());
  3587. break;
  3588. case 'w':
  3589. opt_embed = EARGF(usage());
  3590. break;
  3591. case 'v':
  3592. default:
  3593. usage();
  3594. } ARGEND;
  3595. run:
  3596. if(argc > 0) {
  3597. /* eat all remaining arguments */
  3598. opt_cmd = argv;
  3599. if(!opt_title && !opt_line)
  3600. opt_title = basename(xstrdup(argv[0]));
  3601. }
  3602. setlocale(LC_CTYPE, "");
  3603. XSetLocaleModifiers("");
  3604. tnew(MAX(cols, 1), MAX(rows, 1));
  3605. xinit();
  3606. selinit();
  3607. run();
  3608. return 0;
  3609. }