What is wrong with my X11 code? - c

I am attempting to get the X Window at a certain location on screen. When I asked people for a function to do this, they said you would just call XQueryTree recursively.
This is the code snippet which I think is somehow wrong. When I debug it, it seems to work perfectly. The only problem is that the output it gives seems a little strange. When I do XQueryTree on the root window, I get hundreds of children, when I only have five or so open. Also, it seems to think that there is a top-level window somewhere where there simply isn't one, and returns it as a result. No matter how I move my actual windows around, XQueryTree seems to indicate that there is another window on top of my windows (not covering the entire screen.) When I look at where it says the window is, it is at some arbitrary point on my desktop.
If this is of any help:
The display is from XOpenDisplay(NULL), and the root window I originally pass it is XDefaultRootWindow(display). I am running gnome under debian with metacity.
point getwindowatloc(Display * display, Window root, jint x, jint y) {
Window returnedroot;
Window returnedparent;
Window * children;
unsigned int numchildren;
XQueryTree(display,root,&returnedroot,&returnedparent,&children, &numchildren);
XWindowAttributes w;
int i;
for(i=numchildren-1; i>=0; i--) {
XGetWindowAttributes(display,children[i],&w);
if(x>=w.x && x<=w.x+w.width && y>=w.y && y <= w.y+w.height) {
point result={w.x,w.y};
XFree(children);
return result;
} else {
point result=getwindowatloc(display,children[i],x-w.x,y-w.y);
if(result.x!=INT_MAX) {
result.x+=w.x;
result.y+=w.y;
XFree(children);
return result;
}
}
}
if(children) {
XFree(children);
}
return notfound;
}
Thanks!
EDIT: For anyone who is searching for similar information: I ended up looking into the source of xwininfo. The key function is Find_Client in dsimple.c, which somehow ignores window managers to get the window you are actually looking for. If you want to look into subwindows, this is some code I added to Select_Window in dsimple.c which will recursively look inside subwindows, using XTranslateCoordinates.
Window child;
do {
XTranslateCoordinates(dpy,target_temp,target_win,x,y,&x,&y,&child);
target_temp=target_win;
target_win=child;
} while(target_win);
return target_temp;

I think what you want to do is query the root window's _NET_CLIENT_LIST property. This will produce a list of Window IDs for all client windows, excluding all of the "virtual" windows created by the window manager. Most window managers apparently support _NET_CLIENT_LIST, but you can also query whether or not any given feature is supported.

Your code looks right (I haven't tested it), and the results you describe don't seem strange at all. Metacity (and other X window managers) will create lots of windows around and near the application-owned windows to show the window title, borders and other decorations.
Try running your test with some simpler window manager like TVM (or even none at all). TVM should create a lot less windows than current window managers. This should make things easier to understand.
Usually, however, it's a bad idea to fight against the window manager. Can't you solve your problem in a higher level way withour having to use xlib directly?

Related

Retrieving Specific Active Directory Record Attributes using C#

I've been asked to set up a process which monitors the active directory, specifically certain accounts, to check that they are not locked so that should this happen, the support team can get an early warning.
I've found some code to get me started which basically sets up requests and adds them to a notification queue. This event is then assigned to a change event and has an ObjectChangedEventArgs object passed to it.
Currently, it iterates through the attributes and writes them to a text file, as so:
private static void NotifierObjectChanged(object sender,
ObjectChangedEventArgs e)
{
if (e.ResultEntry.Attributes.AttributeNames == null)
{
return;
}
// write the data for the user to a text file...
using (var file = new StreamWriter(#"C:\Temp\UserDataLog.txt", true))
{
file.WriteLine("{0} {1}", DateTime.UtcNow.ToShortDateString(), DateTime.UtcNow.ToShortTimeString());
foreach (string attrib in e.ResultEntry.Attributes.AttributeNames)
{
foreach (object item in e.ResultEntry.Attributes[attrib].GetValues(typeof(string)))
{
file.WriteLine("{0}: {1}", attrib, item);
}
}
}
}
What I'd like is to check the object and if a specific field, such as name, is a specific value, then check to see if the IsAccountLocked attribute is True, otherwise skip the record and wait until the next notification comes in. I'm struggling how to access specific attributes of the ResultEntry without having to iterate through them all.
I hope this makes sense - please ask if I can provide any additional information.
Thanks
Martin
This could get gnarly depending upon your exact business requirements. If you want to talk in more detail ping me offline and I'm happy to help over email/phone/IM.
So the first thing I'd note is that depending upon what the query looks like before this, this could be quite expensive or error prone (ie missing results). This worries me somewhat as most sample code out there gets this wrong. :) How are you getting things that have changed? While this sounds simple, this is actually a somewhat tricky question in directory land, given the semantics supported by AD and the fact that it is a multi-master system where writes happen all over the place (and replicate in after the fact).
Other variables would be things like how often you're going to run this, how large the data set could be in AD, and so on.
AD has some APIs built to help you here (the big one that comes to mind is called DirSync) but this can be somewhat complicated if you haven't used it before. This is where the "ping me offline" part comes in.
To your exact question, I'm assuming your result is actually a SearchResultEntry (if not I can revise, tell me what you have in hand). If that is the case then you'll find an Attributes field hanging off of that guy, and from there there is AttributeNames and Values. I think you'll see how it works from there if you have Values in hand, for example:
foreach (var attr in sre.Attributes.Values)
{
var da = (DirectoryAttribute)attr;
Console.WriteLine(da.Name);
foreach (var val in da.GetValues(typeof(byte[])))
{
// Handle a byte[] val ...
}
}
As I said, if you have something other than a SearchResultEntry in hand, let us know and I can revise the code sample.

Create widget array using Qt Designer?

In Qt Designer I'm creating multiple labels (for instance):
my_label1
my_label2
my_label3
...
my_label n
Then if I want to hide them I do this:
ui->my_label1->hide();
ui->my_label2->hide();
ui->my_label3->hide();
...
ui->my_labeln->hide();
However I would like to define the labels like
my_label[n]
So then I would be able to do this:
for(i=0;i<n;i++)
{
ui->my_label[n]->hide();
}
I read that I can define the widget like:
QLabel* my_label[5];
but is there any way to do the same from Qt Designer?
Thanks in advance!
Finally I decided to do direct assignment:
QLabel* my_label_array[5];
my_label_array[0] = ui->my_label1;
my_label_array[1] = ui->my_label2;
my_label_array[2] = ui->my_label3;
my_label_array[3] = ui->my_label4;
my_label_array[4] = ui->my_label5;
Then I can do for instance:
for(idx=0;idx<6;idx++) my_label_array[idx]->show();
for(idx=0;idx<6;idx++) my_label_array[idx]->hide();
for(idx=0;idx<6;idx++) my_label_array[idx]->setEnabled(1);
for(idx=0;idx<6;idx++) my_label_array[idx]->setDisabled(1);
etc...
Then I was able to perform iterations. I believe is not the cleanest way to do it but given my basic knowledge of Qt is ok for me.
Thank you very much for your answers and your support! This is a great site with great people.
Instead of creating an explicit array, you may be able to name your widgets using a particular scheme and then use QObject::findChildren() on the parent widget to get a list of the widgets you are after.
If you only want to hide widgets, you can put all the widgets you want to hide in an invisible QFrame (set frameShape to NoFrame) and hide them all by calling setVisible(false) on the QFrame. This may cause some unwanted side effects with layouts so you may have to tweak some size policy settings.
In case you are wanting to hide controls so that you can simulate a wizard type UI, you may want to check into QStackedWidget.
I have another dirty workaround for this:
in header file
// .hpp
class UiBlabla : public QWidget {
...
QLabel** labels;
};
in source file
// constructor
ui->setupUi(this);
labels = new QLabel*[10]{ui->label_0, ui->label_1, ui->label_2, ui->label_3,
ui->label_4, ui->label_5, ui->label_6,
ui->label_7, ui->label_8, ui->label_9};
I haven't seen anything in QtDesigner to do that, but there are a couple of relatively easy ways to get that behavior.
1) Simply store the my_labelx pointers (from QtDesigner) in an array (or better, a QVector):
QVector<QLabel*> my_labels;
my_labels.push_back(ui->my_label1);
my_labels.push_back(ui->my_label2);
Then you can iterate through the QVector.
for(int i=0; i < my_labels.size(); ++i) {
my_labels[i]-> hide();
}
// or with QFOREACH
foreach(QLabel* label, my_labels)
label->hide();
There is a little setup needed in terms of adding all the labels to the QVector, but on the plus side you only do that once.
2) Depending on the layout of your gui, you could have all your labels be children of a container object and iterate through the children

Custom Find/Replace dialog box

First of all, please bear in mind that I'm new to Windows Programming. I'll try to cover my question in great detail, so that hopefully the answer will be too.
A short introduction:
I'm copying writing a Notepad-like application using Win32 API and pure C. For those of you familiar with Petzold's Windows Programming, this is a modified version of his POPPAD program which he used to describe Common Dialog Boxes. I'm writing this strictly for educational purposes, so please refrain from posting comments like "why you using old technology, use .NET", as those comments will not help me solve my problem :).
Description of a problem:
Petzold in his POPPAD program used Common Dialog Boxes to write this Notepad-like application. He used Edit Control to provide all the functions of a basic text editor. POPPAD, much like a Notepad, also had Find and Replace dialog boxes where you could, well, find stuff AND replace it! Mind boggling, I know.
So this is where I wanted to test my newly acquired knowledge from reading the past chapters, as I decided to write my very own Find and Replace dialog box. Granted, it would be in the simplest form possibly. How hard can it be? You have one text field where you enter some text and you have one fancy button which says "Find!" on it.
Now I'd like to remind you once more that I'm new to Windows programming, so excuse me for any possibly newbie questions. Also, I'd like to point out that I'll focus solely on making the Find dialog box working, as Replace shouldn't be too hard to implement then.
So I played with the resource editor in Visual Studio, and few hours later I got this:
(stackoverflow doesn't actually allows me to post images, so here's the link below)
http://i.imgur.com/R98x4.png
I named this dialog box "Find" (with the quotation marks), so I don't have to use MAKEINTRESOURCE macro in my program, as per Petzold's school of thought. I changed the caption of "Ok" button to "Find Next" and changed it's ID from IDOK to IDC_FIND. Also changed IDCANCEL to IDC_CANCEL and that single line Edit Control is IDC_FIND_FIND.
Now to the more serious things. In my main program's Windows Procedure, I have this piece of code:
case IDM_SEARCH_FIND:
hDlgModeless = CreateDialog (hInst, TEXT ("Find"),
hwnd, FindDlgProc) ;
return 0 ;
IDM_SEARCH_FIND is a message identifier of a Menu item, which when clicked should open up the Find dialog box. CreateDialog function is used to create a modeless dialog box and store it's handle into a global variable hDlgModeless. FindDlgProc is name of the dialog box procedure where (I think) all the code of finding the text should go.
So without further ado, here's the code of my Find dialog box procedure:
BOOL CALLBACK FindDlgProc (HWND hDlg, UINT message,
WPARAM wParam, LPARAM lParam)
{
static TCHAR szFindWhat[MAX_STRING_LEN]; //Text to find
static int iOffset ; //Offset from the beginning of Edit control to the result
int iLength, iPos, iSingleLength ; //Length of a main Edit control and single line Edit control
PTSTR pstrDoc, pstrPos ;
switch (message)
{
case WM_INITDIALOG:
return TRUE ;
case WM_COMMAND:
switch (LOWORD (wParam))
{
//If the button "Find Next" has been pressed, process all the logic of finding the text
case IDC_FIND:
// Get the text from a single-line edit control in Find dialog box
// and save it in szFindWhat variable
iSingleLength = GetWindowTextLength(GetDlgItem(hDlg, IDE_FIND_FIND)) ;
GetWindowText(GetDlgItem(hDlg, IDE_FIND_FIND), szFindWhat, iSingleLength) ;
// Get the text from a main Edit control, allocate memory for it
// and store it in pstrDoc variable
iLength = GetWindowTextLength (hwndEdit) ;
if (NULL == (pstrDoc = (PTSTR) malloc ((iLength + 1) * sizeof (TCHAR))))
return FALSE ;
GetWindowText (hwndEdit, pstrDoc, iLength + 1) ;
// Search the document for the find string
pstrPos = _tcsstr (pstrDoc + iOffset, szFindWhat) ;
free (pstrDoc) ;
// Return an error code if the string cannot be found
if (pstrPos == NULL)
return FALSE ;
// Find the position in the document and the new start offset
iPos = pstrPos - pstrDoc ;
iOffset = iPos + lstrlen (szFindWhat) ;
// Select the found text
SendMessage (hwndEdit, EM_SETSEL, iPos, iOffset) ;
SendMessage (hwndEdit, EM_SCROLLCARET, 0, 0) ;
case IDC_CANCEL:
DestroyWindow (hDlg) ;
hDlgModeless = NULL ;
break ;
}
break ;
case WM_CLOSE:
DestroyWindow (hDlg) ;
hDlgModeless = NULL ;
break ;
default:
return FALSE;
}
return FALSE ;
}
The only actual error I get here is that hwndEdit is undeclared identifier. hwndEdit is the main Edit control (not the single-line in Find dialog box). How do I get the handle to hwndEdit while I'm in a Find dialog box procedure?
I'd like to point out that I'm feeling a bit over my head here, so please say if I'm missing/doing wrong something obvious. I'm pretty sure that even if I fix the only error I'm getting, the program still won't work. Even though the concept of what I should be doing sounds fairly simple, actually programming that seems quite difficult :)
This is what the code above should do, in simplest form:
- Get the text from Find dialog box which I wish to search
- Get the text from main Edit control
- Do a substring search from the last offset (don't start from beginning every time)
- Find the position of a result and readjust offset
- Select the found text
I know I haven't really asked a direct question here, well I guess the direct question would be: How do I make this work? :) But more importantly it would be to understand how this exactly works. I'd appreciate if you can provide me with an elaborate answer. Thanks for all the help!
It looks like you're very close, you just need to get the hwndEdit from your main window. You passed your main window's handle in as a parent to your dialog box, so you should be able to get the parent window of your dialog box like so:
HWND hwndParent = GetParent(hDlg);
After that you can get the edit control from that parent by referencing the edit control ID in your main window definition. Something like this (assuming the control ID is IDC_EDIT):
HWND hwndEdit = GetDlgItem(hwndParent, IDC_EDIT);

How do I convert a WPF size to physical pixels?

What's the best way to convert a WPF (resolution-independent) width and height to physical screen pixels?
I'm showing WPF content in a WinForms Form (via ElementHost) and trying to work out some sizing logic. I've got it working fine when the OS is running at the default 96 dpi. But it won't work when the OS is set to 120 dpi or some other resolution, because then a WPF element that reports its Width as 96 will actually be 120 pixels wide as far as WinForms is concerned.
I couldn't find any "pixels per inch" settings on System.Windows.SystemParameters. I'm sure I could use the WinForms equivalent (System.Windows.Forms.SystemInformation), but is there a better way to do this (read: a way using WPF APIs, rather than using WinForms APIs and manually doing the math)? What's the "best way" to convert WPF "pixels" to real screen pixels?
EDIT: I'm also looking to do this before the WPF control is shown on the screen. It looks like Visual.PointToScreen could be made to give me the right answer, but I can't use it, because the control isn't parented yet and I get InvalidOperationException "This Visual is not connected to a PresentationSource".
Transforming a known size to device pixels
If your visual element is already attached to a PresentationSource (for example, it is part of a window that is visible on screen), the transform is found this way:
var source = PresentationSource.FromVisual(element);
Matrix transformToDevice = source.CompositionTarget.TransformToDevice;
If not, use HwndSource to create a temporary hWnd:
Matrix transformToDevice;
using(var source = new HwndSource(new HwndSourceParameters()))
transformToDevice = source.CompositionTarget.TransformToDevice;
Note that this is less efficient than constructing using a hWnd of IntPtr.Zero but I consider it more reliable because the hWnd created by HwndSource will be attached to the same display device as an actual newly-created Window would. That way, if different display devices have different DPIs you are sure to get the right DPI value.
Once you have the transform, you can convert any size from a WPF size to a pixel size:
var pixelSize = (Size)transformToDevice.Transform((Vector)wpfSize);
Converting the pixel size to integers
If you want to convert the pixel size to integers, you can simply do:
int pixelWidth = (int)pixelSize.Width;
int pixelHeight = (int)pixelSize.Height;
but a more robust solution would be the one used by ElementHost:
int pixelWidth = (int)Math.Max(int.MinValue, Math.Min(int.MaxValue, pixelSize.Width));
int pixelHeight = (int)Math.Max(int.MinValue, Math.Min(int.MaxValue, pixelSize.Height));
Getting the desired size of a UIElement
To get the desired size of a UIElement you need to make sure it is measured. In some circumstances it will already be measured, either because:
You measured it already
You measured one of its ancestors, or
It is part of a PresentationSource (eg it is in a visible Window) and you are executing below DispatcherPriority.Render so you know measurement has already happened automatically.
If your visual element has not been measured yet, you should call Measure on the control or one of its ancestors as appropriate, passing in the available size (or new Size(double.PositivieInfinity, double.PositiveInfinity) if you want to size to content:
element.Measure(availableSize);
Once the measuring is done, all that is necessary is to use the matrix to transform the DesiredSize:
var pixelSize = (Size)transformToDevice.Transform((Vector)element.DesiredSize);
Putting it all together
Here is a simple method that shows how to get the pixel size of an element:
public Size GetElementPixelSize(UIElement element)
{
Matrix transformToDevice;
var source = PresentationSource.FromVisual(element);
if(source!=null)
transformToDevice = source.CompositionTarget.TransformToDevice;
else
using(var source = new HwndSource(new HwndSourceParameters()))
transformToDevice = source.CompositionTarget.TransformToDevice;
if(element.DesiredSize == new Size())
element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
return (Size)transformToDevice.Transform((Vector)element.DesiredSize);
}
Note that in this code I call Measure only if no DesiredSize is present. This provides a convenient method to do everything but has several deficiencies:
It may be that the element's parent would have passed in a smaller availableSize
It is inefficient if the actual DesiredSize is zero (it is remeasured repeatedly)
It may mask bugs in a way that causes the application to fail due to unexpected timing (eg. the code being called at or above DispatchPriority.Render)
Because of these reasons, I would be inclined to omit the Measure call in GetElementPixelSize and just let the client do it.
Simple proportion between Screen.WorkingArea and SystemParameters.WorkArea:
private double PointsToPixels (double wpfPoints, LengthDirection direction)
{
if (direction == LengthDirection.Horizontal)
{
return wpfPoints * Screen.PrimaryScreen.WorkingArea.Width / SystemParameters.WorkArea.Width;
}
else
{
return wpfPoints * Screen.PrimaryScreen.WorkingArea.Height / SystemParameters.WorkArea.Height;
}
}
private double PixelsToPoints(int pixels, LengthDirection direction)
{
if (direction == LengthDirection.Horizontal)
{
return pixels * SystemParameters.WorkArea.Width / Screen.PrimaryScreen.WorkingArea.Width;
}
else
{
return pixels * SystemParameters.WorkArea.Height / Screen.PrimaryScreen.WorkingArea.Height;
}
}
public enum LengthDirection
{
Vertical, // |
Horizontal // ——
}
This works fine with multiple monitors as well.
I found a way to do it, but I don't like it much:
using (var graphics = Graphics.FromHwnd(IntPtr.Zero))
{
var pixelWidth = (int) (element.DesiredSize.Width * graphics.DpiX / 96.0);
var pixelHeight = (int) (element.DesiredSize.Height * graphics.DpiY / 96.0);
// ...
}
I don't like it because (a) it requires a reference to System.Drawing, rather than using WPF APIs; and (b) I have to do the math myself, which means I'm duplicating WPF's implementation details. In .NET 3.5, I have to truncate the result of the calculation to match what ElementHost does with AutoSize=true, but I don't know whether this will still be accurate in future versions of .NET.
This does seem to work, so I'm posting it in case it helps others. But if anyone has a better answer, please, post away.
Just did a quick lookup in the ObjectBrowser and found something quite interesting, you might want to check it out.
System.Windows.Form.AutoScaleMode, it has a property called DPI. Here's the docs, it might be what you are looking for :
public const
System.Windows.Forms.AutoScaleMode Dpi
= 2
Member of System.Windows.Forms.AutoScaleMode
Summary: Controls scale relative to
the display resolution. Common
resolutions are 96 and 120 DPI.
Apply that to your form, it should do the trick.
{enjoy}

What is a parent freezable? What does this error mean?

I'm getting this error:
Cannot use a DependencyObject that belongs to a different thread than
its parent Freezable
What does that even mean? Is it in English? Is the parent frozen, or is it just freezable? Any way to make a parent not freezable, if it makes the error go away?
What's happening:
I have two opengl winforms controls in a WPF app, and so far, everything's been working smoothly (I think). Now, I've added an update so that when one winform control updates the image, the other should as well. That actually used to work, and now I'm getting that error. Stepping through the code has the crash happen in random places, which leads me to believe that it's a garbage collection fault (ie, some update in another thread is creating something that's getting garbage collected, and that collection happens at a random time).
The exception is caught in the main run method, and it's an InvalidOperationException.
I'm grasping at straws here. Where do I start?
EDIT: It looks like the call that's causing the problem is this one:
if (imagePanel.InvokeRequired)
{
imagePanel.Invoke(new System.Windows.Forms.MethodInvoker(delegate{
imagePanel.ClearImages();
}));
}
else
{
imagePanel.ClearImages();
}
I'm still tracking it down; if that series of lines is commented out, the crash still happens, and the thread status has a 'just ended' thread (hence the garbage collection assumption).
OK, I've figured it out. Ordinarily, I'd just delete this question, but it was a pain to find any information about how to fix this.
The problem was a call that looked like this:
ImageBrush theBrush = new ImageBrush(new Bitmap(new Uri(...)));
if (labelStatus.Dispatcher.Thread == System.Threading.Thread.CurrentThread) {
button.background = theBrush;
}
else {
labelStatus.Dispatcher.BeginInvoke((System.Threading.ThreadStart)(delegate {
button.background = theBrush;
}));
}
But! if you do that, then the dispatcher works, and then it tries to delete the brush, but the brush itself is also apparently getting deleted in another location.
So, the take-home lesson is, if you declare an ImageBrush, then delete it in the same thread, like so:
void MyFunc(){
ImageBrush theBrush = new ImageBrush(new Bitmap(new Uri(...)));
button.background = theBrush;
}
if (labelStatus.Dispatcher.Thread == System.Threading.Thread.CurrentThread) {
MyFunc();
}
else {
labelStatus.Dispatcher.BeginInvoke((System.Threading.ThreadStart)(delegate {
MyFunc();
}));
}

Resources