質問
Linuxでは、C ++アプリケーションはfork()およびexecv()を使用してOpenOfficeの複数のインスタンスを起動し、パワーポイントスライドショーを表示します。この部分は機能します。
次に、OpenOfficeウィンドウをディスプレイ上の特定の場所に移動できるようにします。 XMoveResizeWindow()関数でそれを行うことができますが、各インスタンスのウィンドウを見つける必要があります。
各インスタンスのプロセスIDを持っていますが、そこからX11ウィンドウを見つけるにはどうすればよいですか?
更新-Andyの提案のおかげで、私はこれをやめました。ここにコードを投稿して、Stack Overflowコミュニティと共有しています。
残念ながら、Open Officeは_NET_WM_PIDプロパティを設定していないようですので、これは最終的に私の問題を解決しませんが、質問には答えます。
// Attempt to identify a window by name or attribute.
// by Adam Pierce <adam@doctort.org>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <iostream>
#include <list>
using namespace std;
class WindowsMatchingPid
{
public:
WindowsMatchingPid(Display *display, Window wRoot, unsigned long pid)
: _display(display)
, _pid(pid)
{
// Get the PID property atom.
_atomPID = XInternAtom(display, "_NET_WM_PID", True);
if(_atomPID == None)
{
cout << "No such atom" << endl;
return;
}
search(wRoot);
}
const list<Window> &result() const { return _result; }
private:
unsigned long _pid;
Atom _atomPID;
Display *_display;
list<Window> _result;
void search(Window w)
{
// Get the PID for the current Window.
Atom type;
int format;
unsigned long nItems;
unsigned long bytesAfter;
unsigned char *propPID = 0;
if(Success == XGetWindowProperty(_display, w, _atomPID, 0, 1, False, XA_CARDINAL,
&type, &format, &nItems, &bytesAfter, &propPID))
{
if(propPID != 0)
{
// If the PID matches, add this window to the result set.
if(_pid == *((unsigned long *)propPID))
_result.push_back(w);
XFree(propPID);
}
}
// Recurse into child windows.
Window wRoot;
Window wParent;
Window *wChild;
unsigned nChildren;
if(0 != XQueryTree(_display, w, &wRoot, &wParent, &wChild, &nChildren))
{
for(unsigned i = 0; i < nChildren; i++)
search(wChild[i]);
}
}
};
int main(int argc, char **argv)
{
if(argc < 2)
return 1;
int pid = atoi(argv[1]);
cout << "Searching for windows associated with PID " << pid << endl;
// Start with the root window.
Display *display = XOpenDisplay(0);
WindowsMatchingPid match(display, XDefaultRootWindow(display), pid);
// Print the result.
const list<Window> &result = match.result();
for(list<Window>::const_iterator it = result.begin(); it != result.end(); it++)
cout << "Window #" << (unsigned long)(*it) << endl;
return 0;
}
解決
これを行う唯一の方法は、探しているものが見つかるまでウィンドウツリーを走査することです。トラバースは難しくありません(例が必要な場合は、xwininfo.cを見てxwininfo -root -treeの動作を確認してください)。
しかし、探しているウィンドウをどのように識別しますか? 一部のアプリケーションは、_NET_WM_PIDというウィンドウプロパティを設定します。
OpenOfficeは、(ほとんどのGnomeアプリと同様に)そのプロパティを設定するアプリケーションの1つであると考えているため、あなたは幸運です。
他のヒント
/ proc / PID / environにWINDOWIDという変数が含まれているかどうかを確認します
パーティーに少し遅れました。しかしながら: 2004年に、Harald Welteは、LD_PRELOADを介してXCreateWindow()呼び出しをラップし、_NET_WM_PIDにプロセスIDを格納するコードスニペットを投稿しました。これにより、作成された各ウィンドウにPIDエントリが含まれるようになります。
http://www.mail-archive.com/devel@xfree86.org/msg05806 .html
xdotool
をインストールしてから、次の操作を行います:
#!/bin/bash
# --any and --name present only as a work-around, see: https://github.com/jordansissel/xdotool/issues/14
ids=$(xdotool search --any --pid "$1" --name "dummy")
多くのIDを取得します。プログラム seturgent
を使用して長いコマンドを実行したときに、これを使用してターミナルウィンドウを緊急に設定します。 xdotool
から取得したすべてのIDをループし、それらに対して seturgent
を実行します。
良い方法はありません。私が見る唯一の本当のオプションは:
- プロセスのアドレス空間を見て、接続情報とウィンドウIDを見つけることができます。
- netstatまたはlsofまたはipcsを使用して接続をXserverにマッピングしてから、(どういうわけか、少なくともrootが必要です)接続情報を見て接続を見つけることができます。
- インスタンスを生成するとき、別のウィンドウがマップされるまで待ち、それが正しいウィンドウであると想定し、「移動」します。
各インスタンスのプロセスIDを持っていますか? OOoの私の経験では、OOoの2番目のインスタンスを実行しようとすると、OOoの最初のインスタンスと単に会話し、追加のファイルを開くように指示するだけです。
Xのメッセージ送信機能を使用して、ウィンドウを適切に要求する必要があると思います。 OOoがそのカバーをどこかに文書化することを望みます。
Pythonを使用する場合、こちらという方法を見つけました。 BurntSushi
からアプリケーションを起動した場合、 xprop
への呼び出しを減らすことができるcmd文字列を知っている必要があります。すべてのxidを常にループして、pidが次と同じかどうかを確認できます。必要なpid
import subprocess
import re
import struct
import xcffib as xcb
import xcffib.xproto
def get_property_value(property_reply):
assert isinstance(property_reply, xcb.xproto.GetPropertyReply)
if property_reply.format == 8:
if 0 in property_reply.value:
ret = []
s = ''
for o in property_reply.value:
if o == 0:
ret.append(s)
s = ''
else:
s += chr(o)
else:
ret = str(property_reply.value.buf())
return ret
elif property_reply.format in (16, 32):
return list(struct.unpack('I' * property_reply.value_len,
property_reply.value.buf()))
return None
def getProperty(connection, ident, propertyName):
propertyType = eval(' xcb.xproto.Atom.%s' % propertyName)
try:
return connection.core.GetProperty(False, ident, propertyType,
xcb.xproto.GetPropertyType.Any,
0, 2 ** 32 - 1)
except:
return None
c = xcb.connect()
root = c.get_setup().roots[0].root
_NET_CLIENT_LIST = c.core.InternAtom(True, len('_NET_CLIENT_LIST'),
'_NET_CLIENT_LIST').reply().atom
raw_clientlist = c.core.GetProperty(False, root, _NET_CLIENT_LIST,
xcb.xproto.GetPropertyType.Any,
0, 2 ** 32 - 1).reply()
clientlist = get_property_value(raw_clientlist)
cookies = {}
for ident in clientlist:
wm_command = getProperty(c, ident, 'WM_COMMAND')
cookies[ident] = (wm_command)
xids=[]
for ident in cookies:
cmd = get_property_value(cookies[ident].reply())
if cmd and spref in cmd:
xids.append(ident)
for xid in xids:
pid = subprocess.check_output('xprop -id %s _NET_WM_PID' % xid, shell=True)
pid = re.search('(?<=\s=\s)\d+', pid).group()
if int(pid) == self.pid:
print 'found pid:', pid
break
print 'your xid:', xid
最新のC ++機能を使用して、OPのコードを自由に再実装しました。同じ機能を維持しますが、もう少し読みやすいと思います。また、ベクターの挿入がスローされてもリークしません。
// Attempt to identify a window by name or attribute.
// originally written by Adam Pierce <adam@doctort.org>
// revised by Dario Pellegrini <pellegrini.dario@gmail.com>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <iostream>
#include <vector>
std::vector<Window> pid2windows(pid_t pid, Display* display, Window w) {
struct implementation {
struct FreeWrapRAII {
void * data;
FreeWrapRAII(void * data): data(data) {}
~FreeWrapRAII(){ XFree(data); }
};
std::vector<Window> result;
pid_t pid;
Display* display;
Atom atomPID;
implementation(pid_t pid, Display* display): pid(pid), display(display) {
// Get the PID property atom
atomPID = XInternAtom(display, "_NET_WM_PID", True);
if(atomPID == None) {
throw std::runtime_error("pid2windows: no such atom");
}
}
std::vector<Window> getChildren(Window w) {
Window wRoot;
Window wParent;
Window *wChild;
unsigned nChildren;
std::vector<Window> children;
if(0 != XQueryTree(display, w, &wRoot, &wParent, &wChild, &nChildren)) {
FreeWrapRAII tmp( wChild );
children.insert(children.end(), wChild, wChild+nChildren);
}
return children;
}
void emplaceIfMatches(Window w) {
// Get the PID for the given Window
Atom type;
int format;
unsigned long nItems;
unsigned long bytesAfter;
unsigned char *propPID = 0;
if(Success == XGetWindowProperty(display, w, atomPID, 0, 1, False, XA_CARDINAL,
&type, &format, &nItems, &bytesAfter, &propPID)) {
if(propPID != 0) {
FreeWrapRAII tmp( propPID );
if(pid == *reinterpret_cast<pid_t*>(propPID)) {
result.emplace_back(w);
}
}
}
}
void recurse( Window w) {
emplaceIfMatches(w);
for (auto & child: getChildren(w)) {
recurse(child);
}
}
std::vector<Window> operator()( Window w ) {
result.clear();
recurse(w);
return result;
}
};
//back to pid2windows function
return implementation{pid, display}(w);
}
std::vector<Window> pid2windows(const size_t pid, Display* display) {
return pid2windows(pid, display, XDefaultRootWindow(display));
}
int main(int argc, char **argv) {
if(argc < 2)
return 1;
int pid = atoi(argv[1]);
std::cout << "Searching for windows associated with PID " << pid << std::endl;
// Start with the root window.
Display *display = XOpenDisplay(0);
auto res = pid2windows(pid, display);
// Print the result.
for( auto & w: res) {
std::cout << "Window #" << static_cast<unsigned long>(w) << std::endl;
}
XCloseDisplay(display);
return 0;
}