Merge main: use the Haiku port of #175, keep the fixes it does not have

main now has a Haiku backend (#175). This branch takes it in place of
its own backend (haiku_be.cpp and its CI job are removed), and keeps
only these changes on top of it:

- RTLD_NOLOAD and ESOCKTNOSUPPORT are optional, so that the library
  also builds with the headers of Haiku R1/beta5 (the sysroot of
  D-Modem's haiku_sysroot.py, which the D-Modem GUI uses).
- COMn is the nth serial port in /dev/ports.
- A click on a disabled window (the owner of a modal dialog) brings
  the dialog to the front and does not go to the window.
- docs/haiku.md tells these items.

Tested with the D-Modem GUI on Haiku R1/beta6 in QEMU.

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:46:52 +00:00
commit 7c56025a50
28 files changed
+1674 -1170

No files matched your search

+75 -34
View File
@@ -226,6 +226,81 @@ jobs:
build/arm64-apple-macos11/tests/a
build/arm64-apple-macos11/tests/u
# Haiku: the libraries over the portable layer with the Haiku backend,
# built with the runner's clang 18 against a sysroot made from Haiku's
# own packages (clang-retro/unix-sdk's haiku/build-sysroot.sh). For
# x86_64, the tests and the showcase sample run in the newest nightly
# image of Haiku in QEMU with KVM, and the screenshots of the sample are
# kept. For 32-bit x86 the tests are only built.
haiku:
runs-on: ubuntu-24.04
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
include:
- { arch: x86_64, triple: x86_64-unknown-haiku, image: x86_64, run: true }
- { arch: x86, triple: i586-pc-haiku, image: x86_gcc2h, run: false }
steps:
- uses: actions/checkout@v4
with:
submodules: true
- uses: actions/checkout@v4
with:
repository: clang-retro/unix-sdk
path: unix-sdk
persist-credentials: false
- name: Install the tools
run: |
sudo apt-get update -q
sudo apt-get install -y -q --no-install-recommends clang lld llvm python3-zstandard \
${{ matrix.run && 'qemu-system-x86' || '' }}
- name: Restore the sysroot packages
uses: actions/cache@v4
with:
path: ~/haiku-packages
key: haiku-packages-v1-${{ matrix.arch }}-${{ github.run_id }}
restore-keys: haiku-packages-v1-${{ matrix.arch }}-
- name: Build the sysroot
run: |
rm -f ~/haiku-packages/*.repo
ARCH=${{ matrix.arch }} WORK=$HOME/haiku-packages unix-sdk/haiku/build-sysroot.sh $RUNNER_TEMP/sysroot
- name: Build
run: make -j"$(nproc)" TARGET=${{ matrix.triple }} SYSROOT=$RUNNER_TEMP/sysroot STDLIB= AR=llvm-ar
- name: Find the newest Haiku image
if: matrix.run
id: image
run: echo "name=$(LIST=1 unix-sdk/haiku/tools/fetch-image.sh ${{ matrix.image }})" >> "$GITHUB_OUTPUT"
- name: Restore the Haiku image
if: matrix.run
uses: actions/cache@v4
with:
path: ~/haiku-images
key: ${{ steps.image.outputs.name }}
# The runner has KVM, but only for the group kvm; a udev rule opens it.
- name: Enable KVM
if: matrix.run
run: |
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm.rules
sudo udevadm control --reload-rules
sudo udevadm trigger --name-match=kvm
- name: Test
run: |
if [ "${{ matrix.run }}" = true ]; then
export HAIKU_IMAGE=$(unix-sdk/haiku/tools/fetch-image.sh ${{ matrix.image }} ~/haiku-images)
fi
make check TARGET=${{ matrix.triple }} SYSROOT=$RUNNER_TEMP/sysroot STDLIB= AR=llvm-ar \
HAIKU_VM=unix-sdk/haiku/tools/haiku-vm.py
- uses: actions/upload-artifact@v4
if: always()
with:
name: test-output-haiku-${{ matrix.arch }}
path: |
build/${{ matrix.triple }}/tests/a
build/${{ matrix.triple }}/tests/u
build/${{ matrix.triple }}/tests/shots
build/${{ matrix.triple }}/tests/*.log
# Mac OS X 10.4 on PowerPC and Intel: builds the libraries against the
# macosx10.4 sysroot of the nightly (libc++ and the builtins) and Apple's
# MacOSX10.4u.sdk. This libc++ does not declare std::abs and other
@@ -255,37 +330,3 @@ 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 --cache haiku-packages \
"$RUNNER_TEMP/haiku-sysroot" 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
+13 -18
View File
@@ -46,16 +46,6 @@ 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++).
@@ -98,6 +88,12 @@ else
OUT ?= build/$(TARGET)
TARGET_FLAGS = --target=$(TARGET) $(if $(SYSROOT),--sysroot=$(SYSROOT),)
endif
# Haiku (make TARGET=x86_64-unknown-haiku SYSROOT=...): its BSD
# functions (timegm, dl_iterate_phdr) need _DEFAULT_SOURCE and libbsd.
ifneq ($(findstring haiku,$(TARGET)),)
HAIKU = 1
TARGET_FLAGS += -D_DEFAULT_SOURCE
endif
ifeq ($(PORTABLE)$(SYSROOT),1)
PREFIX ?= /usr/local
endif
@@ -151,7 +147,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 $(HAIKU_FLAGS)
ALL_CXXFLAGS += -Iport/include -fPIC
endif
PORT_LIB = $(OUT)/libwinport.a
SCRNSAVE_LIBS = $(OUT)/libscrnsave.a $(OUT)/libscrnsavw.a
@@ -260,16 +256,13 @@ ifneq ($(findstring darwin,$(TARGET))$(findstring apple,$(TARGET)),)
SHLIB_EXT = dylib
SHLIB_SYSLIBS = -framework Cocoa -framework OpenGL -lpthread
SHLIB_FLAGS = -dynamiclib -Wl,-install_name,@rpath/$(notdir $@) -Wl,-rpath,@loader_path
else ifeq ($(HAIKU),1)
SHLIB_EXT = so
SHLIB_SYSLIBS = -lbe -lnetwork -lbsd
SHLIB_FLAGS = -shared -Wl,-soname,$(notdir $@)
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
@@ -452,6 +445,8 @@ else ifeq ($(MACOS_CLASSIC),1)
BIN=$(BIN) MACSDK=$(MACSDK) TARGET=$(TARGET) OUT=$(OUT) sh tests/run-macos-tests.sh
else ifeq ($(WIN16),1)
BIN=$(BIN) SYSROOT=$(SYSROOT) OUT=$(OUT) sh tests/run-win16-tests.sh
else ifeq ($(HAIKU),1)
BIN=$(BIN) SYSROOT=$(SYSROOT) TARGET=$(TARGET) OUT=$(OUT) sh tests/run-haiku-tests.sh
else
BIN=$(BIN) STDLIB="$(STDLIB)" RC="$(TEST_RC)" LDFLAGS="$(LDFLAGS)" CFG=$(CFG) SYSROOT=$(SYSROOT) TARGET=$(TARGET) OUT=$(OUT) sh tests/run-tests.sh
endif
+4 -7
View File
@@ -98,6 +98,10 @@ clang++ -std=c++17 -Ipath/to/mfc/port/include -Ipath/to/mfc/include app.cpp \
On macOS the system libraries are `-framework Cocoa -framework OpenGL -lpthread` instead
of `-ldl -lpthread`.
The libraries also build for Haiku (`TARGET=x86_64-unknown-haiku` or
`i586-pc-haiku`, with a sysroot from clang-retro/unix-sdk), where the
windows show with the Be API. See [Haiku](docs/haiku.md).
`make install` (to `/usr/local`, or `PREFIX=dir`; `DESTDIR` works too)
puts the headers in `include/libmfc` (the portable layer's in
`include/libmfc/winport`), the static libraries in `lib`, the shared
@@ -542,13 +546,6 @@ 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
Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

+106 -95
View File
@@ -1,124 +1,135 @@
# 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.
The portable layer and the library build for [Haiku](https://www.haiku-os.org/)
R1 on x86_64 and on 32-bit x86. The windows show with the Haiku backend,
which uses the Be API (`BApplication`, `BWindow`, `BView`, `BBitmap`).
## 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.
- clang 18 or later, with `ld.lld`. Upstream clang has a Haiku driver.
You can use the clang of your Linux system.
- A Haiku sysroot. clang-retro/unix-sdk's `haiku/build-sysroot.sh` makes
one from the packages of Haiku and HaikuPorts. You do not need a copy
of Haiku:
```sh
python3 platforms/haiku/haiku_sysroot.py haiku-sysroot \
haiku haiku_devel gcc gcc_syslibs gcc_syslibs_devel
```
```sh
unix-sdk/haiku/build-sysroot.sh haiku-sysroot # x86_64
ARCH=x86 unix-sdk/haiku/build-sysroot.sh haiku-sysroot32 # 32-bit x86
```
A sysroot from D-Modem's `platforms/haiku/haiku_sysroot.py` (the
packages of Haiku R1/beta5) also builds the x86_64 library.
## Build the library
```sh
make TARGET=x86_64-unknown-haiku SYSROOT=path/to/haiku-sysroot STDLIB= all
make TARGET=x86_64-unknown-haiku SYSROOT=path/to/haiku-sysroot STDLIB=
make TARGET=i586-pc-haiku SYSROOT=path/to/haiku-sysroot32 STDLIB=
```
`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`.
The build adds `-D_DEFAULT_SOURCE`, because Haiku declares some BSD and
GNU functions (for example `timegm` and `dl_iterate_phdr`) only with it.
The output is in `build/TARGET`: the static libraries, and the shared
libraries in `build/TARGET/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
clang++ --target=x86_64-unknown-haiku --sysroot=path/to/haiku-sysroot -fuse-ld=lld \
-std=c++17 -D_DEFAULT_SOURCE -Ipath/to/mfc/port/include -Ipath/to/mfc/include app.cpp \
-Lpath/to/mfc/build/x86_64-unknown-haiku -lmfc -lwinport -lbe -lnetwork -lbsd -o app
```
Compile the resources with `port/tools/res2cpp.py`. Link these system
libraries:
Compile the resources with `port/tools/res2cpp.py`, as on Linux.
| Library | Contents |
|--------------|----------------------------------------------|
| `libbe` | The Interface Kit and the clipboard. |
| `libnetwork` | The sockets (Winsock, WinInet). |
| `libbsd` | `timegm` and `dl_iterate_phdr`. |
## The Haiku backend
The threads and `dlopen` are in `libroot`, which clang links
automatically.
The backend has two parts, because the headers of Haiku and the headers
of the portable layer have types and macros with the same names:
## What the port does
| File | Contents |
|---|---|
| `port/src/haiku.h` | the interface between the two parts; it includes no headers of Haiku or of Windows |
| `port/src/backend_haiku_be.cpp` | the part that uses the Be API |
| `port/src/backend_haiku.cpp` | the part that uses the window manager of the layer |
The port uses the portable layer (`PORTABLE=1`), as on Linux. These parts
are special to Haiku:
How it works:
- **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 backend starts a `BApplication` on a thread of its own. The
signature of the application is `application/x-vnd.winport-NAME`, where
NAME is the name of the program file.
- Each top-level window is a `BWindow` with no border
(`B_NO_BORDER_WINDOW_LOOK`). The window manager of the layer draws the
frame and the caption into the pixels of the window, as on X11 and
Wayland.
- Menus, tooltips and drop-down lists are floating windows that do not
take the focus (`B_FLOATING_ALL_WINDOW_FEEL`, `B_AVOID_FOCUS`).
- The layer copies the pixels of a window into a `BBitmap`. A `BView`
draws the bitmap.
- The window threads put the mouse, keyboard and activation events into
a queue. The thread of the program takes them from the queue in
`Wait`.
- The Command key of Haiku (the key with the label Alt on a PC keyboard)
is Alt. The Option key (the Windows key) is the Windows key.
- The clipboard is `be_clipboard`, with `text/plain`.
- The fonts come from `/boot/system/data/fonts` and the font folders of
the user. The user interface font is Noto Sans.
- 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.
- `COM1` is the first serial port in `/dev/ports` (by name), `COM2` is
the second port, and so on. The path of a port (`/dev/ports/usb0`)
also opens it.
## The settings
Set `WINPORT_BACKEND=headless` to keep the windows in memory, as on
Linux.
| 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`. |
## Tests
## Limits
```sh
make check TARGET=x86_64-unknown-haiku SYSROOT=path/to/haiku-sysroot STDLIB= \
HAIKU_IMAGE=path/to/haiku-master-x86_64-anyboot.iso
```
- 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.
`tests/run-haiku-tests.sh` builds the tests and the showcase sample.
With `HAIKU_IMAGE`, it starts Haiku in QEMU with clang-retro/unix-sdk's
`haiku/tools/haiku-vm.py` and runs each test in Haiku. Without
`HAIKU_IMAGE`, it only builds the tests.
## Test on Haiku
| Variable | Default | Meaning |
|---|---|---|
| `HAIKU_IMAGE` | none | an anyboot image of Haiku, for example a nightly image |
| `HAIKU_VM` | `../unix-sdk/haiku/tools/haiku-vm.py` | the VM tool |
| `HAIKU_VM_PORT` | `8765` | the port of the VM tool on the host |
| `HAIKU_VM_RUNNING` | none | `1` to use a `haiku-vm.py serve` that runs already (started with `--files build/TARGET/tests`) |
| `HAIKU_TESTS` | all the tests | the names of the tests to build and run |
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.
The tests run with the headless backend. The showcase sample
(`samples/showcase`) runs with the Haiku backend. It opens its dialogs
by itself and the script keeps a screenshot of each step in
`build/TARGET/tests/shots`.
Without KVM, Haiku takes about five minutes to start in QEMU. With KVM,
it takes less than one minute.
Differences from Linux in the tests:
- The tests run in `/boot/home/mfc`, because `/tmp` is a symbolic link
in Haiku and some tests compare paths.
- The registry file is not watched with a node monitor. The layer looks
at the file four times a second.
- `odbctest`, `inettest`, `atlnettest` and `wtltest` are not in the
list: Haiku has no unixODBC package for the sysroot, and the others
need a network server or WTL on the host.
## Screenshots
The showcase sample on Haiku (x86_64, nightly hrev60504):
![The main window](assets/haiku/showcase-main.png)
![The settings dialog](assets/haiku/showcase-settings.png)
![The main window with the new settings](assets/haiku/showcase-changed.png)
![The about box](assets/haiku/showcase-about.png)
+2 -2
View File
@@ -36,8 +36,8 @@ enum REParseError {
class CAtlRECharTraitsA {
public:
typedef char RECHAR;
static RECHAR ToLower(RECHAR ch) { return (RECHAR)::tolower((unsigned char)ch); }
static RECHAR ToUpper(RECHAR ch) { return (RECHAR)::toupper((unsigned char)ch); }
static RECHAR ToLower(RECHAR ch) { return (RECHAR)(::tolower)((unsigned char)ch); }
static RECHAR ToUpper(RECHAR ch) { return (RECHAR)(::toupper)((unsigned char)ch); }
static size_t Length(const RECHAR* psz) { return ::strlen(psz); }
};
+16 -15
View File
@@ -6,9 +6,10 @@
// "headless" keeps every window in memory, which suits tests and
// 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, 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
// display when DISPLAY names one, and headless otherwise. On Haiku the
// Haiku backend (backend_haiku.cpp) shows the windows. 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
// screen's size, and on DOS the screen mode's.
//
// Part of clang-retro MFC, an independent implementation of the MFC API.
@@ -96,6 +97,18 @@ Backend* GetBackend() {
}();
return b;
}
#elif defined(__HAIKU__)
// Haiku: app_server shows the windows (backend_haiku.cpp), 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;
}
#elif defined(macintosh)
// The classic Mac OS: the Toolbox shows the windows, unless
// WINPORT_BACKEND is "headless" or the Toolbox cannot.
@@ -108,18 +121,6 @@ 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 = [] {
+220 -268
View File
@@ -1,10 +1,11 @@
// 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).
// which shows top-level windows on Haiku (see haiku.h and
// backend_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.
// Keys reach the program as they would on Windows, by their place on the
// keyboard: the key marked Ctrl is Control, the key marked Alt (Haiku's
// Command key) is Alt, and the Windows key (Haiku's Option key) is the
// Windows key. Letters and digits follow the keyboard layout.
//
// Part of clang-retro MFC, an independent implementation of the MFC API.
// SPDX-License-Identifier: AGPL-3.0-only
@@ -14,6 +15,7 @@
#include "haiku.h"
#include <algorithm>
#include <set>
namespace winport {
@@ -24,105 +26,209 @@ struct Native {
Window* w = NULL;
haiku::Win* win = NULL;
bool popup = false;
std::vector<DWORD> composed; // a translucent window's look, made opaque
};
std::set<Native*> g_natives;
unsigned g_buttons; // MK_ flags of the mouse buttons down
// The window of an owner that the other half gives, or NULL when that
// window has gone.
// The native window of an owner pointer from an event, or NULL when that
// window is 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
// The virtual keys by Haiku's key code (the place of the key on the
// keyboard), from 0x00 to 0x6B.
const BYTE kHaikuKeys[0x6C] = {
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, 0, 0, // 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
// Tells if a key is one of the extended keys of a PC keyboard (bit 24
// of a key message's lParam): the arrows and the keys above them, the
// right-hand modifiers, keypad Enter and keypad /.
bool Extended(unsigned key) {
switch (key) {
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
case 0x5b: case 0x23: case 0x5f: case 0x60: case 0x0e: // keypad Enter and /, right Alt and Ctrl
case 0x66: case 0x67: case 0x68: // Windows and Menu keys
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];
// Tells if a key types no character on Windows: the arrows, the editing
// keys above them, the function keys and the modifiers.
bool TypesNothing(UINT vk) {
switch (vk) {
case VK_INSERT: case VK_DELETE: case VK_HOME: case VK_END: case VK_PRIOR: case VK_NEXT:
case VK_LEFT: case VK_RIGHT: case VK_UP: case VK_DOWN: case VK_SNAPSHOT: case VK_SCROLL:
case VK_PAUSE: case VK_NUMLOCK: case VK_CAPITAL: 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_APPS:
return true;
}
return vk >= VK_F1 && vk <= VK_F24;
}
// The MK_ flags of the buttons and the modifiers held.
WPARAM Keys(unsigned mods) {
WPARAM k = g_buttons;
if (mods & haiku::kShift) k |= MK_SHIFT;
if (mods & haiku::kControl) k |= MK_CONTROL;
return k;
}
// Gives a key to the program, as WM_KEYDOWN or WM_KEYUP and the
// character it types.
void Key(Native* n, const haiku::Event& e) {
unsigned code = e.key;
UINT vk = code < sizeof kHaikuKeys ? kHaikuKeys[code] : 0;
// Letters and digits follow the keyboard's layout.
uint32_t plain = e.raw;
if (plain >= 'a' && plain <= 'z') vk = plain - 'a' + 'A';
else if (plain >= 'A' && plain <= 'Z') vk = plain;
else if (plain >= '0' && plain <= '9' && !(vk >= VK_NUMPAD0 && vk <= VK_NUMPAD9)) vk = plain;
bool down = e.kind == haiku::Event::kKeyDown;
LPARAM lp = 1 | ((LPARAM)(code & 0xFF) << 16) | (Extended(code) ? (1 << 24) : 0);
wchar_t ch = 0;
if (down && !TypesNothing(vk)) {
if (vk == VK_RETURN) ch = '\r';
else if (vk == VK_BACK) ch = '\b';
else if (vk == VK_TAB) ch = '\t';
else if (vk == VK_ESCAPE) ch = 0x1B;
else if ((e.mods & haiku::kControl) && !(e.mods & haiku::kAlt))
// Control with a letter types the control character.
ch = (vk >= 'A' && vk <= 'Z') ? (wchar_t)(vk - 'A' + 1) : 0;
else if (e.mods & haiku::kAlt)
// Alt with a letter is a menu's mnemonic: the plain letter.
ch = (plain >= 0x20 && plain < 0x7F) ? (wchar_t)plain : 0;
else if (e.ch >= 0x20 && e.ch != 0x7F)
ch = (wchar_t)e.ch;
}
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);
}
// The window that keys go to: the event's window, or the program's
// active window when the event's window is a popup or gone.
Native* KeyNative(void* owner) {
Native* n = Valid(owner);
if (!n || n->popup) {
HWND active = GetActiveWindow();
for (Native* c : g_natives)
if (c->w->hwnd == active) return c;
}
return n;
}
// Gives one event from the queue to the window manager.
void Handle(const haiku::Event& e) {
using haiku::Event;
if (e.kind == Event::kQuit) {
// Quit from the Deskbar: the active window is asked to close, as
// Alt+F4 would; with no window, the program ends.
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);
return;
}
if (e.kind == Event::kKeyDown || e.kind == Event::kKeyUp) {
if (Native* n = KeyNative(e.owner)) Key(n, e);
return;
}
Native* n = Valid(e.owner);
if (!n) return;
switch (e.kind) {
case Event::kMouseDown:
case Event::kMouseUp:
case Event::kMouseMove: {
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 (e.kind == Event::kMouseDown) {
msg = down[e.button];
g_buttons |= flag[e.button];
} else if (e.kind == Event::kMouseUp) {
msg = up[e.button];
g_buttons &= ~flag[e.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 (e.kind != Event::kMouseDown) break;
HWND h = GetLastActivePopup(n->w->hwnd);
for (Native* p : g_natives)
if (p->w->hwnd == h && h != n->w->hwnd && IsWindowEnabled(h)) {
SetForegroundWindow(h);
haiku::Show(p->win, true, true);
}
break;
}
MouseInput(n->w, msg, e.x, e.y, Keys(e.mods));
break;
}
case Event::kWheel: {
// Haiku's wheel moves down for a positive delta; Windows' moves up.
if (e.wheelY)
MouseInput(n->w, WM_MOUSEWHEEL, e.x, e.y, MAKEWPARAM(Keys(e.mods), (WORD)(short)(-e.wheelY * WHEEL_DELTA)));
if (e.wheelX)
MouseInput(n->w, WM_MOUSEHWHEEL, e.x, e.y, MAKEWPARAM(Keys(e.mods), (WORD)(short)(e.wheelX * WHEEL_DELTA)));
break;
}
case Event::kActivated:
if (e.active && !n->popup) {
HWND h = n->w->hwnd;
if (GetActiveWindow() != h && IsWindowEnabled(h)) SetActiveWindow(h);
}
break;
case Event::kClose:
CloseRequested(n->w);
break;
default:
break;
}
}
// UTF-8 text of a window's title.
std::string Utf8(const std::wstring& w) { return Narrow(w.c_str(), (int)w.size()); }
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) {
@@ -131,18 +237,6 @@ struct HaikuBackend : Backend {
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) {
@@ -154,13 +248,12 @@ struct HaikuBackend : Backend {
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);
haiku::SetTitle(n->win, Utf8(w->text));
Put(n, RECT{0, 0, r.right - r.left, r.bottom - r.top});
}
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);
haiku::Show(n->win, show, show && !n->popup && !(w->style & WS_DISABLED));
}
// Releases the Haiku window of a top-level window.
void Destroy(Window* w) override {
Native* n = (Native*)w->native;
if (!n) return;
@@ -170,7 +263,6 @@ struct HaikuBackend : Backend {
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;
@@ -178,17 +270,41 @@ struct HaikuBackend : Backend {
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);
if (Native* n = (Native*)w->native) haiku::SetTitle(n->win, Utf8(w->text));
}
void TranslucencyChanged(Window* w) override {
if (Native* n = (Native*)w->native)
if (w->surface) Put(n, RECT{0, 0, w->surface->width, w->surface->height});
}
// Copies a part of the window's surface to its bitmap. Haiku has no
// translucent windows: a translucent one is drawn over the panel color.
void Put(Native* n, const RECT& r) {
Surface* s = n->w->surface;
if (!s || s->width <= 0 || s->height <= 0) return;
const DWORD* px = s->pixels.data();
if (Translucent(n->w)) {
n->composed.resize((size_t)s->width * s->height);
Composite(n->w, RECT{0, 0, s->width, s->height}, n->composed.data(), s->width);
for (DWORD& p : n->composed) {
unsigned a = p >> 24, back = 255 - a;
unsigned red = ((p >> 16) & 0xFF) + 0xD8 * back / 255;
unsigned green = ((p >> 8) & 0xFF) + 0xD8 * back / 255;
unsigned blue = (p & 0xFF) + 0xD8 * back / 255;
p = (std::min(red, 255u) << 16) | (std::min(green, 255u) << 8) | std::min(blue, 255u);
}
px = n->composed.data();
}
haiku::Update(n->win, (const uint32_t*)px, s->width, s->height, s->width, r.left, r.top, r.right - r.left,
r.bottom - r.top);
}
// 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);
@@ -196,18 +312,15 @@ struct HaikuBackend : Backend {
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;
long clipboardCount = -1; // the system clipboard's, when this program last set it
// 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;
long count = haiku::ClipboardCount();
if (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;
@@ -215,182 +328,21 @@ struct HaikuBackend : Backend {
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 ClipboardOwn(const std::wstring& text) override { clipboardCount = haiku::SetClipboardText(Utf8(text)); }
void Wait(DWORD timeout) override { haiku::Wait(timeout == INFINITE ? -1 : (long)timeout); }
void Wait(DWORD timeout) override {
for (const haiku::Event& e : haiku::Take(timeout == INFINITE ? -1 : (long)timeout)) Handle(e);
}
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
+569
View File
@@ -0,0 +1,569 @@
// backend_haiku_be.cpp - the Haiku API 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 that
// shows a BBitmap: a copy of the window's pixels. The window manager
// draws the frame and the caption in those pixels, as it does on X11 and
// Wayland. The BWindow threads do not touch the window manager. They put
// the input in a queue, and the thread that waits for input (Take) takes
// it from there. The BApplication runs on a thread of its own.
//
// 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 <Message.h>
#include <OS.h>
#include <Screen.h>
#include <View.h>
#include <Window.h>
#include <image.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <chrono>
#include <condition_variable>
#include <deque>
#include <mutex>
namespace winport {
namespace haiku {
namespace {
// The message that asks a window to show the part of its bitmap that
// Update changed.
const uint32 kShowDirty = 'wpDy';
std::mutex g_queueLock;
std::condition_variable g_queueReady;
std::deque<Event> g_events;
bool g_woken = false;
bool g_exiting = false; // the program is ending: windows may close
thread_id g_appThread = -1;
// Puts one input event in the queue and wakes the waiting thread.
void Post(const Event& e) {
std::lock_guard<std::mutex> g(g_queueLock);
g_events.push_back(e);
g_queueReady.notify_all();
}
// The k flags of haiku.h for Haiku's modifier flags.
unsigned ModsOf(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;
return r;
}
// The first character of a UTF-8 string, or 0.
uint32_t FirstChar(const char* s) {
if (!s || !*s) return 0;
const unsigned char* p = (const unsigned char*)s;
if (p[0] < 0x80) return p[0];
int n = p[0] >= 0xF0 ? 3 : p[0] >= 0xE0 ? 2 : 1;
uint32_t c = p[0] & (0x3F >> n);
for (int i = 1; i <= n; i++) {
if ((p[i] & 0xC0) != 0x80) return 0;
c = (c << 6) | (p[i] & 0x3F);
}
return c;
}
// The Haiku key codes of the modifier keys, by the modifier flag that
// each one sets, for B_MODIFIERS_CHANGED.
struct ModifierKey {
uint32 flag;
unsigned key;
};
const ModifierKey kModifierKeys[] = {
{B_LEFT_SHIFT_KEY, 0x4b}, {B_RIGHT_SHIFT_KEY, 0x56}, {B_LEFT_CONTROL_KEY, 0x5c},
{B_RIGHT_CONTROL_KEY, 0x60}, {B_LEFT_COMMAND_KEY, 0x5d}, {B_RIGHT_COMMAND_KEY, 0x5f},
{B_LEFT_OPTION_KEY, 0x66}, {B_RIGHT_OPTION_KEY, 0x67},
};
// Tells if a key code is one of the modifier keys or Caps Lock.
bool IsModifierKey(unsigned key) {
if (key == 0x3b) return true;
for (const ModifierKey& m : kModifierKeys)
if (m.key == key) return true;
return false;
}
class PixelView;
} // namespace
// A window: the BWindow, its view, and the bitmap the view shows. The
// lock keeps the bitmap and the dirty rectangle.
struct Win {
void* owner = NULL;
BWindow* window = NULL;
PixelView* view = NULL;
std::mutex lock;
BBitmap* bitmap = NULL;
BRect dirty;
bool dirtyPosted = false;
bool shown = false;
uint32 buttons = 0; // the mouse buttons down, as Haiku gives them
};
namespace {
// The view that fills the window: it draws the bitmap and gives the
// mouse to the queue.
class PixelView : public BView {
public:
// Makes the view for a window, as big as the window.
PixelView(BRect frame, Win* w) : BView(frame, "winport", B_FOLLOW_ALL, B_WILL_DRAW), win(w) {
SetViewColor(B_TRANSPARENT_COLOR);
}
// Draws the part of the bitmap that the update rectangle covers.
void Draw(BRect r) override {
std::lock_guard<std::mutex> g(win->lock);
if (win->bitmap) DrawBitmap(win->bitmap, r, r);
}
// Sends a mouse event with the current message's modifiers.
void Send(Event::Kind kind, BPoint where, int button) {
Event e;
e.kind = kind;
e.owner = win->owner;
e.x = (int)where.x;
e.y = (int)where.y;
e.button = button;
e.mods = ModsOf(modifiers());
Post(e);
}
// Gives the buttons that were pressed. The view keeps the mouse until
// all of them are let go, also outside the window.
void MouseDown(BPoint where) override {
int32 buttons = 0;
if (BMessage* m = Window()->CurrentMessage()) m->FindInt32("buttons", &buttons);
if (!buttons) buttons = B_PRIMARY_MOUSE_BUTTON;
SetMouseEventMask(B_POINTER_EVENTS, B_NO_POINTER_HISTORY);
Buttons(where, (uint32)buttons);
}
// Gives the buttons that were let go.
void MouseUp(BPoint where) override {
int32 buttons = 0;
if (BMessage* m = Window()->CurrentMessage()) m->FindInt32("buttons", &buttons);
Buttons(where, (uint32)buttons);
}
// Gives a mouse move, also when it leaves the window.
void MouseMoved(BPoint where, uint32, const BMessage*) override { Send(Event::kMouseMove, where, 0); }
// Compares the buttons now down with those before, and sends a press
// or a release for each one that changed.
void Buttons(BPoint where, uint32 now) {
static const uint32 kFlags[3] = {B_PRIMARY_MOUSE_BUTTON, B_SECONDARY_MOUSE_BUTTON, B_TERTIARY_MOUSE_BUTTON};
for (int i = 0; i < 3; i++) {
bool was = (win->buttons & kFlags[i]) != 0, is = (now & kFlags[i]) != 0;
if (was != is) Send(is ? Event::kMouseDown : Event::kMouseUp, where, i);
}
win->buttons = now;
}
Win* win;
};
// A window: it sends the keys, the wheel, activation and closing to the
// queue, and shows the bitmap when Update asks it to.
class PixelWindow : public BWindow {
public:
// Makes a window with no border: floating and without the focus for a
// popup, an ordinary one otherwise.
PixelWindow(BRect frame, Win* w, bool popup)
: BWindow(frame, "", B_NO_BORDER_WINDOW_LOOK, popup ? B_FLOATING_ALL_WINDOW_FEEL : B_NORMAL_WINDOW_FEEL,
B_WILL_ACCEPT_FIRST_CLICK | B_NO_SERVER_SIDE_WINDOW_MODIFIERS | B_ASYNCHRONOUS_CONTROLS |
(popup ? B_AVOID_FOCUS : 0)),
win(w) {}
// Takes the keys before BWindow can use them as shortcuts, and the
// wheel; gives the other messages to BWindow.
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);
// The modifier keys come with B_MODIFIERS_CHANGED.
if (IsModifierKey((unsigned)key)) return;
Event e;
e.kind = (m->what == B_KEY_DOWN || m->what == B_UNMAPPED_KEY_DOWN) ? Event::kKeyDown : Event::kKeyUp;
e.owner = win->owner;
e.key = (unsigned)key;
e.mods = ModsOf((uint32)mods);
const char* bytes = NULL;
if (m->what == B_KEY_DOWN && m->FindString("bytes", &bytes) == B_OK) e.ch = FirstChar(bytes);
e.raw = (uint32_t)raw & 0xFF;
Post(e);
return;
}
case B_MODIFIERS_CHANGED: {
int32 now = 0, old = 0;
m->FindInt32("modifiers", &now);
m->FindInt32("be:old_modifiers", &old);
for (const ModifierKey& k : kModifierKeys) {
bool was = (old & k.flag) != 0, is = (now & k.flag) != 0;
if (was == is) continue;
Event e;
e.kind = is ? Event::kKeyDown : Event::kKeyUp;
e.owner = win->owner;
e.key = k.key;
e.mods = ModsOf((uint32)now);
Post(e);
}
if ((old ^ now) & B_CAPS_LOCK) {
// Caps Lock is pressed and let go at once, as its state says.
Event e;
e.kind = Event::kKeyDown;
e.owner = win->owner;
e.key = 0x3b;
e.mods = ModsOf((uint32)now);
Post(e);
e.kind = Event::kKeyUp;
Post(e);
}
return;
}
case 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;
win->view->GetMouse(&where, &buttons, false);
Event e;
e.kind = Event::kWheel;
e.owner = win->owner;
e.x = (int)where.x;
e.y = (int)where.y;
e.wheelX = dx;
e.wheelY = dy;
e.mods = ModsOf(modifiers());
Post(e);
return;
}
}
BWindow::DispatchMessage(m, target);
}
// Shows the part of the bitmap that changed since the last time.
void MessageReceived(BMessage* m) override {
if (m->what == kShowDirty) {
BRect r;
{
std::lock_guard<std::mutex> g(win->lock);
r = win->dirty;
win->dirtyPosted = false;
win->dirty = BRect();
}
if (r.IsValid()) win->view->Invalidate(r);
return;
}
BWindow::MessageReceived(m);
}
// Tells the window manager that the window became active or not.
void WindowActivated(bool active) override {
Event e;
e.kind = Event::kActivated;
e.owner = win->owner;
e.active = active;
Post(e);
}
// Asks the window manager to close the window (Alt+F4 does the same
// on Windows); the window stays until the program destroys it.
bool QuitRequested() override {
if (g_exiting) return true;
Event e;
e.kind = Event::kClose;
e.owner = win->owner;
Post(e);
return false;
}
Win* win;
};
// The application: Quit from the Deskbar asks the program to end.
class PixelApp : public BApplication {
public:
// Makes the application with a signature from the program's name.
explicit PixelApp(const char* signature) : BApplication(signature) {}
// Gives the program a quit event instead of quitting, unless the
// program is ending.
bool QuitRequested() override {
if (g_exiting) return BApplication::QuitRequested();
Event e;
e.kind = Event::kQuit;
Post(e);
return false;
}
};
// Runs the application's message loop. The thread made the BApplication,
// so it is the application's thread.
int32 AppThread(void* data) {
PixelApp* app = new PixelApp((const char*)data);
free(data);
app->Run();
delete app;
return 0;
}
// Ends the application when the program ends: the windows may close
// now, and the application thread finishes.
void StopApp() {
if (g_appThread < 0 || !be_app) return;
g_exiting = true;
be_app->PostMessage(B_QUIT_REQUESTED);
status_t ignored;
wait_for_thread(g_appThread, &ignored);
g_appThread = -1;
}
// The application signature: application/x-vnd.winport-NAME, from the
// file name of the program, with the characters a MIME type allows.
char* Signature() {
std::string path;
const char* name = "program";
if (ImagePath(&path)) {
size_t slash = path.rfind('/');
name = path.c_str() + (slash == std::string::npos ? 0 : slash + 1);
}
std::string sig = "application/x-vnd.winport-";
for (const char* p = name; *p && sig.size() < 200; p++) {
char c = *p;
sig += (isalnum((unsigned char)c) || c == '-' || c == '.') ? c : '-';
}
return strdup(sig.c_str());
}
} // namespace
bool ImagePath(std::string* path) {
image_info info;
int32 cookie = 0;
while (get_next_image_info(B_CURRENT_TEAM, &cookie, &info) == B_OK)
if (info.type == B_APP_IMAGE) {
*path = info.name;
return true;
}
return false;
}
bool Start() {
if (be_app) return true;
// The application thread makes the BApplication; the program waits
// until it is there.
g_appThread = spawn_thread(AppThread, "winport app", B_NORMAL_PRIORITY, Signature());
if (g_appThread < 0) return false;
resume_thread(g_appThread);
for (int i = 0; i < 500 && (!be_app || be_app->IsLaunching()); i++) snooze(10000);
if (!be_app) return false;
atexit(StopApp);
return true;
}
void ScreenSize(int* width, int* height) {
BScreen s(B_MAIN_SCREEN_ID);
BRect f = s.Frame();
*width = (int)f.Width() + 1;
*height = (int)f.Height() + 1;
}
Win* Create(void* owner, int x, int y, int width, int height, bool popup) {
Win* w = new Win;
w->owner = owner;
BRect frame(x, y, x + (width > 0 ? width : 1) - 1, y + (height > 0 ? height : 1) - 1);
PixelWindow* pw = new PixelWindow(frame, w, popup);
w->window = pw;
w->view = new PixelView(pw->Bounds(), w);
pw->AddChild(w->view);
return w;
}
void Destroy(Win* w) {
if (!w) return;
if (w->window->Lock()) w->window->Quit();
delete w->bitmap;
delete w;
}
void Show(Win* w, bool show, bool activate) {
if (!w->window->Lock()) return;
if (show && !w->shown) {
w->window->Show();
w->shown = true;
} else if (!show && w->shown) {
w->window->Hide();
w->shown = false;
}
if (show && activate) {
w->window->Activate(true);
w->view->MakeFocus(true);
}
w->window->Unlock();
}
void SetFrame(Win* w, int x, int y, int width, int height) {
if (!w->window->Lock()) return;
w->window->MoveTo(x, y);
w->window->ResizeTo((width > 0 ? width : 1) - 1, (height > 0 ? height : 1) - 1);
w->window->Unlock();
}
void SetTitle(Win* w, const std::string& utf8) {
if (!w->window->Lock()) return;
w->window->SetTitle(utf8.c_str());
w->window->Unlock();
}
void Update(Win* w, const uint32_t* pixels, int width, int height, int stride, int x, int y, int cx, int cy) {
if (width <= 0 || height <= 0) return;
bool post = false;
{
std::lock_guard<std::mutex> g(w->lock);
BRect size(0, 0, width - 1, height - 1);
if (!w->bitmap || w->bitmap->Bounds() != size) {
// A new size: the whole bitmap is new.
delete w->bitmap;
w->bitmap = new BBitmap(size, B_RGB32);
x = 0;
y = 0;
cx = width;
cy = height;
}
if (x < 0) cx += x, x = 0;
if (y < 0) cy += y, y = 0;
if (x + cx > width) cx = width - x;
if (y + cy > height) cy = height - y;
if (cx <= 0 || cy <= 0) return;
// B_RGB32 is 0x00RRGGBB in the machine's byte order, as the pixels are.
uint8* bits = (uint8*)w->bitmap->Bits();
int32 bpr = w->bitmap->BytesPerRow();
for (int row = y; row < y + cy; row++)
memcpy(bits + (size_t)row * bpr + (size_t)x * 4, pixels + (size_t)row * stride + x, (size_t)cx * 4);
BRect r(x, y, x + cx - 1, y + cy - 1);
w->dirty = w->dirty.IsValid() ? (w->dirty | r) : r;
if (!w->dirtyPosted) post = w->dirtyPosted = true;
}
if (post) w->window->PostMessage(kShowDirty);
}
void SetCursor(bool hidden, int systemId, const uint32_t* argb, int width, int height, int hotX, int hotY) {
static bool s_hidden = false;
if (!be_app) return;
if (hidden != s_hidden) {
if (hidden)
be_app->HideCursor();
else
be_app->ShowCursor();
s_hidden = hidden;
}
if (hidden) return;
BCursorID id = B_CURSOR_ID_SYSTEM_DEFAULT;
bool system = true;
switch (systemId) {
case 32512: id = B_CURSOR_ID_SYSTEM_DEFAULT; break; // IDC_ARROW
case 32513: id = B_CURSOR_ID_I_BEAM; break; // IDC_IBEAM
case 32514: id = B_CURSOR_ID_PROGRESS; break; // IDC_WAIT
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 32650: id = B_CURSOR_ID_PROGRESS; break; // IDC_APPSTARTING
case 32651: id = B_CURSOR_ID_HELP; break; // IDC_HELP
default: system = false;
}
if (system || !argb || width <= 0 || height <= 0) {
BCursor c(id);
be_app->SetCursor(&c, true);
return;
}
// B_RGBA32 is 0xAARRGGBB in the machine's byte order, not premultiplied.
BBitmap bitmap(BRect(0, 0, width - 1, height - 1), B_RGBA32);
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 c(&bitmap, BPoint(hotX, hotY));
be_app->SetCursor(&c, true);
}
long ClipboardCount() { return be_clipboard ? (long)be_clipboard->SystemCount() : 0; }
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;
}
long SetClipboardText(const std::string& utf8) {
if (!be_clipboard || !be_clipboard->Lock()) return 0;
be_clipboard->Clear();
if (BMessage* data = be_clipboard->Data()) data->AddData("text/plain", B_MIME_TYPE, utf8.data(), utf8.size());
be_clipboard->Commit();
be_clipboard->Unlock();
return ClipboardCount();
}
std::vector<Event> Take(long timeout) {
std::unique_lock<std::mutex> g(g_queueLock);
auto ready = [] { return g_woken || !g_events.empty(); };
if (timeout < 0)
g_queueReady.wait(g, ready);
else
g_queueReady.wait_for(g, std::chrono::milliseconds(timeout), ready);
g_woken = false;
std::vector<Event> out(g_events.begin(), g_events.end());
g_events.clear();
return out;
}
void Wake() {
std::lock_guard<std::mutex> g(g_queueLock);
g_woken = true;
g_queueReady.notify_all();
}
} // namespace haiku
} // namespace winport
#endif
+8 -9
View File
@@ -350,18 +350,16 @@ std::vector<std::string> FontDirs() {
}
if (const char* windir = getenv("WINDIR")) dirs.push_back(std::string(windir) + "/FONTS");
dirs.push_back("C:/WINDOWS/FONTS");
#elif defined(__HAIKU__)
// The user's fonts, then those of packages and the system's.
if (home) dirs.push_back(std::string(home) + "/config/non-packaged/data/fonts");
if (home) 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");
#elif defined(__APPLE__)
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");
@@ -409,7 +407,8 @@ const wchar_t* const kSerif[] = {L"Times New Roman", L"Liberation Serif", L"Time
const wchar_t* const kMono[] = {L"Courier New", L"Liberation Mono", L"Courier", L"Cousine", L"DejaVu Sans Mono",
L"FreeMono", L"Menlo", L"Monaco", L"Noto Sans Mono", NULL};
const wchar_t* const kUi[] = {L"Tahoma", L"Microsoft Sans Serif", L"Arial", L"Liberation Sans", L"Helvetica",
L"Arimo", L"DejaVu Sans", L"FreeSans", L"Geneva", L"Lucida Grande", NULL};
L"Arimo", L"DejaVu Sans", L"FreeSans", L"Geneva", L"Lucida Grande", L"Noto Sans",
NULL};
enum Kind { kKindSans, kKindSerif, kKindMono, kKindUi };
+54 -59
View File
@@ -1,17 +1,13 @@
// 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.
// haiku.h - between the two halves of the Haiku backend:
// backend_haiku_be.cpp, which uses the Haiku API (BApplication, BWindow,
// BView, BBitmap) and sees none of the Windows headers, and
// backend_haiku.cpp, which uses the window manager and sees none of the
// Haiku headers. Their types and macros clash, so neither includes the
// other's headers.
//
// 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.
// Coordinates are screen pixels from the top left of the screen, as in
// Windows. A window has no border from app_server: the window manager
// draws the frame and the caption into the window's pixels.
//
// Part of clang-retro MFC, an independent implementation of the MFC API.
// SPDX-License-Identifier: AGPL-3.0-only
@@ -22,68 +18,67 @@
#include <stdint.h>
#include <string>
#include <vector>
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.
// A window, known to the other half only through this pointer and the
// owner pointer given to Create.
struct Win;
// Starts the application (BApplication) in a thread of its own. False
// when there is no app_server to show windows on.
// The modifier keys that are held, as one set of flags. Haiku's Command
// key (the key marked Alt on a PC keyboard) is Alt, and its Option key
// (the Windows key) is kWin, as their places on the keyboard say.
enum { kShift = 1, kControl = 2, kAlt = 4, kWin = 8, kCapsLock = 16 };
// Input that the windows receive. The window threads put it in a queue,
// and Take gives it to the thread that waits for input.
struct Event {
enum Kind { kMouseDown, kMouseUp, kMouseMove, kWheel, kKeyDown, kKeyUp, kActivated, kClose, kQuit } kind;
void* owner = NULL; // the window's owner, or NULL for kQuit
int x = 0, y = 0; // the mouse, in the window
int button = 0; // 0 left, 1 right, 2 middle
float wheelX = 0, wheelY = 0; // in notches: down and right are positive
unsigned mods = 0; // the k flags above
unsigned key = 0; // Haiku's key code (the key's place on the keyboard)
uint32_t ch = 0; // the character the key types with its modifiers, or 0
uint32_t raw = 0; // the character the key types without modifiers, or 0
bool active = false; // kActivated: the window became active (true) or not
};
// The path of the program's image (the executable), from the kernel;
// false when there is none. kernel_module.cpp uses it.
bool ImagePath(std::string* path);
// Called on the window manager's side (backend_haiku.cpp).
// Start makes the BApplication and runs it on a thread of its own. It
// returns false when there is no app_server to connect to.
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.
// Makes a window. A popup (a menu, a tooltip, a drop-down list) floats
// over the other 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 Show(Win* w, bool show, bool activate);
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
// Copies a rectangle of the window's pixels (0x00RRGGBB, top row first,
// stride pixels to a row) and shows it. The rectangle is in the window.
void Update(Win* w, const uint32_t* pixels, int width, int height, int stride, int x, int y, int cx, int cy);
// The pointer's shape: a system cursor by its IDC_ number, or 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();
// The system clipboard: a number that changes when its contents change,
// its text, and putting text there (which gives the new number).
long 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);
long SetClipboardText(const std::string& utf8);
// Waits up to timeout ms (-1 for no limit) for input or Wake, and gives
// the input that came.
std::vector<Event> Take(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
-628
View File
@@ -1,628 +0,0 @@
// 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
+3 -3
View File
@@ -528,8 +528,7 @@ std::string CommDevice(const std::string& name) {
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.
// The serial ports in /dev/ports (pc_serial0, usb0 and on), by name.
std::vector<std::string> devs;
if (DIR* d = opendir("/dev/ports")) {
while (dirent* e = readdir(d))
@@ -602,7 +601,8 @@ 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
#ifdef __HAIKU__
// Haiku has 7 and 8 bits only: CS5, CS6 and CS7 are all 0.
d->ByteSize = (t.c_cflag & CSIZE) == CS8 ? 8 : 7;
#else
switch (t.c_cflag & CSIZE) {
-5
View File
@@ -705,12 +705,7 @@ 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";
}
+18 -20
View File
@@ -16,6 +16,11 @@
#include <dirent.h>
#include <dlfcn.h>
// The headers of Haiku R1/beta5 have 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 <errno.h>
#include <fcntl.h>
#include <limits.h>
@@ -34,22 +39,10 @@
#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>
@@ -63,6 +56,12 @@ extern "C" char** __libc_argv;
extern char** environ;
#endif
extern "C" void _WinportAddResources(const void* anchor, const void* data, size_t size);
#ifdef __HAIKU__
#include "haiku.h"
// libroot keeps main's arguments here.
extern "C" int __libc_argc;
extern "C" char** __libc_argv;
#endif
using namespace winport;
@@ -124,19 +123,17 @@ std::string ExecutablePath() {
if (p.empty() || p.back() != '/') p += '/';
p.append((const char*)app + 1, app[0] > 31 ? 31 : app[0]);
return p;
#elif defined(__HAIKU__)
// The path of the program's image, from the kernel.
std::string p;
if (haiku::ImagePath(&p)) return RealPath(p.c_str());
return std::string();
#elif defined(__MSDOS__)
// DOS gives the program's path after the environment (argv[0]).
std::string p = __argc > 0 && __argv[0] ? __argv[0] : "";
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);
@@ -846,7 +843,8 @@ std::vector<std::string> Argv() {
#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]);
// libroot keeps the arguments that main got.
for (int i = 0; i < __libc_argc; i++) v.push_back(__libc_argv[i]);
#else
FILE* f = fopen("/proc/self/cmdline", "rb");
if (f) {
+1 -1
View File
@@ -463,9 +463,9 @@ 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
Backend* NewHaikuBackend(); // app_server, on Haiku only; NULL without it
} // namespace winport
+18
View File
@@ -520,6 +520,24 @@ void WatchFile() {
if (r > 0) FileChanged();
}
}).detach();
#elif defined(__HAIKU__)
// Haiku's node monitor needs a BLooper; looking at the file four times
// a second is enough for an editor that saves it.
std::thread([file] {
struct stat was;
bool had = stat(file.c_str(), &was) == 0;
for (;;) {
std::this_thread::sleep_for(std::chrono::milliseconds(250));
struct stat now;
bool has = stat(file.c_str(), &now) == 0;
if (has != had || (has && (now.st_ino != was.st_ino || now.st_size != was.st_size ||
now.st_mtim.tv_sec != was.st_mtim.tv_sec ||
now.st_mtim.tv_nsec != was.st_mtim.tv_nsec)))
FileChanged();
had = has;
was = now;
}
}).detach();
#endif
}
+1 -2
View File
@@ -97,8 +97,7 @@ 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 (on Haiku,
// ~/config/settings/libmfc).
// are: $XDG_CONFIG_HOME/libmfc, or ~/.config/libmfc.
std::string ConfigDir();
// The registry file: $WINPORT_REGISTRY, or registry.reg there.
std::string RegistryPath();
+2 -2
View File
@@ -47,7 +47,7 @@ const ErrnoMap kErrors[] = {
{EPROTOTYPE, WSAEPROTOTYPE},
{ENOPROTOOPT, WSAENOPROTOOPT},
{EPROTONOSUPPORT, WSAEPROTONOSUPPORT},
#ifdef ESOCKTNOSUPPORT // (not on Haiku)
#ifdef ESOCKTNOSUPPORT // not in the headers of Haiku R1/beta5
{ESOCKTNOSUPPORT, WSAESOCKTNOSUPPORT},
#endif
{EOPNOTSUPP, WSAEOPNOTSUPP},
@@ -65,7 +65,7 @@ const ErrnoMap kErrors[] = {
{EISCONN, WSAEISCONN},
{ENOTCONN, WSAENOTCONN},
{ESHUTDOWN, WSAESHUTDOWN},
#ifdef ETOOMANYREFS // (not on Haiku)
#ifdef ETOOMANYREFS
{ETOOMANYREFS, WSAETOOMANYREFS},
#endif
{ETIMEDOUT, WSAETIMEDOUT},
+284
View File
@@ -0,0 +1,284 @@
// showcase.cpp - a small MFC program that shows the usual parts of an MFC
// program: a frame with a menu bar, a toolbar and a status bar, a view
// that draws with GDI, and two modal dialogs with standard and common
// controls. It builds unchanged for Windows and over the portable layer
// (Linux, macOS, Haiku).
//
// SHOWCASE_DEMO=1 in the environment opens the dialogs by itself and ends
// the program after some seconds, for screenshots in a test machine.
// SHOWCASE_SHOT names a command that the program runs (with system()) at
// each step of the demonstration, with the step's name as its argument.
//
// Part of clang-retro MFC, an independent implementation of the MFC API.
// SPDX-License-Identifier: AGPL-3.0-only
#include <afxwin.h>
#include <afxext.h>
#include <afxcmn.h>
#include <stdlib.h>
#include "showcase.h"
// The settings of the drawing, which the settings dialog changes.
struct Settings {
CString title = _T("Hello from MFC");
int shape = 0; // 0 ellipses, 1 rectangles, 2 rounded rectangles
BOOL filled = TRUE;
int size = 5;
int color = 0;
};
static Settings g_settings;
static const COLORREF kColors[] = {RGB(0x2E, 0x6E, 0xC8), RGB(0xC8, 0x3C, 0x2E), RGB(0x2E, 0x9C, 0x4A),
RGB(0xD0, 0x8A, 0x10)};
static const TCHAR* const kColorNames[] = {_T("Blue"), _T("Red"), _T("Green"), _T("Orange")};
// Runs the screenshot command of SHOWCASE_SHOT, if there is one, for a
// step of the demonstration.
static void Shot(const char* step) {
const char* cmd = getenv("SHOWCASE_SHOT");
if (!cmd || !*cmd) return;
CStringA line;
line.Format("%s %s", cmd, step);
int ignored = system(line);
(void)ignored;
}
// The settings dialog: an edit box, a drop-down list, a check box, a
// trackbar and a list box.
class CSettingsDlg : public CDialog {
public:
// Makes the dialog from its template.
CSettingsDlg(CWnd* parent) : CDialog(IDD_SETTINGS, parent), m_demo(FALSE) {}
BOOL m_demo;
// Fills the controls from the settings.
virtual BOOL OnInitDialog() {
CDialog::OnInitDialog();
SetDlgItemText(IDC_NAME, g_settings.title);
CComboBox* shape = (CComboBox*)GetDlgItem(IDC_SHAPE);
shape->AddString(_T("Ellipses"));
shape->AddString(_T("Rectangles"));
shape->AddString(_T("Rounded"));
shape->SetCurSel(g_settings.shape);
CheckDlgButton(IDC_FILLED, g_settings.filled ? BST_CHECKED : BST_UNCHECKED);
CSliderCtrl* size = (CSliderCtrl*)GetDlgItem(IDC_SHAPESIZE);
size->SetRange(1, 10);
size->SetPos(g_settings.size);
CListBox* colors = (CListBox*)GetDlgItem(IDC_COLORS);
for (const TCHAR* name : kColorNames) colors->AddString(name);
colors->SetCurSel(g_settings.color);
if (m_demo) SetTimer(1, 2500, NULL);
return TRUE;
}
// Keeps the values of the controls in the settings.
virtual void OnOK() {
GetDlgItemText(IDC_NAME, g_settings.title);
g_settings.shape = ((CComboBox*)GetDlgItem(IDC_SHAPE))->GetCurSel();
g_settings.filled = IsDlgButtonChecked(IDC_FILLED) == BST_CHECKED;
g_settings.size = ((CSliderCtrl*)GetDlgItem(IDC_SHAPESIZE))->GetPos();
g_settings.color = ((CListBox*)GetDlgItem(IDC_COLORS))->GetCurSel();
CDialog::OnOK();
}
// In the demonstration: changes the settings, takes the screenshot and
// closes the dialog.
afx_msg void OnTimer(UINT_PTR) {
KillTimer(1);
SetDlgItemText(IDC_NAME, _T("MFC on Haiku"));
((CComboBox*)GetDlgItem(IDC_SHAPE))->SetCurSel(2);
((CSliderCtrl*)GetDlgItem(IDC_SHAPESIZE))->SetPos(7);
((CListBox*)GetDlgItem(IDC_COLORS))->SetCurSel(3);
UpdateWindow();
Shot("settings");
OnOK();
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(CSettingsDlg, CDialog)
ON_WM_TIMER()
END_MESSAGE_MAP()
// The about box. In the demonstration it closes itself.
class CAboutDlg : public CDialog {
public:
// Makes the dialog from its template.
CAboutDlg(CWnd* parent) : CDialog(IDD_ABOUTBOX, parent), m_demo(FALSE) {}
BOOL m_demo;
// Starts the timer of the demonstration.
virtual BOOL OnInitDialog() {
CDialog::OnInitDialog();
if (m_demo) SetTimer(1, 2500, NULL);
return TRUE;
}
// Takes the screenshot and closes the dialog.
afx_msg void OnTimer(UINT_PTR) {
KillTimer(1);
Shot("about");
EndDialog(IDOK);
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
ON_WM_TIMER()
END_MESSAGE_MAP()
// The document holds nothing: the drawing comes from the settings.
class CShowDoc : public CDocument {
DECLARE_DYNCREATE(CShowDoc)
};
IMPLEMENT_DYNCREATE(CShowDoc, CDocument)
// The view draws a gradient, shapes and text.
class CShowView : public CView {
DECLARE_DYNCREATE(CShowView)
public:
// Draws the view from the settings.
virtual void OnDraw(CDC* dc) {
CRect rc;
GetClientRect(&rc);
// A vertical gradient as the background.
for (int y = 0; y < rc.Height(); y += 4) {
int t = rc.Height() > 0 ? y * 255 / rc.Height() : 0;
dc->FillSolidRect(0, y, rc.Width(), 4, RGB(240 - t / 8, 244 - t / 10, 250 - t / 16));
}
COLORREF color = kColors[g_settings.color >= 0 && g_settings.color < 4 ? g_settings.color : 0];
CPen pen(PS_SOLID, 2, color);
CBrush brush(color);
CPen* oldPen = dc->SelectObject(&pen);
CBrush* oldBrush = g_settings.filled ? dc->SelectObject(&brush) : (CBrush*)dc->SelectStockObject(NULL_BRUSH);
int step = 12 + g_settings.size * 6;
for (int i = 0; i < 6; i++) {
CRect r(20 + i * (step + 10), 70 + (i % 2) * 20, 20 + i * (step + 10) + step, 70 + (i % 2) * 20 + step);
if (g_settings.shape == 0)
dc->Ellipse(r);
else if (g_settings.shape == 1)
dc->Rectangle(r);
else
dc->RoundRect(r, CPoint(12, 12));
}
dc->SelectObject(oldPen);
dc->SelectObject(oldBrush);
// The title in a big font.
CFont font;
font.CreatePointFont(200, _T("Arial"), dc);
CFont* oldFont = dc->SelectObject(&font);
dc->SetBkMode(TRANSPARENT);
dc->SetTextColor(RGB(0x20, 0x20, 0x30));
dc->TextOut(20, 20, g_settings.title);
dc->SelectObject(oldFont);
CString line;
line.Format(_T("This window is %d x %d pixels."), rc.Width(), rc.Height());
dc->TextOut(20, rc.bottom - 30, line);
}
};
IMPLEMENT_DYNCREATE(CShowView, CView)
static const UINT kIndicators[] = {ID_SEPARATOR, ID_INDICATOR_CAPS, ID_INDICATOR_NUM};
// The frame: toolbar, status bar, and the commands of the View menu.
class CMainFrame : public CFrameWnd {
DECLARE_DYNCREATE(CMainFrame)
public:
CToolBar m_toolBar;
CStatusBar m_statusBar;
int m_step = 0;
// Makes the bars, and starts the demonstration when it is asked for.
afx_msg int OnCreate(LPCREATESTRUCT cs) {
if (CFrameWnd::OnCreate(cs) == -1) return -1;
if (!m_toolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_TOOLTIPS | CBRS_FLYBY) ||
!m_toolBar.LoadToolBar(IDR_MAINFRAME))
return -1;
if (!m_statusBar.Create(this) || !m_statusBar.SetIndicators(kIndicators, 3)) return -1;
const char* demo = getenv("SHOWCASE_DEMO");
if (demo && *demo) SetTimer(1, 3000, NULL);
return 0;
}
// Opens the settings dialog and redraws the view with its settings.
afx_msg void OnSettings() { Settings(FALSE); }
// Opens the settings dialog; in the demonstration it closes itself.
void Settings(BOOL demo) {
CSettingsDlg dlg(this);
dlg.m_demo = demo;
if (dlg.DoModal() == IDOK) {
SetWindowText(g_settings.title);
if (CView* v = GetActiveView()) v->Invalidate();
}
}
// The steps of the demonstration: the main window, the settings
// dialog, the window with the new settings, the about box, the end.
afx_msg void OnTimer(UINT_PTR id) {
if (id != 1) return;
switch (m_step++) {
case 0:
Shot("main");
break;
case 1:
KillTimer(1);
Settings(TRUE);
SetTimer(1, 2000, NULL);
break;
case 2:
UpdateWindow();
Shot("changed");
break;
case 3: {
KillTimer(1);
CAboutDlg dlg(this);
dlg.m_demo = TRUE;
dlg.DoModal();
SetTimer(1, 1000, NULL);
break;
}
default:
KillTimer(1);
PostMessage(WM_CLOSE);
}
}
DECLARE_MESSAGE_MAP()
};
IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_WM_CREATE()
ON_WM_TIMER()
ON_COMMAND(ID_VIEW_SETTINGS, OnSettings)
END_MESSAGE_MAP()
// The application: one document template, and the about box.
class CShowApp : public CWinApp {
public:
// Makes the main frame with its document and view.
virtual BOOL InitInstance() {
CWinApp::InitInstance();
AddDocTemplate(new CSingleDocTemplate(IDR_MAINFRAME, RUNTIME_CLASS(CShowDoc), RUNTIME_CLASS(CMainFrame),
RUNTIME_CLASS(CShowView)));
CCommandLineInfo info;
ParseCommandLine(info);
if (!ProcessShellCommand(info)) return FALSE;
m_pMainWnd->SetWindowPos(NULL, 120, 90, 640, 420, SWP_NOZORDER);
m_pMainWnd->SetWindowText(_T("Showcase"));
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
return TRUE;
}
// Opens the about box.
afx_msg void OnAppAbout() {
CAboutDlg dlg(m_pMainWnd);
dlg.DoModal();
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(CShowApp, CWinApp)
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
END_MESSAGE_MAP()
CShowApp theApp;
+10
View File
@@ -0,0 +1,10 @@
// showcase.h - resource IDs for the showcase sample.
#define IDR_MAINFRAME 128
#define IDD_ABOUTBOX 100
#define IDD_SETTINGS 101
#define IDC_NAME 1001
#define IDC_SHAPE 1002
#define IDC_FILLED 1003
#define IDC_SHAPESIZE 1004
#define IDC_COLORS 1005
#define ID_VIEW_SETTINGS 32771
+73
View File
@@ -0,0 +1,73 @@
// showcase.rc - resources for the showcase sample.
#include <windows.h>
#include <afxres.h>
#include "showcase.h"
IDR_MAINFRAME MENU
BEGIN
POPUP "&File"
BEGIN
MENUITEM "&New\tCtrl+N", ID_FILE_NEW
MENUITEM SEPARATOR
MENUITEM "E&xit", ID_APP_EXIT
END
POPUP "&View"
BEGIN
MENUITEM "&Toolbar", ID_VIEW_TOOLBAR
MENUITEM "&Status Bar", ID_VIEW_STATUS_BAR
MENUITEM SEPARATOR
MENUITEM "Se&ttings...", ID_VIEW_SETTINGS
END
POPUP "&Help"
BEGIN
MENUITEM "&About Showcase...", ID_APP_ABOUT
END
END
IDR_MAINFRAME ACCELERATORS
BEGIN
"N", ID_FILE_NEW, VIRTKEY, CONTROL
END
// The toolbar: version, image width, image height, count, command IDs.
IDR_MAINFRAME 241
BEGIN
1, 16, 15, 8,
ID_FILE_NEW, ID_FILE_OPEN, ID_FILE_SAVE, 0,
ID_EDIT_CUT, ID_EDIT_COPY, ID_EDIT_PASTE, 0
END
IDR_MAINFRAME BITMAP "toolbar.bmp"
STRINGTABLE
BEGIN
IDR_MAINFRAME "Showcase\n\nShowcase\n\n\nShowcase.Document\nShowcase Document"
AFX_IDS_IDLEMESSAGE "Ready"
END
IDD_ABOUTBOX DIALOGEX 0, 0, 220, 70
STYLE DS_MODALFRAME | DS_SHELLFONT | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "About Showcase"
FONT 8, "MS Shell Dlg"
BEGIN
LTEXT "Showcase, an MFC program", -1, 10, 10, 200, 10
LTEXT "Built with clang-retro MFC.", -1, 10, 24, 200, 10
DEFPUSHBUTTON "OK", IDOK, 160, 48, 50, 14
END
IDD_SETTINGS DIALOGEX 0, 0, 230, 130
STYLE DS_MODALFRAME | DS_SHELLFONT | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Settings"
FONT 8, "MS Shell Dlg"
BEGIN
LTEXT "&Title:", -1, 10, 12, 40, 10
EDITTEXT IDC_NAME, 55, 10, 165, 13, ES_AUTOHSCROLL
LTEXT "&Shape:", -1, 10, 32, 40, 10
COMBOBOX IDC_SHAPE, 55, 30, 100, 60, CBS_DROPDOWNLIST | WS_TABSTOP
AUTOCHECKBOX "&Filled", IDC_FILLED, 165, 31, 55, 12
LTEXT "Si&ze:", -1, 10, 52, 40, 10
CONTROL "", IDC_SHAPESIZE, "msctls_trackbar32", TBS_AUTOTICKS | WS_TABSTOP, 52, 49, 170, 16
LTEXT "&Colors:", -1, 10, 72, 40, 10
LISTBOX IDC_COLORS, 55, 70, 100, 34, LBS_NOTIFY | WS_VSCROLL | WS_TABSTOP
DEFPUSHBUTTON "OK", IDOK, 115, 110, 50, 14
PUSHBUTTON "Cancel", IDCANCEL, 170, 110, 50, 14
END
+12
View File
@@ -449,6 +449,12 @@ BOOL CAsyncSocket::GetPeerName(CString& rPeerAddress, UINT& rPeerPort) {
memset(&sa, 0, sizeof(sa));
int nLen = sizeof(sa);
if (!GetPeerName((SOCKADDR*)&sa, &nLen)) return FALSE;
// Windows's SOCKADDR_IN cannot hold an IPv6 address, and the call
// fails. Some systems (Haiku) have a larger sockaddr_in that can.
if (sa.sin_family != AF_INET) {
::WSASetLastError(WSAEFAULT);
return FALSE;
}
AddressToString(sa, rPeerAddress, rPeerPort);
return TRUE;
}
@@ -462,6 +468,12 @@ BOOL CAsyncSocket::GetSockName(CString& rSocketAddress, UINT& rSocketPort) {
memset(&sa, 0, sizeof(sa));
int nLen = sizeof(sa);
if (!GetSockName((SOCKADDR*)&sa, &nLen)) return FALSE;
// Windows's SOCKADDR_IN cannot hold an IPv6 address, and the call
// fails. Some systems (Haiku) have a larger sockaddr_in that can.
if (sa.sin_family != AF_INET) {
::WSASetLastError(WSAEFAULT);
return FALSE;
}
AddressToString(sa, rSocketAddress, rSocketPort);
return TRUE;
}
+3 -2
View File
@@ -114,9 +114,10 @@ static void TestChild() {
if (!ok) return;
DWORD n;
CHECK(::WriteFile(inW, "at&f\r", 5, &n, NULL) && n == 5);
// Polled, as a program polls a helper's output without blocking.
// Polled, as a program polls a helper's output without blocking. The
// child can take some seconds to start in a virtual machine.
DWORD avail = 0;
for (int i = 0; i < 500 && avail < 5; i++) {
for (int i = 0; i < 3000 && avail < 5; i++) {
if (!::PeekNamedPipe(outR, NULL, 0, NULL, &avail, NULL)) break;
if (avail < 5) ::Sleep(10);
}
+182
View File
@@ -0,0 +1,182 @@
#!/bin/sh
# run-haiku-tests.sh - builds the tests for Haiku against the libraries
# and runs them in Haiku, in a QEMU virtual machine.
#
# Called by `make check TARGET=x86_64-unknown-haiku SYSROOT=...` (or
# i586-pc-haiku), which sets BIN, SYSROOT, TARGET and OUT.
#
# HAIKU_IMAGE names a Haiku anyboot image (the nightly images of
# download.haiku-os.org). clang-retro/unix-sdk's haiku/tools/haiku-vm.py
# (HAIKU_VM, by default ../unix-sdk/haiku/tools/haiku-vm.py) starts it,
# and runs each test in it. Without HAIKU_IMAGE the tests are only built.
# A test passes when it ends with status 0. The tests run with the
# headless backend (WINPORT_BACKEND=headless), as on Linux. With
# HAIKU_VM_RUNNING=1 the tests use a "haiku-vm.py serve" that already
# runs (started with --files $OUT/tests), and leave it running. showcase,
# the sample, runs with the Haiku backend and its screenshots go to
# $OUT/tests/shots.
set -u
TARGET=${TARGET:-x86_64-unknown-haiku}
OUT=${OUT:-build/$TARGET}
SYSROOT=${SYSROOT:?set SYSROOT to the Haiku sysroot}
BIN=${BIN:-}
CXX=${BIN:+$BIN/}clang++
HAIKU_IMAGE=${HAIKU_IMAGE:-}
HAIKU_VM=${HAIKU_VM:-../unix-sdk/haiku/tools/haiku-vm.py}
PORT=${HAIKU_VM_PORT:-8765}
TESTS=${HAIKU_TESTS:-"core memtest wintest disptest isapitest dlgtest sditest mditest cmntest splittest docktest rvtest socktest occtest dlltest oletest iptest docobtest linktest bindtest richtest richsrvtest autotest srvtest atlwintest atltest conntest ctltest wltest dragtest daotest dvtest htmltest atlctltest atlutiltest comdeftest fptest fpctrltest cdlgtest vistatest iotest dpitest imetest sstest hlptest gltest"}
T=$OUT/tests
mkdir -p "$T/a" "$T/u" "$T/winhelp"
# hlptest reads the help files of tests/winhelp.
cp tests/winhelp/*.hlp tests/winhelp/*.cnt "$T/winhelp/"
python3 tests/gen-toolbar-bmp.py "$T/toolbar.bmp" 6 || exit 1
# llvm-rc compiles the resources: the one in BIN, on the PATH, or one
# that came with an LLVM installed beside the system compiler.
RC_NATIVE=${BIN:+$BIN/}llvm-rc
if [ -z "$BIN" ] && ! command -v llvm-rc >/dev/null 2>&1; then
for rc in /usr/lib/llvm-*/bin/llvm-rc; do
[ -x "$rc" ] && RC_NATIVE=$rc
done
fi
CXXFLAGS="--target=$TARGET --sysroot=$SYSROOT -fuse-ld=lld -std=c++17 -D_DEFAULT_SOURCE"
CXXFLAGS="$CXXFLAGS -Wall -Wno-unused-function -Wno-overloaded-virtual -Wno-missing-exception-spec"
CXXFLAGS="$CXXFLAGS -Iport/include -Iinclude -Itests -Iport/softgl/include"
SYSLIBS="-lbe -lnetwork -lbsd"
nfail=0
npass=0
built=
# Builds one test (name, a or u). The program goes to $T/NAME-V, and a
# DLL of its own to $T/NAME-dll-V.dll, as run-tests.sh makes them.
build_test() { # name v
name=$1 v=$2
flags= lib=-lmfc
[ $v = u ] && flags="-DUNICODE -D_UNICODE" && lib=-lmfcu
srcs=tests/$name.cpp
if [ -f tests/$name.rc ]; then
CXX="$CXX" RC="$RC_NATIVE" python3 port/tools/res2cpp.py -I include -I tests -I "$T" \
tests/$name.rc -o "$T/$name-res.cpp" 2>"$T/$name-rc.log" || return 1
srcs="$srcs $T/$name-res.cpp"
fi
exeflags=
if [ -f tests/$name-dll.cpp ]; then
[ -f tests/$name-dll.def ] || return 2
dllsrcs=tests/$name-dll.cpp
if [ -f tests/$name-dll.rc ]; then
CXX="$CXX" RC="$RC_NATIVE" python3 port/tools/res2cpp.py -I include -I tests -I "$T" \
tests/$name-dll.rc -o "$T/$name-dll-res.cpp" 2>"$T/$name-dll-rc.log" || return 1
dllsrcs="$dllsrcs $T/$name-dll-res.cpp"
fi
dll=$T/$name-dll-$v.dll
exports=$(sed -n '/^EXPORTS/,$p' tests/$name-dll.def | sed '1d' | awk '{split($1, a, "="); print a[1]}')
{ echo "{ global:"; for e in DllMain $exports; do echo " $e;"; done; echo "local: *; };"; } > "$T/$name-dll.map"
# The DLL takes the layer from the program, which exports it.
# shellcheck disable=SC2086
"$CXX" $CXXFLAGS $flags -fPIC -shared -Wl,-soname,"$(basename "$dll")" -Wl,--version-script="$T/$name-dll.map" \
-Wl,--allow-shlib-undefined -Wl,--unresolved-symbols=ignore-all -D_USRDLL $dllsrcs -L"$OUT" $lib \
-o "$dll" 2>"$T/$name-dll-$v-build.log" || return 1
exeflags=-rdynamic
fi
[ $name = sstest ] && { [ $v = u ] && lib="-lscrnsavw $lib" || lib="-lscrnsave $lib"; }
# shellcheck disable=SC2086
"$CXX" $CXXFLAGS $flags $exeflags $srcs -L"$OUT" $lib -lwinport $SYSLIBS -o "$T/$name-$v" \
2>"$T/$name-$v-build.log"
}
for v in a u; do
for name in $TESTS; do
build_test "$name" $v
case $? in
0) built="$built $name-$v" ;;
2) echo "skip $name-$v (an extension DLL needs the shared library)" ;;
*) echo "FAIL $name-$v (build; see $T/$name-$v-build.log)"; nfail=$((nfail + 1)) ;;
esac
done
done
# The sample, which shows the Haiku backend.
S=samples/showcase
if CXX="$CXX" RC="$RC_NATIVE" python3 port/tools/res2cpp.py -I include -I $S -I "$T" $S/showcase.rc \
-o "$T/showcase-res.cpp" 2>"$T/showcase-rc.log" &&
"$CXX" $CXXFLAGS -I$S $S/showcase.cpp "$T/showcase-res.cpp" -L"$OUT" -lmfc -lwinport $SYSLIBS \
-o "$T/showcase" 2>"$T/showcase-build.log"; then
showcase=1
else
echo "FAIL showcase (build; see $T/showcase-build.log)"
nfail=$((nfail + 1))
showcase=0
fi
if [ -z "$HAIKU_IMAGE" ] && [ -z "${HAIKU_VM_RUNNING:-}" ]; then
for t in $built; do echo "built $t (no HAIKU_IMAGE; not run)"; done
echo "$nfail failed to build"
[ $nfail = 0 ]
exit
fi
# The virtual machine: its agent fetches the programs from $T.
if [ -z "${HAIKU_VM_RUNNING:-}" ]; then
python3 "$HAIKU_VM" serve "$HAIKU_IMAGE" --files "$T" --shots "$T/shots" --port "$PORT" > "$T/vm.log" 2>&1 &
vm=$!
# A "serve" that is still starting does not take "stop": kill it then.
trap 'python3 "$HAIKU_VM" stop --port "$PORT" 2>/dev/null || kill $vm 2>/dev/null; wait $vm 2>/dev/null' EXIT
fi
# Runs a shell command in Haiku and writes its output; the status is the
# command's.
vmexec() {
python3 "$HAIKU_VM" exec --port "$PORT" "$1"
}
G=http://10.0.2.2:$PORT/files
# The tests work in /boot/home/mfc: /tmp is a symbolic link in Haiku, and
# the tests compare the paths that they make with the paths that the
# system gives.
# The first command waits until Haiku has started.
if ! vmexec "mkdir -p /boot/home/mfc && echo Haiku is ready: \$(uname -a)"; then
echo "FAIL Haiku did not start (see $T/vm.log)"
exit 1
fi
for t in $built; do
name=${t%-*} v=${t##*-}
outdir=$T/$v
mkdir -p "$outdir"
get="curl -sf -o $t $G/$t && chmod +x $t"
[ -f "$T/$name-dll-$v.dll" ] && get="$get && curl -sf -o $name-dll-$v.dll $G/$name-dll-$v.dll"
args=
[ $name = sstest ] && args=/s
if [ $name = hlptest ]; then
for f in "$T"/winhelp/*; do
get="$get && curl -sf -o winhelp/$(basename "$f") $G/winhelp/$(basename "$f")"
done
get="mkdir -p winhelp && $get"
fi
box=
case $name in rvtest|dvtest) box=window ;; esac
if vmexec "mkdir -p /boot/home/mfc/$v && cd /boot/home/mfc && $get && cd /boot/home/mfc/$v &&
WINPORT_BACKEND=headless WINPORT_MESSAGEBOX=$box MFC_TEST_OUT=/boot/home/mfc/$v MFC_TEST_HLP_DIR=/boot/home/mfc/winhelp \
WINPORT_REGISTRY=/boot/home/mfc/$v/registry.reg timeout 600 ../$t $args; s=\$?;
cat /boot/home/mfc/$v/$name.log 2>/dev/null; rm -f ../$t; exit \$s" > "$outdir/$name.log" 2>&1; then
echo "PASS $t"; npass=$((npass + 1))
else
echo "FAIL $t"; sed 's/^/ /' "$outdir/$name.log" | tail -20; nfail=$((nfail + 1))
fi
done
if [ $showcase = 1 ]; then
# The sample with the Haiku backend; shot.sh asks the host for a
# screenshot of the screen at each step.
if vmexec "cd /boot/home/mfc && curl -sf -o showcase $G/showcase && chmod +x showcase &&
printf '#!/bin/sh\ncurl -s -o /dev/null http://10.0.2.2:$PORT/shot/showcase-\$1\n' > shot.sh &&
chmod +x shot.sh && SHOWCASE_DEMO=1 SHOWCASE_SHOT=/boot/home/mfc/shot.sh timeout 120 ./showcase" \
> "$T/showcase.log" 2>&1 && [ -f "$T/shots/showcase-about.png" ]; then
echo "PASS showcase (screenshots in $T/shots)"; npass=$((npass + 1))
else
echo "FAIL showcase"; sed 's/^/ /' "$T/showcase.log"; nfail=$((nfail + 1))
fi
fi
echo "$npass passed, $nfail failed"
[ $nfail = 0 ]