Показаны сообщения с ярлыком embedded window. Показать все сообщения
Показаны сообщения с ярлыком embedded window. Показать все сообщения

7 дек. 2012 г.

Tcl/Tk: встраивание окна внешнего приложения

Ссылки

В Tk есть несколько способов встроить окно внешнего приложения в виджет.

Способ #1


Использовать frame с опцией -container.
Приложению нужно передавать window-id контейнера.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#! /usr/bin/wish

wm geometry . 400x400+100+100

frame .container -container yes

frame .other_frame -bg blue

pack .container .other_frame -fill both -expand 1

set container_window_id [scan [winfo id .container] %x]

exec ./embedded_window $container_window_id &  

Способ #2


Использовать blt::container.
Приложению нужно передавать window-id контейнера.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#! /usr/bin/wish

package require BLT

wm geometry . 400x500+100+100

blt::container .container

frame .other_frame -bg green

pack .container .other_frame -expand 1 -fill both

set container_window_id [scan [winfo id .container] %x]

exec ./embedded_window $container_window_id & 

.container configure -name embedded_window


Способ #3


Использовать blt::container совместно с  TkXext.
В этом случае можно встраивать даже те приложения, которым нет возможности передать window-id.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#! /usr/bin/wish

lappend auto_path /path/to/TkXext

package require TkXext
package require BLT

wm geometry . 400x500+100+100

blt::container .container

frame .other_frame -bg red

pack .container .other_frame -expand 1 -fill both

exec ./embedded_window &

set child_window_id [TkXext.find.window embedded_window]

after 1000 {
    TkXext.reparent.window $child_window_id [winfo id .container]
    .container configure -window 0x$child_window_id
}


Тестовое приложение


Ниже приведен код программы, с помощью которой можно проверить, корректно ли передаются события изменения размера окна и нажатия клавиши при встраивании.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
 * Compile: gcc embedded_window.c -o embedded_window -lX11
 * 
 */
#include <X11/Xlib.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    Display *display = XOpenDisplay(NULL);
 
    int screen = DefaultScreen(display);
    
    Window parent_window = RootWindow(display, screen);

    if (argc == 2)
        parent_window = atol(argv[1]);

    Window child_window = XCreateSimpleWindow(display, parent_window,
                                              0,
                                              0,
                                              100,
                                              40,
                                              1,
                                              BlackPixel(display, screen),
                                              WhitePixel(display, screen));
    
    XSelectInput(display, child_window, KeyPressMask | ExposureMask);
    XMapWindow(display, child_window);
    
    XStoreName(display, child_window, "embedded_window");
    
    for (;;)
    {
        XEvent event;
        XNextEvent(display, &event);

        if (event.type == KeyPress)
        {
            printf("KeyPress\n");
        }
        
        if (event.type == Expose)
        {
            XWindowAttributes attrs;
            XGetWindowAttributes(display, child_window, &attrs);
                
            XClearWindow(display, child_window);
            
            XDrawLine(display, child_window, DefaultGC(display, screen), 0, 0, attrs.width, attrs.height);
            XDrawLine(display, child_window, DefaultGC(display, screen), 0, attrs.height, attrs.width, 0);
        }
    }
 
    XCloseDisplay(display);
    
    return 0;
 }
 

Xlib: вложение/встраивание окна одного приложения в окно другого (embedding)

Ссылки
  1. Volume One: Xlib Programming Manual (by Adrian Nye)
  2. The Xlib Manual 
  3. Tk: unix/tkUnixEmbed.c (реализация контейнера в Tcl/Tk)
  4. Re-parenting window manager 
  5. Xlib: Hello, World! 

X11 допускает, чтобы родительское и дочернее окна находились в разных приложения.

Для того, чтобы приложение могло создать свое окно как дочернее, достаточно ему каким-либо способом передать window-id родительского окна. Оно сможет передать этот идентификатор в функцию XCreateWindow() или XCreateSimpleWindow().

Например, mplayer принимает опцию -wid, а xterm принимает опцию -into.

Для того, чтобы создать окно, которое может использоваться как родительское, требуется для него реализовать обработку запросов от дочернего окна и обновление дочернего окна при изменении родительского.

Более полный пример реализации контейнера можно найти в исходниках Tk в файле unix/tkUnixEmbed.c.

Ниже приведен пример приложения, реализующего функцию контейнера. Программа создает окно, запускает дочерний процесс, добавив в конец командной строки идентификатор окна, и запускает цикл обработки событий, рассчитывая, что запущенный процесс создаст дочернее окно.

При запуске mplayer с опцией -wid окно mplayer-а не обрабатывает события от мышки и клавиатуры.

Скорее всего это происходит потому, что mplayer не создает дочернее окно, а использует для отрисовки родительское (это видно по отсутствию синей рамки в примере).
В то же время, если родительский процесс сделал для своего окна вызов XSelectInput(), то он сам обрабатывает события этого окна, и mplayer их не получает.

Результат запуска команды ./container xterm -into













Реализация контейнера:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
/*
 * Compile: gcc container.c -o container -lX11
 * 
 * This sample:
 * 
 *   - creates container window
 * 
 *   - executes child process appending container window id
 *     to its command line arguments
 * 
 *   - handles child window requests
 * 
 *   - propagates container window events to child window
 * 
 * Examples:
 * 
 *  $ ./container xterm -into
 * 
 *  $ ./container mplayer video.mp4 -wid
 * 
 */
#include <X11/Xlib.h>
#include <X11/Xutil.h>

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <sys/signal.h>
#include <sys/wait.h>

#define WIDTH   400
#define HEIGHT  200

static const char *event_names[] = {
   "",
   "",
   "KeyPress",
   "KeyRelease",
   "ButtonPress",
   "ButtonRelease",
   "MotionNotify",
   "EnterNotify",
   "LeaveNotify",
   "FocusIn",
   "FocusOut",
   "KeymapNotify",
   "Expose",
   "GraphicsExpose",
   "NoExpose",
   "VisibilityNotify",
   "CreateNotify",
   "DestroyNotify",
   "UnmapNotify",
   "MapNotify",
   "MapRequest",
   "ReparentNotify",
   "ConfigureNotify",
   "ConfigureRequest",
   "GravityNotify",
   "ResizeRequest",
   "CirculateNotify",
   "CirculateRequest",
   "PropertyNotify",
   "SelectionClear",
   "SelectionRequest",
   "SelectionNotify",
   "ColormapNotify",
   "ClientMessage",
   "MappingNotify"
};

int main(int argc, char **argv)
{
    if (argc < 2)
    {
        fprintf(stderr, "usage: ./container CHILD_PROGRAM CHILD_OPTIONS..\n");
        exit(1);
    }
    
    Display *display = XOpenDisplay(NULL);
    
    if (display == NULL)
    {
        fprintf(stderr, "error: can't open display!\n");
        exit(1);
    }
 
    int screen = DefaultScreen(display);
    
    Colormap colormap = DefaultColormap(display, screen);
    
    XColor blue;
    XAllocNamedColor(display, colormap, "blue", &blue, &blue);
    
    //
    // Initialize container window attributes
    //
    XSetWindowAttributes attrs;
    
    attrs.event_mask = SubstructureRedirectMask  // handle child window requests        (MapRequest)
                     | SubstructureNotifyMask    // handle child window notifications   (DestroyNotify)
                     | StructureNotifyMask       // handle container notifications      (ConfigureNotify)
                     | ExposureMask              // handle container redraw             (Expose)
                     ;

    attrs.do_not_propagate_mask = 0;             // do not hide any events from child window
    
    attrs.background_pixel = blue.pixel;         // background color
    
    unsigned long attrs_mask = CWEventMask       // enable attrs.event_mask
                             | NoEventMask       // enable attrs.do_not_propagate_mask
                             | CWBackPixel       // enable attrs.background_pixel
                             ;
    
    //
    // Create and map container window
    //
    Window container_window = XCreateWindow(display, RootWindow(display, screen),
                                            0,
                                            0,
                                            WIDTH,
                                            HEIGHT,
                                            1,
                                            CopyFromParent,
                                            InputOutput,
                                            CopyFromParent,
                                            attrs_mask,
                                            &attrs);
    
    //
    // Make window visible
    //
    XMapWindow(display, container_window);
    
    //
    // Set window title
    //
    XStoreName(display, container_window, "Container");
    
    //
    // Get WM_DELETE_WINDOW atom
    //
    Atom wm_delete = XInternAtom(display, "WM_DELETE_WINDOW", True);
    
    //
    // Subscribe WM_DELETE_WINDOW message
    //
    XSetWMProtocols(display, container_window, &wm_delete, 1);
    
    //
    // Create child process
    //
    int child_pid = fork();
    
    if (child_pid == 0)
    {
        char window_id[64];
        sprintf(window_id, "%lu", container_window);
        
        char **child_argv = calloc(argc + 1, sizeof(char *));
        
        int a;
        for (a = 1; a < argc; ++a)
            child_argv[a - 1] = argv[a];
        
        child_argv[argc - 1] = window_id;
        
        execvp(child_argv[0], child_argv);
        
        fprintf(stderr, "error: can't execute child process!\n");
        exit(1);
    }
    
    //
    // Child window ID and its display
    //
    Display *child_display = NULL;
    Window child_window = 0;
    
    //
    // Container window event loop
    //
    for (;;)
    {
        XEvent event;
        XNextEvent(display, &event);
        
        printf("container_event: %s\n", event_names[event.type]);
        
        //
        // Map child window when it requests and store its display and window id
        //
        if (event.type == MapRequest)
        {
            XMapWindow(event.xmaprequest.display, event.xmaprequest.window);
            
            child_display = event.xmaprequest.display;
            child_window = event.xmaprequest.window;
        }
        
        //
        // Propagate resize event to child window, and also resize it after MapRequest
        //
        if (event.type == ConfigureNotify || event.type == MapRequest)
        {
            if (child_window)
            {
                //
                // Get container window attributes
                //
                XWindowAttributes attrs;
                XGetWindowAttributes(display, container_window, &attrs);
        
                //
                // Move and resize child
                //
                XMoveResizeWindow(child_display, child_window, 2, 2, attrs.width - 6, attrs.height - 6);
            }
        }

        //
        // Refresh container window
        //
        if (event.type == Expose)
        {
            XClearWindow(display, container_window);
        }
        
        //
        // Exit if child window was destroyed
        //
        if (event.type == DestroyNotify)
        {
            fprintf(stderr, "child window destroyed, exiting\n");
            break;
        }
        
        //
        // Close button
        //
        if (event.type == ClientMessage)
        {
            if (event.xclient.data.l[0] == wm_delete)
            {
                break;
            }
        }
    }
    
    //
    // Kill child process
    //
    kill(child_pid, SIGTERM);
    wait(0);
    
    XCloseDisplay(display);
    
    return 0;
}