Cannot turn on input method on a SDL2 created window - sdl-2

I wrote a test program for SDL2 text event handling, and the input method cannot be turned on when I'm focusing on the window created by SDL2.
I'm testing that on Linux with Xfce desktop and Fcitx input method engine.
The code is simple:
#include <SDL.h>
int main(int argc, char** argv)
{
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_EVENTS);
SDL_Window* window = SDL_CreateWindow("sdl text test", 50, 50, 400, 400, SDL_WINDOW_OPENGL);
SDL_StartTextInput();
while (1)
{
// process events
SDL_Event event{};
bool should_exit = false;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
should_exit = true;
break;
case SDL_TEXTEDITING:
printf("text edit: %s %d %d\n", event.edit.text, event.edit.start, event.edit.length);
break;
case SDL_TEXTINPUT:
printf("text input: %s\n", event.text.text);
break;
}
}
if (should_exit) break;
SDL_Delay(20);
}
SDL_StopTextInput();
}
I have a brief look on SDL2's documents, but failed to find anything related with keyboard grabbing.

try delete
videodata->ime_uilesss = UILess_SetupSinks(videodata);
in function IME_Init of SDL_windowskeyboard.c.
It's ugly, but works.
If videodata->ime_uiless == SDL_False,
then windows will show input method,
else the sdl2 will render and show input method.

I'm using Windows 10 + SDL and was looking at SDL support for the IME under Windows, and have no idea how it could possibly work considering the IME_Render/IME_Present function are never called in SDL codebase.
Compiling SDL with #define SDL_DISABLE_WINDOWS_IME in SDL_windowskeyboard.c fixed it for me (xwang's suggestion will lead to a similar result).

I don't know why but it may do the trick: build SDL2 yourself.
I once use SDL2 comes with Ubuntu apt repo, libsdl2-dev/bionic-updates,now 2.0.8+dfsg1-1ubuntu1.18.04.1 amd64 . IME cannot be shown or switched.
After I replace with myself-built SDL2 lib(same version 2.0.8), IME works good.

Related

D programming language - input without pressing enter

I'm playing around with the D programming language and am wondering how I
can grab a character without requiring the user to press enter.
Pseudocode example of what I want:
while(true){
if(userHasPressedChar()){
writeln(getChar());
}
}
In C++ I can use conio.h's "getch()", but i have yet to find anything similar here.
Edit: I am using Windows 7.
Edit 2: I found a solution at this forum, which I could alter for my own use.
module main;
import std.stdio;
import core.sys.windows.windows;
void main() {
auto hCon = GetStdHandle(STD_INPUT_HANDLE);
FlushConsoleInputBuffer(hCon);
for(;;) { // in default console mode, ctrl-C will terminate
INPUT_RECORD inrec;
DWORD numread;
while(inrec.EventType != KEY_EVENT) {
WaitForSingleObject(hCon, INFINITE);
ReadConsoleInputW(hCon, &inrec, 1, &numread);
}
auto keyEvent = inrec.KeyEvent;
writefln("VK: %x \tChar: %x \tState: %x",
keyEvent.wVirtualKeyCode,
keyEvent.UnicodeChar,
keyEvent.dwControlKeyState);
}
}
You can also use various libraries. For example, my terminal.d can do this https://github.com/adamdruppe/arsd/blob/master/terminal.d for windows and linux.
Here's an example file from my book (see my SO profile if you're interested) that demonstrates the usage http://arsdnet.net/dcode/book/chapter_12/07/input.d
import terminal;
void main() {
auto terminal = Terminal(ConsoleOutputType.linear);
auto input = RealTimeConsoleInput(&terminal, ConsoleInputFlags.raw);
terminal.writeln("Press any key to exit");
auto ch = input.getch();
terminal.writeln("Bye!");
}
The input object does the necessary conversions to the console mode to turn off line buffering and cleans up after itself. Once you create one, you have methods like input.getch() and input.kbhit() similarly to conio.
My terminal library also offers other event types for things like mouse input if you want to get into more advanced usages.
To compile, just download terminal.d and add it to your command, e.g. dmd yourfile.d terminal.d.

Add breakpoints and install handlers

My high-level goal is something like this:
void print_backtrace() {
void *callstack[128];
int framesC = backtrace(callstack, sizeof(callstack));
printf("backtrace() returned %d addresses\n", framesC);
char** strs = backtrace_symbols(callstack, framesC);
for(int i = 0; i < framesC; ++i) {
if(strs[i])
printf("%s\n", strs[i]);
else
break;
}
free(strs);
}
install_breakpoint_handler("__NSAutoreleaseNoPool", print_backtrace);
So, each time the __NSAutoreleaseNoPool function breakpoint is catched, print_backtrace should be called. (All within the same binary. I'm not trying to catch the breakpoint of separate processes.)
I guess I can somehow do this via ptrace. Is there some easy-to-use and lightweight library?
Currently I'm searching for a MacOSX solution, but cross-platform would be nice of course.
I just found one lib (I even had used it a few years ago...): mach_override
I also found this debuglib but didn't tried.
See here for a demonstration for __NSAutoreleaseNoPool: It automatically executes print_backtrace.

Win32 console problem

is it possible to create a program that works as console application if started from the console and works as windows program (with GUI) when started otherwise?
If it is possible - how can I do that?
regards
Tobias
If you set the program up to build as a GUI program you can then attempt to attach to the console using AttachConsole(). You you attach OK then you were started from a console and you can proceed to redirect your standard handles to the newly attached console.
In this way you can start up and see if you are being started from a console that you can attach to and if so become a console program. If you cant attach you can show a GUI.
I've had some success with this, the main problem I have is redisplaying the command window's prompt when my program exits (which is how normal console programs operate), but I expect you could do something clever (read the console buffer on start up and find the prompt to redisplay when you exit?) if you really wanted to ...
If you need the program to act as a console application (e.g. print the usage information to the console) you must complile as a console application. A windows application will not have access to the console and cmd.exe will not wait for it to finish before printing the prompt and accepting the next command.
The best solution is to have two versions, one for command line and one for the GUI (which users usually run via a link on the desktop or start menu).
If you insist on using a single binary you will have to live with a console window appearing, at least for a short time. You can get rid of the console window using
FreeConsole();
You can tell that your application was run from GUI if it is the only process attached to the console. You can use GetConsoleProcessList to find the list of processes attached to the console.
This is the answer from Dan Tillett and it is remarkably effective. No flashes, no .com and .exe to trick cmd.exe. Seems to work flawlessly typing the command, in a .bat file, with focus, without focus and as double-click GUI app.
It's the bees knees!
Here is web page describing it, but I've posted it here because if that page goes 404 next month or 2 years from now, the excellent and "most complete" solution I've seen would be "off the grid".
http://www.tillett.info/2013/05/13/how-to-create-a-windows-program-that-works-as-both-as-a-gui-and-console-application/
#define WINVER 0x0501 // Allow use of features specific to Windows XP or later.
#define _WIN32_WINNT 0x0501
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <io.h>
#include <fcntl.h>
#include <stdio.h>
#pragma comment(lib, "User32.lib")
// Attach output of application to parent console
static BOOL attachOutputToConsole(void) {
HANDLE consoleHandleOut, consoleHandleError;
int fdOut, fdError;
FILE *fpOut, *fpError;
if (AttachConsole(ATTACH_PARENT_PROCESS)) {
//redirect unbuffered STDOUT to the console
consoleHandleOut = GetStdHandle(STD_OUTPUT_HANDLE);
fdOut = _open_osfhandle((intptr_t)consoleHandleOut, _O_TEXT);
fpOut = _fdopen(fdOut, "w" );
*stdout = *fpOut;
setvbuf(stdout, NULL, _IONBF, 0 );
//redirect unbuffered STDERR to the console
consoleHandleError = GetStdHandle(STD_ERROR_HANDLE);
fdError = _open_osfhandle((intptr_t)consoleHandleError, _O_TEXT);
fpError = _fdopen(fdError, "w" );
*stderr = *fpError;
setvbuf(stderr, NULL, _IONBF, 0 );
return TRUE;
}
//Not a console application
return FALSE;
}
//Send the "enter" to the console to release the command prompt on the parent console
static void sendEnterKey(void) {
INPUT ip;
// Set up a generic keyboard event.
ip.type = INPUT_KEYBOARD;
ip.ki.wScan = 0; // hardware scan code for key
ip.ki.time = 0;
ip.ki.dwExtraInfo = 0;
//Send the "Enter" key
ip.ki.wVk = 0x0D; // virtual-key code for the "Enter" key
ip.ki.dwFlags = 0; // 0 for key press
SendInput(1, &ip, sizeof(INPUT));
// Release the "Enter" key
ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release
SendInput(1, &ip, sizeof(INPUT));
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, INT nCmdShow) {
int argc = __argc;
char **argv = __argv;
UNREFERENCED_PARAMETER(hInstance);
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
UNREFERENCED_PARAMETER(nCmdShow);
BOOL console;
int i;
//Is the program running as console or GUI application
console = attachOutputToConsole();
if (console) {
//Print to stdout
printf("Program running as console application\n");
for (i = 0; i < argc; i++) {
printf("argv[%d] %s\n", i, argv[i]);
}
//Print to stderr
fprintf(stderr, "Output to stderr\n");
}
else {
MessageBox(NULL, "Program running as windows gui application",
"Windows GUI Application", MB_OK | MB_SETFOREGROUND);
}
//Send "enter" to release application from the console
//This is a hack, but if not used the console doesn't know the application has returned
//"enter" only sent if the console window is in focus
if (console && GetConsoleWindow() == GetForegroundWindow()){
sendEnterKey();
}
return 0;
}
The program itself will never know how it was started. Unless you are willing to pass an execution arguments to the program. For example: program.exe -GUI ... you can capture the passed parameters and decide how the program should run based on parameters passed.
your program whould be something like:
class MainClass
{
public static int Main(string[] args)
{
// Test if input arguments were supplied:
if(args[0]=="GUI")
new myGUI().show(); //runs an instance of your gui
else
//you know what should go here
}
}
You can sort of guess whether you are started from the console or not by doing this:
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
fConsole = csbi.dwCursorPosition.X | csbi.dwCursorPosition.Y;
It's a guess -- if your cursor position is not 0,0 than you are in a console and can work as a console app. Otherwise go and create your windows.
Another way to guess is to look at the process tree and see what process launched your app. If it is cmd.exe go in console mode, otherwise go into GUI mode.
Make it a console application and put this into the code:
void ConsoleWindowVisible(bool show)
{
DWORD dummy;
if
(
!show && // Trying to hide
GetConsoleProcessList(&dummy, 1) == 1 // Have our own console window
)
ShowWindow(GetConsoleWindow, SW_HIDE); // Hide the window
else // Trying to show or use parent console window
ShowWindow(GetConsoleWindow, SW_NORMAL); // Show the window
}
int main(int argc, char** argv)
{
ConsoleWindowVisible(false);
}
Cheers.
gor.f.gyolchanyan#gmail.com

Setting process name on Mac OS X at runtime

I'm trying to change my process' name as it appears in ps and Activity Monitor at runtime. I found several notes that there is no portable way to do this (which I don't care about).
Here's what I tried. None of these approaches worked for me.
Changing argv[0] (seems to be the way to go on some Unix systems)
Calling [[NSProcessInfo processInfo] setProcessName:#"someName"]
Calling setprogname (calling getprogname returns the name I set, but that is irrelevant)
I also read about a function called setproctitle which should be defined in stdlib.h if it is available, but it's not there.
There must be a way to accomplish this because QTKitServer - the faceless decoder for QuickTime Player X - has its corresponding QuickTime Player's PID in its process name.
Does anybody have a clue about how to accomplish this? I'd very much prefer a Core Foundation or POSIXy way over an Objective-C method to do this.
Thanks,
Marco
Edit: If it is in any way relevant, I'm using Mac OS X 10.6.5 and Xcode 3.2.5
There are good reasons to change the process name. Java software should change process names because when running different java tools I want to see which java process is for which tool.
Chromium does it: http://src.chromium.org/viewvc/chrome/trunk/src/base/mac/mac_util.mm.
Node.js uses same code to implement Process.title = 'newtitle': https://github.com/joyent/node/blob/master/src/platform_darwin_proctitle.cc
Note: This fails if someone does su to a different not logged-in user: https://github.com/joyent/node/issues/1727
Here the source code in its full complex glory. By the way, someone told me it also works for Mac OS X Lion and also fails with su.
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
void SetProcessName(CFStringRef process_name) {
if (!process_name || CFStringGetLength(process_name) == 0) {
NOTREACHED() << "SetProcessName given bad name.";
return;
}
if (![NSThread isMainThread]) {
NOTREACHED() << "Should only set process name from main thread.";
return;
}
// Warning: here be dragons! This is SPI reverse-engineered from WebKit's
// plugin host, and could break at any time (although realistically it's only
// likely to break in a new major release).
// When 10.7 is available, check that this still works, and update this
// comment for 10.8.
// Private CFType used in these LaunchServices calls.
typedef CFTypeRef PrivateLSASN;
typedef PrivateLSASN (*LSGetCurrentApplicationASNType)();
typedef OSStatus (*LSSetApplicationInformationItemType)(int, PrivateLSASN,
CFStringRef,
CFStringRef,
CFDictionaryRef*);
static LSGetCurrentApplicationASNType ls_get_current_application_asn_func =
NULL;
static LSSetApplicationInformationItemType
ls_set_application_information_item_func = NULL;
static CFStringRef ls_display_name_key = NULL;
static bool did_symbol_lookup = false;
if (!did_symbol_lookup) {
did_symbol_lookup = true;
CFBundleRef launch_services_bundle =
CFBundleGetBundleWithIdentifier(CFSTR("com.apple.LaunchServices"));
if (!launch_services_bundle) {
LOG(ERROR) << "Failed to look up LaunchServices bundle";
return;
}
ls_get_current_application_asn_func =
reinterpret_cast<LSGetCurrentApplicationASNType>(
CFBundleGetFunctionPointerForName(
launch_services_bundle, CFSTR("_LSGetCurrentApplicationASN")));
if (!ls_get_current_application_asn_func)
LOG(ERROR) << "Could not find _LSGetCurrentApplicationASN";
ls_set_application_information_item_func =
reinterpret_cast<LSSetApplicationInformationItemType>(
CFBundleGetFunctionPointerForName(
launch_services_bundle,
CFSTR("_LSSetApplicationInformationItem")));
if (!ls_set_application_information_item_func)
LOG(ERROR) << "Could not find _LSSetApplicationInformationItem";
CFStringRef* key_pointer = reinterpret_cast<CFStringRef*>(
CFBundleGetDataPointerForName(launch_services_bundle,
CFSTR("_kLSDisplayNameKey")));
ls_display_name_key = key_pointer ? *key_pointer : NULL;
if (!ls_display_name_key)
LOG(ERROR) << "Could not find _kLSDisplayNameKey";
// Internally, this call relies on the Mach ports that are started up by the
// Carbon Process Manager. In debug builds this usually happens due to how
// the logging layers are started up; but in release, it isn't started in as
// much of a defined order. So if the symbols had to be loaded, go ahead
// and force a call to make sure the manager has been initialized and hence
// the ports are opened.
ProcessSerialNumber psn;
GetCurrentProcess(&psn);
}
if (!ls_get_current_application_asn_func ||
!ls_set_application_information_item_func ||
!ls_display_name_key) {
return;
}
PrivateLSASN asn = ls_get_current_application_asn_func();
// Constant used by WebKit; what exactly it means is unknown.
const int magic_session_constant = -2;
OSErr err =
ls_set_application_information_item_func(magic_session_constant, asn,
ls_display_name_key,
process_name,
NULL /* optional out param */);
LOG_IF(ERROR, err) << "Call to set process name failed, err " << err;
}
Edit: It's a complex and confusing problem.
On OS X there is no setproctitle(3). One has to write into the argv array (ugly
and a bit dangerous because it is possible to overwrite some environment variables with bogus stuff). Done correctly it works very well.
Additionally Apple has the ActivityMonitor application, something like the Task Manager under Windows. The code above manipulates ActivityMonitor but this manipulation doesn't seem to be encouraged by Apple (hence the use of undocumented functions).
Important: ps and ActivityMonitor don't show the same information.
Also important: ActivityMonitor is not available if you don't have GUI. This can happen if you ssh in to a remote Apple box and there is nobody logged in by GUI. Sadly there is a bug by Apple IMO. Just querying if there is a GUI sends an annoying warning message to stderr.
Summary: If you need to change ActivityMonitor, use the code above. If you have GUI-less situations and and dislike warnings on stderr, redirect stderr temporarily to /dev/null during the call of SetProcessName. If you need to change ps information, write into argv.
You can use the lsappinfo tool which comes with macOS since at least 10.6 and up to present day (10.13.2):
Shell:
lsappinfo setinfo <PID> --name <NAME>
C++:
#include <sstream>
#include <string>
#include <stdlib.h>
void setProcessName (pid_t pid, std::string name)
{
std::ostringstream cmd;
cmd << "/usr/bin/lsappinfo setinfo " << pid;
cmd << " --name \"" << name << "\"";
system (cmd.str().c_str());
}

Xlib mouse events and ButtonPressMask

I have written a simple program which will report key press and release events for a particular window. In my case, it is mostly the terminal since I invoke the program from the terminal. I am able to get the key press and release events taking place in the terminal window (I have used XSelectInput() with KeyPressMask and KeyReleaseMask on the terminal) but the same is not working with ButtonPress and ButtonRelease. Not just these, but any events related to the mouse are not being reported. Any idea why this is happening?
#include
#include
#include
#include
#include
#include
int main() {
Display *display = XOpenDisplay(NULL);
KeySym k;
int revert_to;
Window window;
XEvent event;
XGetInputFocus(display, &window, &revert_to);
XSelectInput(display, window, KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask);
while(1)
{
XNextEvent(display,&event);
switch (event.type) {
case KeyPress : printf("Key Pressed\n"); break;
case KeyRelease : printf("Key Released\n"); break;
case ButtonPress : printf("Button Pressed\n"); break;
case ButtonRelease : printf("Button Released\n"); break;
case EnterNotify : printf("Enter\n"); break;
}
}
XCloseDisplay(display);
return 0;
}
The problem you encounter is that Xlib sends ButtonPress/Release events to only one client. I think that the window you're working with already has a client which is listening to its mouse events. Therefore your SelectInput call did not actually set ButtonPress/Release masks and generated an error which you didn't check for.

Resources