Getting current terminal background color
is there any way to retrieve the current background color in the active terminal (xterm/konsole/whatever)? preferably in c.
tnx.
in C it wouldn't be that hard, however it gets difficult when you talk about different WMs...
Basically, you iterate over each top level window (the frame)... but you'd need a way to determin which child of the fram is the application (the title bar, buttons, and possibly status bar are all children as well).
Then you just call a "property get" on the app window...
the main difficulty is going to be different window managers...
Similar Messages
-
In 10.9.1 Calendar, how do you change the "current date background color"? The default is pink.
Hello,
There is no easy way to do this. The only thing I can think of is this.
1) In your calendar template add this.
In the "Day Open Format","Today Open Format","Non-Day Open Format","Weekend Open Format" add id="#DD##MM##YYYY#" to the containing HTML tag, usually a TD. This will give you a way to identify the table cells.
2) Now add some javascript. This will change 1/31/2005 to have a background color of red.
<script>
// Simple crossbrowser function to grab elements on the page
function html_GetElement(pNd){
switch(typeof (pNd)){
case 'string':node = document.getElementById(pNd); break;
case 'object':node = pNd; break;
default:node = null; break;
return node;
// now change the color
html_GetElement("31012005").style.backgroundColor="red";');
</script>
While that works for 1 day you want a range. So, printing the javascript from pl/sql would give you the flexibility to do anything.
Here's a simple example to highlight 1/12/2005 - 1/28/2005.
declare
i number;
begin
htp.p('<script>');
-- This is a simple function to grab elements in the page
-- Same function from above
htp.p(' function html_GetElement(pNd){
switch(typeof (pNd)){
case "string":node = document.getElementById(pNd); break;
case "object":node = pNd; break;
default:node = null; break;
return node;
for i in 12..28 loop
-- build the ID to be passed
htp.p(' html_GetElement("'||i||'012005").style.backgroundColor="red";');
end loop;
htp.p('</script>');
end; -
Is there any way to get the black background color back in fullscreen mode?
The current background color in fullscreen mode is grey and it's distracting. It used to be black. Is there a way to change the color outside of the document boundaries?
AndyboyMac wrote:
The only way you can get themes for your ipod is by a jailbrake, jailbraking is illegal, and yes,, you can downgrade your iOS.
Jailbreaking is actually not illegal due to exemptions in the DMCA documentation (http://en.wikipedia.org/wiki/IOS_jailbreaking#cite_note-22).
I've got no explanation on to why the trusty interface for the old iPod style app was butchered, unfortunately (I think we're all at a loss, besides someone being given too much free reign). I came here to supplement the original question with, another alternative question:
Is there a way, similar to downgrading 3rd party apps, downgrade the Music app or restore the old iPod app as an additonal app? Without jailbreaking?
< Edited By Host > -
How to get the foreground/background color in photoshop.
I want to get the foreground or background color at runtime ( by any action ) in photoshop.
What steps should I follow.For example here is a script I use within Photoshop Actions to save and restore the users foreground and background colors so the action can mess with Photoshops foreground and background colors during its processing.
SaveAndRestoreColors.jsx
/* ======================================================================================
// 2009 John J. McAssey (JJMack) http://www.mouseprints.net/
// This script is supplied as is. It is provided as freeware.
// The author accepts no liability for any problems arising from its use.
// This script is designed to be used by a Photoshop Action twice
// A good pratice to use when creating an actions that use this scipt is for the action
// not to do a save or play some other action between its two useages of this Script.
// The first time this script is used by an action Photoshops Current Forground
// and Background Colors are saved into the document's meta-data Info Instructions field.
// The second time this script used by the action the script retreives what was
// saved in the meta-data during the first usage and these colors are set.
// and the saved data is removed from the document's meta-data Info Instructions field.
// ===================================================================================== */
<javascriptresource>
<about>$$$/JavaScripts/SaveAndRestoreColors/About=JJMack's SaveAndRestoreColors.^r^rCopyright 2009 Mouseprints.^r^rRun twice script utility for action.^rNOTE:Don't play other actions between runs!^r^rFirst Run records Photoshops foreground and background swatch colors.^rSecond Run restores the recorded colors and removes the recording.</about>
<category>JJMack's Action Run Twice Utility</category>
</javascriptresource>
if (app.documents.length > 0) {
if (app.activeDocument.info.instructions.indexOf("<Colorf>") == -1 ){ // no footprint fisrt useage
//alert("first");
// Retreive Document information for Foot Print
saveforeColor = new SolidColor;
saveforeColor.rgb.red = app.foregroundColor.rgb.red;
saveforeColor.rgb.green = app.foregroundColor.rgb.green;
saveforeColor.rgb.blue = app.foregroundColor.rgb.blue;
savebackColor = new SolidColor;
savebackColor.rgb.red = app.backgroundColor.rgb.red;
savebackColor.rgb.green = app.backgroundColor.rgb.green;
savebackColor.rgb.blue = app.backgroundColor.rgb.blue;
// put footprint in metadata info instructions
app.activeDocument.info.instructions = app.activeDocument.info.instructions + "<Colorf>" + saveforeColor.rgb.red + "," + saveforeColor.rgb.green + "," + saveforeColor.rgb.blue + "</Colorf>" + "<Colorb>" + savebackColor.rgb.red + "," + savebackColor.rgb.green + "," + savebackColor.rgb.blue + "</Colorb>";
//alert( "Saved =" + "<Colorf>" + saveforeColor.rgb.red + "," + saveforeColor.rgb.green + "," + saveforeColor.rgb.blue + "</Colorf>" + "<Colorb>" + savebackColor.rgb.red + "," + savebackColor.rgb.green + "," + savebackColor.rgb.blue + "</Colorb>");
else {
//alert("second");
// Retreive saved information
colorfOffset = app.activeDocument.info.instructions.indexOf("<Colorf>") + "<Colorf>".length;
colorfLength = app.activeDocument.info.instructions.indexOf("</Colorf") -colorfOffset;
saveforeColor = app.activeDocument.info.instructions.substr(colorfOffset, colorfLength);
colorbOffset = app.activeDocument.info.instructions.indexOf("<Colorb>") + "<Colorb>".length;
colorbLength = app.activeDocument.info.instructions.indexOf("</Colorb") -colorbOffset;
savebackColor = app.activeDocument.info.instructions.substr(colorbOffset, colorbLength);
//alert("Colorf = " + saveforeColor + " Colorb = " + savebackColor );
// Restore Colors
app.foregroundColor.rgb.red = saveforeColor.substr(0,saveforeColor.indexOf(","));
saveforeColor = saveforeColor.substr(saveforeColor.indexOf(",") + 1,saveforeColor.length);
app.foregroundColor.rgb.green = saveforeColor.substr(0,saveforeColor.indexOf(","));
saveforeColor = saveforeColor.substr(saveforeColor.indexOf(",") + 1,saveforeColor.length);
app.foregroundColor.rgb.blue = saveforeColor ;
app.backgroundColor.rgb.red = savebackColor.substr(0,savebackColor.indexOf(","));
savebackColor = savebackColor.substr((savebackColor.indexOf(",") + 1),savebackColor.length);
app.backgroundColor.rgb.green = savebackColor.substr(0,savebackColor.indexOf(","));
savebackColor = savebackColor.substr(savebackColor.indexOf(",") + 1,savebackColor.length);
app.backgroundColor.rgb.blue = savebackColor ;
// Remove footprint from metadata info instructions
before = app.activeDocument.info.instructions.substr(0,app.activeDocument.info.instructions.indexO f("<Colorf>"));
afterOffset = app.activeDocument.info.instructions.indexOf("</Colorb>") + "</Colorb>".length;
after = app.activeDocument.info.instructions.substr(afterOffset, app.activeDocument.info.instructions.length - afterOffset);
//alert ("before = " + before + " after = " + after);
app.activeDocument.info.instructions = before + after;
else { alert("You must have at least one open document to run this script!"); } -
Get/read stage background color
hello one and all,
how do you read or get the stage's background color?
then, how do you set the fill color of that stage color to a drawing object under a movieclip symbol?
using flash cs4 and as3.
lucasuse a movieclip or sprite at depth 0 to cover the stage and control its color.
-
How to get secondary tile background color on WP 8.1?
Currently, all secondary tiles are returning background color #7FFFFFFF regardless of color
Hi TaskBasic,
>>all secondary tiles are returning background color #7FFFFFFF regardless of color
We can use the following code to convert HEX color to Color in runtime:
var hexCode = "#7FFFFFFF";
var color = new Color();
color.A = byte.Parse(hexCode.Substring(1, 2), NumberStyles.AllowHexSpecifier);
color.R = byte.Parse(hexCode.Substring(3, 2), NumberStyles.AllowHexSpecifier);
color.G = byte.Parse(hexCode.Substring(5, 2), NumberStyles.AllowHexSpecifier);
color.B = byte.Parse(hexCode.Substring(7, 2), NumberStyles.AllowHexSpecifier);
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
How to change the current item background color
I m working in forms 6.0.
I want to mak the background color of the current item (whatsoever the item name is ) as 'yellow'. How can i do that.How can i accoplish that? I've tried
set_item_property(:system.cursor_item,background_color,'yellow');
in Pre_text_item
set_item_property(:system.cursor_item,background_color,'white');
in post_item_item
at block level
But i failed to do that
anyone to help me plz
Riaz Shahidhi riaz,
i think instead of pre-text-item put the code in when new item instance.or try creating a visual attribute with background color as yellow and attach that using set_item_property in when new item instance or check for help on DISPLAY_ITEM built in in forms help.I think one of these should definitely help u.
bye
Atul -
Set current row background color
during post-query process, if record meets condition,
i would like to set the color of entire line.
thank you
[email protected]Hi Jim,
create a visual_attribute named e.g. PQR and set the desired background color.
In post-query trigger:
declare
currec number := Get_block_property('block1', current_record);
begin
if "condition" then
set_item_instance_property('item1', currec,visual_attribute,'PQR');
set_item_instance_property('item2', currec,visual_attribute,'PQR');
set_item_instance_property('item3', currec,visual_attribute,'PQR');
end if;
end;
Good luck,
Monica -
How do I get a different background color in the dock in Mavericks?
Has anyone figured out how to change the background color in the dock? The default is really bad and hard to read.
dont know how but looking at this video, this guy sems to have a solution
=> http://www.youtube.com/watch?v=TXwGP9hkHDQ&ytsession=1uKskJuFULWJ4S9dtlGhOuS2K1F egefIt4_t4UMOVdnn24KtXByipkEVNKRIm0un6jlloUu8at22J1pboQ56RPHKX0Sp1PkvfCtVKga_f9H NN9n104j5psKQFS4q8yBii2OiaZ8IXqXmGIkXmXs_DD2ypL-Er4kRe2YLnEBIpbv9kNbkFSsNsZu_BXu 8qGqQ7H4WCxq4m3yevxbUhY6G-f-5rWtrERD6o4oCB-OOGs1_BzgpsfxT9JYZBIhx53EgZpsNQEdVvPL USgXhw82EdXYwwpuJs0gLawJV1gWEE2Q
if you look at his dock, it's not silver bright but blue and he add a line before the trash -
How do I get rid of background color in shortdesc
Every time I remove the background color from the short.description paragraph tag, it comes back when I reopen FrameMaker. I don't want any background colors in my short descriptions.
Ah .. FM10 and DITA 1.2 .. too bad, you're in for a bit of a chore.
The 1.2 apps are here .. AdobeFrameMaker10\Structure\xml\DITA_1.2\
Unfortunately, there are lots of them, and it's not immediately clear how to approach things. Opening an XML file in Frame requires a structured application in order to define the valid document model and to apply the proper formatting. The formatting is applied by an EDD, which defines the mapping from elements and associated styles which live in the template (the EDD itself is embedded in the template as well). The structured applications are defined in the structapps.fm file (of which there are two). One of these can be seen when you choose the Structure Tools > Edit Application Definitions file (this lives in the user's "app data" area), but another is at AdobeFrameMaker10\Structure\structapps.fm (this is the "core" structapps file). The two files define the available structure applications, any definitions in the user's file override those in the other file (I'm pretty sure).
So .. when you open an XML file, Frame scans the structapps files for matching doctypes, if only one is found, that app is used. If multiple matching doctypes are found, you are presented with a dialog that lets you choose from the available apps. If you didn't select an app when opening the file, you'll need to look in the structapp files to see which one was used for your file. The root element in your file defines the doctype (as well as the Public ID). If this is a "task" topic, you'd look in the structapp files for matching apps that support the "task" doctype (if you're using DITA 1.2 you'll be looking for a DITA 1.2 task .. I'm not totally clear on how FM differentiates between the two). In my installation the DITA 1.2 definitions are in the core structapps file, but it could be in either place (or both).
Once you locate the structure app definition, it will have nodes that define the Template, the DTD, the ReadWriteRules, and other things. You're just looking for the template though. If you're using a "task", for DITA 1.2 that's likely to be the DITA_1.2_task structure application .. the template is located at ..
$STRUCTDIR\xml\DITA_1.2\app\technicalContent\template\task.template.fm
where "$STRUCTDIR" is the location of the FrameMaker\Structure folder (or possibly defined differently in the maker.ini .. but that's a different issue).
Editing this one file will affect the formatting of future task topics you open. You'll have to do the same thing in the other corresponding topic type templates to affect all of the topics.
In previous versions of Frame, it used the "ditabase" model for authoring and publishing. This encapsulates all of the models in one file making it much easier to maintain. This model is more parallel to the DITA model, but will be a real nightmare for people to customize. I'm not going to begin to try and explain how you'd clone these apps to make your own, although you can read a document written for DITA-FMx and DITA 1.1 that gives you the fundamental process ..
http://docs.leximation.com/dita-fmx/1.1/?ditafmx_cloningtapps.html
I'm hoping that I've explained this correctly .. I'm still trying to wrap my head around it myself.
Cheers?
...scott -
How to get current free background process number
hi,guys:
i have a question: how to get the current free and total background or dialog process number in speicifc server name?
best regards,kevinYou can get those details from SM50 transaction.
You can also use these FM.
TH_GET_WPINFO.
TH_WPINFO. -
Getting a JPanels Background Color?
Hi guys,
Can anyone teach me how to know what background colour a JPanel has?
I tried panel.getBackground(). but no luck so far....
is there another way to achieve this?
thank you very much!getBackground() returns background in RGB constraints.
Since the objects in the Color class eg:
* The color white. In the default sRGB space.
public final static Color white = new Color(255, 255, 255);are pre-defined(named) based on the RGB, one can directly use those objects.
So you won't to get the color directly for the JPanel instead you will get the RGB values.
Hope this helps you. -
Hello Friends,
I am facing some problem in changing the bachgroud color of the selected field in block,
Basically i want to make visible the current field in a record,not the enire record but just the current item.
thanks to all;Create WNII and POST-TEXT-ITEM triggers (block level) with command
Set_Item_Instance_Property(:SYSTEM.CURRENT_ITEM, CURRENT_RECORD, VISUAL_ATTRIBUTE, <VA_NAME>);
Note! Current record VISUAL ATTRIBUTE of block must be <NULL>. -
How do I get rid of background color in a table?
I insert a table and it shows up with a blue background. The properties panel shows no background selected. I changed it to a white background but nothing happened. I made a new class named tableformat, it took all the styles I applied to the class except the background, still blue. Here is the code:
<table width="600" border="1" cellpadding="3">
<tr>
<th scope="col"> </th>
<th scope="col"> </th>
<th scope="col"> </th>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
<p align="left"> </p>
<p> </p>
Thank you in advance for any help anyone can give me.Here is code for the page with the table:
<title>Biological Sciences - Home</title>
<style type="text/css">
</style>
<link href="CSS/Style.css" rel="stylesheet" type="text/css" />
<script src="SpryAssets/SpryMenuBar.js" type="text/javascript"></script>
<link href="SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<div id="header"><img src="images/header.jpg" width="900" height="200" alt="Biology Department" /></div>
<div id="MainNav">
<ul id="MenuBar1" class="MenuBarHorizontal">
<li><a href="welcome.html">Welcome</a> </li>
<li><a href="faculty.html">Faculty/Staff</a></li>
<li><a class="MenuBarItemSubmenu" href="programs.html">Programs</a>
<ul>
<li><a class="MenuBarItemSubmenu" href="#">Item 3.1</a>
<ul>
<li><a href="#">Item 3.1.1</a></li>
<li><a href="#">Item 3.1.2</a></li>
</ul>
</li>
<li><a href="#">Item 3.2</a></li>
<li><a href="#">Item 3.3</a></li>
</ul>
</li>
<li><a href="resources.html">Student Resources</a></li>
<li><a href="#">Clubs</a></li>
<li><a href="#">COC Links</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>
<div id="content">
<p>Content for id "content" Goes Here</p>
<table width="600" border="1" cellpadding="3">
<tr>
<th scope="col"> </th>
<th scope="col"> </th>
<th scope="col"> </th>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
<p> </p>
<p> </p>
</div>
<div id="footer"><img src="images/footer.jpg" width="772" height="297" alt="Aliso Lab" /></div>
Content for id "wrapper" Goes Here</div>
<script type="text/javascript">
var MenuBar1 = new Spry.Widget.MenuBar("MenuBar1", {imgDown:"SpryAssets/SpryMenuBarDownHover.gif", imgRight:"SpryAssets/SpryMenuBarRightHover.gif"});
</script>
</body>
</html> -
RGB values of current terminal color settings?
The colors displayed for different ANSI escape codes are configurable via .Xdefaults or directly on the command line via other ANSI escapes.
Is there any way to dump the current values from a terminal? For example, given the ANSI escape code "\033[31m", I would like to know the current RGB values used to display it.
Obviously this will depend on the terminal (e.g. urxvt can have different settings from xterm), but I'm hoping that there is some obscure tool to do this.Coincidentally, I recently wrote a script to do exactly this: query all the color values from a terminal emulator and show them in a nice table. I was planning to make a thread for this, but this thread is perfect. In my opinion, the strategy of querying colors from the terminal itself is superior (when it is supported by the terminal) to mucking around with .Xresources, .Xdefaults, or "xrdb --query", which only work in pretty limited situations. The drawbacks of my approach are: (1) it can be challenging to make the same code work on different terminal emulators, and (2) you have to use it from the terminal you want to query, and not from within a screen or tmux session. (I think there may be partial workarounds for (2), but I haven't implemented them.) I've tested my code on a number of terminals, and the upshot is that xterm and urxvt are supported flawlessly, and VTE-based terminals like gnome-terminal and XFCE's "Terminal" are almost fully supported. (I wasn't able to query the default foreground and background colors, but everything else seems to work.) Most other X terminals don't seem to support this method of querying color values.
Here's an example of what the script produces:
Obviously, that's a heavily formatted table, but I think the code has enough comments that you can take what you need from it. It works under python 3 or python 2.7.
Edit: This version is superseded by the one in post #27, which is structured better. I'm leaving this here since some of the future replies refer to it.
#!/usr/bin/python
This is a Python script to show off your terminal ANSI colors (or more
colors, if your terminal has them). It works on both Python 2.7 and
Python 3.
This script must be run from the terminal whose colors you want to
showcase. Not all terminal types are supported (see below). At the
very minimum, 16-color support is required.
Fully supported terminals:
xterm
urxvt
For these terminals, this script can show a color table with correct RGB
values for each color. It queries the RGB values from the terminal
itself, so it works even if you change the colors after starting the
terminal.
Mostly supported terminals: pretty much all VTE-based terminals. This
includes:
vte
Terminal (XFCE)
gnome-terminal
terminator
tilda
and many more. These are on "mostly" status because I don't know how to
query their foreground and background colors. Everything else works,
though, albeit with noticeable slowness (which may be beyond this
script's control).
Somewhat supported terminals: pretty much all other X-client terminals
I've tried. These include:
konsole (KDE)
terminology (Enlightenment)
Eterm (Enlightenment)
(etc.)
For these terminals, the script can output a color table just fine, but
without RGB values.
Unsupported terminals:
ajaxterm
Linux virtual console (i.e., basic TTY without X-windows)
Warning: do not run this script on the Linux virtual console unless you
want a garbled TTY! That said, you can still type `tput reset<Enter>'
afterward to get back to a usable console. :-) The situation with
ajaxterm is similar, but not as bad.
If a terminal isn't mentioned here, I probably haven't tried it. Attempt
at your own risk!
Note regarding screen/tmux: this script can theoretically be run from a
screen or tmux session, but you will not get any RGB values in the
output (indeed, a screen session can be opened on multiple terminals
simultaneously, so there typically isn't a well defined color value for
a given index). However, it's interesting to observe that screen and
tmux emulate a 256 color terminal independently of the terminal(s)
to which they are attached, which is very apparent if you run the script
with 256-color output on a screen session attached to a terminal with 8-
or 16-color terminfo (or with $TERM set to such).
This code is licensed under the terms of the GNU General Public License:
http://www.gnu.org/licenses/gpl-3.0.html
and with absolutely no warranty. All use is strictly at your own risk.
from sys import stdin, stdout, stderr
import re
import select
import termios
from collections import defaultdict
from argparse import (ArgumentParser, ArgumentError)
# Operating system command
osc = "\033]"
# String terminator
# ("\033\\" is another option, but "\007" seems to be understood by
# more terminals. Terminology, for example, doesn't seem to like
# "\033\\".)
st = "\007"
# Control sequence introducer
csi = "\033["
# ANSI SGR0
reset = csi + 'm'
# Errors that may be raised by rgb_query
num_errors = 0
class InvalidResponseError(Exception):
The terminal's response couldn't be parsed.
def __init__(self, q, r):
global num_errors
num_errors += 1
Exception.__init__(self, "Couldn't parse response " + repr(r) +
" to query " + repr(q))
class NoResponseError(Exception):
The terminal didn't respond, or we were too impatient.
def __init__(self, q):
global num_errors
num_errors += 1
Exception.__init__(self, "Timeout on query " + repr(q))
# Wrappers for xterm & urxvt operating system controls.
# These codes are all common to xterm and urxvt. Their responses aren't
# always in the same format (xterm generally being more consistent), but
# the regular expression used to parse the responses is general enough
# to work for both.
# Note: none of these functions is remotely thread-safe.
def get_fg(timeout):
Get the terminal's foreground (text) color as a 6-digit
hexadecimal string.
return rgb_query([10], timeout)
def get_bg(timeout):
Get the terminal's background color as a 6-digit hexadecimal
string.
return rgb_query([11], timeout)
def get_color(a, timeout):
Get color a as a 6-digit hexadecimal string.
return rgb_query([4, a], timeout)
def test_fg(timeout):
Return True if the terminal responds to the "get foreground" query
within the time limit and False otherwise.
return test_rgb_query([10], timeout)
def test_bg(timeout):
Return True if the terminal responds to the "get background" query
within the time limit and False otherwise.
return test_rgb_query([11], timeout)
def test_color(timeout):
Return True if the terminal responds to the "get color 0" query
within the time limit and False otherwise.
return test_rgb_query([4, 0], timeout)
def test_rgb_query(q, timeout):
Determine if the terminal supports query q.
Arguments: `q' and `timeout' have the same interpretation as in
rgb_query().
Return: True if the terminal gives a valid response within the
time limit and False otherwise.
This function will not raise InvalidResponseError or
NoResponseError, but any other errors raised by rgb_query will
be propagated.
try:
rgb_query(q, timeout)
return True
except (InvalidResponseError, NoResponseError):
return False
# String to use for color values that couldn't be determined
rgb_placeholder = '??????'
# This is what we expect the terminal's response to a query for a color
# to look like. If we didn't care about urxvt, we could get away with a
# simpler implementation here, since xterm and vte seem to give pretty
# consistent and systematic responses. But I actually use urxvt most of
# the time, so....
ndec = "[0-9]+"
nhex = "[0-9a-fA-F]+"
crgb = ("\033\\]({ndec};)+rgba?:" +
"({nhex})/({nhex})/({nhex})(/({nhex}))?").format(**vars())
re_response = re.compile(crgb)
# The problem I'm attempting to work around with this complicated
# implementation is that if you supply a terminal with a query that it
# does not recognize or does not have a good response to, it will simply
# not respond *at all* rather than signaling the error in any way.
# Moreover, there is a large variation in how long terminals take to
# respond to valid queries, so it's difficult to know whether the
# terminal has decided not to respond at all or it needs more time.
# This is why rgb_query has a user-settable timeout.
P = select.poll()
P.register(stdin.fileno(), select.POLLIN)
def flush_input():
Discard any input that can be read at this moment.
repeat = True
while repeat:
evs = P.poll(0)
if len(evs) > 0:
stdin.read()
repeat = True
else:
repeat = False
def rgb_query(q, timeout=-1):
Query a color-valued terminal parameter.
Arguments:
q: The query code as a sequence of nonnegative integers, i.e.,
[q0, q1, ...] if the escape sequence in pseudo-Python is
"\033]{q0};{q1};...;?\007"
timeout: how long to wait for a response. (negative means
wait indefinitely if necessary)
Return: the color value as a 6-digit hexadecimal string.
Errors:
NoResponseError will be raised if the query times out.
InvalidResponseError will be raised if the terminal's
response can't be parsed.
See
http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
("Operating System Controls") to see the various queries
supported by xterm. Urxvt supports some, but not all, of them,
and has a number of its own (see man -s7 urxvt).
Warning: before calling this function, make sure the terminal is
in noncanonical, non-blocking mode.
query = osc + ';'.join([str(k) for k in q]) + ';?' + st
flush_input()
stdout.write(query)
stdout.flush()
# This is addmittedly flawed, since it assumes the entire response
# will appear in one shot. It seems to work in practice, though.
evs = P.poll(timeout)
if len(evs) == 0:
raise NoResponseError(query)
r = stdin.read()
m = re_response.search(r)
if not m:
raise InvalidResponseError(query, r)
# (possibly overkill, since I've never seen anything but 4-digit RGB
# components in responses from terminals, in which case `nd' is 4
# and `u' is 0xffff, and the following can be simplified as well
# (and parse_component can be eliminated))
nd = len(m.group(2))
u = int('f'*nd, 16)
# An "rgba"-type reply (for urxvt) is apparently actually
# rgba:{alpha}/{alpha * red}/{alpha * green}/{alpha * blue}
# I opt to extract the actual RGB values by eliminating alpha. (In
# other words, the alpha value is discarded completely in the
# reported color value, which is a compromise I make in order to get
# an intuitive and compact output.)
if m.group(5):
# There is an alpha component
alpha = float(int(m.group(2), 16))/u
idx = [3, 4, 6]
else:
# There is no alpha component
alpha = 1.0
idx = [2, 3, 4]
c_fmt = '%0' + ('%d' % nd) + 'x'
components = [int(m.group(i), 16) for i in idx]
t = tuple(parse_component(c_fmt % (c/alpha)) for c in components)
return "%02X%02X%02X" % t
def parse_component(s):
Take a string representation of a hexadecimal integer and transorm
the two most significant digits into an actual integer (or double
the string if it has only one character).
n = len(s)
if n == 1:
s += s
elif n > 2:
s = s[:2]
return int(s, 16)
def test_num_colors(timeout):
Attempt to determine the number of colors we are able to query from
the terminal. timeout is measured in milliseconds and has the same
interpretation as in rgb_query. A larger timeout is safer but will
cause this function to take proportionally more time.
if not test_color(timeout):
return 0
a = 0
b = 1
while test_rgb_query([4, b], timeout):
a = b
b += b
while b - a > 1:
c = (a + b)>>1
if test_rgb_query([4, c], timeout):
a = c
else:
b = c
return b
class ColorDisplay(object):
Class for producing a colored display of terminal RGB values.
def __init__(self, timeout=100, color_level=3, do_query=True):
timeout: same interpretation as in rgb_query. A larger timeout
will be used a small number of times to test the
capabilities of the terminal.
color_level: how much color should be in the output. Use 0 to
suppress all color and 3 or greater for maximum coloredness.
do_query: whether to attempt to query RGB values from the
terminal or just use placeholders everywhere
self.timeout=timeout
self.color_level=color_level
# try getting the rgb value for color 0 to decide whether to
# bother trying to query any more colors.
self.do_query = do_query and test_color(self.timeout*5)
def none_factory():
return None
# colors for highlighting
self.hi = defaultdict(none_factory)
self.hi['['] = 10
self.hi[']'] = 10
self.hi['+'] = 9
self.hi['/'] = 9
for c in '0123456789ABCDEF':
self.hi[c] = 12
def show_ansi(self):
Show the 16 ANSI colors (colors 0-15).
color_order = [0, 1, 3, 2, 6, 4, 5, 7]
names = [' Black ', ' Red ', ' Green ', ' Yellow ',
' Blue ', ' Magenta', ' Cyan ', ' White ']
stdout.write(self.fgcolor('15', 3))
for k in range(8):
a = color_order[k]
stdout.write(names[a])
stdout.write('\n')
stdout.write(self.fgcolor(None, 3))
c = None
for k in range(8):
a = color_order[k]
c = self.hiprint(' [%X/%X] ' % (a, 8 + a), c)
stdout.write('\n')
self.show_color_table([0,8], color_order)
def show_color_cube(self, n):
Show the "RGB cube" (xterm colors 16-231 (256-color) or 16-79
(88-color)). The cube has sides of length 6 or 4 (for 256-color
or 88-color, respectively).
base = {256:6, 88:4}[n]
c = None
c = self.hiprint('[ + ] ', c)
for w in range(base):
c = self.hiprint('[%X] ' % w, c)
stdout.write('\n\n' + self.fgcolor(None, 3))
for u in range(base):
for v in range(base):
stdout.write(' '*v)
x = (u*base + v)*base
self.hiprint(' [%02X] ' % (16 + x))
for w in range(base):
self.show_color(x + w + 16)
stdout.write('\n')
stdout.write('\n\n')
def show_grayscale_ramp(self, end):
Show the "grayscale ramp" (xterm colors 232-255 (256-color) or
80-87 (88-color)).
start = {256:232, 88:80}[end]
n = end - start
vals = [self.get_color(a) for a in range(start, end)]
#stdout.write(reset)
c = None
c = self.hiprint('[ ', c)
for v in range(n):
c = self.hiprint('%02X ' % (start + v), c)
c = self.hiprint(']\n', c)
stdout.write('\n ' + self.fgcolor(None, 3))
for v in range(n):
stdout.write(' ' + self.block(start + v, 2))
stdout.write('\n ')
for u in range(3):
for v in range(n):
stdout.write(' ')
stdout.write(self.fgcolor(start + v, 2))
stdout.write(vals[v][2*u : 2*(u + 1)])
stdout.write(self.fgcolor(None, 2))
stdout.write('\n ')
stdout.write('\n')
def show_colors(self, n):
Make a table showing colors 0 through n-1.
self.show_color_table(range(0,n,8), range(8), n, True)
def show_color_table(self, rows, cols, stop=-1, label=False):
Make a color table with all possible color indices of the form
rows[k] + cols[j] that are less than `stop' (if `stop' is not
negative). If label is True, then print row and column labels.
if label:
self.hiprint('[ + ]')
stdout.write(self.fgcolor(None, 3))
for a in cols:
stdout.write(' ' + self.octal(a) + ' ')
stdout.write('\n')
if label:
stdout.write(' ')
stdout.write('\n')
for b in rows:
if label:
stdout.write(self.octal(b) + ' ')
for a in cols:
c = a + b
if stop < 0 or c < stop:
self.show_color(b + a)
else:
stdout.write(' ')
stdout.write('\n')
stdout.write('\n')
def show_color(self, a):
Make a pretty display of color number `a', showing a block of
that color followed by the 6-character hexadecimal code for the
color.
stdout.write(' ' + self.block(a) + ' ')
stdout.write(self.fgcolor(a, 2) + (self.get_color(a)))
stdout.write(self.fgcolor(None, 2))
def hiprint(self, s, last_color=-1):
Print s to stdout, highlighting digits, brackets, etc. if the
color level allows it.
Arguments:
s: the string to print.
last_color: the current terminal foreground color. This
should be `None' if no color is set, or the current
color index, or something else (like a negative integer)
if the color isn't known. (The last option is always
safe and will force this function to do the right
thing.)
Return: the current foreground color, which can be passed as
last_color to the next call if the color isn't changed in
between.
for c in s:
if c == ' ':
color = last_color
else:
color = self.hi[c]
if color != last_color:
stdout.write(self.fgcolor(color, 3))
stdout.write(c)
last_color = color
return last_color
def octal(self, x):
Return a base-8 string for the integer x, highlighted if the
color level allows it.
return self.fgcolor(self.hi['+'], 3) + '0' + \
self.fgcolor(self.hi['0'], 3) + ('%03o' % x)
def block(self, c, n=1):
Return a string that prints as a block of color `c' and size `n'.
return self.bgcolor(c, 1) + ' '*n + self.bgcolor(None, 1)
# Changing the foreground and background colors.
# While the 38;5 and 48;5 SGR codes are less portable than the usual
# 30-37 and 40-47, these codes seem to be fairly widely implemented (on
# X-windows terminals, screen, and tmux) and support the whole color
# range, as opposed to just colors 0-8. They also make it very easy to
# set the background to a given color without needing to mess around
# with bold or reverse video (which are hardly portable themselves).
# This is useful even for the 16 ANSI colors.
def fgcolor(self, a=None, level=-1):
Return a string designed to set the foreground color to `a' when
printed to the terminal. None means default.
if self.color_level >= level:
if a is None:
return csi + '39m'
else:
return csi + '38;5;' + str(a) + 'm'
else:
return ''
def bgcolor(self, a=None, level=-1):
Return a string designed to set the background color to `a' when
printed to the terminal. None means default.
if self.color_level >= level:
if a is None:
return csi + '49m'
else:
return csi + '48;5;' + str(a) + 'm'
else:
return ''
def get_color(self, a):
if self.do_query:
try:
return get_color(a, timeout=self.timeout)
except (InvalidResponseError, NoResponseError):
return rgb_placeholder
else:
return rgb_placeholder
# Command-line arguments
timeout_dft = 200
parser = ArgumentParser(
description="Python script to show off terminal colors.",
epilog="Run this script from the terminal whose colors " +
"you want to showcase. " +
"For a brief synopsis of which terminal types are " +
"supported, see the top of the source code.")
mode_group = parser.add_mutually_exclusive_group()
p_choices = [16, 88, 256]
arg_p = mode_group.add_argument(
'-p', '--pretty',
action='store_true', default=False,
help="show colors 0 through N-1 in a pretty format. " +
("N must belong to %r. " % p_choices) +
"If N > 16, it should be the actual number of colors " +
"supported by the terminal, or the output will almost " +
"certainly not be pretty.")
mode_group.add_argument(
'-f', '--flat',
action='store_true', default=False,
help="show a simple table with colors 0 through N-1. ")
parser.add_argument(
'n', nargs='?', metavar='N',
type=int, default=16,
help="number of colors to show. " +
"Unless you explicitly supply -p/--pretty or -f/--flat, " +
"--pretty is used if possible and --flat is used " +
"otherwise. " +
"N defaults to 16, showing the ANSI colors 0-15. " +
"If N is 0, the script will attempt to determine the " +
"maximum number of colors automatically " +
"(which may be slow).")
parser.add_argument(
'--no-fgbg',
action='store_false', dest='fgbg', default=True,
help="suppress display of foreground/background colors.")
parser.add_argument(
'--no-query',
action='store_false', dest='do_query', default=True,
help="don't try to query any RGB values from the terminal " +
"and just use placeholders.")
parser.add_argument(
'-t', '--timeout', metavar='T',
type=int, default=timeout_dft,
help="how long to wait for the terminal to "
"respond to a query, in milliseconds " +
"[default: {0}]. ".format(timeout_dft) +
"If your output has '?' characters " +
"instead of RGB values " +
"or junk printed after the script runs, " +
"increasing this value may or may not " +
"help, depending on the terminal. " +
"A negative T will behave like infinity.")
parser.add_argument(
'-l', '--level', metavar='L',
type=int, default=3,
help="choose how much color to use in the output. " +
"(0 = no color; 3 = most color [default])")
if __name__ == '__main__':
args = parser.parse_args()
assert not (args.pretty and args.flat)
if args.pretty:
if args.n not in p_choices:
raise ArgumentError(
arg_p,
"N must belong to %r" % p_choices)
tc_save = None
try:
tc_save = termios.tcgetattr(stdout.fileno())
tc = termios.tcgetattr(stdout.fileno())
# Don't echo the terminal's responses
tc[3] &= ~termios.ECHO
# Noncanonical mode (i.e., disable buffering on the terminal
# level)
tc[3] &= ~termios.ICANON
# Make input non-blocking
tc[6][termios.VMIN] = 0
tc[6][termios.VTIME] = 0
termios.tcsetattr(stdout.fileno(), termios.TCSANOW, tc)
if args.n == 0:
args.n = test_num_colors(args.timeout)
# We are guaranteed to have failed some queries now, but
# that isn't meaningful.
num_errors = 0
if not (args.pretty or args.flat):
if args.n in p_choices:
args.pretty = True
else:
args.flat = True
if args.level >= 1:
stdout.write(reset)
if args.fgbg:
if args.do_query:
try:
bg = get_bg(timeout=args.timeout)
except (InvalidResponseError, NoResponseError):
bg = rgb_placeholder
try:
fg = get_fg(timeout=args.timeout)
except (InvalidResponseError, NoResponseError):
fg = rgb_placeholder
else:
bg = rgb_placeholder
fg = rgb_placeholder
stdout.write("\n Background: %s\n" % bg)
stdout.write(" Foreground: %s\n\n" % fg)
C = ColorDisplay(args.timeout, args.level, args.do_query)
if args.pretty:
assert args.n in p_choices
stdout.write('\n ANSI colors:\n\n')
C.show_ansi()
if args.n > 16:
stdout.write('\n RGB cube:\n\n')
C.show_color_cube(args.n)
stdout.write(' Grayscale ramp:\n\n')
C.show_grayscale_ramp(args.n)
else:
C.show_colors(args.n)
if num_errors > 0:
stderr.write("Warning: not all queries succeeded\n" +
"Warning: (output contains " +
"placeholders and may be inaccurate)\n")
finally:
if args.level >= 1:
stdout.write(reset)
flush_input()
if tc_save != None:
termios.tcsetattr(stdout.fileno(),
termios.TCSANOW, tc_save)
Run it as
python showcolors.py -h
to get an overview of the functionality.
TL;DR: you can echo a string like "\033]4;13;?\007" to an xterm, and it will output the RGB value of color #13 to itself in the form "\033]4;13;rgb:rrrr/gggg/bbbb\007", which you can then read and parse. To try it out:
$ echo -en "\033]4;13;?\007"
There are some subtleties if you want this to work on other terminals like urxvt; for that you can experiment yourself or read the code.
Further reading: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html (heading "Operating System Controls").
Xyne, regarding determining the number of colors: I don't know how to do that completely reliably. You can try simply
tput colors
but this relies on the value of $TERM and its terminfo and thus may be unreliable. A kludgy but workable way to do this using the "rgb_query" function in my script is to query color values using binary search to find the highest color value the terminal will allow you to query. The main problem with this is that if you query an invalid color index, then the terminal just won't respond at all, and if you query a valid index, it will respond but after a somewhat unpredictable delay, so it's hard to know for sure which one is the case. Like I said, it's kludgy but workable.
Edit: I went ahead and added that functionality to my script. Try running it as
python showcolors.py 0
or look at the function "test_num_colors".
Last edited by Lux Perpetua (2012-10-22 11:18:21)
Maybe you are looking for
-
Error running Reports 6i using OAS4.0.8
Hi, We have the following architecture: 1. DB Server - Oracle 8.1.7 on W2K server 2. Reports Server - Oracle Reports Server 6.0.8 on W2K server 3. Web Server - OAS 4.0.8 on W2K server When trying to execute report over the web (using Web CGI setup),
-
I keep getting a message that says my computer is associated with an APPLE ID?? That I can download previous purchases again in 82 days with a different ID? I don't understand why it wont allow me to download previous purchases?? I never had this pr
-
Condition Types in Scheduling Agreement(Urgent)
Dear Experts. This is a query with reference to my earlier issue Changes in Condition ME32L.As per suggestions, to get validity periods i have clicked on Time dependent Condition In SPRO settings Under Define document Types. After that i am not able
-
Please help
-
Implemention of Profit center Accounting
Hello, I need some information related to profit Center Accounting. Currently our client is using Business Area for getting requred reports. But now they are thinking to move to Profit Center Accounting. I need some information of benefit of using Pr