port: add a Haiku backend and build for x86_64 Haiku

The portable layer and the library now build for x86_64-unknown-haiku
with the system's clang and a sysroot of Haiku's packages
(SYSROOT=..., STDLIB=). The Interface Kit shows the windows.

- haiku.h, haiku_be.cpp and backend_haiku.cpp: the backend, in two
  halves, as for Cocoa. The BApplication and each BWindow have their
  own threads; they queue the input for the program's thread. A click
  on a disabled window brings its modal dialog to the front.
- GetModuleFileName uses get_next_image_info (no /proc on Haiku), and
  the command line comes from __libc_argv.
- COMn is the nth device in /dev/ports. Haiku's fonts and
  ~/config/settings/libmfc are used.
- Guards for the errno values, SIOCATMARK, RTLD_NOLOAD and the CS5 to
  CS8 values that Haiku does not have or defines differently.
- The shared libraries link libbe, libnetwork and libbsd.
- docs/haiku.md, and the cross-haiku CI job, which builds the
  libraries.

Tested with the D-Modem GUI on Haiku R1/beta6 in QEMU: menus, dialogs,
modal dialogs, the keyboard, moving windows and the serial ports.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B82eRTJUdomcnCN8okhJSr
Signed-off-by: Neo-Desktop <321592+Neo-Desktop@users.noreply.github.com>
This commit is contained in:
Neo-DesktopandClaude Opus 5.5 committed 2026-11-28 20:06:36 +00:00
1 parent 5de614d1f4
commit 3952742dcd
17 files changed
+1381 -7

No files matched your search

+34
View File
@@ -255,3 +255,37 @@ jobs:
s="$CLANG_DOS/macosx10.4"
make -j"$(nproc)" TARGET=${{ matrix.arch }}-apple-macosx10.4 BIN="$CLANG_DOS/bin" \
SDK="$s/MacOSX10.4u.sdk" LIBCXX="$s" AR="$CLANG_DOS/bin/llvm-ar" static
# Haiku (x86_64): builds the libraries with the runner's clang against a
# sysroot of Haiku's own packages (from D-Modem's haiku_sysroot.py,
# which checks them against the repositories' SHA-256). It does not run
# the tests: that needs a Haiku guest. See docs/haiku.md.
cross-haiku:
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
with:
submodules: true
- uses: actions/checkout@v4
with:
repository: D-Modem/D-Modem
path: dmodem
sparse-checkout: platforms/haiku
- name: Install clang, lld and libzstd
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends clang lld libzstd1 python3
- name: Restore the Haiku packages
uses: actions/cache@v4
with:
path: haiku-packages
key: haiku-packages-${{ hashFiles('dmodem/platforms/haiku/haiku_sysroot.py') }}
- name: Make the sysroot
run: |
python3 dmodem/platforms/haiku/haiku_sysroot.py "$RUNNER_TEMP/haiku-sysroot" \
--cache haiku-packages haiku haiku_devel gcc gcc_syslibs gcc_syslibs_devel
- name: Build
run: |
make -j"$(nproc)" TARGET=x86_64-unknown-haiku SYSROOT="$RUNNER_TEMP/haiku-sysroot" \
STDLIB= AR=ar all
+19 -2
View File
@@ -25,7 +25,7 @@ TARGET ?= i586-pc-windows5.1-gnu
# Linux and macOS targets (make TARGET=x86_64-linux-gnu, or
# TARGET=arm64-apple-macos11) build over the portable Win32 layer in
# port/, which goes into libwinport.a beside the MFC libraries.
ifneq ($(findstring linux,$(TARGET))$(findstring darwin,$(TARGET))$(findstring apple,$(TARGET)),)
ifneq ($(findstring linux,$(TARGET))$(findstring darwin,$(TARGET))$(findstring apple,$(TARGET))$(findstring haiku,$(TARGET)),)
PORTABLE = 1
endif
# The classic Mac OS (make TARGET=m68k-apple-macos or
@@ -46,6 +46,16 @@ STDLIB = -nostdinc++ -isystem $(MACSDK_LIB)/include/c++/15.2.0/$(CLASSIC_TRIPLE)
CLASSIC_FLAGS = $(if $(findstring m68k,$(TARGET)),-mcmodel=large) -femulated-tls \
-fexceptions -frtti -ffunction-sections -fdata-sections -D_GNU_SOURCE
endif
# Haiku (make TARGET=x86_64-unknown-haiku SYSROOT=/path/to/haiku-sysroot
# STDLIB=) builds over the portable layer with the Haiku backend
# (backend_haiku.cpp and haiku_be.cpp), which shows the windows with the
# Interface Kit. The sysroot has Haiku's packages extracted under
# boot/system. The C++ library is libstdc++, which is Haiku's. See
# docs/haiku.md.
ifneq ($(findstring haiku,$(TARGET)),)
HAIKU = 1
HAIKU_FLAGS = -D_DEFAULT_SOURCE
endif
# 32-bit DOS (make TARGET=i386-pc-msdos BIN=/path/to/clang-dos/bin) also
# builds over the portable layer, with the i386-msdos sysroot of
# clang-retro/dos-sdk (picolibc with cooperative threads, and libc++).
@@ -141,7 +151,7 @@ PORT_SRCS := $(filter-out $(patsubst %,port/src/%.cpp,$(CLASSIC_SKIP)),$(PORT_SR
PORT_OBJS = $(patsubst port/src/%.cpp,$(OUT)/port/%.o,$(PORT_SRCS))
ALL_CXXFLAGS += -Iport/include $(CLASSIC_FLAGS) $(DOS32_FLAGS)
else
ALL_CXXFLAGS += -Iport/include -fPIC
ALL_CXXFLAGS += -Iport/include -fPIC $(HAIKU_FLAGS)
endif
PORT_LIB = $(OUT)/libwinport.a
SCRNSAVE_LIBS = $(OUT)/libscrnsave.a $(OUT)/libscrnsavw.a
@@ -252,7 +262,14 @@ SHLIB_SYSLIBS = -framework Cocoa -framework OpenGL -lpthread
SHLIB_FLAGS = -dynamiclib -Wl,-install_name,@rpath/$(notdir $@) -Wl,-rpath,@loader_path
else
SHLIB_EXT = so
ifeq ($(HAIKU),1)
# Haiku has dlopen and the threads in libroot. The Interface Kit is in
# libbe, the sockets in libnetwork, and timegm and dl_iterate_phdr in
# libbsd.
SHLIB_SYSLIBS = -lbe -lnetwork -lbsd
else
SHLIB_SYSLIBS = -ldl -lpthread
endif
SHLIB_FLAGS = -shared -Wl,-soname,$(notdir $@) -Wl,-rpath,'$$ORIGIN'
endif
SHARED_DIR = $(OUT)/shared
+7
View File
@@ -542,6 +542,13 @@ program. Windows show on a VESA screen. See [docs/dos.md](docs/dos.md).
layer for System 7 to Mac OS 9, with the C and C++ libraries of
clang-retro/mac-sdk. The Toolbox shows the windows. See [docs/macos-classic.md](docs/macos-classic.md).
### Haiku
`make TARGET=x86_64-unknown-haiku SYSROOT=path/to/haiku-sysroot STDLIB= all`
builds the library and the portable layer for Haiku (x86_64) with the
system's clang. The Interface Kit shows the windows. See
[docs/haiku.md](docs/haiku.md).
### Mac OS X 10.0 to 10.5
`make TARGET=powerpc-apple-macosx10.4 SDK=path/to/MacOSX10.4u.sdk
+124
View File
@@ -0,0 +1,124 @@
# Haiku
The library and the portable layer build for Haiku (x86_64) with the
system's clang on Linux. The Interface Kit shows the windows. A program
is one native Haiku executable. It needs no other library of this
project.
The programs were tested on Haiku R1/beta6. Earlier versions were not
tested.
## Requirements
- clang and lld, version 18 or later.
- A Haiku sysroot: the packages `haiku`, `haiku_devel`, `gcc`,
`gcc_syslibs` and `gcc_syslibs_devel`, extracted under
`boot/system`, as Haiku installs them. D-Modem's
`platforms/haiku/haiku_sysroot.py` makes this sysroot on Linux. It
downloads the packages from Haiku's repositories and checks them
against the repositories' SHA-256.
```sh
python3 platforms/haiku/haiku_sysroot.py haiku-sysroot \
haiku haiku_devel gcc gcc_syslibs gcc_syslibs_devel
```
## Build the library
```sh
make TARGET=x86_64-unknown-haiku SYSROOT=path/to/haiku-sysroot STDLIB= all
```
`STDLIB=` is necessary. The C++ library is Haiku's own libstdc++. The
libraries are in `build/x86_64-unknown-haiku`: `libmfc.a`, `libmfcu.a`,
`libwinport.a`, `libscrnsave.a` and `libglaux.a`. The shared libraries
are in `build/x86_64-unknown-haiku/shared`.
## Build a program
```sh
clang++ --target=x86_64-unknown-haiku --sysroot=path/to/haiku-sysroot \
-fuse-ld=lld -std=c++17 -D_DEFAULT_SOURCE -Iinclude -Iport/include \
app.cpp app-res.cpp \
build/x86_64-unknown-haiku/libmfc.a build/x86_64-unknown-haiku/libwinport.a \
-lbe -lnetwork -lbsd -o app
```
Compile the resources with `port/tools/res2cpp.py`. Link these system
libraries:
| Library | Contents |
|--------------|----------------------------------------------|
| `libbe` | The Interface Kit and the clipboard. |
| `libnetwork` | The sockets (Winsock, WinInet). |
| `libbsd` | `timegm` and `dl_iterate_phdr`. |
The threads and `dlopen` are in `libroot`, which clang links
automatically.
## What the port does
The port uses the portable layer (`PORTABLE=1`), as on Linux. These parts
are special to Haiku:
- **The windows.** The backend has two halves. `port/src/haiku_be.cpp`
uses the Interface Kit and sees none of the Windows headers.
`port/src/backend_haiku.cpp` uses the window manager and sees none of
Haiku's headers. `port/src/haiku.h` is the interface between the two
halves.
- **The threads.** The backend starts the `BApplication` in a thread of
its own. Each `BWindow` also has its own thread. These threads put the
input in a queue. The program's thread empties the queue when it waits
for messages. Thus the window manager sees all input on the program's
thread only.
- **The frame.** A window has no Haiku border (`B_NO_BORDER_WINDOW_LOOK`).
The window manager draws the caption and the frame, as on the other
backends. A popup (a menu, a drop-down list, a tooltip) floats over the
program's windows and does not take the focus.
- **The keys.** The keys are those of a PC keyboard. Control is
Control. The Alt key (Haiku's Command key, by default) is Alt. The
Windows key (Haiku's Option key) is the Windows key. Thus Control+C
copies and Alt+F opens the File menu, as on Windows.
- **The modal dialogs.** A click on a disabled window (the owner of a
modal dialog) does not go to that window. The click brings the dialog
to the front, as on Windows.
- **The clipboard.** Text goes to and from `be_clipboard` as
`text/plain`.
- **The work area.** `SPI_GETWORKAREA` is the screen without the
Deskbar, when the Deskbar is on one edge of the screen.
- **The serial ports.** `COM1` is the first device in `/dev/ports` (by
name), `COM2` is the second device, and so on. `WINPORT_COM1` and the
device's own path (`/dev/ports/usb0`) also work.
- **The fonts.** The layer finds TrueType fonts in
`~/config/non-packaged/data/fonts`, `~/config/data/fonts`,
`/boot/system/non-packaged/data/fonts` and
`/boot/system/data/fonts`.
- **The settings.** The registry and the other settings are in
`~/config/settings/libmfc`.
- **The program's path.** `GetModuleFileName` gets the path from
`get_next_image_info`. Haiku has no `/proc/self/exe`.
## The settings
| Variable | Effect |
|---------------------------|-----------------------------------------------------|
| `WINPORT_BACKEND=headless`| Keeps the windows in memory. Shows no window. |
| `WINPORT_HAIKU_SIGNATURE` | The application's MIME signature. The default is `application/x-vnd.winport-<name>`. |
| `WINPORT_COM1` (and on) | The device of `COM1`. |
## Limits
- No sound. ALSA is not on Haiku, so `waveOut` and `PlaySound` find no
device.
- No printers. Only "Save as PDF" is available, because Haiku has no
CUPS.
- Drag and drop works between the program's own windows only.
- The input methods of Haiku do not send text to the program.
- The Deskbar shows a generic icon for the program, not the icon of
its windows.
## Test on Haiku
The CI job `cross-haiku` builds the libraries. It does not run the
tests. To test a program, copy it to Haiku R1/beta6 (for example, in
QEMU) and start it from a Terminal.
+1
View File
@@ -29,6 +29,7 @@ nav:
- "32-bit DOS": dos.md
- "Classic Mac OS": macos-classic.md
- "Mac OS X 10.0 to 10.5": macosx-10.4.md
- "Haiku": haiku.md
- "Screen savers": screensavers.md
- "Software OpenGL": software-opengl.md
- "WinHelp viewer": winhelp.md
+2 -2
View File
@@ -1,6 +1,6 @@
// malloc.h - the C runtime's memory header: malloc and the rest from
// <stdlib.h>, alloca, and _alloca, _msize-free names that Win32 programs
// use. Linux and the C libraries of the classic Mac OS and DOS have their
// use. Linux, Haiku and the C libraries of the classic Mac OS and DOS have their
// own malloc.h, which comes first.
//
// Part of clang-retro MFC, an independent implementation of the MFC API.
@@ -8,7 +8,7 @@
#ifndef _WINPORT_MALLOC_H
#define _WINPORT_MALLOC_H
#if (defined(__linux__) || defined(macintosh) || defined(__MSDOS__)) && __has_include_next(<malloc.h>)
#if (defined(__linux__) || defined(__HAIKU__) || defined(macintosh) || defined(__MSDOS__)) && __has_include_next(<malloc.h>)
#include_next <malloc.h>
#endif
#include <alloca.h>
+14 -2
View File
@@ -7,8 +7,8 @@
// programs run without a display. Without it macOS uses Cocoa; elsewhere
// the compositor is used when WAYLAND_DISPLAY names one, then the X
// display when DISPLAY names one, and headless otherwise. On the classic
// Mac OS the Toolbox shows the windows, and on 32-bit DOS the DOS backend
// (backend_dos.cpp). WINPORT_SCREEN=WIDTHxHEIGHT sets the headless
// Mac OS the Toolbox shows the windows, on Haiku the Interface Kit
// (backend_haiku.cpp), and on 32-bit DOS the DOS backend (backend_dos.cpp). WINPORT_SCREEN=WIDTHxHEIGHT sets the headless
// screen's size, and on DOS the screen mode's.
//
// Part of clang-retro MFC, an independent implementation of the MFC API.
@@ -108,6 +108,18 @@ Backend* GetBackend() {
}();
return b;
}
#elif defined(__HAIKU__)
// Haiku: the Interface Kit shows the windows, unless WINPORT_BACKEND is
// "headless" or there is no app_server.
Backend* GetBackend() {
static Backend* b = [] {
const char* name = getenv("WINPORT_BACKEND");
Backend* b = NULL;
if (!name || strcmp(name, "headless") != 0) b = NewHaikuBackend();
return b ? b : NewHeadlessBackend();
}();
return b;
}
#else
Backend* GetBackend() {
static Backend* b = [] {
+402
View File
@@ -0,0 +1,402 @@
// backend_haiku.cpp - the window manager's half of the Haiku backend,
// which shows top-level windows on Haiku (see haiku.h and haiku_be.cpp).
//
// The keys are those of a PC keyboard, as Haiku names them: Control is
// Control, the Alt key (Haiku's Command key, by default) is Alt, and the
// Windows key (Haiku's Option key) is the Windows key. Thus Control+C
// copies and Alt+F opens the File menu, as on Windows.
//
// Part of clang-retro MFC, an independent implementation of the MFC API.
// SPDX-License-Identifier: AGPL-3.0-only
#include "user.h"
#if defined(__HAIKU__)
#include "haiku.h"
#include <set>
namespace winport {
namespace {
struct Native {
Window* w = NULL;
haiku::Win* win = NULL;
bool popup = false;
};
std::set<Native*> g_natives;
// The window of an owner that the other half gives, or NULL when that
// window has gone.
Native* Valid(void* owner) {
Native* n = (Native*)owner;
return g_natives.count(n) ? n : NULL;
}
// The window that keys go to: the owner's, or the program's active
// window when a popup is in front of it.
Native* KeyNative(void* owner) {
Native* n = Valid(owner);
if (n && !n->popup) return n;
HWND active = GetActiveWindow();
for (Native* c : g_natives)
if (c->w->hwnd == active) return c;
return n;
}
// The keys by Haiku's key code, which names a place on the keyboard
// rather than what the key types. With Num Lock off, the keys of the
// numeric keypad are those of kKeypadNav.
const BYTE kHaikuKeys[0x6A] = {
0, VK_ESCAPE, VK_F1, VK_F2, VK_F3, VK_F4, VK_F5, VK_F6, // 0x00
VK_F7, VK_F8, VK_F9, VK_F10, VK_F11, VK_F12, VK_SNAPSHOT, VK_SCROLL, // 0x08
VK_PAUSE, VK_OEM_3, '1', '2', '3', '4', '5', '6', // 0x10
'7', '8', '9', '0', VK_OEM_MINUS, VK_OEM_PLUS, VK_BACK, VK_INSERT, // 0x18
VK_HOME, VK_PRIOR, VK_NUMLOCK, VK_DIVIDE, VK_MULTIPLY, VK_SUBTRACT, VK_TAB, 'Q', // 0x20
'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', // 0x28
'P', VK_OEM_4, VK_OEM_6, VK_OEM_5, VK_DELETE, VK_END, VK_NEXT, VK_NUMPAD7, // 0x30
VK_NUMPAD8, VK_NUMPAD9, VK_ADD, VK_CAPITAL, 'A', 'S', 'D', 'F', // 0x38
'G', 'H', 'J', 'K', 'L', VK_OEM_1, VK_OEM_7, VK_RETURN, // 0x40
VK_NUMPAD4, VK_NUMPAD5, VK_NUMPAD6, VK_LSHIFT, 'Z', 'X', 'C', 'V', // 0x48
'B', 'N', 'M', VK_OEM_COMMA, VK_OEM_PERIOD, VK_OEM_2, VK_RSHIFT, VK_UP, // 0x50
VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD3, VK_RETURN, VK_LCONTROL, VK_LMENU, VK_SPACE, VK_RMENU, // 0x58
VK_RCONTROL, VK_LEFT, VK_DOWN, VK_RIGHT, VK_NUMPAD0, VK_DECIMAL, VK_LWIN, VK_RWIN, // 0x60
VK_APPS, VK_OEM_102, // 0x68
};
// A key of the numeric keypad with Num Lock off: the key it works as.
UINT KeypadNav(unsigned code) {
switch (code) {
case 0x37: return VK_HOME;
case 0x38: return VK_UP;
case 0x39: return VK_PRIOR;
case 0x48: return VK_LEFT;
case 0x49: return VK_CLEAR;
case 0x4A: return VK_RIGHT;
case 0x58: return VK_END;
case 0x59: return VK_DOWN;
case 0x5A: return VK_NEXT;
case 0x64: return VK_INSERT;
case 0x65: return VK_DELETE;
}
return 0;
}
// Whether Windows marks a key as extended (bit 24 of lParam): the
// arrows and the block above them, the right Control and Alt, the
// keypad's divide and Enter, and the Windows and menu keys.
bool Extended(unsigned code) {
switch (code) {
case 0x1F: case 0x20: case 0x21: case 0x34: case 0x35: case 0x36: // Insert to Page Down
case 0x57: case 0x61: case 0x62: case 0x63: // the arrows
case 0x5F: case 0x60: // right Alt and Control
case 0x23: case 0x5B: // keypad / and Enter
case 0x66: case 0x67: case 0x68: case 0x0E: // Windows, menu, Print Screen
return true;
}
return false;
}
// The first character of UTF-8 text, or 0.
wchar_t FirstChar(const std::string& s) {
if (s.empty()) return 0;
std::wstring w = Widen(s.c_str(), (int)s.size());
return w.empty() ? 0 : w[0];
}
struct HaikuBackend : Backend {
const char* Name() override { return "haiku"; }
// Gives the size of the screen.
SIZE ScreenSize() override {
int w, h;
haiku::ScreenSize(&w, &h);
return SIZE{w, h};
}
// Gives the screen without the Deskbar.
RECT WorkArea() override {
int x, y, w, h;
haiku::WorkArea(&x, &y, &w, &h);
return RECT{x, y, x + w, y + h};
}
// Menus, drop-downs and tooltips float; windows with a caption, or
// shown in the Deskbar, are ordinary windows.
static bool IsPopup(Window* w) {
if ((w->style & WS_CAPTION) == WS_CAPTION) return false;
if (w->exStyle & WS_EX_APPWINDOW) return false;
return (w->style & WS_POPUP) != 0;
}
// Gives the window's title to Haiku, which shows it in the Deskbar.
static void SetTitle(Native* n) { haiku::SetTitle(n->win, Narrow(n->w->text.c_str(), (int)n->w->text.size())); }
// Copies the part r of the window's surface to the Haiku window.
static void Put(Native* n, const RECT& r) {
Surface* s = n->w->surface;
if (!s || s->width <= 0 || s->height <= 0) return;
haiku::Blit(n->win, (const uint32_t*)s->pixels.data(), s->width, s->width, s->height, r.left, r.top,
r.right - r.left, r.bottom - r.top);
}
// Shows or hides a top-level window. Makes its Haiku window when necessary.
void Show(Window* w, bool show) override {
Native* n = (Native*)w->native;
if (!n) {
if (!show) return;
n = new Native;
n->w = w;
n->popup = IsPopup(w);
RECT r = w->rect;
g_natives.insert(n);
n->win = haiku::Create(n, r.left, r.top, r.right - r.left, r.bottom - r.top, n->popup);
w->native = n;
SetTitle(n);
}
if (show && w->surface) Put(n, RECT{0, 0, w->surface->width, w->surface->height});
haiku::Show(n->win, !show ? haiku::kHide : (n->popup || (w->style & WS_DISABLED)) ? haiku::kShow : haiku::kShowKey);
}
// Releases the Haiku window of a top-level window.
void Destroy(Window* w) override {
Native* n = (Native*)w->native;
if (!n) return;
haiku::Destroy(n->win);
g_natives.erase(n);
w->native = NULL;
delete n;
}
// Moves and resizes the Haiku window to the window's rectangle.
void Moved(Window* w) override {
Native* n = (Native*)w->native;
if (!n) return;
RECT r = w->rect;
haiku::SetFrame(n->win, r.left, r.top, r.right - r.left, r.bottom - r.top);
}
// Sets the Haiku window's title to the window's text.
void TitleChanged(Window* w) override {
if (Native* n = (Native*)w->native) SetTitle(n);
}
// Copies the part r of the window's surface to the screen.
void Present(Window* w, const RECT& r) override {
if (Native* n = (Native*)w->native) Put(n, r);
}
// Sets the pointer's shape from a cursor handle.
void SetCursor(HCURSOR h) override {
CursorPicture p;
bool have = h && CursorImage(h, &p);
if (!have) p.systemId = 32512;
haiku::SetCursor(!h, p.systemId, (const uint32_t*)p.argb.data(), p.width, p.height, p.hotspot.x, p.hotspot.y);
}
uint32_t clipboardCount = 0; // the system clipboard's, when this program last set it
bool clipboardSet = false;
// Tells if another program changed the clipboard since generation.
bool ClipboardForeign(DWORD* generation) override {
uint32_t count = haiku::ClipboardCount();
if (clipboardSet && count == clipboardCount) return false;
*generation = (DWORD)count;
return true;
}
// Gives the system clipboard's text.
bool ClipboardFetch(std::wstring* text) override {
std::string u;
if (!haiku::ClipboardText(&u)) return false;
*text = Widen(u.c_str(), (int)u.size());
return true;
}
// Puts the program's text on the system clipboard.
void ClipboardOwn(const std::wstring& text) override {
clipboardCount = haiku::SetClipboardText(Narrow(text.c_str(), (int)text.size()));
clipboardSet = true;
}
void Wait(DWORD timeout) override { haiku::Wait(timeout == INFINITE ? -1 : (long)timeout); }
void Wake() override { haiku::Wake(); }
};
unsigned g_buttons; // MK_ flags of the buttons down
// The MK_ flags of the buttons and of Shift and Control.
WPARAM Keys(unsigned mods) {
WPARAM k = g_buttons;
if (mods & haiku::kShift) k |= MK_SHIFT;
if (mods & haiku::kControl) k |= MK_CONTROL;
return k;
}
} // namespace
// Makes the Haiku backend. NULL when there is no app_server.
Backend* NewHaikuBackend() {
if (!haiku::Start()) return NULL;
return new HaikuBackend;
}
namespace haiku {
// Sends a mouse move or button to the window manager.
void OnMouse(void* owner, int kind, int button, int x, int y, unsigned mods) {
Native* n = Valid(owner);
if (!n) return;
static const UINT down[] = {WM_LBUTTONDOWN, WM_RBUTTONDOWN, WM_MBUTTONDOWN};
static const UINT up[] = {WM_LBUTTONUP, WM_RBUTTONUP, WM_MBUTTONUP};
static const unsigned flag[] = {MK_LBUTTON, MK_RBUTTON, MK_MBUTTON};
UINT msg = WM_MOUSEMOVE;
if (kind == kDown) {
msg = down[button];
g_buttons |= flag[button];
} else if (kind == kUp) {
msg = up[button];
g_buttons &= ~flag[button];
}
// A disabled window (the owner of a modal dialog) takes no mouse
// input. A click on it brings its last active popup to the front, as
// on Windows.
if ((n->w->style & WS_DISABLED) && !GetCapture()) {
if (kind != kDown) return;
Native* pop = n;
HWND h = GetLastActivePopup(n->w->hwnd);
for (Native* p : g_natives)
if (p->w->hwnd == h && h != n->w->hwnd && IsWindowEnabled(h)) pop = p;
if (pop != n) {
SetForegroundWindow(pop->w->hwnd);
haiku::Show(pop->win, kShowKey);
}
return;
}
MouseInput(n->w, msg, x, y, Keys(mods));
}
// Sends the wheel's notches to the window manager, keeping fractions.
void OnWheel(void* owner, int x, int y, double up, double right, unsigned mods) {
static double acc[2];
double d[2] = {up, right};
for (int i = 0; i < 2; i++) {
acc[i] += d[i];
int notches = (int)acc[i];
acc[i] -= notches;
Native* n = Valid(owner);
if (!notches || !n) continue;
MouseInput(n->w, i == 0 ? WM_MOUSEWHEEL : WM_MOUSEHWHEEL, x, y,
MAKEWPARAM(Keys(mods), (WORD)(short)(notches * WHEEL_DELTA)));
}
}
// Sends a key, and the character it types, to the window manager.
void OnKey(void* owner, bool down, unsigned code, unsigned mods, const std::string& text, unsigned rawChar) {
Native* n = KeyNative(owner);
if (!n) return;
UINT vk = code < sizeof kHaikuKeys ? kHaikuKeys[code] : 0;
bool keypad = KeypadNav(code) != 0;
if (keypad && !(mods & kNumLock)) vk = KeypadNav(code);
// The modifier keys come as OnModifier, and Caps Lock as its state.
switch (vk) {
case VK_LSHIFT: case VK_RSHIFT: case VK_LCONTROL: case VK_RCONTROL:
case VK_LMENU: case VK_RMENU: case VK_LWIN: case VK_RWIN: case VK_CAPITAL:
return;
}
// Letters and digits follow the keyboard's layout.
if (!keypad) {
unsigned c = rawChar;
if (c >= 'a' && c <= 'z') vk = c - 'a' + 'A';
else if (c >= 'A' && c <= 'Z') vk = c;
else if (c >= '0' && c <= '9') vk = c;
}
LPARAM lp = 1 | ((LPARAM)(code & 0xFF) << 16) | (Extended(code) ? (1 << 24) : 0);
wchar_t ch = 0;
if (down) {
switch (vk) {
case VK_BACK: ch = '\b'; break;
case VK_RETURN: ch = '\r'; break;
case VK_TAB: ch = '\t'; break;
case VK_ESCAPE: ch = 0x1B; break;
default:
ch = FirstChar(text);
// Haiku's characters for the arrows, Home, Delete and the
// function keys: Windows types none.
if (ch < 0x20 || ch == 0x7F) ch = 0;
if (keypad && !(mods & kNumLock)) ch = 0;
break;
}
// Control with a letter types the control character.
if ((mods & kControl) && vk >= 'A' && vk <= 'Z') ch = (wchar_t)(vk - 'A' + 1);
// Alt with a key is a menu's mnemonic: the character with no
// modifiers, as WM_SYSCHAR has it.
if ((mods & kAlt) && !(mods & kControl) && rawChar >= 0x20 && rawChar < 0x7F) ch = (wchar_t)rawChar;
}
if (ch) lp |= 0x02000000; // the character comes from here, not TranslateMessage
if (vk) KeyInput(n->w, down ? WM_KEYDOWN : WM_KEYUP, vk, lp);
if (ch) CharInput(n->w, ch);
}
// Sends a modifier key (Shift, Control, Alt or Windows) to the window manager.
void OnModifier(void* owner, unsigned mod, bool right, bool down) {
Native* n = KeyNative(owner);
if (!n) return;
UINT vk = 0;
unsigned code = 0;
switch (mod) {
case kShift: vk = right ? VK_RSHIFT : VK_LSHIFT, code = right ? 0x56 : 0x4B; break;
case kControl: vk = right ? VK_RCONTROL : VK_LCONTROL, code = right ? 0x60 : 0x5C; break;
case kAlt: vk = right ? VK_RMENU : VK_LMENU, code = right ? 0x5F : 0x5D; break;
case kWin: vk = right ? VK_RWIN : VK_LWIN, code = right ? 0x67 : 0x66; break;
case kCapsLock: vk = VK_CAPITAL, code = 0x3B; break;
}
if (!vk) return;
LPARAM lp = 1 | ((LPARAM)code << 16) | (Extended(code) ? (1 << 24) : 0);
if (mod == kCapsLock) {
// Caps Lock reports only its state: it is pressed and let go at once.
KeyInput(n->w, WM_KEYDOWN, vk, lp);
KeyInput(n->w, WM_KEYUP, vk, lp);
return;
}
KeyInput(n->w, down ? WM_KEYDOWN : WM_KEYUP, vk, lp);
}
// Tells the window manager that the window became active, or is no longer.
void OnActivated(void* owner, bool active) {
Native* n = Valid(owner);
if (!n || n->popup || !active) return;
HWND h = n->w->hwnd;
if (GetActiveWindow() != h && IsWindowEnabled(h)) SetActiveWindow(h);
}
// Asks the active window to close, when the system asks the program to quit.
void OnQuit() {
// As Alt+F4 would: the active window is asked to close.
HWND active = GetActiveWindow();
for (Native* n : g_natives)
if (n->w->hwnd == active && !n->popup) {
CloseRequested(n->w);
return;
}
for (Native* n : g_natives)
if (!n->popup && n->w->Visible()) {
CloseRequested(n->w);
return;
}
PostQuitMessage(0);
}
} // namespace haiku
} // namespace winport
#else
namespace winport {
Backend* NewHaikuBackend() { return NULL; }
} // namespace winport
#endif
+8
View File
@@ -354,6 +354,14 @@ std::vector<std::string> FontDirs() {
dirs.push_back("/System/Library/Fonts");
dirs.push_back("/Library/Fonts");
if (home) dirs.push_back(std::string(home) + "/Library/Fonts");
#elif defined(__HAIKU__)
// The fonts of the packages and those put in by hand, the user's first.
if (home) {
dirs.push_back(std::string(home) + "/config/non-packaged/data/fonts");
dirs.push_back(std::string(home) + "/config/data/fonts");
}
dirs.push_back("/boot/system/non-packaged/data/fonts");
dirs.push_back("/boot/system/data/fonts");
#else
if (const char* xdg = getenv("XDG_DATA_HOME"))
dirs.push_back(std::string(xdg) + "/fonts");
+90
View File
@@ -0,0 +1,90 @@
// haiku.h - between the Haiku backend's two halves: haiku_be.cpp, which
// uses the Interface Kit and sees none of the Windows headers, and
// backend_haiku.cpp, which uses the window manager and sees none of
// Haiku's headers. Their types and macros clash, so neither includes the
// other's.
//
// The Interface Kit runs each window in a thread of its own, and the
// application's messages in one more. Input from those threads is put in
// a queue, which Wait empties on the program's thread: the On functions
// below are called there and only there, as the window manager needs.
//
// Coordinates are Windows' screen coordinates: from the top left of the
// main screen, growing down, in pixels. Mouse positions are in the
// window, from its top left.
//
// Part of clang-retro MFC, an independent implementation of the MFC API.
// SPDX-License-Identifier: AGPL-3.0-only
#ifndef _WINPORT_HAIKU_H
#define _WINPORT_HAIKU_H
#include <stddef.h>
#include <stdint.h>
#include <string>
namespace winport {
namespace haiku {
// Called on the window manager's side (backend_haiku.cpp). A window is
// known to the other side by its owner, an opaque pointer.
struct Win;
// Starts the application (BApplication) in a thread of its own. False
// when there is no app_server to show windows on.
bool Start();
void ScreenSize(int* width, int* height);
// The screen without the Deskbar, when the Deskbar is on one edge.
void WorkArea(int* x, int* y, int* width, int* height);
// A window with no border: the window manager draws the caption and the
// frame. A popup (a menu, a drop-down, a tooltip) floats over the
// program's windows and does not take the focus.
Win* Create(void* owner, int x, int y, int width, int height, bool popup);
void Destroy(Win* w);
enum { kHide, kShow, kShowKey };
void Show(Win* w, int how);
void SetFrame(Win* w, int x, int y, int width, int height);
void SetTitle(Win* w, const std::string& utf8);
// Copies the part (x, y, width, height) of the window's pixels
// (0x00RRGGBB in the machine's byte order, top row first, stride pixels
// to a row, of a surface surfaceWidth by surfaceHeight) to the window,
// and draws it.
void Blit(Win* w, const uint32_t* pixels, int stride, int surfaceWidth, int surfaceHeight, int x, int y, int width,
int height);
// The pointer's shape: a system cursor by its IDC_ number, or else the
// picture (ARGB, not premultiplied, top row first); hidden hides it.
void SetCursor(bool hidden, int systemId, const uint32_t* argb, int width, int height, int hotX, int hotY);
// The system clipboard: the number that changes each time something new
// goes there, its text (false when it has none), and putting text there,
// which returns the new number.
uint32_t ClipboardCount();
bool ClipboardText(std::string* utf8);
uint32_t SetClipboardText(const std::string& utf8);
// Takes and handles input for up to timeout ms (-1 for no limit), or
// until Wake.
void Wait(long timeout);
void Wake();
// Called on the window manager's side, on the program's thread, with
// the owner given to Create.
enum { kShift = 1, kControl = 2, kAlt = 4, kWin = 8, kCapsLock = 16, kNumLock = 32 };
enum { kMove, kDown, kUp };
// button: 0 left, 1 right, 2 middle. x and y are in the window.
void OnMouse(void* owner, int kind, int button, int x, int y, unsigned mods);
// In notches: up and right are positive.
void OnWheel(void* owner, int x, int y, double up, double right, unsigned mods);
// A key, by Haiku's key code (a place on the keyboard), down or up, with
// the UTF-8 text it types (empty for none) and the character it types
// with no modifiers (rawChar, 0 for none).
void OnKey(void* owner, bool down, unsigned code, unsigned mods, const std::string& text, unsigned rawChar);
// A modifier key, down or up: mod is one of kShift, kControl, kAlt and
// kWin, and right tells the right key from the left.
void OnModifier(void* owner, unsigned mod, bool right, bool down);
// The window has become the active one, or is no longer.
void OnActivated(void* owner, bool active);
// The system asks the program to quit (the Deskbar's Quit, or shutdown).
void OnQuit();
} // namespace haiku
} // namespace winport
#endif
+628
View File
@@ -0,0 +1,628 @@
// haiku_be.cpp - the Interface Kit's half of the Haiku backend, which
// shows top-level windows on Haiku (see haiku.h and backend_haiku.cpp).
//
// Each top-level window is a BWindow with no border and one BView, which
// draws a BBitmap: the window's pixels, as Blit copies them there. The
// application (BApplication) runs in a thread of its own, and each
// window in its own thread, as the Interface Kit does it. Their input
// goes into one queue, which Wait empties on the program's thread.
//
// After Create, the program's threads never lock a window: they send the
// window a message, and the window does the work in its own thread. A
// window's thread never takes the window manager's lock. Thus the two
// cannot wait for each other.
//
// Part of clang-retro MFC, an independent implementation of the MFC API.
// SPDX-License-Identifier: AGPL-3.0-only
#if defined(__HAIKU__)
#include "haiku.h"
#include <Application.h>
#include <Bitmap.h>
#include <Clipboard.h>
#include <Cursor.h>
#include <Deskbar.h>
#include <Message.h>
#include <Messenger.h>
#include <OS.h>
#include <Screen.h>
#include <View.h>
#include <Window.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <chrono>
#include <condition_variable>
#include <deque>
#include <functional>
#include <memory>
#include <mutex>
#include <vector>
namespace winport {
namespace haiku {
namespace {
// The messages that the program's thread sends to a window.
enum : uint32 {
kMsgShow = 'wpSh',
kMsgHide = 'wpHi',
kMsgFrame = 'wpFr',
kMsgTitle = 'wpTi',
kMsgDraw = 'wpDr',
kMsgQuit = 'wpQu',
};
// The queue of input for the program's thread.
std::mutex g_queueLock;
std::condition_variable g_queueCv;
std::deque<std::function<void()>> g_queue;
bool g_woken = false;
// Puts a call in the queue, for Wait to make on the program's thread.
void Post(std::function<void()> f) {
{
std::lock_guard<std::mutex> g(g_queueLock);
g_queue.push_back(std::move(f));
}
g_queueCv.notify_all();
}
// The modifiers of a Haiku message as haiku.h has them. Haiku's Control
// is Control, its Command (the Alt key, by default) is Alt, and its
// Option (the Windows key) is the Windows key.
unsigned Mods(uint32 m) {
unsigned r = 0;
if (m & B_SHIFT_KEY) r |= kShift;
if (m & B_CONTROL_KEY) r |= kControl;
if (m & B_COMMAND_KEY) r |= kAlt;
if (m & B_OPTION_KEY) r |= kWin;
if (m & B_CAPS_LOCK) r |= kCapsLock;
if (m & B_NUM_LOCK) r |= kNumLock;
return r;
}
// The modifiers of the message that the window handles now, or of the
// keyboard when there is none.
unsigned CurrentMods(BWindow* w) {
BMessage* m = w ? w->CurrentMessage() : NULL;
int32 mods;
if (m && m->FindInt32("modifiers", &mods) == B_OK) return Mods((uint32)mods);
return Mods(modifiers());
}
// What a window draws: its pixels, which both threads use, with a lock.
struct Canvas {
std::mutex lock;
BBitmap* bitmap = NULL;
BRect dirty; // the part to draw, not yet drawn (invalid for none)
bool pending = false; // a kMsgDraw is on its way
~Canvas() { delete bitmap; }
};
// The view that draws the window's pixels and takes the mouse.
class WinportView : public BView {
public:
// A view that fills its window, with the canvas that it draws.
WinportView(BRect frame, void* owner, std::shared_ptr<Canvas> canvas)
: BView(frame, "winport", B_FOLLOW_ALL, B_WILL_DRAW), owner_(owner), canvas_(canvas) {
SetViewColor(B_TRANSPARENT_COLOR);
SetDrawingMode(B_OP_COPY);
}
// Draws the part of the canvas that the Interface Kit asks for.
void Draw(BRect update) override {
std::lock_guard<std::mutex> g(canvas_->lock);
if (canvas_->bitmap) {
BRect r = update & canvas_->bitmap->Bounds();
if (r.IsValid()) DrawBitmap(canvas_->bitmap, r, r);
Sync();
}
}
// A button goes down: the view takes the mouse until all go up, as
// Windows does with a capture.
void MouseDown(BPoint where) override {
SetMouseEventMask(B_POINTER_EVENTS, B_NO_POINTER_HISTORY);
Buttons(where);
}
// A button goes up.
void MouseUp(BPoint where) override { Buttons(where); }
// The mouse moves, over the view or (with buttons down) anywhere.
void MouseMoved(BPoint where, uint32 /*transit*/, const BMessage* /*drag*/) override {
void* o = owner_;
int x = (int)where.x, y = (int)where.y;
unsigned mods = CurrentMods(Window());
Post([=] { OnMouse(o, kMove, 0, x, y, mods); });
}
// The wheel, as notches (Haiku's positive y is down).
void MessageReceived(BMessage* m) override {
if (m->what == B_MOUSE_WHEEL_CHANGED) {
float dx = 0, dy = 0;
m->FindFloat("be:wheel_delta_x", &dx);
m->FindFloat("be:wheel_delta_y", &dy);
BPoint where;
uint32 buttons;
GetMouse(&where, &buttons, false);
void* o = owner_;
int x = (int)where.x, y = (int)where.y;
unsigned mods = CurrentMods(Window());
Post([=] { OnWheel(o, x, y, -dy, dx, mods); });
return;
}
BView::MessageReceived(m);
}
private:
// The buttons of the current message against those down before: a
// down or an up for each one that changed.
void Buttons(BPoint where) {
BMessage* m = Window()->CurrentMessage();
int32 now = 0;
if (m) m->FindInt32("buttons", &now);
void* o = owner_;
int x = (int)where.x, y = (int)where.y;
unsigned mods = CurrentMods(Window());
static const int32 kButton[3] = {B_PRIMARY_MOUSE_BUTTON, B_SECONDARY_MOUSE_BUTTON, B_TERTIARY_MOUSE_BUTTON};
for (int b = 0; b < 3; b++) {
bool was = (buttons_ & kButton[b]) != 0, is = (now & kButton[b]) != 0;
if (was == is) continue;
int kind = is ? kDown : kUp;
Post([=] { OnMouse(o, kind, b, x, y, mods); });
}
buttons_ = now;
}
void* owner_;
std::shared_ptr<Canvas> canvas_;
int32 buttons_ = 0;
};
// A top-level window: a BWindow with no border, which takes the keys
// before the Interface Kit's shortcuts can.
class WinportWindow : public BWindow {
public:
// A window at frame (on the screen), ordinary or a popup.
WinportWindow(BRect frame, void* owner, bool popup, std::shared_ptr<Canvas> canvas)
: BWindow(frame, "", B_NO_BORDER_WINDOW_LOOK, popup ? B_FLOATING_APP_WINDOW_FEEL : B_NORMAL_WINDOW_FEEL,
B_WILL_ACCEPT_FIRST_CLICK | B_NOT_ANCHORED_ON_ACTIVATE |
(popup ? (B_AVOID_FOCUS | B_NOT_MOVABLE | B_NOT_RESIZABLE) : 0)),
owner_(owner),
canvas_(canvas) {
view_ = new WinportView(Bounds(), owner, canvas);
AddChild(view_);
}
// The keys and the modifiers go to the program as they come: no
// shortcuts of the Interface Kit (Alt+Q, Alt+W) take them first.
void DispatchMessage(BMessage* m, BHandler* target) override {
switch (m->what) {
case B_KEY_DOWN: case B_UNMAPPED_KEY_DOWN: case B_KEY_UP: case B_UNMAPPED_KEY_UP: {
int32 key = 0, mods = 0, raw = 0;
m->FindInt32("key", &key);
m->FindInt32("modifiers", &mods);
m->FindInt32("raw_char", &raw);
const char* bytes = NULL;
m->FindString("bytes", &bytes);
std::string text = bytes ? bytes : "";
bool down = m->what == B_KEY_DOWN || m->what == B_UNMAPPED_KEY_DOWN;
void* o = owner_;
unsigned code = (unsigned)key, md = Mods((uint32)mods), rc = (unsigned)raw;
Post([=] { OnKey(o, down, code, md, text, rc); });
return;
}
case B_MODIFIERS_CHANGED: {
int32 now = 0, old = 0;
m->FindInt32("modifiers", &now);
m->FindInt32("be:old_modifiers", &old);
Modifiers((uint32)old, (uint32)now);
return;
}
}
BWindow::DispatchMessage(m, target);
}
// The program's requests (haiku.h), in the window's thread.
void MessageReceived(BMessage* m) override {
switch (m->what) {
case kMsgShow: {
if (IsHidden()) Show();
if (m->GetBool("activate", false)) Activate(true);
return;
}
case kMsgHide:
if (!IsHidden()) Hide();
return;
case kMsgFrame: {
BRect r;
if (m->FindRect("frame", &r) == B_OK) {
MoveTo(r.LeftTop());
ResizeTo(r.Width(), r.Height());
}
return;
}
case kMsgTitle: {
const char* t = NULL;
if (m->FindString("title", &t) == B_OK) SetTitle(t);
return;
}
case kMsgDraw: {
BRect r;
{
std::lock_guard<std::mutex> g(canvas_->lock);
r = canvas_->dirty;
canvas_->dirty = BRect();
canvas_->pending = false;
}
if (r.IsValid()) view_->Invalidate(r);
return;
}
case kMsgQuit:
Quit();
return;
}
BWindow::MessageReceived(m);
}
// The window becomes active, or is no longer.
void WindowActivated(bool active) override {
void* o = owner_;
if (active) view_->MakeFocus(true);
Post([=] { OnActivated(o, active); });
}
// A window with no border has no close button: the program decides
// when it goes (kMsgQuit), not the Interface Kit.
bool QuitRequested() override { return false; }
private:
// A key for each modifier that changed, and Caps Lock (a state that
// the key turns on and off).
void Modifiers(uint32 old, uint32 now) {
struct Bit {
uint32 bit;
unsigned mod;
bool right;
};
static const Bit kBits[] = {
{B_LEFT_SHIFT_KEY, kShift, false}, {B_RIGHT_SHIFT_KEY, kShift, true},
{B_LEFT_CONTROL_KEY, kControl, false}, {B_RIGHT_CONTROL_KEY, kControl, true},
{B_LEFT_COMMAND_KEY, kAlt, false}, {B_RIGHT_COMMAND_KEY, kAlt, true},
{B_LEFT_OPTION_KEY, kWin, false}, {B_RIGHT_OPTION_KEY, kWin, true},
};
void* o = owner_;
for (const Bit& b : kBits) {
bool was = (old & b.bit) != 0, is = (now & b.bit) != 0;
if (was == is) continue;
unsigned mod = b.mod;
bool right = b.right;
Post([=] { OnModifier(o, mod, right, is); });
}
if ((old ^ now) & B_CAPS_LOCK) Post([=] { OnModifier(o, kCapsLock, false, true); });
}
void* owner_;
std::shared_ptr<Canvas> canvas_;
WinportView* view_;
};
// The application: it runs in its own thread (AppThread) and tells the
// program when the system asks it to quit.
class WinportApp : public BApplication {
public:
// The application, with its MIME signature; status tells whether the
// app_server took it.
WinportApp(const char* signature, status_t* status) : BApplication(signature, status) {}
// The Deskbar's Quit, or shutdown: the program decides (OnQuit).
bool QuitRequested() override {
Post([] { OnQuit(); });
return false;
}
};
sem_id g_started = -1;
status_t g_status = B_ERROR;
// The application's signature: WINPORT_HAIKU_SIGNATURE, or one made from
// the program's name ("application/x-vnd.winport-dmodem-win32").
std::string Signature() {
if (const char* s = getenv("WINPORT_HAIKU_SIGNATURE"))
if (*s) return s;
std::string name = "program";
image_info info;
int32 cookie = 0;
while (get_next_image_info(B_CURRENT_TEAM, &cookie, &info) == B_OK) {
if (info.type != B_APP_IMAGE) continue;
const char* base = strrchr(info.name, '/');
name = base ? base + 1 : info.name;
break;
}
std::string sig = "application/x-vnd.winport-";
for (char c : name) sig += ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) ? c : '-';
return sig;
}
// The application's thread: makes the BApplication and runs it until
// the process ends.
int32 AppThread(void*) {
std::string sig = Signature();
WinportApp* app = new WinportApp(sig.c_str(), &g_status);
release_sem(g_started);
if (g_status != B_OK) {
delete app;
return 0;
}
app->Run();
return 0;
}
} // namespace
// The handle that the window manager keeps for a window.
struct Win {
WinportWindow* window;
BMessenger to;
std::shared_ptr<Canvas> canvas;
bool popup = false;
};
// Starts the BApplication in a thread of its own (see haiku.h).
bool Start() {
static bool started = false, ok = false;
if (started) return ok;
started = true;
if (be_app) {
// The program has its own BApplication.
ok = true;
return ok;
}
g_started = create_sem(0, "winport start");
thread_id t = spawn_thread(AppThread, "winport application", B_NORMAL_PRIORITY, NULL);
if (t < 0) return false;
resume_thread(t);
acquire_sem(g_started);
delete_sem(g_started);
ok = g_status == B_OK && be_app;
if (!ok) fprintf(stderr, "winport: no app_server; windows stay in memory\n");
return ok;
}
// Gives the size of the main screen in pixels.
void ScreenSize(int* width, int* height) {
BScreen s(B_MAIN_SCREEN_ID);
BRect f = s.IsValid() ? s.Frame() : BRect(0, 0, 1023, 767);
*width = (int)f.Width() + 1;
*height = (int)f.Height() + 1;
}
// Gives the screen without the Deskbar, when the Deskbar is on one edge.
void WorkArea(int* x, int* y, int* width, int* height) {
int w, h;
ScreenSize(&w, &h);
BRect area(0, 0, w, h);
BDeskbar deskbar;
if (deskbar.IsRunning()) {
BRect d = deskbar.Frame();
switch (deskbar.Location()) {
case B_DESKBAR_TOP: area.top = d.bottom + 1; break;
case B_DESKBAR_BOTTOM: area.bottom = d.top; break;
case B_DESKBAR_LEFT_TOP: case B_DESKBAR_LEFT_BOTTOM:
if (deskbar.IsExpanded()) area.left = d.right + 1;
break;
case B_DESKBAR_RIGHT_TOP: case B_DESKBAR_RIGHT_BOTTOM:
if (deskbar.IsExpanded()) area.right = d.left;
break;
}
}
*x = (int)area.left;
*y = (int)area.top;
*width = (int)(area.right - area.left);
*height = (int)(area.bottom - area.top);
}
// Makes a hidden window with no border for the owner.
Win* Create(void* owner, int x, int y, int width, int height, bool popup) {
Win* w = new Win;
w->canvas = std::make_shared<Canvas>();
w->popup = popup;
if (width < 1) width = 1;
if (height < 1) height = 1;
// (Be rectangles hold their right and bottom edges.)
w->window = new WinportWindow(BRect(x, y, x + width - 1, y + height - 1), owner, popup, w->canvas);
w->to = BMessenger(w->window);
// The window's thread starts now, with the window still hidden (Hide
// and then Show leave it hidden once). From now on that thread owns
// the window, and the other threads send it messages. Thus any thread
// of the program can show, move or destroy it.
w->window->Hide();
w->window->Show();
return w;
}
// Closes the window and releases it.
void Destroy(Win* w) {
if (!w) return;
w->to.SendMessage(kMsgQuit);
delete w;
}
// Hides or shows the window, and activates it for kShowKey.
void Show(Win* w, int how) {
BMessage m(how == kHide ? kMsgHide : kMsgShow);
m.AddBool("activate", how == kShowKey);
w->to.SendMessage(&m);
}
// Moves and resizes the window (screen coordinates).
void SetFrame(Win* w, int x, int y, int width, int height) {
if (width < 1) width = 1;
if (height < 1) height = 1;
BRect r(x, y, x + width - 1, y + height - 1);
BMessage m(kMsgFrame);
m.AddRect("frame", r);
w->to.SendMessage(&m);
}
// Sets the window's title, which the Deskbar shows.
void SetTitle(Win* w, const std::string& utf8) {
BMessage m(kMsgTitle);
m.AddString("title", utf8.c_str());
w->to.SendMessage(&m);
}
void Blit(Win* w, const uint32_t* pixels, int stride, int surfaceWidth, int surfaceHeight, int x, int y, int width,
int height) {
if (surfaceWidth <= 0 || surfaceHeight <= 0) return;
Canvas* c = w->canvas.get();
bool send = false;
{
std::lock_guard<std::mutex> g(c->lock);
BRect all(0, 0, surfaceWidth - 1, surfaceHeight - 1);
if (!c->bitmap || c->bitmap->Bounds() != all) {
// A new size: the whole surface goes into a new bitmap.
delete c->bitmap;
c->bitmap = new BBitmap(all, B_RGB32);
x = 0;
y = 0;
width = surfaceWidth;
height = surfaceHeight;
}
if (x < 0) width += x, x = 0;
if (y < 0) height += y, y = 0;
if (x + width > surfaceWidth) width = surfaceWidth - x;
if (y + height > surfaceHeight) height = surfaceHeight - y;
if (width <= 0 || height <= 0 || !c->bitmap->IsValid()) return;
// B_RGB32 is B, G, R, unused: 0x00RRGGBB in little-endian order.
uint8* bits = (uint8*)c->bitmap->Bits();
int32 bpr = c->bitmap->BytesPerRow();
for (int row = y; row < y + height; row++)
memcpy(bits + (size_t)row * bpr + (size_t)x * 4, pixels + (size_t)row * stride + x, (size_t)width * 4);
BRect r(x, y, x + width - 1, y + height - 1);
c->dirty = c->dirty.IsValid() ? (c->dirty | r) : r;
if (!c->pending) {
c->pending = true;
send = true;
}
}
if (send) w->to.SendMessage(kMsgDraw);
}
// Sets the shape of the pointer: hidden, a system cursor or a picture.
void SetCursor(bool hidden, int systemId, const uint32_t* argb, int width, int height, int hotX, int hotY) {
if (!be_app) return;
static bool isHidden = false;
static int lastId = -1;
static std::vector<uint32_t> lastPicture;
static BCursor* custom = NULL;
if (hidden) {
if (!isHidden) be_app->HideCursor();
isHidden = true;
return;
}
if (isHidden) be_app->ShowCursor();
isHidden = false;
std::vector<uint32_t> picture;
if (!systemId && argb && width > 0 && height > 0) picture.assign(argb, argb + (size_t)width * height);
if (systemId == lastId && picture == lastPicture) return;
lastId = systemId;
lastPicture = picture;
if (systemId) {
BCursorID id = B_CURSOR_ID_SYSTEM_DEFAULT;
switch (systemId) {
case 32513: id = B_CURSOR_ID_I_BEAM; break; // IDC_IBEAM
case 32514: case 32650: id = B_CURSOR_ID_PROGRESS; break; // IDC_WAIT, IDC_APPSTARTING
case 32515: id = B_CURSOR_ID_CROSS_HAIR; break; // IDC_CROSS
case 32516: id = B_CURSOR_ID_RESIZE_NORTH; break; // IDC_UPARROW
case 32642: id = B_CURSOR_ID_RESIZE_NORTH_WEST_SOUTH_EAST; break; // IDC_SIZENWSE
case 32643: id = B_CURSOR_ID_RESIZE_NORTH_EAST_SOUTH_WEST; break; // IDC_SIZENESW
case 32644: id = B_CURSOR_ID_RESIZE_EAST_WEST; break; // IDC_SIZEWE
case 32645: id = B_CURSOR_ID_RESIZE_NORTH_SOUTH; break; // IDC_SIZENS
case 32646: id = B_CURSOR_ID_MOVE; break; // IDC_SIZEALL
case 32648: id = B_CURSOR_ID_NOT_ALLOWED; break; // IDC_NO
case 32649: id = B_CURSOR_ID_FOLLOW_LINK; break; // IDC_HAND
case 32651: id = B_CURSOR_ID_HELP; break; // IDC_HELP
}
BCursor c(id);
be_app->SetCursor(&c, true);
return;
}
if (picture.empty()) return;
// B_RGBA32 is B, G, R, A: 0xAARRGGBB in little-endian order.
BBitmap bitmap(BRect(0, 0, width - 1, height - 1), B_RGBA32);
if (!bitmap.IsValid()) return;
uint8* bits = (uint8*)bitmap.Bits();
for (int row = 0; row < height; row++)
memcpy(bits + (size_t)row * bitmap.BytesPerRow(), argb + (size_t)row * width, (size_t)width * 4);
BCursor* next = new BCursor(&bitmap, BPoint(hotX, hotY));
be_app->SetCursor(next, true);
delete custom;
custom = next;
}
// Gives the number that changes each time the clipboard changes.
uint32_t ClipboardCount() {
if (!be_clipboard) return 0;
return be_clipboard->SystemCount();
}
// Gives the clipboard's text. False when it has no text.
bool ClipboardText(std::string* utf8) {
if (!be_clipboard || !be_clipboard->Lock()) return false;
bool ok = false;
const char* text = NULL;
ssize_t length = 0;
if (BMessage* data = be_clipboard->Data())
if (data->FindData("text/plain", B_MIME_TYPE, (const void**)&text, &length) == B_OK && text) {
utf8->assign(text, (size_t)length);
ok = true;
}
be_clipboard->Unlock();
return ok;
}
// Puts the text on the clipboard and gives the new clipboard number.
uint32_t SetClipboardText(const std::string& utf8) {
if (!be_clipboard || !be_clipboard->Lock()) return 0;
be_clipboard->Clear();
if (!utf8.empty())
if (BMessage* data = be_clipboard->Data()) data->AddData("text/plain", B_MIME_TYPE, utf8.data(), utf8.size());
be_clipboard->Commit();
uint32_t count = be_clipboard->SystemCount();
be_clipboard->Unlock();
return count;
}
// Handles the queued input for up to timeout ms (-1: no limit), or until Wake.
void Wait(long timeout) {
std::deque<std::function<void()>> todo;
{
std::unique_lock<std::mutex> g(g_queueLock);
auto ready = [] { return g_woken || !g_queue.empty(); };
if (timeout < 0)
g_queueCv.wait(g, ready);
else
g_queueCv.wait_for(g, std::chrono::milliseconds(timeout), ready);
g_woken = false;
todo.swap(g_queue);
}
for (std::function<void()>& f : todo) f();
}
// Stops a Wait on the program's thread.
void Wake() {
{
std::lock_guard<std::mutex> g(g_queueLock);
g_woken = true;
}
g_queueCv.notify_all();
}
} // namespace haiku
} // namespace winport
#endif
+16
View File
@@ -527,6 +527,18 @@ std::string CommDevice(const std::string& name) {
std::sort(devs.begin(), devs.end());
if ((size_t)num <= devs.size()) return "/dev/" + devs[num - 1];
return "-";
#elif defined(__HAIKU__)
// The serial ports in /dev/ports, in order: pc_serial0 and the others
// on the board first, then usb0 and the others on USB.
std::vector<std::string> devs;
if (DIR* d = opendir("/dev/ports")) {
while (dirent* e = readdir(d))
if (e->d_name[0] != '.') devs.push_back(e->d_name);
closedir(d);
}
std::sort(devs.begin(), devs.end());
if ((size_t)num <= devs.size()) return "/dev/ports/" + devs[num - 1];
return "-";
#else
return "/dev/ttyS" + std::to_string(num - 1);
#endif
@@ -590,12 +602,16 @@ BOOL WINAPI GetCommState(HANDLE h, LPDCB d) {
d->DCBlength = sizeof(DCB);
d->fBinary = 1;
d->BaudRate = BaudOf(cfgetospeed(&t));
#if CS5 == CS6 // Haiku: 7 and 8 bits only, and CS5 to CS7 are 0
d->ByteSize = (t.c_cflag & CSIZE) == CS8 ? 8 : 7;
#else
switch (t.c_cflag & CSIZE) {
case CS5: d->ByteSize = 5; break;
case CS6: d->ByteSize = 6; break;
case CS7: d->ByteSize = 7; break;
default: d->ByteSize = 8; break;
}
#endif
d->Parity = NOPARITY;
if (t.c_cflag & PARENB) {
#ifdef CMSPAR
+5
View File
@@ -705,7 +705,12 @@ std::string winport::ConfigDir() {
base = x;
} else {
const char* h = getenv("HOME");
#ifdef __HAIKU__
// Haiku keeps the settings of programs in ~/config/settings.
base = std::string(h && *h ? h : "/boot/home") + "/config/settings";
#else
base = std::string(h && *h ? h : "/tmp") + "/.config";
#endif
}
return base + "/libmfc";
}
+21
View File
@@ -34,10 +34,22 @@
#elif defined(__MSDOS__)
#include <dos.h> // __argc and __argv
#include <link.h>
#elif defined(__HAIKU__)
#include <image.h> // get_next_image_info
#include <link.h>
// Haiku's C library keeps the program's arguments here (it has no /proc).
extern "C" int __libc_argc;
extern "C" char** __libc_argv;
#else
#include <link.h>
#endif
// Haiku has no RTLD_NOLOAD. There a dlopen of a library that is loaded
// gives its handle, and of one that is not loads it.
#ifndef RTLD_NOLOAD
#define RTLD_NOLOAD 0
#endif
#include <mutex>
#include <string>
#include <vector>
@@ -118,6 +130,13 @@ std::string ExecutablePath() {
for (char& c : p)
if (c == '\\') c = '/';
return p;
#elif defined(__HAIKU__)
// The image of the program itself (Haiku has no /proc).
image_info info;
int32 cookie = 0;
while (get_next_image_info(B_CURRENT_TEAM, &cookie, &info) == B_OK)
if (info.type == B_APP_IMAGE) return RealPath(info.name);
return std::string();
#else
char buf[PATH_MAX];
ssize_t n = readlink("/proc/self/exe", buf, sizeof buf - 1);
@@ -826,6 +845,8 @@ std::vector<std::string> Argv() {
if (i == 0 || strncmp(argv[i], "-psn_", 5) != 0) v.push_back(argv[i]);
#elif defined(__MSDOS__)
for (int i = 0; i < __argc; i++) v.push_back(__argv[i]);
#elif defined(__HAIKU__)
for (int i = 0; i < __libc_argc && __libc_argv; i++) v.push_back(__libc_argv[i]);
#else
FILE* f = fopen("/proc/self/cmdline", "rb");
if (f) {
+1
View File
@@ -463,6 +463,7 @@ Backend* NewHeadlessBackend();
Backend* NewX11Backend(); // NULL when there is no X display
Backend* NewWaylandBackend(); // NULL when there is no Wayland compositor
Backend* NewCocoaBackend(); // NULL except on macOS
Backend* NewHaikuBackend(); // the Interface Kit, on Haiku only; NULL with no app_server
Backend* NewMacBackend(); // the Toolbox, on the classic Mac OS only
Backend* NewDosBackend(); // VESA or VGA, on 32-bit DOS only
+2 -1
View File
@@ -97,7 +97,8 @@ std::string PosixPath(const char* path);
std::string PosixPath(const wchar_t* path);
// The layer's configuration directory, where the registry and .ini files
// are: $XDG_CONFIG_HOME/libmfc, or ~/.config/libmfc.
// are: $XDG_CONFIG_HOME/libmfc, or ~/.config/libmfc (on Haiku,
// ~/config/settings/libmfc).
std::string ConfigDir();
// The registry file: $WINPORT_REGISTRY, or registry.reg there.
std::string RegistryPath();
+7
View File
@@ -9,6 +9,9 @@
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#ifdef __HAIKU__
#include <sys/sockio.h> // SIOCATMARK
#endif
#include <signal.h>
#include <map>
#include <set>
@@ -44,7 +47,9 @@ const ErrnoMap kErrors[] = {
{EPROTOTYPE, WSAEPROTOTYPE},
{ENOPROTOOPT, WSAENOPROTOOPT},
{EPROTONOSUPPORT, WSAEPROTONOSUPPORT},
#ifdef ESOCKTNOSUPPORT // (not on Haiku)
{ESOCKTNOSUPPORT, WSAESOCKTNOSUPPORT},
#endif
{EOPNOTSUPP, WSAEOPNOTSUPP},
{EPFNOSUPPORT, WSAEPFNOSUPPORT},
{EAFNOSUPPORT, WSAEAFNOSUPPORT},
@@ -60,7 +65,9 @@ const ErrnoMap kErrors[] = {
{EISCONN, WSAEISCONN},
{ENOTCONN, WSAENOTCONN},
{ESHUTDOWN, WSAESHUTDOWN},
#ifdef ETOOMANYREFS // (not on Haiku)
{ETOOMANYREFS, WSAETOOMANYREFS},
#endif
{ETIMEDOUT, WSAETIMEDOUT},
{ECONNREFUSED, WSAECONNREFUSED},
{ELOOP, WSAELOOP},