Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- ** Change the RGB background color given in the argument in a foreground
- ** color with the same hue.
- */
- /*
- Modifications:
- * check if color values contain non-hex chars, and return default value if so
- * allow color values in shorthand hex triplet form #HHH
- * ensure each color component is between 0 and 255 to avoid #HHHHHHHH output
- * return default color values #000000 (for white background) or #FFFFFF (for
- black background) for all non-hex triplet color values (!)
- * moved whiteFg initialization up so it is ready when jumping to default
- I tried to follow the Fossil coding style guidelines, and I have some open
- questions:
- * is strchr() allowed for hex-digit testing?
- if( strchr("0123456789abcdefABCDEF",zIn[i])==0 ) ...
- * which is the preferred storage format for the default color values, string
- or sqlite3_snprintf() with constant numeric data?
- */
- static const char *bg_to_fg(const char *zIn){
- int nIn; /* length of zIn */
- int i;
- unsigned int x[3];
- unsigned int mx = 0;
- static int whiteFg = -1;
- static char zRes[10];
- /* Initialization moved here so it is ready when jumping to default_fg */
- if( whiteFg<0 ) whiteFg = skin_detail_boolean("white-foreground");
- nIn = strlen( zIn );
- if(( nIn!=7 && nIn!=4 ) || zIn[0]!='#' )
- goto default_fg;
- /* Testing for non-hex chars, is strchr() allowed? */
- for (i=1; i<nIn; i++){
- if(( zIn[i]<'0' || zIn[i]>'9' ) &&
- ( zIn[i]<'a' || zIn[i]>'f' ) &&
- ( zIn[i]<'A' || zIn[i]>'F' ))
- goto default_fg;
- }
- zIn++;
- if ( nIn==4 ){
- for(i=0; i<3; i++){
- x[i] = hex_digit_value(zIn[0])*17;
- zIn++;
- if( x[i]>mx ) mx = x[i];
- }
- }else{
- for(i=0; i<3; i++){
- x[i] = hex_digit_value(zIn[0])*16 + hex_digit_value(zIn[1]);
- zIn += 2;
- if( x[i]>mx ) mx = x[i];
- }
- }
- if( whiteFg ){
- /* Make the color lighter */
- static const unsigned int t = 215;
- if( mx<t ) for(i=0; i<3; i++) x[i] += t - mx;
- }else{
- /* Make the color darker */
- static const unsigned int t = 128;
- if( mx>t ) for(i=0; i<3; i++) x[i] -= mx - t;
- }
- /* Make sure each color component is between 0 and 255 */
- for (i=0; i<3; i++)
- x[i] = x[i]<0 ? 0 : x[i]>255 ? 255 : x[i];
- sqlite3_snprintf(sizeof(zRes),zRes,"#%02x%02x%02x",x[0],x[1],x[2]);
- return zRes;
- default_fg:
- /* By default, set to black for white background, and vice versa */
- if( whiteFg )
- memcpy(zRes,"#FFFFFF",8);
- /* sqlite3_snprintf(sizeof(zRes),zRes,"#%02x%02x%02x",255,255,255); */
- else
- memcpy(zRes,"#000000",8);
- /* sqlite3_snprintf(sizeof(zRes),zRes,"#%02x%02x%02x",0,0,0); */
- return zRes;
- }
Advertisement
Add Comment
Please, Sign In to add comment