diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..1e10923f9 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +# Shell/python helpers run under MSYS bash on Windows runners too: +# keep them LF everywhere. +*.sh text eol=lf +*.py text eol=lf +tools/* text eol=lf diff --git a/README b/README index 843baf55d..3b811ce16 100644 --- a/README +++ b/README @@ -69,6 +69,14 @@ autogen.sh script as you would to the configure script. If you want to know more about installation options refer to the INSTALL file (not for beginners). +Windows +------- + +Native MSYS2/MinGW-w64 builds and Linux cross-builds (which the CI uses +to produce Windows artifacts) are documented in doc/BUILDING-WINDOWS.md; +the sysroot/packaging helpers live in tools/. The legacy win32/Makefile +flow is described in win32/README. + Using Gpredict -------------- diff --git a/configure.ac b/configure.ac index 088309670..3708db7bf 100644 --- a/configure.ac +++ b/configure.ac @@ -1,5 +1,5 @@ AC_INIT([gpredict],[m4_esyscmd(./git-version-gen .tarball-version)],[https://community.libre.space/c/gpredict]) -AC_CONFIG_MACRO_DIR([m4]) +AC_CONFIG_MACRO_DIRS([m4]) AC_CONFIG_SRCDIR(src/main.c) AC_CONFIG_HEADERS(build-config.h) AM_INIT_AUTOMAKE([subdir-objects dist-bzip2 no-dist-gzip 1.6]) @@ -65,6 +65,39 @@ else havelibgps=false; fi +# winsock2 (rigctld/rotctld TCP clients): on Unix the BSD socket +# functions are in libc, on MinGW/Windows they live in ws2_32. +AC_SEARCH_LIBS([htons],[ws2_32]) + +# Windows builds: link the GUI subsystem (no console window on +# double-click) and embed the app icon + version info from +# win32/gpredict.rc, mirroring what win32/Makefile does. Note that +# autotools running inside MSYS2 reports the host as *-*-msys, so +# *mingw* alone would miss the native build. +case "$host" in + *mingw*|*msys*|*cygwin*) + gp_cv_windows=yes + AC_CHECK_TOOL([WINDRES], [windres], [:]) + ;; + *) + gp_cv_windows=no + ;; +esac +AM_CONDITIONAL([MINGW], [test "$gp_cv_windows" = yes]) +AM_CONDITIONAL([W32RES], + [test "$gp_cv_windows" = yes && test "x$WINDRES" != "x:"]) + +dnl numeric pieces of $VERSION for the VERSIONINFO resource (cut/tr to +dnl keep autoconf's m4 from eating bracketed sed regexes; tag-less +dnl checkouts yield VERSION=UNKNOWN -> 0.0.0) +gp_major=`echo "x$VERSION" | cut -d. -f1 | tr -dc '0-9'` +gp_minor=`echo "x$VERSION" | cut -d. -f2 | tr -dc '0-9'` +test -n "$gp_major" || gp_major=0 +test -n "$gp_minor" || gp_minor=0 +AC_SUBST([VERMAJ], [$gp_major]) +AC_SUBST([VERMIN], [$gp_minor]) +AC_SUBST([VERBLD], [0]) + AC_SUBST(PACKAGE_CFLAGS) AC_SUBST(PACKAGE_LIBS) diff --git a/doc/BUILDING-WINDOWS.md b/doc/BUILDING-WINDOWS.md new file mode 100644 index 000000000..ca891db58 --- /dev/null +++ b/doc/BUILDING-WINDOWS.md @@ -0,0 +1,215 @@ +# Building Gpredict for Windows + +There are two maintained ways to build the Windows 64-bit `gpredict.exe` +(GTK-3, Win32 backend): + +1. **Cross-build on Linux** — distro MinGW-w64 toolchain plus a + dependency sysroot assembled from MSYS2 repository packages, + section 5. This is the path CI uses: the `windows-cross` job in + `.github/workflows/ci.yml` uploads the standalone zip as the + `gpredict-windows-x86_64-cross` artifact. +2. **Native build on Windows with MSYS2/MinGW-w64**, sections 1-3. + Convenient for day-to-day development on a Windows machine. CI does + not run it: a Linux runner cross-compiling to Windows removes the + need for a Windows build server, so there is no Windows CI job. + +Both flows are verified with Gpredict 2.7 (`master`): the native build +with MSYS2 UCRT `mingw-w64-x86_64-gcc` 15.2 / `mingw-w64-x86_64-gtk3` +3.24.51, and the Linux cross-build on Ubuntu 24.04 with +`gcc-mingw-w64` 13 — the resulting exe and its standalone tree start +the GUI and load maps on a stock Windows install. + +The older recipe in `win32/README` (cross-build against the +gtk+-bundle 3.10 zip from win32builder.gnome.org) still exists via +`win32/Makefile`, but it targets 2013-era GTK bundles. The two autotools +builds — native (sections 1-3) and Linux cross (section 5) — are the +maintained paths. + +## 1. Prerequisites + +1. Install [MSYS2](https://www.msys2.org/) (default location `C:\msys64`). +2. Open an **MSYS2 MinGW x64** shell (Start menu shortcut, or + `C:\msys64\msys2_shell.cmd -mingw64`) and install the toolchain and + dependencies: + + ```sh + pacman -Syu # update core, restart shell if asked + pacman -S --needed \ + base-devel \ + git \ + intltool \ + mingw-w64-x86_64-toolchain \ + mingw-w64-x86_64-pkgconf \ + mingw-w64-x86_64-glib2 \ + mingw-w64-x86_64-gtk3 \ + mingw-w64-x86_64-libcurl \ + mingw-w64-x86_64-gettext-runtime \ + mingw-w64-x86_64-gpsd # optional: GPS support via libgps + ``` + + Notes: + - `base-devel` provides the MSYS-side autotools + (autoconf/automake/libtool/intltool/gettext/autopoint). + - `zip` (MSYS package) is only needed by `win32/Makefile`'s `dist` + target; any zip tool works as a stand-in (e.g. `tar -a -cf`). + - The MinGW packages (prefixed `mingw-w64-x86_64-`) provide the + *target* libraries the binary links against. Never link against + MSYS (`/usr/bin`) DLLs — the resulting exe would require the MSYS + runtime and would not be portable. + +## 2. Configure and build + +```sh +cd gpredict +./autogen.sh --prefix=/mingw64 +make -j4 +``` + +The binary is `src/gpredict.exe`. + +## 3. Install and run + +Install into the MinGW tree so the executable sits next to its +`share/gpredict` data (maps, TLE sources, sample QTH/modules), which is +how the Win32 build locates its data files +(`g_win32_get_package_installation_directory_of_module`): + +```sh +make install # installs under C:\msys64\mingw64 +gpredict.exe # from an MSYS2 MinGW x64 shell +``` + +The first run creates `satdata/`, `modules/`, `hwconf/`, `trsp/` under +`%APPDATA%`-based config dirs and populates them from the shipped +defaults; logs land under the user data dir. + +**Gotcha:** depending on the libtool version, `make` leaves the *real* +binary at `src/.libs/gpredict.exe` while `src/gpredict.exe` is a +libtool exec-wrapper stub that may fail silently (exits instantly with +code 0 and no output) when run outside an environment matching the +stub's assumptions. If running `src/gpredict.exe` "does nothing", run +`src/.libs/gpredict.exe` instead — or just `make install` and use +`/mingw64/bin/gpredict.exe`. + +## 4. Known Windows quirks handled by the build + +These are fixed in-tree; listed here as documentation of why the code +looks the way it does: + +| Issue | Fix | +|---|---| +| `#ifdef WIN32` guards never trigger under `-std=c11`: GCC for MinGW only predefines `WIN32` in GNU dialects, never in strict ISO mode | Socket/OS guards changed to `_WIN32` (always predefined by the compiler) in `main.c`, `gtk-rig-ctrl.c`, `gtk-rot-ctrl.c`, `sat-info.c`, `sgpsdp/sgp_time.c` | +| MinGW's `curl/curl.h` itself defines `WIN32` after inclusion, silently switching later `#ifdef WIN32` blocks to the `win32_fetch` backend even when libcurl is linked | TLE/TRSP download code now selects its backend with the build-system macro `HAVE_WIN32_FETCH` (`tle-update.c`, `trsp-update.c`); `win32/Makefile` passes `-DHAVE_WIN32_FETCH` | +| `strcasestr()` is a glibc extension, absent from the Windows CRT | Call sites in `gtk-rig-ctrl.c`/`gtk-rot-ctrl.c` use the existing portable `gpredict_strcasestr()` helper | +| `timegm()` is not declared on Windows unless included as `_mkgmtime` | `sat-info.c` `#define timegm _mkgmtime` guard now triggers on `_WIN32` | +| Winsock2 functions need `ws2_32` on Windows but not on Unix | `configure.ac` uses `AC_SEARCH_LIBS([htons],[ws2_32])` | +| Double-clicking `gpredict.exe` popped up a console window and showed no file icon | On a MinGW host the autotools build links with `-mwindows` and compiles the pre-existing `win32/gpredict.rc` (icon + version info) with `windres` into the exe (`src/Makefile.am`) | + +`gmtime_r()` (`sgpsdp/sgp_time.c`) is shimmed on Windows via the same +`_WIN32` guard; the UCRT also provides it, so the shim is harmless. + +Pixmaps install under `share/pixmaps/gpredict` (FHS) but the Win32 data +lookup in `compat.c` reads `share/gpredict/pixmaps`; see section 7. + +## 5. Cross-building on Linux (MSYS2 sysroot) + +Gpredict can be cross-compiled for Windows from any Linux box using the +system MinGW-w64 toolchain plus a Windows dependency sysroot assembled +on the fly from MSYS2 repository packages (they are plain `.pkg.tar.zst` +archives, no MSYS2 runtime involved): + +```sh +sudo apt-get install mingw-w64 autoconf automake libtool intltool \ + autopoint gettext pkg-config python3 zstd zip + +python3 tools/msys2-sysroot.py ../sysroot # gtk3 + libcurl + gettext deps +./autogen.sh +./configure --host=x86_64-w64-mingw32 --prefix=/mingw64 \ + PKG_CONFIG_LIBDIR=../sysroot/mingw64/lib/pkgconfig +make -j$(nproc) + +sh tools/cross-package.sh . ../sysroot stage/gpredict-x86_64-w64-mingw32 +(cd stage && zip -qr ../gpredict-win64.zip gpredict-x86_64-w64-mingw32) +``` + +`tools/msys2-sysroot.py` resolves the transitive dependency set from the +repo's pacman DB and rewrites the `/mingw64` prefixes in the `.pc` files; +`tools/cross-package.sh` collects the exe, the DLL closure (via +`x86_64-w64-mingw32-objdump`, walking from the exe *and* from the +staged gdk-pixbuf loader DLLs so the SVG/librsvg chain ships), +pixmaps/data in the `compat.c` layout, gdk-pixbuf loaders, themes and +gspawn helpers. Pin package names/versions +as script arguments in CI for reproducibility. This is what the +`windows-cross` job in `.github/workflows/ci.yml` does; the workflow +uploads the zip as the `gpredict-windows-x86_64-cross` build artifact. + +Debian/Ubuntu mingw-w64 builds link the exe against `msvcrt` while the +sysroot libraries are UCRT-built; this works because UCRT keeps the CRT +`FILE` ABI, and stdio across that boundary (a handle opened by glib's +`g_fopen` and closed by application code) was probed. If a real CRT +clash ever surfaces, swap the distro gcc for a UCRT-native toolchain +(e.g. llvm-mingw) — the sysroot and packaging flow stay the same. + +The alternative historical path, `win32/Makefile` pointed at an existing +MSYS2 (`MINGW_ROOT=/mingw64` or `../../msys64/mingw64`), also works +inside an MSYS2 shell and additionally exercises the WinHTTP-based +`win32_fetch` downloader instead of libcurl. + +## 6. Optional: cross-build variant (win32/Makefile, Windows host) + +`win32/Makefile` remains for the historical cross/packaging build +(`make` / `make dist` from inside `win32/`, pointed at a GTK bundle or +at `MINGW_ROOT=/mingw64` in an MSYS2 shell — the latter works as-is +against current MSYS2 packages and `make dist` yields the standalone +`gpredict-.zip`). It compiles the extra `win32/win32-fetch.c` +(WinHTTP-based downloader) and defines `HAVE_WIN32_FETCH` so the +TLE/TRSP fetchers use it instead of libcurl. + +## 7. Packaging a standalone zip + +The fastest path is `tools/cross-package.sh`; it automates everything +described below: the exe (taken from `src/.libs/`, avoiding the libtool +stub), the full DLL closure *including* the dlopen'ed gdk-pixbuf +loaders and their librsvg/SVG chain, the data in the `compat.c` +layout, icons, locales, and gtk schemas — deliberately *without* a +`loaders.cache`, so gdk-pixbuf relocates its loaders from the DLL +location at runtime: + +```sh +sh tools/cross-package.sh . / stage/gpredict-x86_64-w64-mingw32 +``` + +The second argument is `/`: inside an MSYS2 shell the dependency tree +already lives at `/mingw64`. (On Linux, pass the sysroot produced by +`tools/msys2-sysroot.py` instead — section 5.) + +Then zip the stage directory — install `zip` (`pacman -S zip`) or use +PowerShell: + +```sh +PSDIR=$(cygpath -w "$PWD/stage") +powershell.exe -NoProfile -Command \ + "Compress-Archive -Path '$PSDIR\\gpredict-x86_64-w64-mingw32' -DestinationPath '$(cygpath -w "$PWD")\\gpredict-x86_64-w64-mingw32.zip'" +``` + +The result (~30 MB, GUI-subsystem exe with embedded icon) runs from +any folder on a stock Windows install, no installer or runtime +needed. + +Background — what must end up where: the autotools install follows +the Linux FHS layout (`share/pixmaps/gpredict/maps`), but the Win32 +code in `compat.c` (and the `win32/Makefile` packaging) expects the +pixmaps tree under `share/gpredict/pixmaps`. When staging from the +autotools install manually, place it accordingly, e.g.: + +```sh +cp -rp /mingw64/share/pixmaps/gpredict /mingw64/share/gpredict/pixmaps +``` + +Then ship `bin/gpredict.exe` together with the required MinGW DLLs +(`ldd /mingw64/bin/gpredict.exe` lists them) plus `share/gpredict` +(data, pixmaps, TLE templates), `share/icons/Adwaita`, `share/locale`, +the gdk-pixbuf loaders under `lib/gdk-pixbuf-2.0` (with a regenerated +`loaders.cache`) and `gspawn-win*-helper.exe` next to the exe for +hyperlinks. `win32/Makefile`'s `dist` target automates exactly this +collection; mirror it if you script your own packaging. diff --git a/src/Makefile.am b/src/Makefile.am index 020f47583..0dca4ce4e 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -121,5 +121,26 @@ gpredict_SOURCES = \ ##gpredict_LDADD = ./sgpsdp/libsgp4sdp4.a @PACKAGE_LIBS@ gpredict_LDADD = @PACKAGE_LIBS@ +if MINGW +## GUI subsystem: double-clicking gpredict.exe must not open a console +## window; diagnostics go to the log file (win32/Makefile does the same). +gpredict_LDFLAGS = -mwindows +endif + +if W32RES +## App icon + version info in the PE resources (Explorer/taskbar icon). +gpredict_res = gpredict.res +gpredict_LDADD += $(gpredict_res) +CLEANFILES = $(gpredict_res) +$(gpredict_res): $(top_srcdir)/win32/gpredict.rc \ + $(top_srcdir)/win32/resource.h \ + $(top_srcdir)/win32/icons/gpredict-icon.ico + $(WINDRES) $(AM_RCFLAGS) \ + --define VERMAJ=$(VERMAJ) --define VERMIN=$(VERMIN) \ + --define VERBLD=$(VERBLD) \ + --include-dir=$(top_srcdir)/win32 --output-format=coff \ + --input=$(top_srcdir)/win32/gpredict.rc --output=$@ +endif + ## $(INTLLIBS) diff --git a/src/gtk-rig-ctrl.c b/src/gtk-rig-ctrl.c index d42ee46d7..69de7de32 100644 --- a/src/gtk-rig-ctrl.c +++ b/src/gtk-rig-ctrl.c @@ -36,7 +36,7 @@ #endif #define _GNU_SOURCE -#include /* strcasestr */ +#include #include #include @@ -45,7 +45,7 @@ #include /* NETWORK */ -#ifndef WIN32 +#ifndef _WIN32 #include /* htons() */ #include /* gethostbyname() */ #include /* struct sockaddr_in */ @@ -1066,7 +1066,7 @@ static void filter_text_changed_cb(GtkSearchEntry *entry, gpointer data) for (i = 0; i < n; i++) { sat = SAT(g_slist_nth_data(ctrl->sats, i)); - if (sat && strcasestr(sat->nickname, filter)) + if (sat && gpredict_strcasestr(sat->nickname, filter)) { gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(ctrl->SatSel), sat->nickname); @@ -2924,7 +2924,7 @@ static gboolean close_rigctld_socket(gint *sock) sat_log_log(SAT_LOG_LEVEL_ERROR, _("%s:%s: Sent 2 bytes but sent %d."), __FILE__, __func__, written); } -#ifndef WIN32 +#ifndef _WIN32 shutdown(*sock, SHUT_RDWR); close(*sock); #else diff --git a/src/gtk-rot-ctrl.c b/src/gtk-rot-ctrl.c index f32823179..a2eef05d9 100644 --- a/src/gtk-rot-ctrl.c +++ b/src/gtk-rot-ctrl.c @@ -35,7 +35,7 @@ #define _GNU_SOURCE /* needed for strcasestr */ /* NETWORK */ -#ifndef WIN32 +#ifndef _WIN32 #include /* htons() */ #include /* gethostbyname() */ #include /* struct sockaddr_in */ @@ -50,7 +50,7 @@ #include #include -#include /* strerror, strcasestr */ +#include /* strerror */ #include "compat.h" #include "gpredict-utils.h" @@ -91,7 +91,7 @@ static gint rotctld_socket_open(const gchar *host, gint port) { sat_log_log(SAT_LOG_LEVEL_ERROR, _("Name resolution of rotctld server %s failed."), host); -#ifdef WIN32 +#ifdef _WIN32 closesocket(sock); #else close(sock); @@ -110,7 +110,7 @@ static gint rotctld_socket_open(const gchar *host, gint port) _("Connection to rotctld server at %s:%d failed: %s"), host, port, strerror(errno)); -#ifdef WIN32 +#ifdef _WIN32 closesocket(sock); #else close(sock); @@ -137,7 +137,7 @@ static void rotctld_socket_close(gint *sock) __FILE__, __func__, written); } -#ifndef WIN32 +#ifndef _WIN32 shutdown(*sock, SHUT_RDWR); close(*sock); #else @@ -733,7 +733,7 @@ static void filter_text_changed_cb(GtkSearchEntry *entry, gpointer data) for (i = 0; i < n; i++) { sat = SAT(g_slist_nth_data(ctrl->sats, i)); - if (sat && strcasestr(sat->nickname, filter)) + if (sat && gpredict_strcasestr(sat->nickname, filter)) { gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(ctrl->SatSel), sat->nickname); diff --git a/src/main.c b/src/main.c index d01ce654c..dd239f604 100644 --- a/src/main.c +++ b/src/main.c @@ -25,7 +25,7 @@ #include #include #include -#ifdef WIN32 +#ifdef _WIN32 #include #endif @@ -162,7 +162,7 @@ int main(int argc, char *argv[]) /* launch TLE monitoring task; 10 min interval */ tle_mon_id = g_timeout_add(600000, tle_mon_task, NULL); -#ifdef WIN32 +#ifdef _WIN32 // Initializing Windozze Sockets InitWinSock2(); #endif @@ -175,14 +175,14 @@ int main(int argc, char *argv[]) sat_log_close(); sat_cfg_close(); -#ifdef WIN32 +#ifdef _WIN32 CloseWinSock2(); #endif return 0; } -#ifdef WIN32 +#ifdef _WIN32 /* This code was given from MSDN */ static void InitWinSock2(void) { diff --git a/src/sat-info.c b/src/sat-info.c index b09bf5459..c81760f41 100644 --- a/src/sat-info.c +++ b/src/sat-info.c @@ -20,7 +20,7 @@ #include #endif -#ifndef WIN32 +#ifndef _WIN32 #define _DEFAULT_SOURCE // see man timegm #else #define timegm _mkgmtime // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/mkgmtime-mkgmtime32-mkgmtime64?view=vs-2017 diff --git a/src/sgpsdp/sgp_time.c b/src/sgpsdp/sgp_time.c index 4a1e02854..8d01d6614 100644 --- a/src/sgpsdp/sgp_time.c +++ b/src/sgpsdp/sgp_time.c @@ -210,7 +210,7 @@ int Check_Date(struct tm *cdate) /* expressed in Coordinated Universal Time (UTC). */ /* This function is not present in WIN32 */ -#ifdef WIN32 +#ifdef _WIN32 struct tm *gmtime_r(const time_t * timer, struct tm *result) { struct tm *local_result; diff --git a/src/tle-update.c b/src/tle-update.c index b725a8151..b0db027f1 100644 --- a/src/tle-update.c +++ b/src/tle-update.c @@ -32,7 +32,7 @@ #ifdef HAVE_CONFIG_H #include #endif -#ifdef WIN32 +#ifdef HAVE_WIN32_FETCH #include "win32-fetch.h" #else #include @@ -47,7 +47,7 @@ /* private function prototypes */ -#ifndef WIN32 +#ifndef HAVE_WIN32_FETCH static size_t my_write_func(void *ptr, size_t size, size_t nmemb, FILE * stream); #endif @@ -480,7 +480,7 @@ void tle_update_from_network(gboolean silent, gchar *curfile; gchar *locfile; gchar *userconfdir; -#ifdef WIN32 +#ifdef HAVE_WIN32_FETCH int res; #else CURL *curl; @@ -538,7 +538,7 @@ void tle_update_from_network(gboolean silent, if (!silent && (progress != NULL)) start = gtk_progress_bar_get_fraction(GTK_PROGRESS_BAR(progress)); -#ifndef WIN32 +#ifndef HAVE_WIN32_FETCH /* initialise curl */ curl = curl_easy_init(); if (proxy != NULL) @@ -553,7 +553,7 @@ void tle_update_from_network(gboolean silent, { /* set URL */ curfile = g_strdup(files[i]); -#ifndef WIN32 +#ifndef HAVE_WIN32_FETCH curl_easy_setopt(curl, CURLOPT_URL, curfile); #endif @@ -574,7 +574,7 @@ void tle_update_from_network(gboolean silent, outfile = g_fopen(locfile, "wb"); if (outfile != NULL) { -#ifdef WIN32 +#ifdef HAVE_WIN32_FETCH res = win32_fetch(curfile, outfile, proxy, "gpredict/win32"); if (res != 0) { @@ -640,7 +640,7 @@ void tle_update_from_network(gboolean silent, g_free(locfile); } -#ifndef WIN32 +#ifndef HAVE_WIN32_FETCH curl_easy_cleanup(curl); #endif @@ -704,7 +704,7 @@ void tle_update_from_network(gboolean silent, g_mutex_unlock(&tle_in_progress); } -#ifndef WIN32 +#ifndef HAVE_WIN32_FETCH /** * Write TLE data block to file. * diff --git a/src/trsp-update.c b/src/trsp-update.c index da8edb5d2..bbe55e8bd 100644 --- a/src/trsp-update.c +++ b/src/trsp-update.c @@ -46,7 +46,7 @@ #include #endif -#ifdef WIN32 +#ifdef HAVE_WIN32_FETCH #include "win32-fetch.h" #else #include @@ -94,7 +94,7 @@ typedef struct { guint numtrsp; /* Number of transponders. */ } new_trsp_t; -#ifndef WIN32 +#ifndef HAVE_WIN32_FETCH /* private function prototypes */ static size_t my_write_func(void *ptr, size_t size, size_t nmemb, FILE * stream); @@ -404,7 +404,7 @@ void modes_update_from_network() gchar *file_url; gchar *locfile; gchar *userconfdir; -#ifdef WIN32 +#ifdef HAVE_WIN32_FETCH int res; #else CURL *curl; @@ -417,7 +417,7 @@ void modes_update_from_network() proxy = sat_cfg_get_str(SAT_CFG_STR_TRSP_PROXY); modes_file = sat_cfg_get_str(SAT_CFG_STR_TRSP_MODE_FILE); -#ifndef WIN32 +#ifndef HAVE_WIN32_FETCH /* initialise curl */ curl = curl_easy_init(); if (proxy != NULL) @@ -430,7 +430,7 @@ void modes_update_from_network() /* get files */ /* set URL */ file_url = g_strconcat(server, modes_file, NULL); -#ifndef WIN32 +#ifndef HAVE_WIN32_FETCH curl_easy_setopt(curl, CURLOPT_URL, file_url); sat_log_log(SAT_LOG_LEVEL_INFO, _("%s: Ready to fetch modes list from %s"), @@ -447,7 +447,7 @@ void modes_update_from_network() outfile = g_fopen(locfile, "wb"); if (outfile != NULL) { -#ifdef WIN32 +#ifdef HAVE_WIN32_FETCH res = win32_fetch(file_url, outfile, proxy, "gpredict/win32"); if (res != 0) { @@ -495,7 +495,7 @@ void modes_update_from_network() g_free(proxy); g_free(modes_file); -#ifndef WIN32 +#ifndef HAVE_WIN32_FETCH curl_easy_cleanup(curl); #endif @@ -537,7 +537,7 @@ void trsp_update_from_network(gboolean silent, gchar *file_url; gchar *locfile_trsp; gchar *userconfdir; -#ifdef WIN32 +#ifdef HAVE_WIN32_FETCH int res; #else CURL *curl; @@ -570,7 +570,7 @@ void trsp_update_from_network(gboolean silent, proxy = sat_cfg_get_str(SAT_CFG_STR_TRSP_PROXY); freq_file = sat_cfg_get_str(SAT_CFG_STR_TRSP_FREQ_FILE); -#ifndef WIN32 +#ifndef HAVE_WIN32_FETCH /* initialise curl */ curl = curl_easy_init(); if (proxy != NULL) @@ -583,7 +583,7 @@ void trsp_update_from_network(gboolean silent, /* get files */ /* set URL */ file_url = g_strconcat(server, freq_file, NULL); -#ifndef WIN32 +#ifndef HAVE_WIN32_FETCH curl_easy_setopt(curl, CURLOPT_URL, file_url); sat_log_log(SAT_LOG_LEVEL_INFO, _("%s: Ready to fetch transponder list from %s"), @@ -616,7 +616,7 @@ void trsp_update_from_network(gboolean silent, outfile = g_fopen(locfile_trsp, "wb"); if (outfile != NULL) { -#ifdef WIN32 +#ifdef HAVE_WIN32_FETCH res = win32_fetch(file_url, outfile, proxy, "gpredict/win32"); if (res != 0) { @@ -679,7 +679,7 @@ void trsp_update_from_network(gboolean silent, g_free(freq_file); g_free(proxy); -#ifndef WIN32 +#ifndef HAVE_WIN32_FETCH curl_easy_cleanup(curl); #endif @@ -704,7 +704,7 @@ void trsp_update_from_network(gboolean silent, g_mutex_unlock(&trsp_in_progress); } -#ifndef WIN32 +#ifndef HAVE_WIN32_FETCH /** * Write TRSP data block to file. * diff --git a/tools/cross-package.sh b/tools/cross-package.sh new file mode 100644 index 000000000..bd27dbbbe --- /dev/null +++ b/tools/cross-package.sh @@ -0,0 +1,115 @@ +#!/bin/sh +# Assemble a standalone Windows package from a Linux cross-build. +# +# cross-package.sh BUILDDIR SYSROOT OUTDIR +# +# BUILDDIR autotools build tree (top level of gpredict) +# SYSROOT tree produced by tools/msys2-sysroot.py (contains mingw64/); +# when running inside MSYS2 itself, pass `/` (there the mingw64 +# tree lives at /mingw64) +# OUTDIR staging directory that is created and filled +# +# Mirrors the layout that src/compat.c and win32/Makefile expect: +# exe + DLLs at the root, share/gpredict/{data,pixmaps}, Adwaita icons, +# gdk-pixbuf loaders. + +set -e + +BUILDDIR=$(CDPATH= cd -- "$1" && pwd) +SYSROOT=$(CDPATH= cd -- "${2%/}/mingw64" && pwd) +if command -v realpath >/dev/null 2>&1; then + OUT=$(realpath -m -- "$3") +else + mkdir -p "$(dirname -- "$3")" + OUT=$(CDPATH= cd -- "$(dirname -- "$3")" && pwd)/$(basename -- "$3") +fi + +if [ -z "${OBJDUMP:-}" ]; then + for cand in x86_64-w64-mingw32-objdump objdump; do + if command -v "$cand" >/dev/null 2>&1; then OBJDUMP=$cand; break; fi + done +fi +[ -n "$OBJDUMP" ] || { echo "no objdump found; set OBJDUMP" >&2; exit 1; } + +rm -rf "$OUT" +mkdir -p "$OUT/lib/gdk-pixbuf-2.0/2.10.0" "$OUT/share" + +# --- executables ------------------------------------------------------------- +if [ -f "$BUILDDIR/src/.libs/gpredict.exe" ]; then + exe="$BUILDDIR/src/.libs/gpredict.exe" +else + exe="$BUILDDIR/src/gpredict.exe" +fi +cp -p "$exe" "$OUT/" + +# --- gdk-pixbuf loaders ------------------------------------------------------- +# Staged *before* the closure walk and seeded as closure roots: loader +# DLLs are dlopen'ed by gdk-pixbuf at runtime, so they never show up in +# the exe's import table — and the SVG loader drags in the whole +# librsvg chain (librsvg-2-2.dll & friends) that would otherwise be +# missing, making all SVG loading fail with "Couldn't recognize the +# image file format". +if [ -d "$SYSROOT/lib/gdk-pixbuf-2.0/2.10.0/loaders" ]; then + mkdir -p "$OUT/lib/gdk-pixbuf-2.0/2.10.0/loaders" + cp -p "$SYSROOT"/lib/gdk-pixbuf-2.0/2.10.0/loaders/*pixbufloader*.dll \ + "$OUT/lib/gdk-pixbuf-2.0/2.10.0/loaders/" +fi + +# --- DLL dependency closure --------------------------------------------------- +queue="$(basename "$exe")" +for l in "$OUT"/lib/gdk-pixbuf-2.0/2.10.0/loaders/*.dll; do + [ -e "$l" ] || continue + queue="$queue lib/gdk-pixbuf-2.0/2.10.0/loaders/$(basename "$l")" +done +copied="" +while [ -n "$queue" ]; do + next="" + for cur in $queue; do + for m in $("$OBJDUMP" -p "$OUT/$cur" 2>/dev/null | awk '/DLL Name/ {print $3}'); do + m_lc=$(printf '%s' "$m" | tr '[:upper:]' '[:lower:]') + case "$m_lc" in + windows.system32*|windows\system32*|ntdll.dll|kernel32.dll|kernelbase.dll|\ + msvcrt.dll|advapi32.dll|ole32.dll|oleaut32.dll|user32.dll|gdi32.dll|\ + shell32.dll|ws2_32.dll|wldap32.dll|crypt32.dll|rpcrt4.dll|sechost.dll|\ + bcrypt.dll|dbghelp.dll|version.dll|winmm.dll|dwmapi.dll|\ + setupapi.dll|cfgmgr32.dll|hid.dll|winspool.drv|comdlg32.dll|\ + comctl32.dll|imm32.dll|uuid.dll|powrprof.dll|iphlpapi.dll|\ + dnsapi.dll|userenv.dll|profapi.dll|kernel.appcore.dll|\ + bcryptprimitives.dll|ucrtbase.dll|api-ms-win-*|ext-ms-*) continue ;; + esac + if [ -f "$SYSROOT/bin/$m" ]; then + cp -p "$SYSROOT/bin/$m" "$OUT/" + case " $copied " in *" $m "*) ;; *) + copied="$copied $m" + next="$next $m" ;; + esac + fi + done + done + queue=$next +done + +# --- data / pixmaps in the layout compat.c expects on Win32 ------------------- +mkdir -p "$OUT/share/gpredict/data/satdata" +cp -p "$BUILDDIR/data/locations.dat" "$BUILDDIR/data/sample.qth" \ + "$BUILDDIR/data/Amateur.mod" "$OUT/share/gpredict/data/" 2>/dev/null || true +cp -p "$BUILDDIR"/data/satdata/*.cat "$BUILDDIR"/data/satdata/*.dat \ + "$OUT/share/gpredict/data/satdata/" 2>/dev/null || true +cp -rp "$BUILDDIR/pixmaps" "$OUT/share/gpredict/pixmaps" + +# --- GTK theming / icons / schemas / helpers ---------------------------------- +[ -d "$SYSROOT/etc" ] && cp -rp "$SYSROOT/etc" "$OUT/" +if [ -d "$SYSROOT/share/icons/Adwaita" ]; then + mkdir -p "$OUT/share/icons/Adwaita" + cp -rp "$SYSROOT/share/icons/Adwaita/scalable" "$OUT/share/icons/Adwaita/" 2>/dev/null || true + cp -p "$SYSROOT/share/icons/Adwaita/index.theme" "$OUT/share/icons/Adwaita/" 2>/dev/null || true +fi +if [ -f "$SYSROOT/share/glib-2.0/schemas/gschemas.compiled" ]; then + mkdir -p "$OUT/share/glib-2.0/schemas" + cp -p "$SYSROOT/share/glib-2.0/schemas/gschemas.compiled" "$OUT/share/glib-2.0/schemas/" +fi +for h in gspawn-win64-helper.exe gspawn-win64-helper-console.exe; do + [ -f "$SYSROOT/bin/$h" ] && cp -p "$SYSROOT/bin/$h" "$OUT/" +done + +echo "staged: $OUT" diff --git a/tools/msys2-sysroot.py b/tools/msys2-sysroot.py new file mode 100644 index 000000000..d8b3e76e0 --- /dev/null +++ b/tools/msys2-sysroot.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Build a Windows cross-compile sysroot from MSYS2 repo packages. + +Downloads the pacman sync DB of the MSYS2 mingw x86_64 repository, +resolves the transitive dependencies of the requested packages and +extracts them into a self-contained tree: + + /mingw64/{bin,include,lib,share} + +The prefix baked into every .pc file is rewritten from /mingw64 to the +absolute destination path, so a plain pkg-config on any Linux host can +cross-build against the tree with the system mingw-w64 toolchain: + + ./configure --host=x86_64-w64-mingw32 \ + PKG_CONFIG_LIBDIR=/mingw64/lib/pkgconfig + +Usage: + msys2-sysroot.py DEST [PKG ...] + +Default package list: gtk3 + libcurl + gettext-runtime (what Gpredict +needs). Pin exact package file names in CI for reproducible builds. +""" + +import io +import os +import re +import subprocess +import sys +import tarfile +import urllib.request + +REPO = "https://repo.msys2.org/mingw/x86_64" +DEFAULT_PKGS = [ + "mingw-w64-x86_64-gtk3", + "mingw-w64-x86_64-curl", + "mingw-w64-x86_64-gettext-runtime", +] + + +def fetch(url): + req = urllib.request.Request(url, headers={"User-Agent": "gpredict-cross"}) + with urllib.request.urlopen(req) as r: + return r.read() + + +def parse_desc(text): + """Parse one pacman desc stanza -> (filename, depends, names).""" + cur = None + fname = None + depends = [] + names = set() + for line in text.splitlines(): + if line.startswith("%") and line.rstrip().endswith("%"): + cur = line.strip() + continue + line = line.strip() + if not line: + continue + if cur == "%FILENAME%": + fname = line + elif cur in ("%NAME%", "%NAMES%", "%PROVIDES%"): + names |= {re.split(r"[=<>]", x)[0] for x in line.split()} + elif cur == "%DEPENDS%": + depends += line.split() + return fname, depends, names + + +def parse_db(blob): + """Parse pacman sync DB. Returns (entries, index). + + Modern MSYS2 sync DBs are zstd-compressed tar archives containing one + `desc` file per package; older ones are a flat concatenated text DB. + entries: {filename: {"depends": [...], "names": set()}} + index: {lowercased name -> filename} + """ + entries = {} + + def add(text): + fname, depends, names = parse_desc(text) + if fname: + entries[fname] = {"depends": depends, "names": names} + + if blob[:4] == b"\x28\xb5\x2f\xfd": # zstd magic + blob = subprocess.run(["zstd", "-dc"], input=blob, check=True, + stdout=subprocess.PIPE).stdout + + bio = io.BytesIO(blob) + try: + with tarfile.open(fileobj=bio, mode="r:") as tf: + for member in tf: + if member.name.endswith("/desc"): + add(tf.extractfile(member).read().decode("utf-8", "replace")) + return _index(entries) + except tarfile.TarError: + pass + + bio.seek(0) + add(bio.read().decode("utf-8", "replace")) + return _index(entries) + + +def _index(entries): + index = {} + for fname, ent in entries.items(): + for name in ent["names"]: + index.setdefault(name.lower(), fname) + return entries, index + + +def resolve(entries, index, roots): + selected = set() + queue = [p.lower() for p in roots] + missing = [] + while queue: + name = queue.pop() + fname = index.get(name) + if fname is None: + missing.append(name) + continue + if fname in selected: + continue + selected.add(fname) + for dep in entries[fname]["depends"]: + dep_name = re.split(r"[=<>]", dep)[0].lower() + if dep_name.startswith("msys:"): + continue # MSYS(POSIX)-side runtime, not needed when cross-building + queue.append(dep_name) + if missing: + print("unresolvable dependencies: " + " ".join(missing), file=sys.stderr) + sys.exit(1) + return selected + + +def main(): + if len(sys.argv) < 2: + print(__doc__, file=sys.stderr) + return 1 + dest = os.path.abspath(sys.argv[1]) + roots = sys.argv[2:] or DEFAULT_PKGS + + entries, index = parse_db(fetch(f"{REPO}/mingw64.db")) + selected = resolve(entries, index, roots) + print(f"{len(selected)} packages -> {dest}") + + os.makedirs(dest, exist_ok=True) + for i, fname in enumerate(sorted(selected), 1): + print(f"[{i}/{len(selected)}] {fname}") + data = fetch(f"{REPO}/{fname}") + subprocess.run(["tar", "--zstd", "-xf", "-", "-C", dest], + input=data, check=True) + + sysroot = os.path.join(dest, "mingw64") + pcdir = os.path.join(sysroot, "lib", "pkgconfig") + if os.path.isdir(pcdir): + for pc in sorted(os.listdir(pcdir)): + if not pc.endswith(".pc"): + continue + path = os.path.join(pcdir, pc) + with open(path) as f: + text = f.read() + new = re.sub(r"(?