My build of suckless st terminal
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.

4075 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.
10 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 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.
10 years ago
12 years ago
12 years ago
12 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.
10 years ago
11 years ago
10 years ago
14 years ago
10 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
12 years ago
14 years ago
14 years ago
11 years ago
11 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.
10 years ago
14 years ago
14 years ago
14 years ago
11 years ago
14 years ago
14 years ago
14 years ago
14 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.
10 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.
10 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.
10 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.
10 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.
10 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.
10 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.
10 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.
10 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.
10 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.
10 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.
10 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.
10 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.
10 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.
10 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.
10 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.
10 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.
10 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.
10 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.
10 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.
10 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.
10 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 = STDOUT_FILENO;
  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(EXIT_FAILURE);
  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(EXIT_FAILURE);
  1103. }
  1104. void
  1105. sigchld(int a) {
  1106. int stat, ret;
  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. ret = WIFEXITED(stat) ? WEXITSTATUS(stat) : EXIT_FAILURE;
  1113. if (ret != EXIT_SUCCESS)
  1114. die("child finished with error '%d'\n", stat);
  1115. exit(EXIT_SUCCESS);
  1116. }
  1117. void
  1118. stty(void)
  1119. {
  1120. char cmd[_POSIX_ARG_MAX], **p, *q, *s;
  1121. size_t n, siz;
  1122. if((n = strlen(stty_args)) > sizeof(cmd)-1)
  1123. die("incorrect stty parameters\n");
  1124. memcpy(cmd, stty_args, n);
  1125. q = cmd + n;
  1126. siz = sizeof(cmd) - n;
  1127. for(p = opt_cmd; p && (s = *p); ++p) {
  1128. if((n = strlen(s)) > siz-1)
  1129. die("stty parameter length too long\n");
  1130. *q++ = ' ';
  1131. q = memcpy(q, s, n);
  1132. q += n;
  1133. siz-= n + 1;
  1134. }
  1135. *q = '\0';
  1136. if (system(cmd) != 0)
  1137. perror("Couldn't call stty");
  1138. }
  1139. void
  1140. ttynew(void) {
  1141. int m, s;
  1142. struct winsize w = {term.row, term.col, 0, 0};
  1143. if(opt_io) {
  1144. term.mode |= MODE_PRINT;
  1145. iofd = (!strcmp(opt_io, "-")) ?
  1146. STDOUT_FILENO :
  1147. open(opt_io, O_WRONLY | O_CREAT, 0666);
  1148. if(iofd < 0) {
  1149. fprintf(stderr, "Error opening %s:%s\n",
  1150. opt_io, strerror(errno));
  1151. }
  1152. }
  1153. if (opt_line) {
  1154. if((cmdfd = open(opt_line, O_RDWR)) < 0)
  1155. die("open line failed: %s\n", strerror(errno));
  1156. close(STDIN_FILENO);
  1157. dup(cmdfd);
  1158. stty();
  1159. return;
  1160. }
  1161. /* seems to work fine on linux, openbsd and freebsd */
  1162. if(openpty(&m, &s, NULL, NULL, &w) < 0)
  1163. die("openpty failed: %s\n", strerror(errno));
  1164. switch(pid = fork()) {
  1165. case -1:
  1166. die("fork failed\n");
  1167. break;
  1168. case 0:
  1169. close(iofd);
  1170. setsid(); /* create a new process group */
  1171. dup2(s, STDIN_FILENO);
  1172. dup2(s, STDOUT_FILENO);
  1173. dup2(s, STDERR_FILENO);
  1174. if(ioctl(s, TIOCSCTTY, NULL) < 0)
  1175. die("ioctl TIOCSCTTY failed: %s\n", strerror(errno));
  1176. close(s);
  1177. close(m);
  1178. execsh();
  1179. break;
  1180. default:
  1181. close(s);
  1182. cmdfd = m;
  1183. signal(SIGCHLD, sigchld);
  1184. break;
  1185. }
  1186. }
  1187. void
  1188. ttyread(void) {
  1189. static char buf[BUFSIZ];
  1190. static int buflen = 0;
  1191. char *ptr;
  1192. int charsize; /* size of utf8 char in bytes */
  1193. Rune unicodep;
  1194. int ret;
  1195. /* append read bytes to unprocessed bytes */
  1196. if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
  1197. die("Couldn't read from shell: %s\n", strerror(errno));
  1198. /* process every complete utf8 char */
  1199. buflen += ret;
  1200. ptr = buf;
  1201. while((charsize = utf8decode(ptr, &unicodep, buflen))) {
  1202. tputc(unicodep);
  1203. ptr += charsize;
  1204. buflen -= charsize;
  1205. }
  1206. /* keep any uncomplete utf8 char for the next call */
  1207. memmove(buf, ptr, buflen);
  1208. }
  1209. void
  1210. ttywrite(const char *s, size_t n) {
  1211. if(xwrite(cmdfd, s, n) == -1)
  1212. die("write error on tty: %s\n", strerror(errno));
  1213. }
  1214. void
  1215. ttysend(char *s, size_t n) {
  1216. int len;
  1217. Rune u;
  1218. ttywrite(s, n);
  1219. if(IS_SET(MODE_ECHO))
  1220. while((len = utf8decode(s, &u, n)) > 0) {
  1221. techo(u);
  1222. n -= len;
  1223. s += len;
  1224. }
  1225. }
  1226. void
  1227. ttyresize(void) {
  1228. struct winsize w;
  1229. w.ws_row = term.row;
  1230. w.ws_col = term.col;
  1231. w.ws_xpixel = xw.tw;
  1232. w.ws_ypixel = xw.th;
  1233. if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
  1234. fprintf(stderr, "Couldn't set window size: %s\n", strerror(errno));
  1235. }
  1236. int
  1237. tattrset(int attr) {
  1238. int i, j;
  1239. for(i = 0; i < term.row-1; i++) {
  1240. for(j = 0; j < term.col-1; j++) {
  1241. if(term.line[i][j].mode & attr)
  1242. return 1;
  1243. }
  1244. }
  1245. return 0;
  1246. }
  1247. void
  1248. tsetdirt(int top, int bot) {
  1249. int i;
  1250. LIMIT(top, 0, term.row-1);
  1251. LIMIT(bot, 0, term.row-1);
  1252. for(i = top; i <= bot; i++)
  1253. term.dirty[i] = 1;
  1254. }
  1255. void
  1256. tsetdirtattr(int attr) {
  1257. int i, j;
  1258. for(i = 0; i < term.row-1; i++) {
  1259. for(j = 0; j < term.col-1; j++) {
  1260. if(term.line[i][j].mode & attr) {
  1261. tsetdirt(i, i);
  1262. break;
  1263. }
  1264. }
  1265. }
  1266. }
  1267. void
  1268. tfulldirt(void) {
  1269. tsetdirt(0, term.row-1);
  1270. }
  1271. void
  1272. tcursor(int mode) {
  1273. static TCursor c[2];
  1274. bool alt = IS_SET(MODE_ALTSCREEN);
  1275. if(mode == CURSOR_SAVE) {
  1276. c[alt] = term.c;
  1277. } else if(mode == CURSOR_LOAD) {
  1278. term.c = c[alt];
  1279. tmoveto(c[alt].x, c[alt].y);
  1280. }
  1281. }
  1282. void
  1283. treset(void) {
  1284. uint i;
  1285. term.c = (TCursor){{
  1286. .mode = ATTR_NULL,
  1287. .fg = defaultfg,
  1288. .bg = defaultbg
  1289. }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
  1290. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  1291. for(i = tabspaces; i < term.col; i += tabspaces)
  1292. term.tabs[i] = 1;
  1293. term.top = 0;
  1294. term.bot = term.row - 1;
  1295. term.mode = MODE_WRAP;
  1296. memset(term.trantbl, CS_USA, sizeof(term.trantbl));
  1297. term.charset = 0;
  1298. for(i = 0; i < 2; i++) {
  1299. tmoveto(0, 0);
  1300. tcursor(CURSOR_SAVE);
  1301. tclearregion(0, 0, term.col-1, term.row-1);
  1302. tswapscreen();
  1303. }
  1304. }
  1305. void
  1306. tnew(int col, int row) {
  1307. term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
  1308. tresize(col, row);
  1309. term.numlock = 1;
  1310. treset();
  1311. }
  1312. void
  1313. tswapscreen(void) {
  1314. Line *tmp = term.line;
  1315. term.line = term.alt;
  1316. term.alt = tmp;
  1317. term.mode ^= MODE_ALTSCREEN;
  1318. tfulldirt();
  1319. }
  1320. void
  1321. tscrolldown(int orig, int n) {
  1322. int i;
  1323. Line temp;
  1324. LIMIT(n, 0, term.bot-orig+1);
  1325. tsetdirt(orig, term.bot-n);
  1326. tclearregion(0, term.bot-n+1, term.col-1, term.bot);
  1327. for(i = term.bot; i >= orig+n; i--) {
  1328. temp = term.line[i];
  1329. term.line[i] = term.line[i-n];
  1330. term.line[i-n] = temp;
  1331. }
  1332. selscroll(orig, n);
  1333. }
  1334. void
  1335. tscrollup(int orig, int n) {
  1336. int i;
  1337. Line temp;
  1338. LIMIT(n, 0, term.bot-orig+1);
  1339. tclearregion(0, orig, term.col-1, orig+n-1);
  1340. tsetdirt(orig+n, term.bot);
  1341. for(i = orig; i <= term.bot-n; i++) {
  1342. temp = term.line[i];
  1343. term.line[i] = term.line[i+n];
  1344. term.line[i+n] = temp;
  1345. }
  1346. selscroll(orig, -n);
  1347. }
  1348. void
  1349. selscroll(int orig, int n) {
  1350. if(sel.ob.x == -1)
  1351. return;
  1352. if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
  1353. if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
  1354. selclear(NULL);
  1355. return;
  1356. }
  1357. if(sel.type == SEL_RECTANGULAR) {
  1358. if(sel.ob.y < term.top)
  1359. sel.ob.y = term.top;
  1360. if(sel.oe.y > term.bot)
  1361. sel.oe.y = term.bot;
  1362. } else {
  1363. if(sel.ob.y < term.top) {
  1364. sel.ob.y = term.top;
  1365. sel.ob.x = 0;
  1366. }
  1367. if(sel.oe.y > term.bot) {
  1368. sel.oe.y = term.bot;
  1369. sel.oe.x = term.col;
  1370. }
  1371. }
  1372. selnormalize();
  1373. }
  1374. }
  1375. void
  1376. tnewline(int first_col) {
  1377. int y = term.c.y;
  1378. if(y == term.bot) {
  1379. tscrollup(term.top, 1);
  1380. } else {
  1381. y++;
  1382. }
  1383. tmoveto(first_col ? 0 : term.c.x, y);
  1384. }
  1385. void
  1386. csiparse(void) {
  1387. char *p = csiescseq.buf, *np;
  1388. long int v;
  1389. csiescseq.narg = 0;
  1390. if(*p == '?') {
  1391. csiescseq.priv = 1;
  1392. p++;
  1393. }
  1394. csiescseq.buf[csiescseq.len] = '\0';
  1395. while(p < csiescseq.buf+csiescseq.len) {
  1396. np = NULL;
  1397. v = strtol(p, &np, 10);
  1398. if(np == p)
  1399. v = 0;
  1400. if(v == LONG_MAX || v == LONG_MIN)
  1401. v = -1;
  1402. csiescseq.arg[csiescseq.narg++] = v;
  1403. p = np;
  1404. if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
  1405. break;
  1406. p++;
  1407. }
  1408. csiescseq.mode[0] = *p++;
  1409. csiescseq.mode[1] = (p < csiescseq.buf+csiescseq.len) ? *p : '\0';
  1410. }
  1411. /* for absolute user moves, when decom is set */
  1412. void
  1413. tmoveato(int x, int y) {
  1414. tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
  1415. }
  1416. void
  1417. tmoveto(int x, int y) {
  1418. int miny, maxy;
  1419. if(term.c.state & CURSOR_ORIGIN) {
  1420. miny = term.top;
  1421. maxy = term.bot;
  1422. } else {
  1423. miny = 0;
  1424. maxy = term.row - 1;
  1425. }
  1426. term.c.state &= ~CURSOR_WRAPNEXT;
  1427. term.c.x = LIMIT(x, 0, term.col-1);
  1428. term.c.y = LIMIT(y, miny, maxy);
  1429. }
  1430. void
  1431. tsetchar(Rune u, Glyph *attr, int x, int y) {
  1432. static char *vt100_0[62] = { /* 0x41 - 0x7e */
  1433. "", "", "", "", "", "", "", /* A - G */
  1434. 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
  1435. 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
  1436. 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
  1437. "", "", "", "", "", "", "°", "±", /* ` - g */
  1438. "", "", "", "", "", "", "", "", /* h - o */
  1439. "", "", "", "", "", "", "", "", /* p - w */
  1440. "", "", "", "π", "", "£", "·", /* x - ~ */
  1441. };
  1442. /*
  1443. * The table is proudly stolen from rxvt.
  1444. */
  1445. if(term.trantbl[term.charset] == CS_GRAPHIC0 &&
  1446. BETWEEN(u, 0x41, 0x7e) && vt100_0[u - 0x41])
  1447. utf8decode(vt100_0[u - 0x41], &u, UTF_SIZ);
  1448. if(term.line[y][x].mode & ATTR_WIDE) {
  1449. if(x+1 < term.col) {
  1450. term.line[y][x+1].u = ' ';
  1451. term.line[y][x+1].mode &= ~ATTR_WDUMMY;
  1452. }
  1453. } else if(term.line[y][x].mode & ATTR_WDUMMY) {
  1454. term.line[y][x-1].u = ' ';
  1455. term.line[y][x-1].mode &= ~ATTR_WIDE;
  1456. }
  1457. term.dirty[y] = 1;
  1458. term.line[y][x] = *attr;
  1459. term.line[y][x].u = u;
  1460. }
  1461. void
  1462. tclearregion(int x1, int y1, int x2, int y2) {
  1463. int x, y, temp;
  1464. Glyph *gp;
  1465. if(x1 > x2)
  1466. temp = x1, x1 = x2, x2 = temp;
  1467. if(y1 > y2)
  1468. temp = y1, y1 = y2, y2 = temp;
  1469. LIMIT(x1, 0, term.col-1);
  1470. LIMIT(x2, 0, term.col-1);
  1471. LIMIT(y1, 0, term.row-1);
  1472. LIMIT(y2, 0, term.row-1);
  1473. for(y = y1; y <= y2; y++) {
  1474. term.dirty[y] = 1;
  1475. for(x = x1; x <= x2; x++) {
  1476. gp = &term.line[y][x];
  1477. if(selected(x, y))
  1478. selclear(NULL);
  1479. gp->fg = term.c.attr.fg;
  1480. gp->bg = term.c.attr.bg;
  1481. gp->mode = 0;
  1482. gp->u = ' ';
  1483. }
  1484. }
  1485. }
  1486. void
  1487. tdeletechar(int n) {
  1488. int dst, src, size;
  1489. Glyph *line;
  1490. LIMIT(n, 0, term.col - term.c.x);
  1491. dst = term.c.x;
  1492. src = term.c.x + n;
  1493. size = term.col - src;
  1494. line = term.line[term.c.y];
  1495. memmove(&line[dst], &line[src], size * sizeof(Glyph));
  1496. tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
  1497. }
  1498. void
  1499. tinsertblank(int n) {
  1500. int dst, src, size;
  1501. Glyph *line;
  1502. LIMIT(n, 0, term.col - term.c.x);
  1503. dst = term.c.x + n;
  1504. src = term.c.x;
  1505. size = term.col - dst;
  1506. line = term.line[term.c.y];
  1507. memmove(&line[dst], &line[src], size * sizeof(Glyph));
  1508. tclearregion(src, term.c.y, dst - 1, term.c.y);
  1509. }
  1510. void
  1511. tinsertblankline(int n) {
  1512. if(BETWEEN(term.c.y, term.top, term.bot))
  1513. tscrolldown(term.c.y, n);
  1514. }
  1515. void
  1516. tdeleteline(int n) {
  1517. if(BETWEEN(term.c.y, term.top, term.bot))
  1518. tscrollup(term.c.y, n);
  1519. }
  1520. int32_t
  1521. tdefcolor(int *attr, int *npar, int l) {
  1522. int32_t idx = -1;
  1523. uint r, g, b;
  1524. switch (attr[*npar + 1]) {
  1525. case 2: /* direct color in RGB space */
  1526. if (*npar + 4 >= l) {
  1527. fprintf(stderr,
  1528. "erresc(38): Incorrect number of parameters (%d)\n",
  1529. *npar);
  1530. break;
  1531. }
  1532. r = attr[*npar + 2];
  1533. g = attr[*npar + 3];
  1534. b = attr[*npar + 4];
  1535. *npar += 4;
  1536. if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
  1537. fprintf(stderr, "erresc: bad rgb color (%u,%u,%u)\n",
  1538. r, g, b);
  1539. else
  1540. idx = TRUECOLOR(r, g, b);
  1541. break;
  1542. case 5: /* indexed color */
  1543. if (*npar + 2 >= l) {
  1544. fprintf(stderr,
  1545. "erresc(38): Incorrect number of parameters (%d)\n",
  1546. *npar);
  1547. break;
  1548. }
  1549. *npar += 2;
  1550. if(!BETWEEN(attr[*npar], 0, 255))
  1551. fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
  1552. else
  1553. idx = attr[*npar];
  1554. break;
  1555. case 0: /* implemented defined (only foreground) */
  1556. case 1: /* transparent */
  1557. case 3: /* direct color in CMY space */
  1558. case 4: /* direct color in CMYK space */
  1559. default:
  1560. fprintf(stderr,
  1561. "erresc(38): gfx attr %d unknown\n", attr[*npar]);
  1562. break;
  1563. }
  1564. return idx;
  1565. }
  1566. void
  1567. tsetattr(int *attr, int l) {
  1568. int i;
  1569. int32_t idx;
  1570. for(i = 0; i < l; i++) {
  1571. switch(attr[i]) {
  1572. case 0:
  1573. term.c.attr.mode &= ~(
  1574. ATTR_BOLD |
  1575. ATTR_FAINT |
  1576. ATTR_ITALIC |
  1577. ATTR_UNDERLINE |
  1578. ATTR_BLINK |
  1579. ATTR_REVERSE |
  1580. ATTR_INVISIBLE |
  1581. ATTR_STRUCK );
  1582. term.c.attr.fg = defaultfg;
  1583. term.c.attr.bg = defaultbg;
  1584. break;
  1585. case 1:
  1586. term.c.attr.mode |= ATTR_BOLD;
  1587. break;
  1588. case 2:
  1589. term.c.attr.mode |= ATTR_FAINT;
  1590. break;
  1591. case 3:
  1592. term.c.attr.mode |= ATTR_ITALIC;
  1593. break;
  1594. case 4:
  1595. term.c.attr.mode |= ATTR_UNDERLINE;
  1596. break;
  1597. case 5: /* slow blink */
  1598. /* FALLTHROUGH */
  1599. case 6: /* rapid blink */
  1600. term.c.attr.mode |= ATTR_BLINK;
  1601. break;
  1602. case 7:
  1603. term.c.attr.mode |= ATTR_REVERSE;
  1604. break;
  1605. case 8:
  1606. term.c.attr.mode |= ATTR_INVISIBLE;
  1607. break;
  1608. case 9:
  1609. term.c.attr.mode |= ATTR_STRUCK;
  1610. break;
  1611. case 22:
  1612. term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT);
  1613. break;
  1614. case 23:
  1615. term.c.attr.mode &= ~ATTR_ITALIC;
  1616. break;
  1617. case 24:
  1618. term.c.attr.mode &= ~ATTR_UNDERLINE;
  1619. break;
  1620. case 25:
  1621. term.c.attr.mode &= ~ATTR_BLINK;
  1622. break;
  1623. case 27:
  1624. term.c.attr.mode &= ~ATTR_REVERSE;
  1625. break;
  1626. case 28:
  1627. term.c.attr.mode &= ~ATTR_INVISIBLE;
  1628. break;
  1629. case 29:
  1630. term.c.attr.mode &= ~ATTR_STRUCK;
  1631. break;
  1632. case 38:
  1633. if ((idx = tdefcolor(attr, &i, l)) >= 0)
  1634. term.c.attr.fg = idx;
  1635. break;
  1636. case 39:
  1637. term.c.attr.fg = defaultfg;
  1638. break;
  1639. case 48:
  1640. if ((idx = tdefcolor(attr, &i, l)) >= 0)
  1641. term.c.attr.bg = idx;
  1642. break;
  1643. case 49:
  1644. term.c.attr.bg = defaultbg;
  1645. break;
  1646. default:
  1647. if(BETWEEN(attr[i], 30, 37)) {
  1648. term.c.attr.fg = attr[i] - 30;
  1649. } else if(BETWEEN(attr[i], 40, 47)) {
  1650. term.c.attr.bg = attr[i] - 40;
  1651. } else if(BETWEEN(attr[i], 90, 97)) {
  1652. term.c.attr.fg = attr[i] - 90 + 8;
  1653. } else if(BETWEEN(attr[i], 100, 107)) {
  1654. term.c.attr.bg = attr[i] - 100 + 8;
  1655. } else {
  1656. fprintf(stderr,
  1657. "erresc(default): gfx attr %d unknown\n",
  1658. attr[i]), csidump();
  1659. }
  1660. break;
  1661. }
  1662. }
  1663. }
  1664. void
  1665. tsetscroll(int t, int b) {
  1666. int temp;
  1667. LIMIT(t, 0, term.row-1);
  1668. LIMIT(b, 0, term.row-1);
  1669. if(t > b) {
  1670. temp = t;
  1671. t = b;
  1672. b = temp;
  1673. }
  1674. term.top = t;
  1675. term.bot = b;
  1676. }
  1677. void
  1678. tsetmode(bool priv, bool set, int *args, int narg) {
  1679. int *lim, mode;
  1680. bool alt;
  1681. for(lim = args + narg; args < lim; ++args) {
  1682. if(priv) {
  1683. switch(*args) {
  1684. case 1: /* DECCKM -- Cursor key */
  1685. MODBIT(term.mode, set, MODE_APPCURSOR);
  1686. break;
  1687. case 5: /* DECSCNM -- Reverse video */
  1688. mode = term.mode;
  1689. MODBIT(term.mode, set, MODE_REVERSE);
  1690. if(mode != term.mode)
  1691. redraw();
  1692. break;
  1693. case 6: /* DECOM -- Origin */
  1694. MODBIT(term.c.state, set, CURSOR_ORIGIN);
  1695. tmoveato(0, 0);
  1696. break;
  1697. case 7: /* DECAWM -- Auto wrap */
  1698. MODBIT(term.mode, set, MODE_WRAP);
  1699. break;
  1700. case 0: /* Error (IGNORED) */
  1701. case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
  1702. case 3: /* DECCOLM -- Column (IGNORED) */
  1703. case 4: /* DECSCLM -- Scroll (IGNORED) */
  1704. case 8: /* DECARM -- Auto repeat (IGNORED) */
  1705. case 18: /* DECPFF -- Printer feed (IGNORED) */
  1706. case 19: /* DECPEX -- Printer extent (IGNORED) */
  1707. case 42: /* DECNRCM -- National characters (IGNORED) */
  1708. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  1709. break;
  1710. case 25: /* DECTCEM -- Text Cursor Enable Mode */
  1711. MODBIT(term.mode, !set, MODE_HIDE);
  1712. break;
  1713. case 9: /* X10 mouse compatibility mode */
  1714. xsetpointermotion(0);
  1715. MODBIT(term.mode, 0, MODE_MOUSE);
  1716. MODBIT(term.mode, set, MODE_MOUSEX10);
  1717. break;
  1718. case 1000: /* 1000: report button press */
  1719. xsetpointermotion(0);
  1720. MODBIT(term.mode, 0, MODE_MOUSE);
  1721. MODBIT(term.mode, set, MODE_MOUSEBTN);
  1722. break;
  1723. case 1002: /* 1002: report motion on button press */
  1724. xsetpointermotion(0);
  1725. MODBIT(term.mode, 0, MODE_MOUSE);
  1726. MODBIT(term.mode, set, MODE_MOUSEMOTION);
  1727. break;
  1728. case 1003: /* 1003: enable all mouse motions */
  1729. xsetpointermotion(set);
  1730. MODBIT(term.mode, 0, MODE_MOUSE);
  1731. MODBIT(term.mode, set, MODE_MOUSEMANY);
  1732. break;
  1733. case 1004: /* 1004: send focus events to tty */
  1734. MODBIT(term.mode, set, MODE_FOCUS);
  1735. break;
  1736. case 1006: /* 1006: extended reporting mode */
  1737. MODBIT(term.mode, set, MODE_MOUSESGR);
  1738. break;
  1739. case 1034:
  1740. MODBIT(term.mode, set, MODE_8BIT);
  1741. break;
  1742. case 1049: /* swap screen & set/restore cursor as xterm */
  1743. if (!allowaltscreen)
  1744. break;
  1745. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1746. /* FALLTHROUGH */
  1747. case 47: /* swap screen */
  1748. case 1047:
  1749. if (!allowaltscreen)
  1750. break;
  1751. alt = IS_SET(MODE_ALTSCREEN);
  1752. if(alt) {
  1753. tclearregion(0, 0, term.col-1,
  1754. term.row-1);
  1755. }
  1756. if(set ^ alt) /* set is always 1 or 0 */
  1757. tswapscreen();
  1758. if(*args != 1049)
  1759. break;
  1760. /* FALLTHROUGH */
  1761. case 1048:
  1762. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1763. break;
  1764. case 2004: /* 2004: bracketed paste mode */
  1765. MODBIT(term.mode, set, MODE_BRCKTPASTE);
  1766. break;
  1767. /* Not implemented mouse modes. See comments there. */
  1768. case 1001: /* mouse highlight mode; can hang the
  1769. terminal by design when implemented. */
  1770. case 1005: /* UTF-8 mouse mode; will confuse
  1771. applications not supporting UTF-8
  1772. and luit. */
  1773. case 1015: /* urxvt mangled mouse mode; incompatible
  1774. and can be mistaken for other control
  1775. codes. */
  1776. default:
  1777. fprintf(stderr,
  1778. "erresc: unknown private set/reset mode %d\n",
  1779. *args);
  1780. break;
  1781. }
  1782. } else {
  1783. switch(*args) {
  1784. case 0: /* Error (IGNORED) */
  1785. break;
  1786. case 2: /* KAM -- keyboard action */
  1787. MODBIT(term.mode, set, MODE_KBDLOCK);
  1788. break;
  1789. case 4: /* IRM -- Insertion-replacement */
  1790. MODBIT(term.mode, set, MODE_INSERT);
  1791. break;
  1792. case 12: /* SRM -- Send/Receive */
  1793. MODBIT(term.mode, !set, MODE_ECHO);
  1794. break;
  1795. case 20: /* LNM -- Linefeed/new line */
  1796. MODBIT(term.mode, set, MODE_CRLF);
  1797. break;
  1798. default:
  1799. fprintf(stderr,
  1800. "erresc: unknown set/reset mode %d\n",
  1801. *args);
  1802. break;
  1803. }
  1804. }
  1805. }
  1806. }
  1807. void
  1808. csihandle(void) {
  1809. char buf[40];
  1810. int len;
  1811. switch(csiescseq.mode[0]) {
  1812. default:
  1813. unknown:
  1814. fprintf(stderr, "erresc: unknown csi ");
  1815. csidump();
  1816. /* die(""); */
  1817. break;
  1818. case '@': /* ICH -- Insert <n> blank char */
  1819. DEFAULT(csiescseq.arg[0], 1);
  1820. tinsertblank(csiescseq.arg[0]);
  1821. break;
  1822. case 'A': /* CUU -- Cursor <n> Up */
  1823. DEFAULT(csiescseq.arg[0], 1);
  1824. tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
  1825. break;
  1826. case 'B': /* CUD -- Cursor <n> Down */
  1827. case 'e': /* VPR --Cursor <n> Down */
  1828. DEFAULT(csiescseq.arg[0], 1);
  1829. tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
  1830. break;
  1831. case 'i': /* MC -- Media Copy */
  1832. switch(csiescseq.arg[0]) {
  1833. case 0:
  1834. tdump();
  1835. break;
  1836. case 1:
  1837. tdumpline(term.c.y);
  1838. break;
  1839. case 2:
  1840. tdumpsel();
  1841. break;
  1842. case 4:
  1843. term.mode &= ~MODE_PRINT;
  1844. break;
  1845. case 5:
  1846. term.mode |= MODE_PRINT;
  1847. break;
  1848. }
  1849. break;
  1850. case 'c': /* DA -- Device Attributes */
  1851. if(csiescseq.arg[0] == 0)
  1852. ttywrite(vtiden, sizeof(vtiden) - 1);
  1853. break;
  1854. case 'C': /* CUF -- Cursor <n> Forward */
  1855. case 'a': /* HPR -- Cursor <n> Forward */
  1856. DEFAULT(csiescseq.arg[0], 1);
  1857. tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
  1858. break;
  1859. case 'D': /* CUB -- Cursor <n> Backward */
  1860. DEFAULT(csiescseq.arg[0], 1);
  1861. tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
  1862. break;
  1863. case 'E': /* CNL -- Cursor <n> Down and first col */
  1864. DEFAULT(csiescseq.arg[0], 1);
  1865. tmoveto(0, term.c.y+csiescseq.arg[0]);
  1866. break;
  1867. case 'F': /* CPL -- Cursor <n> Up and first col */
  1868. DEFAULT(csiescseq.arg[0], 1);
  1869. tmoveto(0, term.c.y-csiescseq.arg[0]);
  1870. break;
  1871. case 'g': /* TBC -- Tabulation clear */
  1872. switch(csiescseq.arg[0]) {
  1873. case 0: /* clear current tab stop */
  1874. term.tabs[term.c.x] = 0;
  1875. break;
  1876. case 3: /* clear all the tabs */
  1877. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  1878. break;
  1879. default:
  1880. goto unknown;
  1881. }
  1882. break;
  1883. case 'G': /* CHA -- Move to <col> */
  1884. case '`': /* HPA */
  1885. DEFAULT(csiescseq.arg[0], 1);
  1886. tmoveto(csiescseq.arg[0]-1, term.c.y);
  1887. break;
  1888. case 'H': /* CUP -- Move to <row> <col> */
  1889. case 'f': /* HVP */
  1890. DEFAULT(csiescseq.arg[0], 1);
  1891. DEFAULT(csiescseq.arg[1], 1);
  1892. tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
  1893. break;
  1894. case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
  1895. DEFAULT(csiescseq.arg[0], 1);
  1896. tputtab(csiescseq.arg[0]);
  1897. break;
  1898. case 'J': /* ED -- Clear screen */
  1899. selclear(NULL);
  1900. switch(csiescseq.arg[0]) {
  1901. case 0: /* below */
  1902. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1903. if(term.c.y < term.row-1) {
  1904. tclearregion(0, term.c.y+1, term.col-1,
  1905. term.row-1);
  1906. }
  1907. break;
  1908. case 1: /* above */
  1909. if(term.c.y > 1)
  1910. tclearregion(0, 0, term.col-1, term.c.y-1);
  1911. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1912. break;
  1913. case 2: /* all */
  1914. tclearregion(0, 0, term.col-1, term.row-1);
  1915. break;
  1916. default:
  1917. goto unknown;
  1918. }
  1919. break;
  1920. case 'K': /* EL -- Clear line */
  1921. switch(csiescseq.arg[0]) {
  1922. case 0: /* right */
  1923. tclearregion(term.c.x, term.c.y, term.col-1,
  1924. term.c.y);
  1925. break;
  1926. case 1: /* left */
  1927. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1928. break;
  1929. case 2: /* all */
  1930. tclearregion(0, term.c.y, term.col-1, term.c.y);
  1931. break;
  1932. }
  1933. break;
  1934. case 'S': /* SU -- Scroll <n> line up */
  1935. DEFAULT(csiescseq.arg[0], 1);
  1936. tscrollup(term.top, csiescseq.arg[0]);
  1937. break;
  1938. case 'T': /* SD -- Scroll <n> line down */
  1939. DEFAULT(csiescseq.arg[0], 1);
  1940. tscrolldown(term.top, csiescseq.arg[0]);
  1941. break;
  1942. case 'L': /* IL -- Insert <n> blank lines */
  1943. DEFAULT(csiescseq.arg[0], 1);
  1944. tinsertblankline(csiescseq.arg[0]);
  1945. break;
  1946. case 'l': /* RM -- Reset Mode */
  1947. tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
  1948. break;
  1949. case 'M': /* DL -- Delete <n> lines */
  1950. DEFAULT(csiescseq.arg[0], 1);
  1951. tdeleteline(csiescseq.arg[0]);
  1952. break;
  1953. case 'X': /* ECH -- Erase <n> char */
  1954. DEFAULT(csiescseq.arg[0], 1);
  1955. tclearregion(term.c.x, term.c.y,
  1956. term.c.x + csiescseq.arg[0] - 1, term.c.y);
  1957. break;
  1958. case 'P': /* DCH -- Delete <n> char */
  1959. DEFAULT(csiescseq.arg[0], 1);
  1960. tdeletechar(csiescseq.arg[0]);
  1961. break;
  1962. case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
  1963. DEFAULT(csiescseq.arg[0], 1);
  1964. tputtab(-csiescseq.arg[0]);
  1965. break;
  1966. case 'd': /* VPA -- Move to <row> */
  1967. DEFAULT(csiescseq.arg[0], 1);
  1968. tmoveato(term.c.x, csiescseq.arg[0]-1);
  1969. break;
  1970. case 'h': /* SM -- Set terminal mode */
  1971. tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
  1972. break;
  1973. case 'm': /* SGR -- Terminal attribute (color) */
  1974. tsetattr(csiescseq.arg, csiescseq.narg);
  1975. break;
  1976. case 'n': /* DSR – Device Status Report (cursor position) */
  1977. if (csiescseq.arg[0] == 6) {
  1978. len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
  1979. term.c.y+1, term.c.x+1);
  1980. ttywrite(buf, len);
  1981. }
  1982. break;
  1983. case 'r': /* DECSTBM -- Set Scrolling Region */
  1984. if(csiescseq.priv) {
  1985. goto unknown;
  1986. } else {
  1987. DEFAULT(csiescseq.arg[0], 1);
  1988. DEFAULT(csiescseq.arg[1], term.row);
  1989. tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
  1990. tmoveato(0, 0);
  1991. }
  1992. break;
  1993. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  1994. tcursor(CURSOR_SAVE);
  1995. break;
  1996. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  1997. tcursor(CURSOR_LOAD);
  1998. break;
  1999. case ' ':
  2000. switch (csiescseq.mode[1]) {
  2001. case 'q': /* DECSCUSR -- Set Cursor Style */
  2002. DEFAULT(csiescseq.arg[0], 1);
  2003. if (!BETWEEN(csiescseq.arg[0], 0, 6)) {
  2004. goto unknown;
  2005. }
  2006. xw.cursor = csiescseq.arg[0];
  2007. break;
  2008. default:
  2009. goto unknown;
  2010. }
  2011. break;
  2012. }
  2013. }
  2014. void
  2015. csidump(void) {
  2016. int i;
  2017. uint c;
  2018. printf("ESC[");
  2019. for(i = 0; i < csiescseq.len; i++) {
  2020. c = csiescseq.buf[i] & 0xff;
  2021. if(isprint(c)) {
  2022. putchar(c);
  2023. } else if(c == '\n') {
  2024. printf("(\\n)");
  2025. } else if(c == '\r') {
  2026. printf("(\\r)");
  2027. } else if(c == 0x1b) {
  2028. printf("(\\e)");
  2029. } else {
  2030. printf("(%02x)", c);
  2031. }
  2032. }
  2033. putchar('\n');
  2034. }
  2035. void
  2036. csireset(void) {
  2037. memset(&csiescseq, 0, sizeof(csiescseq));
  2038. }
  2039. void
  2040. strhandle(void) {
  2041. char *p = NULL;
  2042. int j, narg, par;
  2043. term.esc &= ~(ESC_STR_END|ESC_STR);
  2044. strparse();
  2045. par = (narg = strescseq.narg) ? atoi(strescseq.args[0]) : 0;
  2046. switch(strescseq.type) {
  2047. case ']': /* OSC -- Operating System Command */
  2048. switch(par) {
  2049. case 0:
  2050. case 1:
  2051. case 2:
  2052. if(narg > 1)
  2053. xsettitle(strescseq.args[1]);
  2054. return;
  2055. case 4: /* color set */
  2056. if(narg < 3)
  2057. break;
  2058. p = strescseq.args[2];
  2059. /* FALLTHROUGH */
  2060. case 104: /* color reset, here p = NULL */
  2061. j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
  2062. if(xsetcolorname(j, p)) {
  2063. fprintf(stderr, "erresc: invalid color %s\n", p);
  2064. } else {
  2065. /*
  2066. * TODO if defaultbg color is changed, borders
  2067. * are dirty
  2068. */
  2069. redraw();
  2070. }
  2071. return;
  2072. }
  2073. break;
  2074. case 'k': /* old title set compatibility */
  2075. xsettitle(strescseq.args[0]);
  2076. return;
  2077. case 'P': /* DCS -- Device Control String */
  2078. case '_': /* APC -- Application Program Command */
  2079. case '^': /* PM -- Privacy Message */
  2080. return;
  2081. }
  2082. fprintf(stderr, "erresc: unknown str ");
  2083. strdump();
  2084. }
  2085. void
  2086. strparse(void) {
  2087. int c;
  2088. char *p = strescseq.buf;
  2089. strescseq.narg = 0;
  2090. strescseq.buf[strescseq.len] = '\0';
  2091. if(*p == '\0')
  2092. return;
  2093. while(strescseq.narg < STR_ARG_SIZ) {
  2094. strescseq.args[strescseq.narg++] = p;
  2095. while((c = *p) != ';' && c != '\0')
  2096. ++p;
  2097. if(c == '\0')
  2098. return;
  2099. *p++ = '\0';
  2100. }
  2101. }
  2102. void
  2103. strdump(void) {
  2104. int i;
  2105. uint c;
  2106. printf("ESC%c", strescseq.type);
  2107. for(i = 0; i < strescseq.len; i++) {
  2108. c = strescseq.buf[i] & 0xff;
  2109. if(c == '\0') {
  2110. return;
  2111. } else if(isprint(c)) {
  2112. putchar(c);
  2113. } else if(c == '\n') {
  2114. printf("(\\n)");
  2115. } else if(c == '\r') {
  2116. printf("(\\r)");
  2117. } else if(c == 0x1b) {
  2118. printf("(\\e)");
  2119. } else {
  2120. printf("(%02x)", c);
  2121. }
  2122. }
  2123. printf("ESC\\\n");
  2124. }
  2125. void
  2126. strreset(void) {
  2127. memset(&strescseq, 0, sizeof(strescseq));
  2128. }
  2129. void
  2130. tprinter(char *s, size_t len) {
  2131. if(iofd != -1 && xwrite(iofd, s, len) < 0) {
  2132. fprintf(stderr, "Error writing in %s:%s\n",
  2133. opt_io, strerror(errno));
  2134. close(iofd);
  2135. iofd = -1;
  2136. }
  2137. }
  2138. void
  2139. toggleprinter(const Arg *arg) {
  2140. term.mode ^= MODE_PRINT;
  2141. }
  2142. void
  2143. printscreen(const Arg *arg) {
  2144. tdump();
  2145. }
  2146. void
  2147. printsel(const Arg *arg) {
  2148. tdumpsel();
  2149. }
  2150. void
  2151. tdumpsel(void) {
  2152. char *ptr;
  2153. if((ptr = getsel())) {
  2154. tprinter(ptr, strlen(ptr));
  2155. free(ptr);
  2156. }
  2157. }
  2158. void
  2159. tdumpline(int n) {
  2160. char buf[UTF_SIZ];
  2161. Glyph *bp, *end;
  2162. bp = &term.line[n][0];
  2163. end = &bp[MIN(tlinelen(n), term.col) - 1];
  2164. if(bp != end || bp->u != ' ') {
  2165. for( ;bp <= end; ++bp)
  2166. tprinter(buf, utf8encode(bp->u, buf));
  2167. }
  2168. tprinter("\n", 1);
  2169. }
  2170. void
  2171. tdump(void) {
  2172. int i;
  2173. for(i = 0; i < term.row; ++i)
  2174. tdumpline(i);
  2175. }
  2176. void
  2177. tputtab(int n) {
  2178. uint x = term.c.x;
  2179. if(n > 0) {
  2180. while(x < term.col && n--)
  2181. for(++x; x < term.col && !term.tabs[x]; ++x)
  2182. /* nothing */ ;
  2183. } else if(n < 0) {
  2184. while(x > 0 && n++)
  2185. for(--x; x > 0 && !term.tabs[x]; --x)
  2186. /* nothing */ ;
  2187. }
  2188. term.c.x = LIMIT(x, 0, term.col-1);
  2189. }
  2190. void
  2191. techo(Rune u) {
  2192. if(ISCONTROL(u)) { /* control code */
  2193. if(u & 0x80) {
  2194. u &= 0x7f;
  2195. tputc('^');
  2196. tputc('[');
  2197. } else if(u != '\n' && u != '\r' && u != '\t') {
  2198. u ^= 0x40;
  2199. tputc('^');
  2200. }
  2201. }
  2202. tputc(u);
  2203. }
  2204. void
  2205. tdeftran(char ascii) {
  2206. static char cs[] = "0B";
  2207. static int vcs[] = {CS_GRAPHIC0, CS_USA};
  2208. char *p;
  2209. if((p = strchr(cs, ascii)) == NULL) {
  2210. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  2211. } else {
  2212. term.trantbl[term.icharset] = vcs[p - cs];
  2213. }
  2214. }
  2215. void
  2216. tdectest(char c) {
  2217. int x, y;
  2218. if(c == '8') { /* DEC screen alignment test. */
  2219. for(x = 0; x < term.col; ++x) {
  2220. for(y = 0; y < term.row; ++y)
  2221. tsetchar('E', &term.c.attr, x, y);
  2222. }
  2223. }
  2224. }
  2225. void
  2226. tstrsequence(uchar c) {
  2227. switch (c) {
  2228. case 0x90: /* DCS -- Device Control String */
  2229. c = 'P';
  2230. break;
  2231. case 0x9f: /* APC -- Application Program Command */
  2232. c = '_';
  2233. break;
  2234. case 0x9e: /* PM -- Privacy Message */
  2235. c = '^';
  2236. break;
  2237. case 0x9d: /* OSC -- Operating System Command */
  2238. c = ']';
  2239. break;
  2240. }
  2241. strreset();
  2242. strescseq.type = c;
  2243. term.esc |= ESC_STR;
  2244. }
  2245. void
  2246. tcontrolcode(uchar ascii) {
  2247. switch(ascii) {
  2248. case '\t': /* HT */
  2249. tputtab(1);
  2250. return;
  2251. case '\b': /* BS */
  2252. tmoveto(term.c.x-1, term.c.y);
  2253. return;
  2254. case '\r': /* CR */
  2255. tmoveto(0, term.c.y);
  2256. return;
  2257. case '\f': /* LF */
  2258. case '\v': /* VT */
  2259. case '\n': /* LF */
  2260. /* go to first col if the mode is set */
  2261. tnewline(IS_SET(MODE_CRLF));
  2262. return;
  2263. case '\a': /* BEL */
  2264. if(term.esc & ESC_STR_END) {
  2265. /* backwards compatibility to xterm */
  2266. strhandle();
  2267. } else {
  2268. if(!(xw.state & WIN_FOCUSED))
  2269. xseturgency(1);
  2270. if (bellvolume)
  2271. XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
  2272. }
  2273. break;
  2274. case '\033': /* ESC */
  2275. csireset();
  2276. term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
  2277. term.esc |= ESC_START;
  2278. return;
  2279. case '\016': /* SO (LS1 -- Locking shift 1) */
  2280. case '\017': /* SI (LS0 -- Locking shift 0) */
  2281. term.charset = 1 - (ascii - '\016');
  2282. return;
  2283. case '\032': /* SUB */
  2284. tsetchar('?', &term.c.attr, term.c.x, term.c.y);
  2285. case '\030': /* CAN */
  2286. csireset();
  2287. break;
  2288. case '\005': /* ENQ (IGNORED) */
  2289. case '\000': /* NUL (IGNORED) */
  2290. case '\021': /* XON (IGNORED) */
  2291. case '\023': /* XOFF (IGNORED) */
  2292. case 0177: /* DEL (IGNORED) */
  2293. return;
  2294. case 0x84: /* TODO: IND */
  2295. break;
  2296. case 0x85: /* NEL -- Next line */
  2297. tnewline(1); /* always go to first col */
  2298. break;
  2299. case 0x88: /* HTS -- Horizontal tab stop */
  2300. term.tabs[term.c.x] = 1;
  2301. break;
  2302. case 0x8d: /* TODO: RI */
  2303. case 0x8e: /* TODO: SS2 */
  2304. case 0x8f: /* TODO: SS3 */
  2305. case 0x98: /* TODO: SOS */
  2306. break;
  2307. case 0x9a: /* DECID -- Identify Terminal */
  2308. ttywrite(vtiden, sizeof(vtiden) - 1);
  2309. break;
  2310. case 0x9b: /* TODO: CSI */
  2311. case 0x9c: /* TODO: ST */
  2312. break;
  2313. case 0x90: /* DCS -- Device Control String */
  2314. case 0x9f: /* APC -- Application Program Command */
  2315. case 0x9e: /* PM -- Privacy Message */
  2316. case 0x9d: /* OSC -- Operating System Command */
  2317. tstrsequence(ascii);
  2318. return;
  2319. }
  2320. /* only CAN, SUB, \a and C1 chars interrupt a sequence */
  2321. term.esc &= ~(ESC_STR_END|ESC_STR);
  2322. }
  2323. /*
  2324. * returns 1 when the sequence is finished and it hasn't to read
  2325. * more characters for this sequence, otherwise 0
  2326. */
  2327. int
  2328. eschandle(uchar ascii) {
  2329. switch(ascii) {
  2330. case '[':
  2331. term.esc |= ESC_CSI;
  2332. return 0;
  2333. case '#':
  2334. term.esc |= ESC_TEST;
  2335. return 0;
  2336. case 'P': /* DCS -- Device Control String */
  2337. case '_': /* APC -- Application Program Command */
  2338. case '^': /* PM -- Privacy Message */
  2339. case ']': /* OSC -- Operating System Command */
  2340. case 'k': /* old title set compatibility */
  2341. tstrsequence(ascii);
  2342. return 0;
  2343. case 'n': /* LS2 -- Locking shift 2 */
  2344. case 'o': /* LS3 -- Locking shift 3 */
  2345. term.charset = 2 + (ascii - 'n');
  2346. break;
  2347. case '(': /* GZD4 -- set primary charset G0 */
  2348. case ')': /* G1D4 -- set secondary charset G1 */
  2349. case '*': /* G2D4 -- set tertiary charset G2 */
  2350. case '+': /* G3D4 -- set quaternary charset G3 */
  2351. term.icharset = ascii - '(';
  2352. term.esc |= ESC_ALTCHARSET;
  2353. return 0;
  2354. case 'D': /* IND -- Linefeed */
  2355. if(term.c.y == term.bot) {
  2356. tscrollup(term.top, 1);
  2357. } else {
  2358. tmoveto(term.c.x, term.c.y+1);
  2359. }
  2360. break;
  2361. case 'E': /* NEL -- Next line */
  2362. tnewline(1); /* always go to first col */
  2363. break;
  2364. case 'H': /* HTS -- Horizontal tab stop */
  2365. term.tabs[term.c.x] = 1;
  2366. break;
  2367. case 'M': /* RI -- Reverse index */
  2368. if(term.c.y == term.top) {
  2369. tscrolldown(term.top, 1);
  2370. } else {
  2371. tmoveto(term.c.x, term.c.y-1);
  2372. }
  2373. break;
  2374. case 'Z': /* DECID -- Identify Terminal */
  2375. ttywrite(vtiden, sizeof(vtiden) - 1);
  2376. break;
  2377. case 'c': /* RIS -- Reset to inital state */
  2378. treset();
  2379. xresettitle();
  2380. xloadcols();
  2381. break;
  2382. case '=': /* DECPAM -- Application keypad */
  2383. term.mode |= MODE_APPKEYPAD;
  2384. break;
  2385. case '>': /* DECPNM -- Normal keypad */
  2386. term.mode &= ~MODE_APPKEYPAD;
  2387. break;
  2388. case '7': /* DECSC -- Save Cursor */
  2389. tcursor(CURSOR_SAVE);
  2390. break;
  2391. case '8': /* DECRC -- Restore Cursor */
  2392. tcursor(CURSOR_LOAD);
  2393. break;
  2394. case '\\': /* ST -- String Terminator */
  2395. if(term.esc & ESC_STR_END)
  2396. strhandle();
  2397. break;
  2398. default:
  2399. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  2400. (uchar) ascii, isprint(ascii)? ascii:'.');
  2401. break;
  2402. }
  2403. return 1;
  2404. }
  2405. void
  2406. tputc(Rune u) {
  2407. char c[UTF_SIZ];
  2408. bool control;
  2409. int width, len;
  2410. Glyph *gp;
  2411. len = utf8encode(u, c);
  2412. if((width = wcwidth(u)) == -1) {
  2413. memcpy(c, "\357\277\275", 4); /* UTF_INVALID */
  2414. width = 1;
  2415. }
  2416. if(IS_SET(MODE_PRINT))
  2417. tprinter(c, len);
  2418. control = ISCONTROL(u);
  2419. /*
  2420. * STR sequence must be checked before anything else
  2421. * because it uses all following characters until it
  2422. * receives a ESC, a SUB, a ST or any other C1 control
  2423. * character.
  2424. */
  2425. if(term.esc & ESC_STR) {
  2426. if(u == '\a' || u == 030 || u == 032 || u == 033 ||
  2427. ISCONTROLC1(u)) {
  2428. term.esc &= ~(ESC_START|ESC_STR);
  2429. term.esc |= ESC_STR_END;
  2430. } else if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
  2431. memmove(&strescseq.buf[strescseq.len], c, len);
  2432. strescseq.len += len;
  2433. return;
  2434. } else {
  2435. /*
  2436. * Here is a bug in terminals. If the user never sends
  2437. * some code to stop the str or esc command, then st
  2438. * will stop responding. But this is better than
  2439. * silently failing with unknown characters. At least
  2440. * then users will report back.
  2441. *
  2442. * In the case users ever get fixed, here is the code:
  2443. */
  2444. /*
  2445. * term.esc = 0;
  2446. * strhandle();
  2447. */
  2448. return;
  2449. }
  2450. }
  2451. /*
  2452. * Actions of control codes must be performed as soon they arrive
  2453. * because they can be embedded inside a control sequence, and
  2454. * they must not cause conflicts with sequences.
  2455. */
  2456. if(control) {
  2457. tcontrolcode(u);
  2458. /*
  2459. * control codes are not shown ever
  2460. */
  2461. return;
  2462. } else if(term.esc & ESC_START) {
  2463. if(term.esc & ESC_CSI) {
  2464. csiescseq.buf[csiescseq.len++] = u;
  2465. if(BETWEEN(u, 0x40, 0x7E)
  2466. || csiescseq.len >= \
  2467. sizeof(csiescseq.buf)-1) {
  2468. term.esc = 0;
  2469. csiparse();
  2470. csihandle();
  2471. }
  2472. return;
  2473. } else if(term.esc & ESC_ALTCHARSET) {
  2474. tdeftran(u);
  2475. } else if(term.esc & ESC_TEST) {
  2476. tdectest(u);
  2477. } else {
  2478. if (!eschandle(u))
  2479. return;
  2480. /* sequence already finished */
  2481. }
  2482. term.esc = 0;
  2483. /*
  2484. * All characters which form part of a sequence are not
  2485. * printed
  2486. */
  2487. return;
  2488. }
  2489. if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
  2490. selclear(NULL);
  2491. gp = &term.line[term.c.y][term.c.x];
  2492. if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
  2493. gp->mode |= ATTR_WRAP;
  2494. tnewline(1);
  2495. gp = &term.line[term.c.y][term.c.x];
  2496. }
  2497. if(IS_SET(MODE_INSERT) && term.c.x+width < term.col)
  2498. memmove(gp+width, gp, (term.col - term.c.x - width) * sizeof(Glyph));
  2499. if(term.c.x+width > term.col) {
  2500. tnewline(1);
  2501. gp = &term.line[term.c.y][term.c.x];
  2502. }
  2503. tsetchar(u, &term.c.attr, term.c.x, term.c.y);
  2504. if(width == 2) {
  2505. gp->mode |= ATTR_WIDE;
  2506. if(term.c.x+1 < term.col) {
  2507. gp[1].u = '\0';
  2508. gp[1].mode = ATTR_WDUMMY;
  2509. }
  2510. }
  2511. if(term.c.x+width < term.col) {
  2512. tmoveto(term.c.x+width, term.c.y);
  2513. } else {
  2514. term.c.state |= CURSOR_WRAPNEXT;
  2515. }
  2516. }
  2517. void
  2518. tresize(int col, int row) {
  2519. int i;
  2520. int minrow = MIN(row, term.row);
  2521. int mincol = MIN(col, term.col);
  2522. bool *bp;
  2523. TCursor c;
  2524. if(col < 1 || row < 1) {
  2525. fprintf(stderr,
  2526. "tresize: error resizing to %dx%d\n", col, row);
  2527. return;
  2528. }
  2529. /*
  2530. * slide screen to keep cursor where we expect it -
  2531. * tscrollup would work here, but we can optimize to
  2532. * memmove because we're freeing the earlier lines
  2533. */
  2534. for(i = 0; i <= term.c.y - row; i++) {
  2535. free(term.line[i]);
  2536. free(term.alt[i]);
  2537. }
  2538. /* ensure that both src and dst are not NULL */
  2539. if (i > 0) {
  2540. memmove(term.line, term.line + i, row * sizeof(Line));
  2541. memmove(term.alt, term.alt + i, row * sizeof(Line));
  2542. }
  2543. for(i += row; i < term.row; i++) {
  2544. free(term.line[i]);
  2545. free(term.alt[i]);
  2546. }
  2547. /* resize to new width */
  2548. term.specbuf = xrealloc(term.specbuf, col * sizeof(XftGlyphFontSpec));
  2549. /* resize to new height */
  2550. term.line = xrealloc(term.line, row * sizeof(Line));
  2551. term.alt = xrealloc(term.alt, row * sizeof(Line));
  2552. term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
  2553. term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
  2554. /* resize each row to new width, zero-pad if needed */
  2555. for(i = 0; i < minrow; i++) {
  2556. term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
  2557. term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
  2558. }
  2559. /* allocate any new rows */
  2560. for(/* i == minrow */; i < row; i++) {
  2561. term.line[i] = xmalloc(col * sizeof(Glyph));
  2562. term.alt[i] = xmalloc(col * sizeof(Glyph));
  2563. }
  2564. if(col > term.col) {
  2565. bp = term.tabs + term.col;
  2566. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  2567. while(--bp > term.tabs && !*bp)
  2568. /* nothing */ ;
  2569. for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
  2570. *bp = 1;
  2571. }
  2572. /* update terminal size */
  2573. term.col = col;
  2574. term.row = row;
  2575. /* reset scrolling region */
  2576. tsetscroll(0, row-1);
  2577. /* make use of the LIMIT in tmoveto */
  2578. tmoveto(term.c.x, term.c.y);
  2579. /* Clearing both screens (it makes dirty all lines) */
  2580. c = term.c;
  2581. for(i = 0; i < 2; i++) {
  2582. if(mincol < col && 0 < minrow) {
  2583. tclearregion(mincol, 0, col - 1, minrow - 1);
  2584. }
  2585. if(0 < col && minrow < row) {
  2586. tclearregion(0, minrow, col - 1, row - 1);
  2587. }
  2588. tswapscreen();
  2589. tcursor(CURSOR_LOAD);
  2590. }
  2591. term.c = c;
  2592. }
  2593. void
  2594. xresize(int col, int row) {
  2595. xw.tw = MAX(1, col * xw.cw);
  2596. xw.th = MAX(1, row * xw.ch);
  2597. XFreePixmap(xw.dpy, xw.buf);
  2598. xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
  2599. DefaultDepth(xw.dpy, xw.scr));
  2600. XftDrawChange(xw.draw, xw.buf);
  2601. xclear(0, 0, xw.w, xw.h);
  2602. }
  2603. ushort
  2604. sixd_to_16bit(int x) {
  2605. return x == 0 ? 0 : 0x3737 + 0x2828 * x;
  2606. }
  2607. bool
  2608. xloadcolor(int i, const char *name, Color *ncolor) {
  2609. XRenderColor color = { .alpha = 0xffff };
  2610. if(!name) {
  2611. if(BETWEEN(i, 16, 255)) { /* 256 color */
  2612. if(i < 6*6*6+16) { /* same colors as xterm */
  2613. color.red = sixd_to_16bit( ((i-16)/36)%6 );
  2614. color.green = sixd_to_16bit( ((i-16)/6) %6 );
  2615. color.blue = sixd_to_16bit( ((i-16)/1) %6 );
  2616. } else { /* greyscale */
  2617. color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
  2618. color.green = color.blue = color.red;
  2619. }
  2620. return XftColorAllocValue(xw.dpy, xw.vis,
  2621. xw.cmap, &color, ncolor);
  2622. } else
  2623. name = colorname[i];
  2624. }
  2625. return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
  2626. }
  2627. void
  2628. xloadcols(void) {
  2629. int i;
  2630. static bool loaded;
  2631. Color *cp;
  2632. if(loaded) {
  2633. for (cp = dc.col; cp < &dc.col[LEN(dc.col)]; ++cp)
  2634. XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
  2635. }
  2636. for(i = 0; i < LEN(dc.col); i++)
  2637. if(!xloadcolor(i, NULL, &dc.col[i])) {
  2638. if(colorname[i])
  2639. die("Could not allocate color '%s'\n", colorname[i]);
  2640. else
  2641. die("Could not allocate color %d\n", i);
  2642. }
  2643. loaded = true;
  2644. }
  2645. int
  2646. xsetcolorname(int x, const char *name) {
  2647. Color ncolor;
  2648. if(!BETWEEN(x, 0, LEN(dc.col)))
  2649. return 1;
  2650. if(!xloadcolor(x, name, &ncolor))
  2651. return 1;
  2652. XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
  2653. dc.col[x] = ncolor;
  2654. return 0;
  2655. }
  2656. void
  2657. xtermclear(int col1, int row1, int col2, int row2) {
  2658. XftDrawRect(xw.draw,
  2659. &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
  2660. borderpx + col1 * xw.cw,
  2661. borderpx + row1 * xw.ch,
  2662. (col2-col1+1) * xw.cw,
  2663. (row2-row1+1) * xw.ch);
  2664. }
  2665. /*
  2666. * Absolute coordinates.
  2667. */
  2668. void
  2669. xclear(int x1, int y1, int x2, int y2) {
  2670. XftDrawRect(xw.draw,
  2671. &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
  2672. x1, y1, x2-x1, y2-y1);
  2673. }
  2674. void
  2675. xhints(void) {
  2676. XClassHint class = {opt_class ? opt_class : termname, termname};
  2677. XWMHints wm = {.flags = InputHint, .input = 1};
  2678. XSizeHints *sizeh = NULL;
  2679. sizeh = XAllocSizeHints();
  2680. sizeh->flags = PSize | PResizeInc | PBaseSize;
  2681. sizeh->height = xw.h;
  2682. sizeh->width = xw.w;
  2683. sizeh->height_inc = xw.ch;
  2684. sizeh->width_inc = xw.cw;
  2685. sizeh->base_height = 2 * borderpx;
  2686. sizeh->base_width = 2 * borderpx;
  2687. if(xw.isfixed == True) {
  2688. sizeh->flags |= PMaxSize | PMinSize;
  2689. sizeh->min_width = sizeh->max_width = xw.w;
  2690. sizeh->min_height = sizeh->max_height = xw.h;
  2691. }
  2692. if(xw.gm & (XValue|YValue)) {
  2693. sizeh->flags |= USPosition | PWinGravity;
  2694. sizeh->x = xw.l;
  2695. sizeh->y = xw.t;
  2696. sizeh->win_gravity = xgeommasktogravity(xw.gm);
  2697. }
  2698. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
  2699. &class);
  2700. XFree(sizeh);
  2701. }
  2702. int
  2703. xgeommasktogravity(int mask) {
  2704. switch(mask & (XNegative|YNegative)) {
  2705. case 0:
  2706. return NorthWestGravity;
  2707. case XNegative:
  2708. return NorthEastGravity;
  2709. case YNegative:
  2710. return SouthWestGravity;
  2711. }
  2712. return SouthEastGravity;
  2713. }
  2714. int
  2715. xloadfont(Font *f, FcPattern *pattern) {
  2716. FcPattern *match;
  2717. FcResult result;
  2718. match = FcFontMatch(NULL, pattern, &result);
  2719. if(!match)
  2720. return 1;
  2721. if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
  2722. FcPatternDestroy(match);
  2723. return 1;
  2724. }
  2725. f->set = NULL;
  2726. f->pattern = FcPatternDuplicate(pattern);
  2727. f->ascent = f->match->ascent;
  2728. f->descent = f->match->descent;
  2729. f->lbearing = 0;
  2730. f->rbearing = f->match->max_advance_width;
  2731. f->height = f->ascent + f->descent;
  2732. f->width = f->lbearing + f->rbearing;
  2733. return 0;
  2734. }
  2735. void
  2736. xloadfonts(char *fontstr, double fontsize) {
  2737. FcPattern *pattern;
  2738. double fontval;
  2739. float ceilf(float);
  2740. if(fontstr[0] == '-') {
  2741. pattern = XftXlfdParse(fontstr, False, False);
  2742. } else {
  2743. pattern = FcNameParse((FcChar8 *)fontstr);
  2744. }
  2745. if(!pattern)
  2746. die("st: can't open font %s\n", fontstr);
  2747. if(fontsize > 1) {
  2748. FcPatternDel(pattern, FC_PIXEL_SIZE);
  2749. FcPatternDel(pattern, FC_SIZE);
  2750. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
  2751. usedfontsize = fontsize;
  2752. } else {
  2753. if(FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
  2754. FcResultMatch) {
  2755. usedfontsize = fontval;
  2756. } else if(FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
  2757. FcResultMatch) {
  2758. usedfontsize = -1;
  2759. } else {
  2760. /*
  2761. * Default font size is 12, if none given. This is to
  2762. * have a known usedfontsize value.
  2763. */
  2764. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
  2765. usedfontsize = 12;
  2766. }
  2767. defaultfontsize = usedfontsize;
  2768. }
  2769. FcConfigSubstitute(0, pattern, FcMatchPattern);
  2770. FcDefaultSubstitute(pattern);
  2771. if(xloadfont(&dc.font, pattern))
  2772. die("st: can't open font %s\n", fontstr);
  2773. if(usedfontsize < 0) {
  2774. FcPatternGetDouble(dc.font.match->pattern,
  2775. FC_PIXEL_SIZE, 0, &fontval);
  2776. usedfontsize = fontval;
  2777. if(fontsize == 0)
  2778. defaultfontsize = fontval;
  2779. }
  2780. /* Setting character width and height. */
  2781. xw.cw = ceilf(dc.font.width * cwscale);
  2782. xw.ch = ceilf(dc.font.height * chscale);
  2783. FcPatternDel(pattern, FC_SLANT);
  2784. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
  2785. if(xloadfont(&dc.ifont, pattern))
  2786. die("st: can't open font %s\n", fontstr);
  2787. FcPatternDel(pattern, FC_WEIGHT);
  2788. FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
  2789. if(xloadfont(&dc.ibfont, pattern))
  2790. die("st: can't open font %s\n", fontstr);
  2791. FcPatternDel(pattern, FC_SLANT);
  2792. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
  2793. if(xloadfont(&dc.bfont, pattern))
  2794. die("st: can't open font %s\n", fontstr);
  2795. FcPatternDestroy(pattern);
  2796. }
  2797. void
  2798. xunloadfont(Font *f) {
  2799. XftFontClose(xw.dpy, f->match);
  2800. FcPatternDestroy(f->pattern);
  2801. if(f->set)
  2802. FcFontSetDestroy(f->set);
  2803. }
  2804. void
  2805. xunloadfonts(void) {
  2806. /* Free the loaded fonts in the font cache. */
  2807. while(frclen > 0)
  2808. XftFontClose(xw.dpy, frc[--frclen].font);
  2809. xunloadfont(&dc.font);
  2810. xunloadfont(&dc.bfont);
  2811. xunloadfont(&dc.ifont);
  2812. xunloadfont(&dc.ibfont);
  2813. }
  2814. void
  2815. xzoom(const Arg *arg) {
  2816. Arg larg;
  2817. larg.f = usedfontsize + arg->f;
  2818. xzoomabs(&larg);
  2819. }
  2820. void
  2821. xzoomabs(const Arg *arg) {
  2822. xunloadfonts();
  2823. xloadfonts(usedfont, arg->f);
  2824. cresize(0, 0);
  2825. redraw();
  2826. xhints();
  2827. }
  2828. void
  2829. xzoomreset(const Arg *arg) {
  2830. Arg larg;
  2831. if(defaultfontsize > 0) {
  2832. larg.f = defaultfontsize;
  2833. xzoomabs(&larg);
  2834. }
  2835. }
  2836. void
  2837. xinit(void) {
  2838. XGCValues gcvalues;
  2839. Cursor cursor;
  2840. Window parent;
  2841. pid_t thispid = getpid();
  2842. if(!(xw.dpy = XOpenDisplay(NULL)))
  2843. die("Can't open display\n");
  2844. xw.scr = XDefaultScreen(xw.dpy);
  2845. xw.vis = XDefaultVisual(xw.dpy, xw.scr);
  2846. /* font */
  2847. if(!FcInit())
  2848. die("Could not init fontconfig.\n");
  2849. usedfont = (opt_font == NULL)? font : opt_font;
  2850. xloadfonts(usedfont, 0);
  2851. /* colors */
  2852. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  2853. xloadcols();
  2854. /* adjust fixed window geometry */
  2855. xw.w = 2 * borderpx + term.col * xw.cw;
  2856. xw.h = 2 * borderpx + term.row * xw.ch;
  2857. if(xw.gm & XNegative)
  2858. xw.l += DisplayWidth(xw.dpy, xw.scr) - xw.w - 2;
  2859. if(xw.gm & YNegative)
  2860. xw.t += DisplayWidth(xw.dpy, xw.scr) - xw.h - 2;
  2861. /* Events */
  2862. xw.attrs.background_pixel = dc.col[defaultbg].pixel;
  2863. xw.attrs.border_pixel = dc.col[defaultbg].pixel;
  2864. xw.attrs.bit_gravity = NorthWestGravity;
  2865. xw.attrs.event_mask = FocusChangeMask | KeyPressMask
  2866. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  2867. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  2868. xw.attrs.colormap = xw.cmap;
  2869. if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
  2870. parent = XRootWindow(xw.dpy, xw.scr);
  2871. xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
  2872. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  2873. xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
  2874. | CWEventMask | CWColormap, &xw.attrs);
  2875. memset(&gcvalues, 0, sizeof(gcvalues));
  2876. gcvalues.graphics_exposures = False;
  2877. dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
  2878. &gcvalues);
  2879. xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
  2880. DefaultDepth(xw.dpy, xw.scr));
  2881. XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
  2882. XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
  2883. /* Xft rendering context */
  2884. xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
  2885. /* input methods */
  2886. if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  2887. XSetLocaleModifiers("@im=local");
  2888. if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  2889. XSetLocaleModifiers("@im=");
  2890. if((xw.xim = XOpenIM(xw.dpy,
  2891. NULL, NULL, NULL)) == NULL) {
  2892. die("XOpenIM failed. Could not open input"
  2893. " device.\n");
  2894. }
  2895. }
  2896. }
  2897. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  2898. | XIMStatusNothing, XNClientWindow, xw.win,
  2899. XNFocusWindow, xw.win, NULL);
  2900. if(xw.xic == NULL)
  2901. die("XCreateIC failed. Could not obtain input method.\n");
  2902. /* white cursor, black outline */
  2903. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  2904. XDefineCursor(xw.dpy, xw.win, cursor);
  2905. XRecolorCursor(xw.dpy, cursor,
  2906. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  2907. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  2908. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  2909. xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
  2910. xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
  2911. XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
  2912. xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
  2913. XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
  2914. PropModeReplace, (uchar *)&thispid, 1);
  2915. xresettitle();
  2916. XMapWindow(xw.dpy, xw.win);
  2917. xhints();
  2918. XSync(xw.dpy, False);
  2919. }
  2920. int
  2921. xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
  2922. {
  2923. float winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch, xp, yp;
  2924. ushort mode, prevmode = USHRT_MAX;
  2925. Font *font = &dc.font;
  2926. int frcflags = FRC_NORMAL;
  2927. float runewidth = xw.cw;
  2928. Rune rune;
  2929. FT_UInt glyphidx;
  2930. FcResult fcres;
  2931. FcPattern *fcpattern, *fontpattern;
  2932. FcFontSet *fcsets[] = { NULL };
  2933. FcCharSet *fccharset;
  2934. int i, f, numspecs = 0;
  2935. for(i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
  2936. /* Fetch rune and mode for current glyph. */
  2937. rune = glyphs[i].u;
  2938. mode = glyphs[i].mode;
  2939. /* Skip dummy wide-character spacing. */
  2940. if(mode == ATTR_WDUMMY)
  2941. continue;
  2942. /* Determine font for glyph if different from previous glyph. */
  2943. if(prevmode != mode) {
  2944. prevmode = mode;
  2945. font = &dc.font;
  2946. frcflags = FRC_NORMAL;
  2947. runewidth = xw.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
  2948. if((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
  2949. font = &dc.ibfont;
  2950. frcflags = FRC_ITALICBOLD;
  2951. } else if(mode & ATTR_ITALIC) {
  2952. font = &dc.ifont;
  2953. frcflags = FRC_ITALIC;
  2954. } else if(mode & ATTR_BOLD) {
  2955. font = &dc.bfont;
  2956. frcflags = FRC_BOLD;
  2957. }
  2958. yp = winy + font->ascent;
  2959. }
  2960. /* Lookup character index with default font. */
  2961. glyphidx = XftCharIndex(xw.dpy, font->match, rune);
  2962. if(glyphidx) {
  2963. specs[numspecs].font = font->match;
  2964. specs[numspecs].glyph = glyphidx;
  2965. specs[numspecs].x = (short)xp;
  2966. specs[numspecs].y = (short)yp;
  2967. xp += runewidth;
  2968. numspecs++;
  2969. continue;
  2970. }
  2971. /* Fallback on font cache, search the font cache for match. */
  2972. for(f = 0; f < frclen; f++) {
  2973. glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
  2974. /* Everything correct. */
  2975. if(glyphidx && frc[f].flags == frcflags)
  2976. break;
  2977. /* We got a default font for a not found glyph. */
  2978. if(!glyphidx && frc[f].flags == frcflags
  2979. && frc[f].unicodep == rune) {
  2980. break;
  2981. }
  2982. }
  2983. /* Nothing was found. Use fontconfig to find matching font. */
  2984. if(f >= frclen) {
  2985. if(!font->set)
  2986. font->set = FcFontSort(0, font->pattern,
  2987. FcTrue, 0, &fcres);
  2988. fcsets[0] = font->set;
  2989. /*
  2990. * Nothing was found in the cache. Now use
  2991. * some dozen of Fontconfig calls to get the
  2992. * font for one single character.
  2993. *
  2994. * Xft and fontconfig are design failures.
  2995. */
  2996. fcpattern = FcPatternDuplicate(font->pattern);
  2997. fccharset = FcCharSetCreate();
  2998. FcCharSetAddChar(fccharset, rune);
  2999. FcPatternAddCharSet(fcpattern, FC_CHARSET,
  3000. fccharset);
  3001. FcPatternAddBool(fcpattern, FC_SCALABLE,
  3002. FcTrue);
  3003. FcConfigSubstitute(0, fcpattern,
  3004. FcMatchPattern);
  3005. FcDefaultSubstitute(fcpattern);
  3006. fontpattern = FcFontSetMatch(0, fcsets, 1,
  3007. fcpattern, &fcres);
  3008. /*
  3009. * Overwrite or create the new cache entry.
  3010. */
  3011. if(frclen >= LEN(frc)) {
  3012. frclen = LEN(frc) - 1;
  3013. XftFontClose(xw.dpy, frc[frclen].font);
  3014. frc[frclen].unicodep = 0;
  3015. }
  3016. frc[frclen].font = XftFontOpenPattern(xw.dpy,
  3017. fontpattern);
  3018. frc[frclen].flags = frcflags;
  3019. frc[frclen].unicodep = rune;
  3020. glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
  3021. f = frclen;
  3022. frclen++;
  3023. FcPatternDestroy(fcpattern);
  3024. FcCharSetDestroy(fccharset);
  3025. }
  3026. specs[numspecs].font = frc[f].font;
  3027. specs[numspecs].glyph = glyphidx;
  3028. specs[numspecs].x = (short)xp;
  3029. specs[numspecs].y = (short)(winy + frc[f].font->ascent);
  3030. xp += runewidth;
  3031. numspecs++;
  3032. }
  3033. return numspecs;
  3034. }
  3035. void
  3036. xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y) {
  3037. int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
  3038. int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
  3039. width = charlen * xw.cw;
  3040. Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
  3041. XRenderColor colfg, colbg;
  3042. XRectangle r;
  3043. /* Determine foreground and background colors based on mode. */
  3044. if(base.fg == defaultfg) {
  3045. if(base.mode & ATTR_ITALIC)
  3046. base.fg = defaultitalic;
  3047. else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD))
  3048. base.fg = defaultitalic;
  3049. else if(base.mode & ATTR_UNDERLINE)
  3050. base.fg = defaultunderline;
  3051. }
  3052. if(IS_TRUECOL(base.fg)) {
  3053. colfg.alpha = 0xffff;
  3054. colfg.red = TRUERED(base.fg);
  3055. colfg.green = TRUEGREEN(base.fg);
  3056. colfg.blue = TRUEBLUE(base.fg);
  3057. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
  3058. fg = &truefg;
  3059. } else {
  3060. fg = &dc.col[base.fg];
  3061. }
  3062. if(IS_TRUECOL(base.bg)) {
  3063. colbg.alpha = 0xffff;
  3064. colbg.green = TRUEGREEN(base.bg);
  3065. colbg.red = TRUERED(base.bg);
  3066. colbg.blue = TRUEBLUE(base.bg);
  3067. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
  3068. bg = &truebg;
  3069. } else {
  3070. bg = &dc.col[base.bg];
  3071. }
  3072. /* Change basic system colors [0-7] to bright system colors [8-15] */
  3073. if((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
  3074. fg = &dc.col[base.fg + 8];
  3075. if(IS_SET(MODE_REVERSE)) {
  3076. if(fg == &dc.col[defaultfg]) {
  3077. fg = &dc.col[defaultbg];
  3078. } else {
  3079. colfg.red = ~fg->color.red;
  3080. colfg.green = ~fg->color.green;
  3081. colfg.blue = ~fg->color.blue;
  3082. colfg.alpha = fg->color.alpha;
  3083. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
  3084. &revfg);
  3085. fg = &revfg;
  3086. }
  3087. if(bg == &dc.col[defaultbg]) {
  3088. bg = &dc.col[defaultfg];
  3089. } else {
  3090. colbg.red = ~bg->color.red;
  3091. colbg.green = ~bg->color.green;
  3092. colbg.blue = ~bg->color.blue;
  3093. colbg.alpha = bg->color.alpha;
  3094. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
  3095. &revbg);
  3096. bg = &revbg;
  3097. }
  3098. }
  3099. if(base.mode & ATTR_REVERSE) {
  3100. temp = fg;
  3101. fg = bg;
  3102. bg = temp;
  3103. }
  3104. if((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
  3105. colfg.red = fg->color.red / 2;
  3106. colfg.green = fg->color.green / 2;
  3107. colfg.blue = fg->color.blue / 2;
  3108. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
  3109. fg = &revfg;
  3110. }
  3111. if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
  3112. fg = bg;
  3113. if(base.mode & ATTR_INVISIBLE)
  3114. fg = bg;
  3115. /* Intelligent cleaning up of the borders. */
  3116. if(x == 0) {
  3117. xclear(0, (y == 0)? 0 : winy, borderpx,
  3118. winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
  3119. }
  3120. if(x + charlen >= term.col) {
  3121. xclear(winx + width, (y == 0)? 0 : winy, xw.w,
  3122. ((y >= term.row-1)? xw.h : (winy + xw.ch)));
  3123. }
  3124. if(y == 0)
  3125. xclear(winx, 0, winx + width, borderpx);
  3126. if(y == term.row-1)
  3127. xclear(winx, winy + xw.ch, winx + width, xw.h);
  3128. /* Clean up the region we want to draw to. */
  3129. XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
  3130. /* Set the clip region because Xft is sometimes dirty. */
  3131. r.x = 0;
  3132. r.y = 0;
  3133. r.height = xw.ch;
  3134. r.width = width;
  3135. XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
  3136. /* Render the glyphs. */
  3137. XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
  3138. /* Render underline and strikethrough. */
  3139. if(base.mode & ATTR_UNDERLINE) {
  3140. XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
  3141. width, 1);
  3142. }
  3143. if(base.mode & ATTR_STRUCK) {
  3144. XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
  3145. width, 1);
  3146. }
  3147. /* Reset clip to none. */
  3148. XftDrawSetClip(xw.draw, 0);
  3149. }
  3150. void
  3151. xdrawglyph(Glyph g, int x, int y) {
  3152. int numspecs;
  3153. XftGlyphFontSpec spec;
  3154. numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
  3155. xdrawglyphfontspecs(&spec, g, numspecs, x, y);
  3156. }
  3157. void
  3158. xdrawcursor(void) {
  3159. static int oldx = 0, oldy = 0;
  3160. int curx;
  3161. Glyph g = {' ', ATTR_NULL, defaultbg, defaultcs};
  3162. LIMIT(oldx, 0, term.col-1);
  3163. LIMIT(oldy, 0, term.row-1);
  3164. curx = term.c.x;
  3165. /* adjust position if in dummy */
  3166. if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
  3167. oldx--;
  3168. if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
  3169. curx--;
  3170. g.u = term.line[term.c.y][term.c.x].u;
  3171. /* remove the old cursor */
  3172. xdrawglyph(term.line[oldy][oldx], oldx, oldy);
  3173. if(IS_SET(MODE_HIDE))
  3174. return;
  3175. /* draw the new one */
  3176. if(xw.state & WIN_FOCUSED) {
  3177. switch (xw.cursor) {
  3178. case 0: /* Blinking Block */
  3179. case 1: /* Blinking Block (Default) */
  3180. case 2: /* Steady Block */
  3181. if(IS_SET(MODE_REVERSE)) {
  3182. g.mode |= ATTR_REVERSE;
  3183. g.fg = defaultcs;
  3184. g.bg = defaultfg;
  3185. }
  3186. g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
  3187. xdrawglyph(g, term.c.x, term.c.y);
  3188. break;
  3189. case 3: /* Blinking Underline */
  3190. case 4: /* Steady Underline */
  3191. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3192. borderpx + curx * xw.cw,
  3193. borderpx + (term.c.y + 1) * xw.ch - cursorthickness,
  3194. xw.cw, cursorthickness);
  3195. break;
  3196. case 5: /* Blinking bar */
  3197. case 6: /* Steady bar */
  3198. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3199. borderpx + curx * xw.cw,
  3200. borderpx + term.c.y * xw.ch,
  3201. cursorthickness, xw.ch);
  3202. break;
  3203. }
  3204. } else {
  3205. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3206. borderpx + curx * xw.cw,
  3207. borderpx + term.c.y * xw.ch,
  3208. xw.cw - 1, 1);
  3209. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3210. borderpx + curx * xw.cw,
  3211. borderpx + term.c.y * xw.ch,
  3212. 1, xw.ch - 1);
  3213. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3214. borderpx + (curx + 1) * xw.cw - 1,
  3215. borderpx + term.c.y * xw.ch,
  3216. 1, xw.ch - 1);
  3217. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3218. borderpx + curx * xw.cw,
  3219. borderpx + (term.c.y + 1) * xw.ch - 1,
  3220. xw.cw, 1);
  3221. }
  3222. oldx = curx, oldy = term.c.y;
  3223. }
  3224. void
  3225. xsettitle(char *p) {
  3226. XTextProperty prop;
  3227. Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
  3228. &prop);
  3229. XSetWMName(xw.dpy, xw.win, &prop);
  3230. XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
  3231. XFree(prop.value);
  3232. }
  3233. void
  3234. xresettitle(void) {
  3235. xsettitle(opt_title ? opt_title : "st");
  3236. }
  3237. void
  3238. redraw(void) {
  3239. tfulldirt();
  3240. draw();
  3241. }
  3242. void
  3243. draw(void) {
  3244. drawregion(0, 0, term.col, term.row);
  3245. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
  3246. xw.h, 0, 0);
  3247. XSetForeground(xw.dpy, dc.gc,
  3248. dc.col[IS_SET(MODE_REVERSE)?
  3249. defaultfg : defaultbg].pixel);
  3250. }
  3251. void
  3252. drawregion(int x1, int y1, int x2, int y2) {
  3253. int i, x, y, ox, numspecs;
  3254. Glyph base, new;
  3255. XftGlyphFontSpec* specs;
  3256. bool ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
  3257. if(!(xw.state & WIN_VISIBLE))
  3258. return;
  3259. for(y = y1; y < y2; y++) {
  3260. if(!term.dirty[y])
  3261. continue;
  3262. xtermclear(0, y, term.col, y);
  3263. term.dirty[y] = 0;
  3264. specs = term.specbuf;
  3265. numspecs = xmakeglyphfontspecs(specs, &term.line[y][x1], x2 - x1, x1, y);
  3266. i = ox = 0;
  3267. for(x = x1; x < x2 && i < numspecs; x++) {
  3268. new = term.line[y][x];
  3269. if(new.mode == ATTR_WDUMMY)
  3270. continue;
  3271. if(ena_sel && selected(x, y))
  3272. new.mode ^= ATTR_REVERSE;
  3273. if(i > 0 && ATTRCMP(base, new)) {
  3274. xdrawglyphfontspecs(specs, base, i, ox, y);
  3275. specs += i;
  3276. numspecs -= i;
  3277. i = 0;
  3278. }
  3279. if(i == 0) {
  3280. ox = x;
  3281. base = new;
  3282. }
  3283. i++;
  3284. }
  3285. if(i > 0)
  3286. xdrawglyphfontspecs(specs, base, i, ox, y);
  3287. }
  3288. xdrawcursor();
  3289. }
  3290. void
  3291. expose(XEvent *ev) {
  3292. redraw();
  3293. }
  3294. void
  3295. visibility(XEvent *ev) {
  3296. XVisibilityEvent *e = &ev->xvisibility;
  3297. MODBIT(xw.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
  3298. }
  3299. void
  3300. unmap(XEvent *ev) {
  3301. xw.state &= ~WIN_VISIBLE;
  3302. }
  3303. void
  3304. xsetpointermotion(int set) {
  3305. MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
  3306. XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
  3307. }
  3308. void
  3309. xseturgency(int add) {
  3310. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  3311. MODBIT(h->flags, add, XUrgencyHint);
  3312. XSetWMHints(xw.dpy, xw.win, h);
  3313. XFree(h);
  3314. }
  3315. void
  3316. focus(XEvent *ev) {
  3317. XFocusChangeEvent *e = &ev->xfocus;
  3318. if(e->mode == NotifyGrab)
  3319. return;
  3320. if(ev->type == FocusIn) {
  3321. XSetICFocus(xw.xic);
  3322. xw.state |= WIN_FOCUSED;
  3323. xseturgency(0);
  3324. if(IS_SET(MODE_FOCUS))
  3325. ttywrite("\033[I", 3);
  3326. } else {
  3327. XUnsetICFocus(xw.xic);
  3328. xw.state &= ~WIN_FOCUSED;
  3329. if(IS_SET(MODE_FOCUS))
  3330. ttywrite("\033[O", 3);
  3331. }
  3332. }
  3333. bool
  3334. match(uint mask, uint state) {
  3335. return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
  3336. }
  3337. void
  3338. numlock(const Arg *dummy) {
  3339. term.numlock ^= 1;
  3340. }
  3341. char*
  3342. kmap(KeySym k, uint state) {
  3343. Key *kp;
  3344. int i;
  3345. /* Check for mapped keys out of X11 function keys. */
  3346. for(i = 0; i < LEN(mappedkeys); i++) {
  3347. if(mappedkeys[i] == k)
  3348. break;
  3349. }
  3350. if(i == LEN(mappedkeys)) {
  3351. if((k & 0xFFFF) < 0xFD00)
  3352. return NULL;
  3353. }
  3354. for(kp = key; kp < key + LEN(key); kp++) {
  3355. if(kp->k != k)
  3356. continue;
  3357. if(!match(kp->mask, state))
  3358. continue;
  3359. if(IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
  3360. continue;
  3361. if(term.numlock && kp->appkey == 2)
  3362. continue;
  3363. if(IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
  3364. continue;
  3365. if(IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
  3366. continue;
  3367. return kp->s;
  3368. }
  3369. return NULL;
  3370. }
  3371. void
  3372. kpress(XEvent *ev) {
  3373. XKeyEvent *e = &ev->xkey;
  3374. KeySym ksym;
  3375. char buf[32], *customkey;
  3376. int len;
  3377. Rune c;
  3378. Status status;
  3379. Shortcut *bp;
  3380. if(IS_SET(MODE_KBDLOCK))
  3381. return;
  3382. len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
  3383. /* 1. shortcuts */
  3384. for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
  3385. if(ksym == bp->keysym && match(bp->mod, e->state)) {
  3386. bp->func(&(bp->arg));
  3387. return;
  3388. }
  3389. }
  3390. /* 2. custom keys from config.h */
  3391. if((customkey = kmap(ksym, e->state))) {
  3392. ttysend(customkey, strlen(customkey));
  3393. return;
  3394. }
  3395. /* 3. composed string from input method */
  3396. if(len == 0)
  3397. return;
  3398. if(len == 1 && e->state & Mod1Mask) {
  3399. if(IS_SET(MODE_8BIT)) {
  3400. if(*buf < 0177) {
  3401. c = *buf | 0x80;
  3402. len = utf8encode(c, buf);
  3403. }
  3404. } else {
  3405. buf[1] = buf[0];
  3406. buf[0] = '\033';
  3407. len = 2;
  3408. }
  3409. }
  3410. ttysend(buf, len);
  3411. }
  3412. void
  3413. cmessage(XEvent *e) {
  3414. /*
  3415. * See xembed specs
  3416. * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
  3417. */
  3418. if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  3419. if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  3420. xw.state |= WIN_FOCUSED;
  3421. xseturgency(0);
  3422. } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  3423. xw.state &= ~WIN_FOCUSED;
  3424. }
  3425. } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
  3426. /* Send SIGHUP to shell */
  3427. kill(pid, SIGHUP);
  3428. exit(EXIT_SUCCESS);
  3429. }
  3430. }
  3431. void
  3432. cresize(int width, int height) {
  3433. int col, row;
  3434. if(width != 0)
  3435. xw.w = width;
  3436. if(height != 0)
  3437. xw.h = height;
  3438. col = (xw.w - 2 * borderpx) / xw.cw;
  3439. row = (xw.h - 2 * borderpx) / xw.ch;
  3440. tresize(col, row);
  3441. xresize(col, row);
  3442. ttyresize();
  3443. }
  3444. void
  3445. resize(XEvent *e) {
  3446. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  3447. return;
  3448. cresize(e->xconfigure.width, e->xconfigure.height);
  3449. }
  3450. void
  3451. run(void) {
  3452. XEvent ev;
  3453. int w = xw.w, h = xw.h;
  3454. fd_set rfd;
  3455. int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
  3456. struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
  3457. long deltatime;
  3458. /* Waiting for window mapping */
  3459. do {
  3460. XNextEvent(xw.dpy, &ev);
  3461. if(ev.type == ConfigureNotify) {
  3462. w = ev.xconfigure.width;
  3463. h = ev.xconfigure.height;
  3464. }
  3465. } while(ev.type != MapNotify);
  3466. ttynew();
  3467. cresize(w, h);
  3468. clock_gettime(CLOCK_MONOTONIC, &last);
  3469. lastblink = last;
  3470. for(xev = actionfps;;) {
  3471. FD_ZERO(&rfd);
  3472. FD_SET(cmdfd, &rfd);
  3473. FD_SET(xfd, &rfd);
  3474. if(pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
  3475. if(errno == EINTR)
  3476. continue;
  3477. die("select failed: %s\n", strerror(errno));
  3478. }
  3479. if(FD_ISSET(cmdfd, &rfd)) {
  3480. ttyread();
  3481. if(blinktimeout) {
  3482. blinkset = tattrset(ATTR_BLINK);
  3483. if(!blinkset)
  3484. MODBIT(term.mode, 0, MODE_BLINK);
  3485. }
  3486. }
  3487. if(FD_ISSET(xfd, &rfd))
  3488. xev = actionfps;
  3489. clock_gettime(CLOCK_MONOTONIC, &now);
  3490. drawtimeout.tv_sec = 0;
  3491. drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
  3492. tv = &drawtimeout;
  3493. dodraw = 0;
  3494. if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
  3495. tsetdirtattr(ATTR_BLINK);
  3496. term.mode ^= MODE_BLINK;
  3497. lastblink = now;
  3498. dodraw = 1;
  3499. }
  3500. deltatime = TIMEDIFF(now, last);
  3501. if(deltatime > 1000 / (xev ? xfps : actionfps)) {
  3502. dodraw = 1;
  3503. last = now;
  3504. }
  3505. if(dodraw) {
  3506. while(XPending(xw.dpy)) {
  3507. XNextEvent(xw.dpy, &ev);
  3508. if(XFilterEvent(&ev, None))
  3509. continue;
  3510. if(handler[ev.type])
  3511. (handler[ev.type])(&ev);
  3512. }
  3513. draw();
  3514. XFlush(xw.dpy);
  3515. if(xev && !FD_ISSET(xfd, &rfd))
  3516. xev--;
  3517. if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
  3518. if(blinkset) {
  3519. if(TIMEDIFF(now, lastblink) \
  3520. > blinktimeout) {
  3521. drawtimeout.tv_nsec = 1000;
  3522. } else {
  3523. drawtimeout.tv_nsec = (1E6 * \
  3524. (blinktimeout - \
  3525. TIMEDIFF(now,
  3526. lastblink)));
  3527. }
  3528. drawtimeout.tv_sec = \
  3529. drawtimeout.tv_nsec / 1E9;
  3530. drawtimeout.tv_nsec %= (long)1E9;
  3531. } else {
  3532. tv = NULL;
  3533. }
  3534. }
  3535. }
  3536. }
  3537. }
  3538. void
  3539. usage(void) {
  3540. die("%s " VERSION " (c) 2010-2015 st engineers\n"
  3541. "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]\n"
  3542. " [-i] [-t title] [-w windowid] [-e command ...] [command ...]\n"
  3543. " st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]\n"
  3544. " [-i] [-t title] [-w windowid] [-l line] [stty_args ...]\n",
  3545. argv0);
  3546. }
  3547. int
  3548. main(int argc, char *argv[]) {
  3549. uint cols = 80, rows = 24;
  3550. xw.l = xw.t = 0;
  3551. xw.isfixed = False;
  3552. xw.cursor = 0;
  3553. ARGBEGIN {
  3554. case 'a':
  3555. allowaltscreen = false;
  3556. break;
  3557. case 'c':
  3558. opt_class = EARGF(usage());
  3559. break;
  3560. case 'e':
  3561. if(argc > 0)
  3562. --argc, ++argv;
  3563. goto run;
  3564. case 'f':
  3565. opt_font = EARGF(usage());
  3566. break;
  3567. case 'g':
  3568. xw.gm = XParseGeometry(EARGF(usage()),
  3569. &xw.l, &xw.t, &cols, &rows);
  3570. break;
  3571. case 'i':
  3572. xw.isfixed = True;
  3573. break;
  3574. case 'o':
  3575. opt_io = EARGF(usage());
  3576. break;
  3577. case 'l':
  3578. opt_line = EARGF(usage());
  3579. break;
  3580. case 't':
  3581. opt_title = EARGF(usage());
  3582. break;
  3583. case 'w':
  3584. opt_embed = EARGF(usage());
  3585. break;
  3586. case 'v':
  3587. default:
  3588. usage();
  3589. } ARGEND;
  3590. run:
  3591. if(argc > 0) {
  3592. /* eat all remaining arguments */
  3593. opt_cmd = argv;
  3594. if(!opt_title && !opt_line)
  3595. opt_title = basename(xstrdup(argv[0]));
  3596. }
  3597. setlocale(LC_CTYPE, "");
  3598. XSetLocaleModifiers("");
  3599. tnew(MAX(cols, 1), MAX(rows, 1));
  3600. xinit();
  3601. selinit();
  3602. run();
  3603. return 0;
  3604. }