Author Topic: [SOLVED] Issue to set Focus on a Window by XLib.XSetInputFocus() on KDE-Desktop  (Read 219 times)

Hartmut

  • Hero Member
  • *****
  • Posts: 1188
I have an issue with function XLib.XSetInputFocus() to set the Focus on an open Window.
It fails often on KDE-Plasma Desktop with GTK2 and with QT5 on Ubuntu 24.04 (and Ubuntu 18.04).
It works on GNOME-Desktop with GTK2 on Ubuntu 24.04.
In all cases with X11 Windows-Manager and Lazarus 3.4.0 (same with Lazarus 2.0.10).

Don't know if a bug is in my code or somewhere else. I search a solution (or workaround), so that it works on KDE-Plasma Desktop with GTK2 on Ubuntu 24.04.

I attached a compilable project, if you want to test on your system. Please report your results, if you test something.

Code: Pascal  [Select][+][-]
  1. unit Unit1;
  2.  
  3. {$mode objfpc}{$H+}
  4.  
  5. interface
  6.  
  7. uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls;
  8.  
  9. type
  10.  TForm1 = class(TForm)
  11.   Button_read: TButton;
  12.   Button_set: TButton;
  13.   Button_stop: TButton;
  14.   Button_close: TButton;
  15.   CheckBox1: TCheckBox;
  16.   procedure Button_readClick(Sender: TObject);
  17.   procedure Button_setClick(Sender: TObject);
  18.   procedure Button_stopClick(Sender: TObject);
  19.   procedure Button_closeClick(Sender: TObject);
  20.  private
  21.  public
  22.  end;
  23.  
  24. var Form1: TForm1;
  25.  
  26. implementation
  27.  
  28. {$R *.lfm}
  29.  
  30. uses math, baseunix, XLib, X;
  31.  
  32. const FDisplay: PDisplay = nil; {pointer}
  33.  
  34. function X_openDisplay: boolean;
  35.    {opens only once a connection to the X server}
  36.    begin
  37.    if FDisplay <> nil then exit(true);
  38.  
  39.    FDisplay:=XOpenDisplay(nil);
  40.    if FDisplay=nil then writeln('XOpenDisplay() FAILED!');
  41.    exit(FDisplay <> nil);
  42.    end;
  43.  
  44. procedure GetFocus(out FPreviousWindow: TWindow; out FPreviousRevert: integer);
  45.    {returns the Window-ID and "current focus state" of the window which has the Focus}
  46.    begin
  47.    FPreviousWindow:=0; FPreviousRevert:=0;
  48.    if FDisplay=nil then exit;
  49.  
  50.    XGetInputFocus(FDisplay, @FPreviousWindow, @FPreviousRevert);
  51.    write('got: PrevWindow = ', FPreviousWindow, ' PrevRevert = ', FPreviousRevert);
  52.    end;
  53.  
  54. function XErrorHandler(display: PDisplay; event: PXErrorEvent): longint; cdecl;
  55.    {Error-Handler for RestoreFocus()}
  56.    begin
  57.    writeln;
  58.    writeln('X-Error: code=', event^.error_code, ', request code=', event^.request_code);
  59.    // error code: https://xorg.freedesktop.org/archive/X11R7.7/doc/xproto/x11protocol.html#Encoding::Errors
  60.    //   1 - BadRequest
  61.    //   2 - BadValue
  62.    //   3 - BadWindow
  63.    // request code: https://xorg.freedesktop.org/archive/X11R7.7/doc/xproto/x11protocol.html#Encoding::Requests
  64.    //   42 - SetInputFocus
  65.    Result:=0;
  66.    end;
  67.  
  68. procedure RestoreFocus(FPreviousWindow: TWindow; FPreviousRevert: Integer);
  69.    {sets the Focus to the specified Window}
  70.    var PrevErrorHandler: TXErrorHandler;
  71.    begin
  72.    if (FDisplay=nil) or (FPreviousWindow=0) then
  73.       begin
  74.       writeln('RestoreFocus() FAILED!');
  75.       exit;
  76.       end;
  77.  
  78.    writeln('SET PrevWindow=', FPreviousWindow, ' PrevRevert=', FPreviousRevert);
  79.    PrevErrorHandler:=XSetErrorHandler(@XErrorHandler);
  80.    XSetErrorHandler(@XErrorHandler); {activate Error-Handler}
  81.  
  82.    XSetInputFocus(FDisplay, FPreviousWindow, FPreviousRevert, CurrentTime);
  83.    XSync(FDisplay, False);
  84.    XFlush(FDisplay);
  85.    XSetErrorHandler(PrevErrorHandler); {restore Error-Handler}
  86.    end;
  87.  
  88. procedure wait_ms_AppProcMsg(ms: word);
  89.    {waits 'ms' milliseconds and calls Application.ProcessMessages repeatedly}
  90.    const Step = 125;
  91.    var n: word;
  92.    begin
  93.    while ms > 0 do
  94.       begin
  95.       n:=Min(Step,ms);
  96.       sleep(n);
  97.       Application.ProcessMessages;
  98.       dec(ms,n);
  99.       end;
  100.    end;
  101.  
  102. const stop: boolean = true; {set to 'True' by Buttons 'Stop' and 'Close'}
  103.  
  104. procedure read_Window_IDs;
  105.    {reads and lists repeatedly the Windows-ID, which currently has the Focus}
  106.    var PreviousWindow: TWindow; {qword}
  107.        PreviousRevert: longint;
  108.    begin
  109.    writeln('read_Windows_ID-Start');
  110.    if not X_openDisplay then exit;
  111.  
  112.    stop:=false;
  113.    repeat GetFocus(PreviousWindow,PreviousRevert); writeln;
  114.           wait_ms_AppProcMsg(2000); {waits 2000 ms}
  115.    until  stop;  {until 1 of 2 buttons pressed}
  116.    writeln('read_Windows_ID-Stop');
  117.    end;
  118.  
  119. function takeParam(p: integer): qword;
  120.    {returns ParamStr(p) as 'qword'}
  121.    var res: qword;
  122.        code: integer;
  123.    begin
  124.    val(ParamStr(p), res,code);
  125.    if code=0 then exit(res);
  126.  
  127.    writeln('Parameter ', p, ' is INVALID!');
  128.    exit(0);
  129.    end;
  130.  
  131. procedure set_Window_IDs;
  132.    {sets the Focus alternating to 2 Windows, specified by command line parameters}
  133.    var prevWin1,prevWin2,prevWinS,prevWinG: TWindow; {qword}
  134.        prevRev1,prevRev2,prevRevS,prevRevG, nr: longint;
  135.        ok: boolean;
  136.    begin
  137.    writeln('set_Windows_ID-Start');
  138.    if ParamCount < 4 then
  139.       begin
  140.       writeln('Syntax: <Window-ID1> <focus state1> <Window-ID2> <focus state2>');
  141.       exit;
  142.       end;
  143.  
  144.    prevWin1:=takeParam(1);
  145.    prevRev1:=takeParam(2);
  146.    prevWin2:=takeParam(3);
  147.    prevRev2:=takeParam(4);
  148.    if (prevWin1=0) or (prevWin2=0) then exit;
  149.  
  150.    if not X_openDisplay then exit;
  151.  
  152.    if Form1.CheckBox1.Checked then
  153.       begin
  154.       writeln('PRESS CTRL-C TO ABORT');
  155.       Form1.Hide;
  156.       wait_ms_AppProcMsg(1000); {waits 1000 ms}
  157.       end;
  158.  
  159.    stop:=false;
  160.    nr:=1;
  161.    repeat
  162.       if odd(nr) then begin prevWinS:=prevWin1; prevRevS:=prevRev1; end
  163.                  else begin prevWinS:=prevWin2; prevRevS:=prevRev2; end;
  164.       wait_ms_AppProcMsg(1500); {waits 1500 ms}
  165.       write(nr, ') ');
  166.       RestoreFocus(prevWinS,prevRevS); {set Focus}
  167.       if stop then BREAK;              {if 1 of 2 buttons pressed}
  168.  
  169.       wait_ms_AppProcMsg(500);         {waits 500 ms}
  170.       GetFocus(prevWinG,prevRevG);     {read Focus again}
  171.       ok:=(prevWinG=prevWinS) and (prevRevG=prevRevS);
  172.       if ok then writeln(' => ok') else writeln(' => FAILED!!!');
  173.  
  174.       if not Form1.Visible and (nr >= 4) then Form1.Visible:=true; {make Form visible again}
  175.       inc(nr);
  176.    until stop; {until 1 of 2 buttons pressed}
  177.  
  178.    writeln('set_Windows_ID-Stop');
  179.    end;
  180.  
  181. procedure TForm1.Button_readClick(Sender: TObject);
  182.    begin
  183. // writeln(GetLCLWidgetTypeName);
  184.    if stop then read_Window_IDs else writeln('First stop running job!');
  185.    end;
  186.  
  187. procedure TForm1.Button_setClick(Sender: TObject);
  188.    begin
  189. {$IFDEF LCLGTK2} writeln('gtk2'); {$ELSE} writeln('qt5'); {$ENDIF}
  190.    if stop then set_Window_IDs else writeln('First stop running job!');
  191.    end;
  192.  
  193. procedure TForm1.Button_stopClick(Sender: TObject);
  194.    begin
  195.    stop:=true;
  196.    end;
  197.  
  198. procedure TForm1.Button_closeClick(Sender: TObject);
  199.    begin
  200.    stop:=true;
  201.    writeln;
  202.    Close;
  203.    end;
  204.  
  205. end.
Above functions to read and set the Focus are deviated from the code from paweld in reply #13 from https://forum.lazarus.freepascal.org/index.php/topic,75042.0.html

How to test on your system:
 - start at least 2 programs, so we have open windows to set the Focus there. I tested e.g. with Kate (Texteditor), Synaptic, GParted, Firefox and Lazarus.
 - compile and run my attached demo in a Console
 - press button "read Window-IDs". Klick in the 2 windows of above 2 programs. You'll see their Window-IDs and "current focus state" in the Console.
 - press button "Close"
 - run my demo again, but now with 4 command line parameters with the privious showed values: <Window-ID1> <focus state1> <Window-ID2> <focus state2>.
   Example: project1 92277613 2 92277618 2. You may add a comment (only for yourself) after these 4 values.
 - press button "set Window-IDs"

If it works correctly (in my case on GNOME):
 - the Focus should switch every 2 seconds between the 2 Windows, whose parameters you provided
 - while my demo runs, you may click in these 2 windows and all other open windows, it should not disturb and the Focus continues to switch between the 2 Windows
 - press buttons "Stop" to stop or "Close" to abort.

Issues which I have on KDE-Plasma Desktop:
a) with Lazarus:
Lazarus behaves different (better) than all other programs which I tested. What I get:
 - start my demo and query the Window-IDs of 2 open Lazarus-Editors (from the same IDE). I used Lazarus 3.4.0 (1.8.4 also worked).
 - start my demo again with those 4 values as command line parameters
 - press button "set Window-IDs". It does *not* work, the Focus is *not* set, the Console shows always "FAILED"
 - klick in one of these 2 Lazarus-Editors or *any other* open Lazarus-Window (e.g. Messages, Main-Dialog, Find-Dialog). Now it works!
 - klick into any other open Window (not from Lazarus). Now it stops to work and always fails.
 - if you click again into one of the Lazarus-Windows, it works again, and so on.

Alternatively you can do this with Lazarus:
 - if "set Window-IDs" is running, press button "Stop"
 - press button "set Window-IDs" and *immediately* (in max. 1500 ms) klick in an arbitrary open Lazarus-Window. Now it works!
 - if you klick into any other open Window (not from Lazarus), it fails again.

Alternatively you can do this with Lazarus:
 - if "set Window-IDs" is running, press button "Stop"
 - activate CheckBox "Hide this Form before set Window-IDs"
 - klick in an arbitrary open Lazarus-Window to set the Focus there (if the Focus would now be in another Window, it would *not* work).
 - press button "set Window-IDs". Now it works (if the Focus was before in Lazarus).
Without this CheckBox active this Focus trick does *not* work.

b) with other programs:
I found *no* other program, where my demo worked on KDE-Plasma (e.g. not with Kate (Texteditor), Synaptic, GParted, Firefox).

Does anybody see a bug in my code?
Has anybody an idea for a workaround for KDE-Plasma Desktop with GTK2 on Ubuntu 24.04?
Thanks in advance.
« Last Edit: October 09, 2026, 02:51:25 pm by Hartmut »

paweld

  • Hero Member
  • *****
  • Posts: 1798
If this only affects KDE, the cause may be that focus protection is enabled. Try disabling it and see if that resolves the issue:
System Settings > Window Management > Window Behavior > Focus > Focus Stealing Prevention > set to: None
Next, restart the app and check to see if it works
Best regards / Pozdrawiam
paweld

Hartmut

  • Hero Member
  • *****
  • Posts: 1188
I have great news paweld, your suggestion solved my issue completely!!

I did not know this setting and did not imagine, that KDE could have a setting like this. Never heard about "focus protection" until now.
After changing 'Focus Stealing Prevention' from 'low' to 'none' both above demo and my real program work perfectly :-)))

I'm very happy. Thank you very much paweld for your valuable help. This is a great Forum.

paweld

  • Hero Member
  • *****
  • Posts: 1798
You're welcome.
Best regards / Pozdrawiam
paweld

 

TinyPortal © 2005-2018