How do I configure libinput devices from C code? - c

On wayland there is no configuration file for libinput. This is not usually a problem because desktop environments (such as Gnome) often offer a way to configure the devices. However, there is no way to enable middle click emulation for a clickpad device. By default (using button areas so that I can right click with the bottom right of the touchpad) a middle button area is also created. This often results in me clicking the middle button when I try to left click and middle click instead (causing something to be pasted). This middle click area can be disabled if middle emulation is enabled, however because Gnome does not provide a way to configure this I decided to try to build my own program to do so.
I have looked through libinput's API docs and examples (unfortunately I can't seem to find any examples of device configuration). The following code is what I have put together (compiled with command in comment).
/**
* Simple program to setup libinput touchpad to use middle click emulation in wayland.
*
* To build install libinput-devel and libudev-devel
* gcc -o middleemulation main.c `pkg-config --cflags --libs libinput libudev`
*
* Copyright 2019 Marcus Behel
*
*Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <libudev.h>
#include <libinput.h>
static int open_restricted(const char *path, int flags, void *user_data){
int fd = open(path, flags);
return fd < 0 ? -errno : fd;
}
static void close_restricted(int fd, void *user_data){
close(fd);
}
const static struct libinput_interface interface = {
.open_restricted = open_restricted,
.close_restricted = close_restricted,
};
int main(void){
struct libinput *li;
struct libinput_event *ev;
struct udev *udev = udev_new();
int dev_count = 0, tp_count = 0;
li = libinput_udev_create_context(&interface, NULL, udev);
libinput_udev_assign_seat(li, "seat0");
libinput_dispatch(li);
while ((ev = libinput_get_event(li))) {
if (libinput_event_get_type(ev) == LIBINPUT_EVENT_DEVICE_ADDED){
dev_count++;
double w = 0, h = 0;
struct libinput_device *dev = libinput_event_get_device(ev);
const char *name = libinput_device_get_name(dev);
if(libinput_device_has_capability(dev, LIBINPUT_DEVICE_CAP_POINTER) &&
libinput_device_get_size(dev, &w, &h) == 0){
// Pointer with a size is a touchpad
tp_count++;
// This is a touchpad. Enable middle click emulation
printf("Found touchpad: '%s'.\n", name);
printf("Is middle click enabled: %s.\n", libinput_device_config_middle_emulation_get_enabled(dev) ? "true" : "false");
if(libinput_device_config_middle_emulation_is_available(dev)){
printf("Enabling middle emulation for device...");
enum libinput_config_status err = libinput_device_config_middle_emulation_set_enabled(dev, LIBINPUT_CONFIG_MIDDLE_EMULATION_ENABLED);
if(err == LIBINPUT_CONFIG_STATUS_SUCCESS){
printf("Succeeded.\n");
}else{
printf("Failed.\n");
}
printf("Is middle click enabled: %s.\n\n", libinput_device_config_middle_emulation_get_enabled(dev) ? "true" : "false");
}else{
printf("Device does not support middle emulation.\n\n");
}
}
}
libinput_event_destroy(ev);
libinput_dispatch(li);
}
libinput_unref(li);
if(dev_count == 0){
fprintf(stderr, "No libinput devices were found. Run this as root and make sure libinput driver is enabled.\n");
return 1;
}
if(tp_count == 0){
printf("No touchpads found on this system.");
}
return 0;
}
I have tested this on Ubuntu 18.04 (Dell Inspiron 5000) and on Fedora 30 (HP Pavilion 15). In both cases the program indicates success, however when running libinput list-devices it still shows that middle emulation is disabled and the behavior does not change.
Output from program (HP Pavilion)
Found touchpad: 'SynPS/2 Synaptics TouchPad'.
Is middle click enabled: false.
Enabling middle emulation for device...Succeeded.
Is middle click enabled: true.
Output from libinput list-devices after running the program
Device: SynPS/2 Synaptics TouchPad
Kernel: /dev/input/event4
Group: 9
Seat: seat0, default
Size: 106x61mm
Capabilities: pointer gesture
Tap-to-click: disabled
Tap-and-drag: enabled
Tap drag lock: disabled
Left-handed: disabled
Nat.scrolling: disabled
Middle emulation: disabled
Calibration: n/a
Scroll methods: *two-finger edge
Click methods: *button-areas clickfinger
Disable-w-typing: enabled
Accel profiles: none
Rotation: n/a

It looks like this would require a preload library to work as intended. The solution here: https://github.com/gaul/libinput-force-middle-click-emulation
works for me.

Related

Change name of Application in Pipewire/Pulseaudio

I am currently trying to build a very simple Audio-Tool, which needs to change its name in pavucontrol and qjackctl on runtime. When an Application produces Audio, its name is shown in pavucontrol. E.g. if I use firefox it is shown as "Firefox". I tried the most commonly suggested solutions: Editing argv and using prctl both did not succeed.
I also searched the pipewire documentation but I didn't find anything useful (but maybe I am just blind).
Is it even possible? From where does pipewire get the name of the Application?
Here is a little test-script in C with SDL2:
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <SDL2/SDL.h>
Uint8* audio_buffer = NULL;
Uint32 audio_length = 0;
void audio_callback(void* userdata, Uint8* stream, int n) {
memset(stream, 0, n);
}
int main(int argc, char** argv) {
SDL_Event evt;
SDL_AudioSpec desired;
SDL_Init(SDL_INIT_AUDIO|SDL_INIT_EVENTS);
SDL_LoadWAV("suil.wav", &desired, &audio_buffer, &audio_length);
desired.callback = audio_callback;
SDL_OpenAudio(&desired, NULL);
SDL_PauseAudio(0);
while (1) {
while (SDL_PollEvent(&evt)) {
switch (evt.type) {
case SDL_QUIT:
exit(EXIT_SUCCESS);
}
}
}
}
And a picture of what I would like to have changed on runtime:
(Note: The "test" would be the name in question.)
Disclaimer:
I'm not sure if this would maybe sdl-2 specific, so I added the SDL tag.
SDL's Pipewire backend grabs the application name in this block:
/* Get the hints for the application name, stream name and role */
app_name = SDL_GetHint(SDL_HINT_AUDIO_DEVICE_APP_NAME);
if (!app_name || *app_name == '\0') {
app_name = SDL_GetHint(SDL_HINT_APP_NAME);
if (!app_name || *app_name == '\0') {
app_name = "SDL Application";
}
}
...via the hint system:
SDL_HINT_APP_NAME:
/**
* \brief Specify an application name.
*
* This hint lets you specify the application name sent to the OS when
* required. For example, this will often appear in volume control applets for
* audio streams, and in lists of applications which are inhibiting the
* screensaver. You should use a string that describes your program ("My Game
* 2: The Revenge")
*
* Setting this to "" or leaving it unset will have SDL use a reasonable
* default: probably the application's name or "SDL Application" if SDL
* doesn't have any better information.
*
* Note that, for audio streams, this can be overridden with
* SDL_HINT_AUDIO_DEVICE_APP_NAME.
*
* On targets where this is not supported, this hint does nothing.
*/
#define SDL_HINT_APP_NAME "SDL_APP_NAME"
SDL_HINT_AUDIO_DEVICE_APP_NAME:
/**
* \brief Specify an application name for an audio device.
*
* Some audio backends (such as PulseAudio) allow you to describe your audio
* stream. Among other things, this description might show up in a system
* control panel that lets the user adjust the volume on specific audio
* streams instead of using one giant master volume slider.
*
* This hints lets you transmit that information to the OS. The contents of
* this hint are used while opening an audio device. You should use a string
* that describes your program ("My Game 2: The Revenge")
*
* Setting this to "" or leaving it unset will have SDL use a reasonable
* default: this will be the name set with SDL_HINT_APP_NAME, if that hint is
* set. Otherwise, it'll probably the application's name or "SDL Application"
* if SDL doesn't have any better information.
*
* On targets where this is not supported, this hint does nothing.
*/
#define SDL_HINT_AUDIO_DEVICE_APP_NAME "SDL_AUDIO_DEVICE_APP_NAME"
...and then passes the app name into Pipewire using PW_KEY_APP_NAME, here:
PIPEWIRE_pw_properties_set(props, PW_KEY_APP_NAME, app_name);
...where SDL's PIPEWIRE_pw_properties_set() is just a pointer to Pipewire's pw_properties_set().

glXChooseFBConfig w/ GLX_BIND_TO_TEXTURE_*_EXT returning no FBConfigs on Nvidia driver

I have an application that uses the GLX extension texture_from_pixmap, which requires a color buffer created using an FBConfig with GLX_BIND_TO_TEXTURE_RGB_EXT, or GLX_BIND_TO_TEXTURE_RGBA_EXT, per the spec.
Only a color buffer of a GLX pixmap created using an FBConfig with
attribute GLX_BIND_TO_TEXTURE_RGB_EXT or GLX_BIND_TO_TEXTURE_RGBA_EXT
set to TRUE can be bound as a texture.
https://www.khronos.org/registry/OpenGL/extensions/EXT/GLX_EXT_texture_from_pixmap.txt
My application does this, and works fine with Mesa and the Intel i965 driver, but not with the proprietary Nvidia driver.
When using glXChooseFBConfig with the Nvidia driver, no matching FBConfigs are returned, and I can't seem to figure out why.
I've made a minimal code sample that reproduces this problem.
#include <stdio.h>
#include <X11/Xlib.h>
#include <GL/glx.h>
int main()
{
Display *display = XOpenDisplay(NULL);
if (!display) {
printf("Unable to connect to display.\n");
return 1;
}
int pixmap_config[] = {
GLX_BIND_TO_TEXTURE_RGB_EXT, True,
GLX_NONE
};
int c = 0;
GLXFBConfig *configs = glXChooseFBConfig(display, 0, pixmap_config, &c);
if (!configs) {
printf("No appropriate GLX FBConfig available!\n");
} else {
printf("Number of matching configs: %i\n", c);
}
return 0;
}
On any Nvidia graphics card I test using the proprietary driver, I get:
No appropriate GLX FBConfig available!
Using Intel Graphics with Mesa, I get:
Number of matching configs: 82
What am I doing wrong here?
I think the issue comes from the attributes list passed to glXChooseFBConfig (your pixmap_config[]).
I guess some driver may fill required fields with default values, and then compare its internal configurations with the requested one.
The problem is that EXT_texture_from_pixmap only works with pixmaps, not windows.
So, you should set the GLX_DRAWABLE_TYPE field with a mask containing GLX_PIXMAP_BIT and not the default GLX_WINDOW_BIT.
To quote the spec:
attrib_list
Specifies a list of attribute/value pairs. The last attribute must be None.
Some GL implementations, such as Mesa, are more permissive, and will accept GLX_NONE (0x8000) terminating this list of attributes. However, the Nvidia driver does not, and will return NULL. Specifying Xlib's None (0) works. This is also the case for glXCreatePixmap.

How to determine Windows version in future-proof way

I noticed that GetVersionEx() is declared deprecated. Worse yet, for Windows 8.1 (and presumably future releases) the version number is limited by the application manifest.
My goal is to collect analytics on operating systems which the users are running, so I can appropriately target support. I would like a future-proof solution for collecting this data. Updating the manifest won't work because I can only update the manifest for Windows versions which have already been released, not for future versions. The suggested replacement API, the version helper functions, is useless.
How can I collect the actual Windows version number?
To clarify: By "future proofing", I just mean that I want something that has a reasonably good chance of working on the next version of Windows. Nothing is certain, but the docs do say that GetVersionEx() won't work.
MSDN has an example showing how to use the (useless for your scenario) version helper functions, but in the introduction is the following:
To obtain the full version number for the operating system, call the GetFileVersionInfo function on one of the system DLLs, such as Kernel32.dll, then call VerQueryValue to obtain the \StringFileInfo\\ProductVersion subblock of the file version information.
As of right now, neither the GetFileVersionInfo nor VerQueryValue function are deprecated.
Example
This will extract the product version from kernel32.dll and print it to the console:
#pragma comment(lib, "version.lib")
static const wchar_t kernel32[] = L"\\kernel32.dll";
wchar_t *path = NULL;
void *ver = NULL, *block;
UINT n;
BOOL r;
DWORD versz, blocksz;
VS_FIXEDFILEINFO *vinfo;
path = malloc(sizeof(*path) * MAX_PATH);
if (!path)
abort();
n = GetSystemDirectory(path, MAX_PATH);
if (n >= MAX_PATH || n == 0 ||
n > MAX_PATH - sizeof(kernel32) / sizeof(*kernel32))
abort();
memcpy(path + n, kernel32, sizeof(kernel32));
versz = GetFileVersionInfoSize(path, NULL);
if (versz == 0)
abort();
ver = malloc(versz);
if (!ver)
abort();
r = GetFileVersionInfo(path, 0, versz, ver);
if (!r)
abort();
r = VerQueryValue(ver, L"\\", &block, &blocksz);
if (!r || blocksz < sizeof(VS_FIXEDFILEINFO))
abort();
vinfo = (VS_FIXEDFILEINFO *) block;
printf(
"Windows version: %d.%d.%d",
(int) HIWORD(vinfo->dwProductVersionMS),
(int) LOWORD(vinfo->dwProductVersionMS),
(int) HIWORD(vinfo->dwProductVersionLS));
free(path);
free(ver);
Yikes, the currently accepted answer is over-complicated. Here's how to get the version of the current windows (with build numbers) quickly and reliably without requiring manifests and other nonsense tricks. And works on Windows 2000 and newer (i.e. every version of Windows in existence).
Short answer: use RtlGetVersion.
Don't have the Windows Driver Development Kit? Then it's a little less simple than including the header and using the function. Here's how you do it both with and without the WDK.
With WDK, include:
// Required for RtlGetVersion()
#pragma comment(lib, "ntdll.lib")
#include <Ntddk.h>
Without WDK, include:
// Required for RtlGetVersion()
#pragma comment(lib, "ntdll.lib")
// Define the function because we don't have the driver development
// kit headers. We could probably acquire them but it makes development
// onboarding a pain in the ass for new employees.
extern "C" {
typedef LONG NTSTATUS, *PNTSTATUS;
#define STATUS_SUCCESS (0x00000000)
// Windows 2000 and newer
NTSYSAPI NTSTATUS NTAPI RtlGetVersion(PRTL_OSVERSIONINFOEXW lpVersionInformation);
}
Now, simply get the accurate version details:
RTL_OSVERSIONINFOEXW osVers;
osVers.dwOSVersionInfoSize = sizeof(osVers);
// fill the structure with version details
NTSTATUS status = RtlGetVersion(&osVers);
// this should always succeed
assert(status == STATUS_SUCCESS);
The osVers variable now contains the accurate major, minor, and build number. No need to read file versions and no need to dynamically load libraries at runtime.
Please vote this above the other answer so this correct code can be used in applications rather than the rube-goldberg other answer. Thanks.

Is there a Linux equivalent of SetWindowPos?

A while ago I wrote a script in C that used the Windows API functions EnumWindows, SetWindowPos and SetForegroundWindow to automatically arrange windows (by title) in a particular layout that I commonly wanted.
Are there Linux equivalents for these functions? I will be using Kubuntu, so KDE-specific and/or Ubuntu-specific solutions are fine.
The best way to do this is either in the window manager itself (if yours supports extensions) or with the protocols and hints designed to support "pagers" (pager = any non-window-manager process that does window organization or navigation things).
The EWMH spec includes a _NET_MOVERESIZE_WINDOW designed for use by pagers. http://standards.freedesktop.org/wm-spec/wm-spec-1.3.html#id2731465
Raw Xlib or Xcb is pretty rough but there's a library called libwnck specifically designed to do the kind of thing you're talking about. (I wrote the original library long ago but it's been maintained by others forever.) Even if you don't use it, read the code to see how to do stuff. KDE may have an equivalent with KDE-style APIs I'm not sure.
There should be no need to use anything KDE or GNOME or distribution specific since the needed stuff is all spelled out in EWMH. That said, for certain window managers doing this as an extension may be easier than writing a separate app.
Using old school X calls directly can certainly be made to work but there are lots of details to handle there that require significant expertise if you want to iron out all the bugs and corner cases, in my opinion, so using a WM extension API or pager library would be my advice.
#andrewdotn has a fine answer there but you can do this old school as well fairly simply by walking the tree starting at the root window of the display using XQueryTree and fetching the window name with XFetchName then moving it with XMoveWindow. Here is an example that will list all the windows and if any are called 'xeyes' they get moved to the top left. Like most X programs, there is more to it and this should probably be calling XGetWindowProperty to fetch the _NET_WM_NAME extended window manager property but the example works ok as a starter. Compile with gcc -Wall -g -o demo demo.c -lX11
#include <X11/Xlib.h>
#include <stdio.h>
#include <string.h>
static int
EnumWindows(Display *display, Window window, int depth)
{
Window parent, *children;
unsigned int count = 0;
int r = 1, n = 0;
char *name = NULL;
XFetchName(display, window, &name);
for (n = 0; n < depth; ++n) putchar(' ');
printf("%08x %s\n", (int)window, name?name:"(null)");
if (name && strcmp("xeyes", name) == 0) {
XMoveWindow(display, window, 5, 5);
}
if (name) XFree(name);
if (XQueryTree(display, window, &window, &parent, &children, &count) == 0) {
fprintf(stderr, "error: XQueryTree error\n");
return 0;
}
for (n = 0; r && n < count; ++n) {
r = EnumWindows(display, children[n], depth+1);
}
XFree(children);
return r;
}
int
main(int argc, char *const argv[])
{
Display *display = NULL;
if ((display = XOpenDisplay(NULL)) == NULL) {
fprintf(stderr, "error: cannot connect to X server\n");
return 1;
}
EnumWindows(display, DefaultRootWindow(display), 0);
XCloseDisplay(display);
return 0;
}
Yes, you can do this using the X Windows protocol. It’s a very low-level protocol so it will take some work. You can use xcb_query_tree to find the window to operate on, and then move it with xcb_configure_window. This page gives some details on how to do it. There’s a basic tutorial on using the library those functions come from, but you’ll probably want to Google for a better one.
It may seem daunting, but it’s not too bad. Here’s a 50-line C program that will move all your xterms 10px to the right:
#include <stdio.h>
#include <string.h>
#include <xcb/xcb.h>
void handle(xcb_connection_t* connection, xcb_window_t window) {
xcb_query_tree_reply_t *tree = xcb_query_tree_reply(connection,
xcb_query_tree(connection, window), NULL);
xcb_window_t *children = xcb_query_tree_children(tree);
for (int i = 0; i < xcb_query_tree_children_length(tree); i++) {
xcb_get_property_reply_t *class_reply = xcb_get_property_reply(
connection,
xcb_get_property(connection, 0, children[i], XCB_ATOM_WM_CLASS,
XCB_ATOM_STRING, 0, 512), NULL);
char* class = (char*)xcb_get_property_value(class_reply);
class[xcb_get_property_value_length(class_reply)] = '\0';
if (!strcmp(class, "xterm")) {
/* Get geometry relative to parent window */
xcb_get_geometry_reply_t* geom = xcb_get_geometry_reply(
connection,
xcb_get_geometry(connection, window),
NULL);
/* Move 10 pixels right */
uint32_t values[] = {geom->x + 10};
xcb_configure_window(connection, children[i],
XCB_CONFIG_WINDOW_X, values);
}
/* Recurse down window tree */
handle(connection, children[i]);
}
}
int main() {
xcb_connection_t *connection;
const xcb_setup_t *setup;
connection = xcb_connect(NULL, NULL);
setup = xcb_get_setup(connection);
xcb_screen_iterator_t screen = xcb_setup_roots_iterator(setup);
handle(connection, screen.data->root);
return 0;
}
There’s no error-checking or memory management, and what it can do is pretty limited. But it should be straightforward to update into a program that does what you want, or to turn it into a general-purpose helper program by adding command-line options to specify which windows to operate on and which operations to perform on them.
As it seems you are not looking specifically for a solution in code, but rather in a desktop environment, you need to take a look at one of the window managers that handle the window placement in such a desktop environment.
KDE's KWin's Window Attributes
Compiz (GNOME) has "Window Rules" and "Place Windows" in the CompizConfig Settings Manager application. See e.g. here
Openbox seems a lot harder to get right, although they link to a GUI tool at the bottom of this page.
The problem with using X directly is that X in itself knows nothing about your desktop environment (panels, shortcuts, etc.) and you'll have to compensate manually.
After googling for this, I'm surprised KDE is the only one that has a simple way to do this.

tmpfile() on windows 7 x64

Running the following code on Windows 7 x64
#include <stdio.h>
#include <errno.h>
int main() {
int i;
FILE *tmp;
for (i = 0; i < 10000; i++) {
errno = 0;
if(!(tmp = tmpfile())) printf("Fail %d, err %d\n", i, errno);
fclose(tmp);
}
return 0;
}
Gives errno 13 (Permission denied), on the 637th and 1004th call, it works fine on XP (haven't tried 7 x86). Am I missing something or is this a bug?
I've got similar problem on Windows 8 - tmpfile() was causing win32 ERROR_ACCESS_DENIED error code - and yes, if you run application with administrator privileges - then it works fine.
I guess problem is mentioned over here:
https://lists.gnu.org/archive/html/bug-gnulib/2007-02/msg00162.html
Under Windows, the tmpfile function is defined to always create
its temporary file in the root directory. Most users don't have
permission to do that, so it will often fail.
I would suspect that this is kinda incomplete windows port issue - so this should be an error reported to Microsoft. (Why to code tmpfile function if it's useless ?)
But who have time to fight with Microsoft wind mills ?! :-)
I've coded similar implementation using GetTempPathW / GetModuleFileNameW / _wfopen. Code where I've encountered this problem came from libjpeg - I'm attaching whole source code here, but you can pick up code from jpeg_open_backing_store.
jmemwin.cpp:
//
// Windows port for jpeg lib functions.
//
#define JPEG_INTERNALS
#include <Windows.h> // GetTempFileName
#undef FAR // Will be redefined - disable warning
#include "jinclude.h"
#include "jpeglib.h"
extern "C" {
#include "jmemsys.h" // jpeg_ api interface.
//
// Memory allocation and freeing are controlled by the regular library routines malloc() and free().
//
GLOBAL(void *) jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
{
return (void *) malloc(sizeofobject);
}
GLOBAL(void) jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
{
free(object);
}
/*
* "Large" objects are treated the same as "small" ones.
* NB: although we include FAR keywords in the routine declarations,
* this file won't actually work in 80x86 small/medium model; at least,
* you probably won't be able to process useful-size images in only 64KB.
*/
GLOBAL(void FAR *) jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
{
return (void FAR *) malloc(sizeofobject);
}
GLOBAL(void) jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
{
free(object);
}
//
// Used only by command line applications, not by static library compilation
//
#ifndef DEFAULT_MAX_MEM /* so can override from makefile */
#define DEFAULT_MAX_MEM 1000000L /* default: one megabyte */
#endif
GLOBAL(long) jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed, long max_bytes_needed, long already_allocated)
{
// jmemansi.c's jpeg_mem_available implementation was insufficient for some of .jpg loads.
MEMORYSTATUSEX status = { 0 };
status.dwLength = sizeof(status);
GlobalMemoryStatusEx(&status);
if( status.ullAvailPhys > LONG_MAX )
// Normally goes here since new PC's have more than 4 Gb of ram.
return LONG_MAX;
return (long) status.ullAvailPhys;
}
/*
Backing store (temporary file) management.
Backing store objects are only used when the value returned by
jpeg_mem_available is less than the total space needed. You can dispense
with these routines if you have plenty of virtual memory; see jmemnobs.c.
*/
METHODDEF(void) read_backing_store (j_common_ptr cinfo, backing_store_ptr info, void FAR * buffer_address, long file_offset, long byte_count)
{
if (fseek(info->temp_file, file_offset, SEEK_SET))
ERREXIT(cinfo, JERR_TFILE_SEEK);
size_t readed = fread( buffer_address, 1, byte_count, info->temp_file);
if (readed != (size_t) byte_count)
ERREXIT(cinfo, JERR_TFILE_READ);
}
METHODDEF(void)
write_backing_store (j_common_ptr cinfo, backing_store_ptr info, void FAR * buffer_address, long file_offset, long byte_count)
{
if (fseek(info->temp_file, file_offset, SEEK_SET))
ERREXIT(cinfo, JERR_TFILE_SEEK);
if (JFWRITE(info->temp_file, buffer_address, byte_count) != (size_t) byte_count)
ERREXIT(cinfo, JERR_TFILE_WRITE);
// E.g. if you need to debug writes.
//if( fflush(info->temp_file) != 0 )
// ERREXIT(cinfo, JERR_TFILE_WRITE);
}
METHODDEF(void)
close_backing_store (j_common_ptr cinfo, backing_store_ptr info)
{
fclose(info->temp_file);
// File is deleted using 'D' flag on open.
}
static HMODULE DllHandle()
{
MEMORY_BASIC_INFORMATION info;
VirtualQuery(DllHandle, &info, sizeof(MEMORY_BASIC_INFORMATION));
return (HMODULE)info.AllocationBase;
}
GLOBAL(void) jpeg_open_backing_store(j_common_ptr cinfo, backing_store_ptr info, long total_bytes_needed)
{
// Generate unique filename.
wchar_t path[ MAX_PATH ] = { 0 };
wchar_t dllPath[ MAX_PATH ] = { 0 };
GetTempPathW( MAX_PATH, path );
// Based on .exe or .dll filename
GetModuleFileNameW( DllHandle(), dllPath, MAX_PATH );
wchar_t* p = wcsrchr( dllPath, L'\\');
wchar_t* ext = wcsrchr( p + 1, L'.');
if( ext ) *ext = 0;
wchar_t* outFile = path + wcslen(path);
static int iTempFileId = 1;
// Based on process id (so processes would not fight with each other)
// Based on some process global id.
wsprintfW(outFile, L"%s_%d_%d.tmp",p + 1, GetCurrentProcessId(), iTempFileId++ );
// 'D' - temporary file.
if ((info->temp_file = _wfopen(path, L"w+bD") ) == NULL)
ERREXITS(cinfo, JERR_TFILE_CREATE, "");
info->read_backing_store = read_backing_store;
info->write_backing_store = write_backing_store;
info->close_backing_store = close_backing_store;
} //jpeg_open_backing_store
/*
* These routines take care of any system-dependent initialization and
* cleanup required.
*/
GLOBAL(long)
jpeg_mem_init (j_common_ptr cinfo)
{
return DEFAULT_MAX_MEM; /* default for max_memory_to_use */
}
GLOBAL(void)
jpeg_mem_term (j_common_ptr cinfo)
{
/* no work */
}
}
I'm intentionally ignoring errors from some of functions - have you ever seen GetTempPathW or GetModuleFileNameW failing ?
A bit of a refresher from the manpage of on tmpfile(), which returns a FILE*:
The file will be automatically deleted when it is closed or the program terminates.
My verdict for this issue: Deleting a file on Windows is weird.
When you delete a file on Windows, for as long as something holds a handle, you can't call CreateFile on something with the same absolute path, otherwise it will fail with the NT error code STATUS_DELETE_PENDING, which gets mapped to the Win32 code ERROR_ACCESS_DENIED. This is probably where EPERM in errno is coming from. You can confirm this with a tool like Sysinternals Process Monitor.
My guess is that CRT somehow wound up creating a file that has the same name as something it's used before. I've sometimes witnessed that deleting files on Windows can appear asynchronous because some other process (sometimes even an antivirus product, in reaction to the fact that you've just closed a delete-on-close handle...) will leave a handle open to the file, so for some timing window you will see a visible file that you can't get a handle to without hitting delete pending/access denied. Or, it could be that tmpfile has simply chosen a filename that some other process is working on.
To avoid this sort of thing you might want to consider another mechanism for temp files... For example a function like Win32 GetTempFileName allows you to create your own prefix which might make a collision less likely. That function appears to resolve race conditions by retrying if a create fails with "already exists", so be careful about deleting the temp filenames that thing generates - deleting the file cancels your rights to use it concurrently with other processes/threads.

Resources