all messages for Emacs-related lists mirrored at yhetil.org
 help / color / mirror / code / Atom feed
* bug#51404: Support system dark mode on Windows 10
@ 2021-10-26  4:46 Vince Salvino
  2021-10-26 14:01 ` Eli Zaretskii
                   ` (2 more replies)
  0 siblings, 3 replies; 22+ messages in thread
From: Vince Salvino @ 2021-10-26  4:46 UTC (permalink / raw)
  To: 51404

[-- Attachment #1: Type: text/plain, Size: 111 bytes --]

Attached is the patch. Additional info available here: https://github.com/vsalvino/emacs


Vince Salvino


[-- Attachment #2: 0001-Support-system-dark-mode-on-Windows-10-version-2004-.patch --]
[-- Type: application/octet-stream, Size: 7491 bytes --]

From 25ec63b9e6dfc411837aa936c06a9a848c690f49 Mon Sep 17 00:00:00 2001
From: Vince Salvino <salvino@coderedcorp.com>
Date: Mon, 25 Oct 2021 22:18:46 -0400
Subject: [PATCH] Support system dark mode on Windows 10 version 2004 and
 higher.

---
 src/w32.c    | 11 +++++--
 src/w32.h    |  3 ++
 src/w32fns.c | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++--
 3 files changed, 91 insertions(+), 4 deletions(-)

diff --git a/src/w32.c b/src/w32.c
index 9fe698d28d..f27c47bba5 100644
--- a/src/w32.c
+++ b/src/w32.c
@@ -2822,6 +2822,13 @@ #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
 
 LPBYTE
 w32_get_resource (const char *key, LPDWORD lpdwtype)
+{
+  return w32_query_registry(REG_ROOT, key, lpdwtype);
+}
+
+/* Enables reading any key/name from the Windows Registry */
+LPBYTE
+w32_query_registry (const char *root, const char *key, LPDWORD lpdwtype)
 {
   LPBYTE lpvalue;
   HKEY hrootkey = NULL;
@@ -2830,7 +2837,7 @@ w32_get_resource (const char *key, LPDWORD lpdwtype)
   /* Check both the current user and the local machine to see if
      we have any resources.  */
 
-  if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
+  if (RegOpenKeyEx (HKEY_CURRENT_USER, root, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
     {
       lpvalue = NULL;
 
@@ -2847,7 +2854,7 @@ w32_get_resource (const char *key, LPDWORD lpdwtype)
       RegCloseKey (hrootkey);
     }
 
-  if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
+  if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, root, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
     {
       lpvalue = NULL;
 
diff --git a/src/w32.h b/src/w32.h
index ffa145b148..69468580b4 100644
--- a/src/w32.h
+++ b/src/w32.h
@@ -164,6 +164,9 @@ #define FILE_SERIAL             0x0800
 /* Return the string resource associated with KEY of type TYPE.  */
 extern LPBYTE w32_get_resource (const char * key, LPDWORD type);
 
+/* Utility to query [HKCU|HKLM]\root\key from the Windows Registry */
+extern LPBYTE w32_query_registry (const char * root, const char * key, LPDWORD type);
+
 extern void release_listen_threads (void);
 extern void init_ntproc (int);
 extern void term_ntproc (int);
diff --git a/src/w32fns.c b/src/w32fns.c
index 14d1154a2b..54c03a4a1f 100644
--- a/src/w32fns.c
+++ b/src/w32fns.c
@@ -73,6 +73,15 @@ #define _WIN32_WINNT 0x0600
 #include <imm.h>
 #include <windowsx.h>
 
+/*
+  Internal/undocumented constants for Windows Dark mode.
+  See: https://github.com/microsoft/WindowsAppSDK/issues/41
+*/
+#define DARK_MODE_APP_NAME L"DarkMode_Explorer"
+#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE
+#define DWMWA_USE_IMMERSIVE_DARK_MODE 20
+#endif
+
 #ifndef FOF_NO_CONNECTED_ELEMENTS
 #define FOF_NO_CONNECTED_ELEMENTS 0x2000
 #endif
@@ -185,6 +194,11 @@ DECLARE_HANDLE(HMONITOR);
 typedef HRESULT (WINAPI *SetThreadDescription_Proc)
   (HANDLE hThread, PCWSTR lpThreadDescription);
 
+typedef HRESULT (WINAPI * SetWindowTheme_Proc)
+  (IN HWND hwnd, IN LPCWSTR pszSubAppName, IN LPCWSTR pszSubIdList);
+typedef HRESULT (WINAPI * DwmSetWindowAttribute_Proc)
+  (HWND hwnd, DWORD dwAttribute, IN LPCVOID pvAttribute, DWORD cbAttribute);
+
 TrackMouseEvent_Proc track_mouse_event_fn = NULL;
 ImmGetCompositionString_Proc get_composition_string_fn = NULL;
 ImmGetContext_Proc get_ime_context_fn = NULL;
@@ -199,6 +213,8 @@ DECLARE_HANDLE(HMONITOR);
 GetTitleBarInfo_Proc get_title_bar_info_fn = NULL;
 IsDebuggerPresent_Proc is_debugger_present = NULL;
 SetThreadDescription_Proc set_thread_description = NULL;
+SetWindowTheme_Proc SetWindowTheme_fn = NULL;
+DwmSetWindowAttribute_Proc DwmSetWindowAttribute_fn = NULL;
 
 extern AppendMenuW_Proc unicode_append_menu;
 
@@ -252,6 +268,9 @@ #define MENU_FREE_DELAY 1000
 int w32_minor_version;
 int w32_build_number;
 
+/* If the OS is set to use dark mode. */
+BOOL w32_darkmode = FALSE;
+
 /* Distinguish between Windows NT and Windows 95.  */
 int os_subtype;
 
@@ -2279,10 +2298,31 @@ w32_init_class (HINSTANCE hinst)
     }
 }
 
+/* Applies the Windows system theme (light or dark) to a window handle. */
+static void
+w32_applytheme(HWND hwnd)
+{
+  if (w32_darkmode) {
+    /* Set window theme to that of a built-in Windows app (Explorer)
+       because it has dark scroll bars and other UI elements. */
+    if(SetWindowTheme_fn) {
+      SetWindowTheme_fn(hwnd, DARK_MODE_APP_NAME, NULL);
+    }
+    /* Set the titlebar to system dark mode. */
+    if (DwmSetWindowAttribute_fn) {
+      DwmSetWindowAttribute_fn
+	(hwnd,
+	 DWMWA_USE_IMMERSIVE_DARK_MODE,
+	 &w32_darkmode,
+	 sizeof(w32_darkmode));
+    }
+  }
+}
+
 static HWND
 w32_createvscrollbar (struct frame *f, struct scroll_bar * bar)
 {
-  return CreateWindow ("SCROLLBAR", "",
+  HWND hwnd = CreateWindow ("SCROLLBAR", "",
 		       /* Clip siblings so we don't draw over child
 			  frames.  Apparently this is not always
 			  sufficient so we also try to make bar windows
@@ -2291,12 +2331,16 @@ w32_createvscrollbar (struct frame *f, struct scroll_bar * bar)
 		       /* Position and size of scroll bar.  */
 		       bar->left, bar->top, bar->width, bar->height,
 		       FRAME_W32_WINDOW (f), NULL, hinst, NULL);
+  if(hwnd) {
+    w32_applytheme(hwnd);
+  }
+  return hwnd;
 }
 
 static HWND
 w32_createhscrollbar (struct frame *f, struct scroll_bar * bar)
 {
-  return CreateWindow ("SCROLLBAR", "",
+  HWND hwnd = CreateWindow ("SCROLLBAR", "",
 		       /* Clip siblings so we don't draw over child
 			  frames.  Apparently this is not always
 			  sufficient so we also try to make bar windows
@@ -2305,6 +2349,10 @@ w32_createhscrollbar (struct frame *f, struct scroll_bar * bar)
 		       /* Position and size of scroll bar.  */
 		       bar->left, bar->top, bar->width, bar->height,
 		       FRAME_W32_WINDOW (f), NULL, hinst, NULL);
+  if(hwnd) {
+    w32_applytheme(hwnd);
+  }
+  return hwnd;
 }
 
 static void
@@ -2390,6 +2438,9 @@ w32_createwindow (struct frame *f, int *coords)
       /* Enable drag-n-drop.  */
       DragAcceptFiles (hwnd, TRUE);
 
+      /* Enable system light/dark theme. */
+      w32_applytheme(hwnd);
+
       /* Do this to discard the default setting specified by our parent. */
       ShowWindow (hwnd, SW_HIDE);
 
@@ -11028,6 +11079,32 @@ globals_of_w32fns (void)
   set_thread_description = (SetThreadDescription_Proc)
     get_proc_addr (hm_kernel32, "SetThreadDescription");
 
+  /*
+    Support OS dark mode on Windows 10 version 2004 and higher.
+    For future wretches who may need to understand Windows build numbers:
+    https://docs.microsoft.com/en-us/windows/release-health/release-information
+   */
+  if (w32_major_version >= 10 && w32_build_number >= 19041
+      && os_subtype == OS_SUBTYPE_NT) {
+
+    /* Load dwmapi and uxtheme, which will be needed to set window themes. */
+    HMODULE dwmapi_lib = LoadLibrary("dwmapi.dll");
+    DwmSetWindowAttribute_fn = (DwmSetWindowAttribute_Proc)
+      get_proc_addr (dwmapi_lib, "DwmSetWindowAttribute");
+    HMODULE uxtheme_lib = LoadLibrary("uxtheme.dll");
+    SetWindowTheme_fn = (SetWindowTheme_Proc)
+      get_proc_addr (uxtheme_lib, "SetWindowTheme");
+
+    /* Check Windows Registry for system theme. DWORD set to 0 or 1. */
+    LPBYTE val = w32_query_registry
+      ("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
+       "AppsUseLightTheme",
+       NULL);
+    if (val && (DWORD)*val == 0) {
+      w32_darkmode = TRUE;
+    }
+  }
+
   except_code = 0;
   except_addr = 0;
 #ifndef CYGWIN
-- 
2.33.0.windows.2


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* bug#51404: Support system dark mode on Windows 10
  2021-10-26  4:46 bug#51404: Support system dark mode on Windows 10 Vince Salvino
@ 2021-10-26 14:01 ` Eli Zaretskii
  2021-10-26 16:18   ` Eli Zaretskii
  2021-10-26 16:49   ` Vince Salvino
  2022-01-14  6:00 ` Vince Salvino
  2022-01-23  0:00 ` Vince Salvino
  2 siblings, 2 replies; 22+ messages in thread
From: Eli Zaretskii @ 2021-10-26 14:01 UTC (permalink / raw)
  To: Vince Salvino; +Cc: 51404

> From: Vince Salvino <salvino@coderedcorp.com>
> Date: Tue, 26 Oct 2021 04:46:27 +0000
> 
> Attached is the patch. Additional info available here: https://github.com/vsalvino/emacs

Thanks.  I have some comments and questions below, but in any case
these changes are large enough to require copyright assignment from
you.  If you'd be willing to start the legal paperwork at this time, I
will send you the form to fill with the appropriate instructions.

>  LPBYTE
>  w32_get_resource (const char *key, LPDWORD lpdwtype)
> +{
> +  return w32_query_registry(REG_ROOT, key, lpdwtype);
> +}
> +
> +/* Enables reading any key/name from the Windows Registry */
> +LPBYTE
> +w32_query_registry (const char *root, const char *key, LPDWORD lpdwtype)

I'd prefer that you simply add an extra argument to the existing
w32_get_resource, and adjust its single caller to pass REG_ROOT there.

> +/*
> +  Internal/undocumented constants for Windows Dark mode.
> +  See: https://github.com/microsoft/WindowsAppSDK/issues/41
> +*/

Please follow our style for comments, both single-line and multi-line.

> +#define DARK_MODE_APP_NAME L"DarkMode_Explorer"

Can we make this exposed to Lisp, rather than hard-coded?  Hard-coding
a specific application for a theme sounds un-Emacsy.  People could
want to experiment with other apps.

> +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE
> +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20

Why not use 19 and 20, depending on the Windows build number, and thus
expand the applicability of the feature?

> +/* Applies the Windows system theme (light or dark) to a window handle. */
> +static void
> +w32_applytheme(HWND hwnd)
> +{
> +  if (w32_darkmode) {
> +    /* Set window theme to that of a built-in Windows app (Explorer)
> +       because it has dark scroll bars and other UI elements. */

Likewise here: it should be able to control this behavior by a user
option.  We cannot assume that every Emacs user will automatically
want to follow the system theme.

> +    if(SetWindowTheme_fn) {
> +      SetWindowTheme_fn(hwnd, DARK_MODE_APP_NAME, NULL);
> +    }

Please follow our style of using braces in C code.

> +    /* Set the titlebar to system dark mode. */
> +    if (DwmSetWindowAttribute_fn) {
> +      DwmSetWindowAttribute_fn
> +	(hwnd,
> +	 DWMWA_USE_IMMERSIVE_DARK_MODE,
> +	 &w32_darkmode,
> +	 sizeof(w32_darkmode));
> +    }

Does it make sense to call DwmSetWindowAttribute if we couldn't call
SetWindowTheme?  I know that such a situation shouldn't normally
happen, but what if it does?  If we need both calls, the second call
should be conditioned by SetWindowTheme_fn as well.

Last, but not least: this feature should be called out in NEWS and
preferably also described in the "MS-Windows" Appendix in the Emacs
manual.

Thanks again for working on this.





^ permalink raw reply	[flat|nested] 22+ messages in thread

* bug#51404: Support system dark mode on Windows 10
  2021-10-26 14:01 ` Eli Zaretskii
@ 2021-10-26 16:18   ` Eli Zaretskii
  2021-10-26 16:49   ` Vince Salvino
  1 sibling, 0 replies; 22+ messages in thread
From: Eli Zaretskii @ 2021-10-26 16:18 UTC (permalink / raw)
  To: salvino; +Cc: 51404

> Date: Tue, 26 Oct 2021 17:01:51 +0300
> From: Eli Zaretskii <eliz@gnu.org>
> Cc: 51404@debbugs.gnu.org
> 
> Thanks.  I have some comments and questions below, but in any case
> these changes are large enough to require copyright assignment from
> you.  If you'd be willing to start the legal paperwork at this time, I
> will send you the form to fill with the appropriate instructions.

Actually, I now see that you already started the legal paperwork
rolling, so we are okay in that department.

Thanks.





^ permalink raw reply	[flat|nested] 22+ messages in thread

* bug#51404: Support system dark mode on Windows 10
  2021-10-26 14:01 ` Eli Zaretskii
  2021-10-26 16:18   ` Eli Zaretskii
@ 2021-10-26 16:49   ` Vince Salvino
  2021-10-26 17:05     ` Eli Zaretskii
  1 sibling, 1 reply; 22+ messages in thread
From: Vince Salvino @ 2021-10-26 16:49 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: 51404@debbugs.gnu.org

> > +#define DARK_MODE_APP_NAME L"DarkMode_Explorer"

> Can we make this exposed to Lisp, rather than hard-coded?  Hard-coding a specific application for a theme sounds un-Emacsy.  People could want to experiment with other apps.

Given that this is not so much a preference, as an undocumented magic string in Win32, I think anyone who wants to play with this is going to require knowledge of C and gdb to experiment, to risk causing erratic and unknown behavior. So I would be inclined to keep it in C.


> > +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE #define 
> > +DWMWA_USE_IMMERSIVE_DARK_MODE 20

> Why not use 19 and 20, depending on the Windows build number, and thus expand the applicability of the feature?

I can add support for 19, but do not have the ability to test it on those specific Win10 builds to confirm if it actually works as expected. If someone is able to test on a version of Windows 10 older than 2004, then I will include. Erring on the side of stability for now.


> +/* Applies the Windows system theme (light or dark) to a window 
> +handle. */ static void w32_applytheme(HWND hwnd) {
> +  if (w32_darkmode) {
> +    /* Set window theme to that of a built-in Windows app (Explorer)
> +       because it has dark scroll bars and other UI elements. */

> Likewise here: it should be able to control this behavior by a user option.  We cannot assume that every Emacs user will automatically want to follow the system theme.

I agree this would be a "nice to have", but the current functionality is in-line with behavior on other systems (GTK, macOS, etc. i.e. the application has no say in window decorations which are controlled by the window manager). If we did add an elisp setting it should default to the registry value at runtime. I also have no idea how to create an elisp setting and read it in C. Examples or contributions to this patch would be helpful.


> > +    /* Set the titlebar to system dark mode. */
> > +    if (DwmSetWindowAttribute_fn) {
> > +      DwmSetWindowAttribute_fn
> > +	(hwnd,
> > +	 DWMWA_USE_IMMERSIVE_DARK_MODE,
> > +	 &w32_darkmode,
> > +	 sizeof(w32_darkmode));
> > +    }

> Does it make sense to call DwmSetWindowAttribute if we couldn't call SetWindowTheme?  I know that such a situation shouldn't normally happen, but what if it does?  If we need both calls, the second call should be conditioned by SetWindowTheme_fn as well.

There is no harm in calling one without the other. SetWindowTheme sets things like scrollbars. DwmSetWindowAttribute specifically sets the titlebar. My original proof-of-concept only had DwmSetWindowAttribute and worked fine.

I will make the other requested changes, i.e. registry helper, style guide, and NEWS; and submit an updated patch.


Vince Salvino

-----Original Message-----
From: Eli Zaretskii <eliz@gnu.org> 
Sent: Tuesday, October 26, 2021 10:02 AM
To: Vince Salvino <salvino@coderedcorp.com>
Cc: 51404@debbugs.gnu.org
Subject: Re: bug#51404: Support system dark mode on Windows 10

> From: Vince Salvino <salvino@coderedcorp.com>
> Date: Tue, 26 Oct 2021 04:46:27 +0000
> 
> Attached is the patch. Additional info available here: 
> https://github.com/vsalvino/emacs

Thanks.  I have some comments and questions below, but in any case these changes are large enough to require copyright assignment from you.  If you'd be willing to start the legal paperwork at this time, I will send you the form to fill with the appropriate instructions.

>  LPBYTE
>  w32_get_resource (const char *key, LPDWORD lpdwtype)
> +{
> +  return w32_query_registry(REG_ROOT, key, lpdwtype); }
> +
> +/* Enables reading any key/name from the Windows Registry */ LPBYTE 
> +w32_query_registry (const char *root, const char *key, LPDWORD 
> +lpdwtype)

I'd prefer that you simply add an extra argument to the existing w32_get_resource, and adjust its single caller to pass REG_ROOT there.

> +/*
> +  Internal/undocumented constants for Windows Dark mode.
> +  See: https://github.com/microsoft/WindowsAppSDK/issues/41
> +*/

Please follow our style for comments, both single-line and multi-line.

> +#define DARK_MODE_APP_NAME L"DarkMode_Explorer"

Can we make this exposed to Lisp, rather than hard-coded?  Hard-coding a specific application for a theme sounds un-Emacsy.  People could want to experiment with other apps.

> +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE #define 
> +DWMWA_USE_IMMERSIVE_DARK_MODE 20

Why not use 19 and 20, depending on the Windows build number, and thus expand the applicability of the feature?

> +/* Applies the Windows system theme (light or dark) to a window 
> +handle. */ static void w32_applytheme(HWND hwnd) {
> +  if (w32_darkmode) {
> +    /* Set window theme to that of a built-in Windows app (Explorer)
> +       because it has dark scroll bars and other UI elements. */

Likewise here: it should be able to control this behavior by a user option.  We cannot assume that every Emacs user will automatically want to follow the system theme.

> +    if(SetWindowTheme_fn) {
> +      SetWindowTheme_fn(hwnd, DARK_MODE_APP_NAME, NULL);
> +    }

Please follow our style of using braces in C code.

> +    /* Set the titlebar to system dark mode. */
> +    if (DwmSetWindowAttribute_fn) {
> +      DwmSetWindowAttribute_fn
> +	(hwnd,
> +	 DWMWA_USE_IMMERSIVE_DARK_MODE,
> +	 &w32_darkmode,
> +	 sizeof(w32_darkmode));
> +    }

Does it make sense to call DwmSetWindowAttribute if we couldn't call SetWindowTheme?  I know that such a situation shouldn't normally happen, but what if it does?  If we need both calls, the second call should be conditioned by SetWindowTheme_fn as well.

Last, but not least: this feature should be called out in NEWS and preferably also described in the "MS-Windows" Appendix in the Emacs manual.

Thanks again for working on this.





^ permalink raw reply	[flat|nested] 22+ messages in thread

* bug#51404: Support system dark mode on Windows 10
  2021-10-26 16:49   ` Vince Salvino
@ 2021-10-26 17:05     ` Eli Zaretskii
  2021-10-26 18:20       ` Vince Salvino
  0 siblings, 1 reply; 22+ messages in thread
From: Eli Zaretskii @ 2021-10-26 17:05 UTC (permalink / raw)
  To: Vince Salvino; +Cc: 51404

> From: Vince Salvino <salvino@coderedcorp.com>
> CC: "51404@debbugs.gnu.org" <51404@debbugs.gnu.org>
> Date: Tue, 26 Oct 2021 16:49:34 +0000
> 
> > > +#define DARK_MODE_APP_NAME L"DarkMode_Explorer"
> 
> > Can we make this exposed to Lisp, rather than hard-coded?  Hard-coding a specific application for a theme sounds un-Emacsy.  People could want to experiment with other apps.
> 
> Given that this is not so much a preference, as an undocumented magic string in Win32, I think anyone who wants to play with this is going to require knowledge of C and gdb to experiment, to risk causing erratic and unknown behavior. So I would be inclined to keep it in C.

These "undocumented" strings are all over the Internet, so...

Here are some examples that people may wish trying:

  https://stackoverflow.com/questions/19712368/c-winapi-old-styled-window
  https://developercommunity.visualstudio.com/t/tree-controls-not-displayed-correctly-in-windows-1/423037

And this is just from a couple of minutes of searching the Internet.

> > +/* Applies the Windows system theme (light or dark) to a window 
> > +handle. */ static void w32_applytheme(HWND hwnd) {
> > +  if (w32_darkmode) {
> > +    /* Set window theme to that of a built-in Windows app (Explorer)
> > +       because it has dark scroll bars and other UI elements. */
> 
> > Likewise here: it should be able to control this behavior by a user option.  We cannot assume that every Emacs user will automatically want to follow the system theme.
> 
> I agree this would be a "nice to have", but the current functionality is in-line with behavior on other systems (GTK, macOS, etc. i.e. the application has no say in window decorations which are controlled by the window manager). If we did add an elisp setting it should default to the registry value at runtime. I also have no idea how to create an elisp setting and read it in C. Examples or contributions to this patch would be helpful.

The GTK behavior is a bad example, so I'd rather not follow it.
Doesn't the patch in its current form unconditionally change the
appearance of Emacs in some cases?  I think it does, and that means we
will have complaints about unexpected change in behavior.  You can
also bet on someone disliking the result.  So I think this has to be
customizable; let me know if you need help in doing that.





^ permalink raw reply	[flat|nested] 22+ messages in thread

* bug#51404: Support system dark mode on Windows 10
  2021-10-26 17:05     ` Eli Zaretskii
@ 2021-10-26 18:20       ` Vince Salvino
  2021-10-27 21:41         ` Vince Salvino
  0 siblings, 1 reply; 22+ messages in thread
From: Vince Salvino @ 2021-10-26 18:20 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: 51404@debbugs.gnu.org

[-- Attachment #1: Type: text/plain, Size: 3312 bytes --]

Attached is the patch with some of your comments resolved.

Regarding exposing DARK_MODE_APP_NAME to lisp, I am staunchly against that. If users want to potentially segfault their emacs, or make the frame invisible/unusable, they are more than welcome to play with the C code.

Regarding toggling dark mode from within lisp, I think that is a decent idea, and left a TODO in the relevant place in the code. Help would be appreciated here. The current functionality is not "unconditional" per se, it follows the user-configurable OS setting (which is light by default, so no visual change from previous versions of Emacs). The manual has been updated with a relevant note.


Vince Salvino

-----Original Message-----
From: Eli Zaretskii <eliz@gnu.org> 
Sent: Tuesday, October 26, 2021 1:06 PM
To: Vince Salvino <salvino@coderedcorp.com>
Cc: 51404@debbugs.gnu.org
Subject: Re: bug#51404: Support system dark mode on Windows 10

> From: Vince Salvino <salvino@coderedcorp.com>
> CC: "51404@debbugs.gnu.org" <51404@debbugs.gnu.org>
> Date: Tue, 26 Oct 2021 16:49:34 +0000
> 
> > > +#define DARK_MODE_APP_NAME L"DarkMode_Explorer"
> 
> > Can we make this exposed to Lisp, rather than hard-coded?  Hard-coding a specific application for a theme sounds un-Emacsy.  People could want to experiment with other apps.
> 
> Given that this is not so much a preference, as an undocumented magic string in Win32, I think anyone who wants to play with this is going to require knowledge of C and gdb to experiment, to risk causing erratic and unknown behavior. So I would be inclined to keep it in C.

These "undocumented" strings are all over the Internet, so...

Here are some examples that people may wish trying:

  https://stackoverflow.com/questions/19712368/c-winapi-old-styled-window
  https://developercommunity.visualstudio.com/t/tree-controls-not-displayed-correctly-in-windows-1/423037

And this is just from a couple of minutes of searching the Internet.

> > +/* Applies the Windows system theme (light or dark) to a window 
> > +handle. */ static void w32_applytheme(HWND hwnd) {
> > +  if (w32_darkmode) {
> > +    /* Set window theme to that of a built-in Windows app (Explorer)
> > +       because it has dark scroll bars and other UI elements. */
> 
> > Likewise here: it should be able to control this behavior by a user option.  We cannot assume that every Emacs user will automatically want to follow the system theme.
> 
> I agree this would be a "nice to have", but the current functionality is in-line with behavior on other systems (GTK, macOS, etc. i.e. the application has no say in window decorations which are controlled by the window manager). If we did add an elisp setting it should default to the registry value at runtime. I also have no idea how to create an elisp setting and read it in C. Examples or contributions to this patch would be helpful.

The GTK behavior is a bad example, so I'd rather not follow it.
Doesn't the patch in its current form unconditionally change the appearance of Emacs in some cases?  I think it does, and that means we will have complaints about unexpected change in behavior.  You can also bet on someone disliking the result.  So I think this has to be customizable; let me know if you need help in doing that.

[-- Attachment #2: 0001-Support-system-dark-mode-on-Windows-10-version-2004-.patch --]
[-- Type: application/octet-stream, Size: 10781 bytes --]

From 2cc7ebe9ed7dab0e2443a6830cd6a06d57831d18 Mon Sep 17 00:00:00 2001
From: Vince Salvino <salvino@coderedcorp.com>
Date: Mon, 25 Oct 2021 22:18:46 -0400
Subject: [PATCH] Support system dark mode on Windows 10 version 2004 and
 higher.

---
 doc/emacs/msdos.texi |  7 ++++
 etc/NEWS             |  8 +++++
 src/w32.c            | 23 +++++++-----
 src/w32.h            |  5 +--
 src/w32fns.c         | 85 ++++++++++++++++++++++++++++++++++++++++++--
 5 files changed, 116 insertions(+), 12 deletions(-)

diff --git a/doc/emacs/msdos.texi b/doc/emacs/msdos.texi
index 0f8f429b3f..19adc5256c 100644
--- a/doc/emacs/msdos.texi
+++ b/doc/emacs/msdos.texi
@@ -1181,6 +1181,13 @@ Windows Misc
 click-to-focus policy.
 @end ifnottex
 
+  On Windows 10 (version 2004 and higher) and Windows 11, Emacs title
+bars and scroll bars will follow the system Light or Dark mode,
+similar to other programs such as Explorer and Command Prompt. To
+change the color mode: Windows Settings > Personalization > Colors >
+Choose your color (or Choose your default app mode); then restart
+Emacs.
+
 @ifnottex
 @include msdos-xtra.texi
 @end ifnottex
diff --git a/etc/NEWS b/etc/NEWS
index 6d3256959e..8e8efc5982 100644
--- a/etc/NEWS
+++ b/etc/NEWS
@@ -73,6 +73,14 @@ Image specifiers can now use ':type webp'.
 *** 'display-buffer' now can set up the body size of the chosen window.
 For example, an alist entry as '(window-width . (body-columns . 40))'
 will make the body of the chosen window 40 columns wide.
+
+** MS-Windows
+
++++
+*** Supports OS dark theme on Windows 10 (version 2004 and higher).
+Graphical frames now use the appropriate light or dark title bar and
+scroll bars, based on the user's Windows color settings.
+
 \f
 * Editing Changes in Emacs 29.1
 
diff --git a/src/w32.c b/src/w32.c
index 9fe698d28d..369e7ee4e1 100644
--- a/src/w32.c
+++ b/src/w32.c
@@ -2820,8 +2820,15 @@ sys_putenv (char *str)
 
 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
 
+/* Query a value from the Windows Registry (under HKCU and HKLM),
+   where `key` is the registry key, `name` is the name, and `lpdwtype`
+   is a pointer to the return value's type. `lpwdtype` can be NULL if
+   you do not care about the type.
+
+   Returns: pointer to the value, or null pointer if the key/name does
+   not exist. */
 LPBYTE
-w32_get_resource (const char *key, LPDWORD lpdwtype)
+w32_get_resource (const char *key, const char *name, LPDWORD lpdwtype)
 {
   LPBYTE lpvalue;
   HKEY hrootkey = NULL;
@@ -2830,13 +2837,13 @@ w32_get_resource (const char *key, LPDWORD lpdwtype)
   /* Check both the current user and the local machine to see if
      we have any resources.  */
 
-  if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
+  if (RegOpenKeyEx (HKEY_CURRENT_USER, key, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
     {
       lpvalue = NULL;
 
-      if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
+      if (RegQueryValueEx (hrootkey, name, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
 	  && (lpvalue = xmalloc (cbData)) != NULL
-	  && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
+	  && RegQueryValueEx (hrootkey, name, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
 	{
           RegCloseKey (hrootkey);
 	  return (lpvalue);
@@ -2847,13 +2854,13 @@ w32_get_resource (const char *key, LPDWORD lpdwtype)
       RegCloseKey (hrootkey);
     }
 
-  if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
+  if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
     {
       lpvalue = NULL;
 
-      if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
+      if (RegQueryValueEx (hrootkey, name, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
 	  && (lpvalue = xmalloc (cbData)) != NULL
-	  && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
+	  && RegQueryValueEx (hrootkey, name, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
 	{
           RegCloseKey (hrootkey);
 	  return (lpvalue);
@@ -3077,7 +3084,7 @@ #define SET_ENV_BUF_SIZE (4 * MAX_PATH)	/* to cover EMACSLOADPATH */
 	    int dont_free = 0;
 	    char bufc[SET_ENV_BUF_SIZE];
 
-	    if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
+	    if ((lpval = w32_get_resource (REG_ROOT, env_vars[i].name, &dwType)) == NULL
 		/* Also ignore empty environment variables.  */
 		|| *lpval == 0)
 	      {
diff --git a/src/w32.h b/src/w32.h
index ffa145b148..ec0f37123e 100644
--- a/src/w32.h
+++ b/src/w32.h
@@ -161,8 +161,9 @@ #define FILE_SERIAL             0x0800
 extern void reset_standard_handles (int in, int out,
 				    int err, HANDLE handles[4]);
 
-/* Return the string resource associated with KEY of type TYPE.  */
-extern LPBYTE w32_get_resource (const char * key, LPDWORD type);
+/* Query Windows Registry and return the resource associated
+   associated with KEY and NAME of type TYPE.  */
+extern LPBYTE w32_get_resource (const char * key, const char * name, LPDWORD type);
 
 extern void release_listen_threads (void);
 extern void init_ntproc (int);
diff --git a/src/w32fns.c b/src/w32fns.c
index 14d1154a2b..dbd8a01fdc 100644
--- a/src/w32fns.c
+++ b/src/w32fns.c
@@ -73,6 +73,15 @@ #define _WIN32_WINNT 0x0600
 #include <imm.h>
 #include <windowsx.h>
 
+/*
+  Internal/undocumented constants for Windows Dark mode.
+  See: https://github.com/microsoft/WindowsAppSDK/issues/41
+*/
+#define DARK_MODE_APP_NAME L"DarkMode_Explorer"
+#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE
+#define DWMWA_USE_IMMERSIVE_DARK_MODE 20
+#endif
+
 #ifndef FOF_NO_CONNECTED_ELEMENTS
 #define FOF_NO_CONNECTED_ELEMENTS 0x2000
 #endif
@@ -185,6 +194,11 @@ DECLARE_HANDLE(HMONITOR);
 typedef HRESULT (WINAPI *SetThreadDescription_Proc)
   (HANDLE hThread, PCWSTR lpThreadDescription);
 
+typedef HRESULT (WINAPI * SetWindowTheme_Proc)
+  (IN HWND hwnd, IN LPCWSTR pszSubAppName, IN LPCWSTR pszSubIdList);
+typedef HRESULT (WINAPI * DwmSetWindowAttribute_Proc)
+  (HWND hwnd, DWORD dwAttribute, IN LPCVOID pvAttribute, DWORD cbAttribute);
+
 TrackMouseEvent_Proc track_mouse_event_fn = NULL;
 ImmGetCompositionString_Proc get_composition_string_fn = NULL;
 ImmGetContext_Proc get_ime_context_fn = NULL;
@@ -199,6 +213,8 @@ DECLARE_HANDLE(HMONITOR);
 GetTitleBarInfo_Proc get_title_bar_info_fn = NULL;
 IsDebuggerPresent_Proc is_debugger_present = NULL;
 SetThreadDescription_Proc set_thread_description = NULL;
+SetWindowTheme_Proc SetWindowTheme_fn = NULL;
+DwmSetWindowAttribute_Proc DwmSetWindowAttribute_fn = NULL;
 
 extern AppendMenuW_Proc unicode_append_menu;
 
@@ -252,6 +268,9 @@ #define MENU_FREE_DELAY 1000
 int w32_minor_version;
 int w32_build_number;
 
+/* If the OS is set to use dark mode. */
+BOOL w32_darkmode = FALSE;
+
 /* Distinguish between Windows NT and Windows 95.  */
 int os_subtype;
 
@@ -2279,10 +2298,34 @@ w32_init_class (HINSTANCE hinst)
     }
 }
 
+/* Applies the Windows system theme (light or dark) to a window handle. */
+static void
+w32_applytheme (HWND hwnd)
+{
+  if (w32_darkmode)
+    {
+      /* Set window theme to that of a built-in Windows app (Explorer)
+	 because it has dark scroll bars and other UI elements. */
+      if (SetWindowTheme_fn)
+	{
+	  SetWindowTheme_fn (hwnd, DARK_MODE_APP_NAME, NULL);
+	}
+      /* Set the titlebar to system dark mode. */
+      if (DwmSetWindowAttribute_fn)
+	{
+	  DwmSetWindowAttribute_fn
+	    (hwnd,
+	     DWMWA_USE_IMMERSIVE_DARK_MODE,
+	     &w32_darkmode,
+	     sizeof(w32_darkmode));
+	}
+    }
+}
+
 static HWND
 w32_createvscrollbar (struct frame *f, struct scroll_bar * bar)
 {
-  return CreateWindow ("SCROLLBAR", "",
+  HWND hwnd = CreateWindow ("SCROLLBAR", "",
 		       /* Clip siblings so we don't draw over child
 			  frames.  Apparently this is not always
 			  sufficient so we also try to make bar windows
@@ -2291,12 +2334,15 @@ w32_createvscrollbar (struct frame *f, struct scroll_bar * bar)
 		       /* Position and size of scroll bar.  */
 		       bar->left, bar->top, bar->width, bar->height,
 		       FRAME_W32_WINDOW (f), NULL, hinst, NULL);
+  if (hwnd)
+    w32_applytheme (hwnd);
+  return hwnd;
 }
 
 static HWND
 w32_createhscrollbar (struct frame *f, struct scroll_bar * bar)
 {
-  return CreateWindow ("SCROLLBAR", "",
+  HWND hwnd = CreateWindow ("SCROLLBAR", "",
 		       /* Clip siblings so we don't draw over child
 			  frames.  Apparently this is not always
 			  sufficient so we also try to make bar windows
@@ -2305,6 +2351,9 @@ w32_createhscrollbar (struct frame *f, struct scroll_bar * bar)
 		       /* Position and size of scroll bar.  */
 		       bar->left, bar->top, bar->width, bar->height,
 		       FRAME_W32_WINDOW (f), NULL, hinst, NULL);
+  if (hwnd)
+    w32_applytheme (hwnd);
+  return hwnd;
 }
 
 static void
@@ -2390,6 +2439,9 @@ w32_createwindow (struct frame *f, int *coords)
       /* Enable drag-n-drop.  */
       DragAcceptFiles (hwnd, TRUE);
 
+      /* Enable system light/dark theme. */
+      w32_applytheme (hwnd);
+
       /* Do this to discard the default setting specified by our parent. */
       ShowWindow (hwnd, SW_HIDE);
 
@@ -11028,6 +11080,35 @@ globals_of_w32fns (void)
   set_thread_description = (SetThreadDescription_Proc)
     get_proc_addr (hm_kernel32, "SetThreadDescription");
 
+  /* Support OS dark mode on Windows 10 version 2004 and higher.
+     For future wretches who may need to understand Windows build numbers:
+     https://docs.microsoft.com/en-us/windows/release-health/release-information
+  */
+  if (w32_major_version >= 10 && w32_build_number >= 19041
+      && os_subtype == OS_SUBTYPE_NT)
+    {
+      /* Load dwmapi and uxtheme, which will be needed to set window themes. */
+      HMODULE dwmapi_lib = LoadLibrary("dwmapi.dll");
+      DwmSetWindowAttribute_fn = (DwmSetWindowAttribute_Proc)
+	get_proc_addr (dwmapi_lib, "DwmSetWindowAttribute");
+      HMODULE uxtheme_lib = LoadLibrary("uxtheme.dll");
+      SetWindowTheme_fn = (SetWindowTheme_Proc)
+	get_proc_addr (uxtheme_lib, "SetWindowTheme");
+
+      /* Check Windows Registry for system theme. DWORD set to 0 or 1.
+	 TODO: "Nice to have" would be to create a lisp setting (which
+	 defaults to this Windows Registry value), then read that lisp
+	 value here instead. This would allow the user to forcibly
+	 override the system theme (which is also user-configurable in
+	 Windows settings; see MS-Windows section in Emacs manual). */
+      LPBYTE val = w32_get_resource
+	("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
+	 "AppsUseLightTheme",
+	 NULL);
+      if (val && (DWORD)*val == 0)
+	w32_darkmode = TRUE;
+    }
+
   except_code = 0;
   except_addr = 0;
 #ifndef CYGWIN
-- 
2.33.0.windows.2


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* bug#51404: Support system dark mode on Windows 10
  2021-10-26 18:20       ` Vince Salvino
@ 2021-10-27 21:41         ` Vince Salvino
  2021-10-28  7:15           ` Eli Zaretskii
  0 siblings, 1 reply; 22+ messages in thread
From: Vince Salvino @ 2021-10-27 21:41 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: 51404@debbugs.gnu.org

[-- Attachment #1: Type: text/plain, Size: 505 bytes --]

Update: I managed to get my hands on an 1809 system and was able to get dark mode working there as well. As far as I can tell 1809 is the absolute minimum as that is when this setting and dark mode Explorer were introduced into Windows.

The advantage is that this will now work on Windows Server 2019 and Windows LTSC 2019, which some folks may be limited to as those are the latest Server and LTSC releases.

Attached patch includes the complete change, with relevant notes etc.

Vince Salvino


[-- Attachment #2: 0001-Support-system-dark-mode-on-Windows-10-version-1809-.patch --]
[-- Type: application/octet-stream, Size: 11202 bytes --]

From 856600cd86ce6305023c7dbb8a41649c80d305e0 Mon Sep 17 00:00:00 2001
From: Vince Salvino <salvino@coderedcorp.com>
Date: Wed, 27 Oct 2021 17:32:09 -0400
Subject: [PATCH] Support system dark mode on Windows 10 version 1809 and
 higher.

---
 doc/emacs/msdos.texi |  7 ++++
 etc/NEWS             |  8 ++++
 src/w32.c            | 23 +++++++----
 src/w32.h            |  5 ++-
 src/w32fns.c         | 91 +++++++++++++++++++++++++++++++++++++++++++-
 5 files changed, 122 insertions(+), 12 deletions(-)

diff --git a/doc/emacs/msdos.texi b/doc/emacs/msdos.texi
index 0f8f429b3f..3c6c61613e 100644
--- a/doc/emacs/msdos.texi
+++ b/doc/emacs/msdos.texi
@@ -1181,6 +1181,13 @@ Windows Misc
 click-to-focus policy.
 @end ifnottex
 
+  On Windows 10 (version 1809 and higher) and Windows 11, Emacs title
+bars and scroll bars will follow the system Light or Dark mode,
+similar to other programs such as Explorer and Command Prompt. To
+change the color mode: Windows Settings > Personalization > Colors >
+Choose your color (or Choose your default app mode); then restart
+Emacs.
+
 @ifnottex
 @include msdos-xtra.texi
 @end ifnottex
diff --git a/etc/NEWS b/etc/NEWS
index e475a49b98..82d8048c23 100644
--- a/etc/NEWS
+++ b/etc/NEWS
@@ -73,6 +73,14 @@ Image specifiers can now use ':type webp'.
 *** 'display-buffer' now can set up the body size of the chosen window.
 For example, an alist entry as '(window-width . (body-columns . 40))'
 will make the body of the chosen window 40 columns wide.
+
+** MS-Windows
+
++++
+*** Supports dark mode on Windows 10 (version 1809 and higher) and Windows 11.
+Graphical frames now use the appropriate light or dark title bar and
+scroll bars, based on the user's Windows color settings.
+
 \f
 * Editing Changes in Emacs 29.1
 
diff --git a/src/w32.c b/src/w32.c
index 9fe698d28d..369e7ee4e1 100644
--- a/src/w32.c
+++ b/src/w32.c
@@ -2820,8 +2820,15 @@ sys_putenv (char *str)
 
 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
 
+/* Query a value from the Windows Registry (under HKCU and HKLM),
+   where `key` is the registry key, `name` is the name, and `lpdwtype`
+   is a pointer to the return value's type. `lpwdtype` can be NULL if
+   you do not care about the type.
+
+   Returns: pointer to the value, or null pointer if the key/name does
+   not exist. */
 LPBYTE
-w32_get_resource (const char *key, LPDWORD lpdwtype)
+w32_get_resource (const char *key, const char *name, LPDWORD lpdwtype)
 {
   LPBYTE lpvalue;
   HKEY hrootkey = NULL;
@@ -2830,13 +2837,13 @@ w32_get_resource (const char *key, LPDWORD lpdwtype)
   /* Check both the current user and the local machine to see if
      we have any resources.  */
 
-  if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
+  if (RegOpenKeyEx (HKEY_CURRENT_USER, key, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
     {
       lpvalue = NULL;
 
-      if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
+      if (RegQueryValueEx (hrootkey, name, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
 	  && (lpvalue = xmalloc (cbData)) != NULL
-	  && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
+	  && RegQueryValueEx (hrootkey, name, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
 	{
           RegCloseKey (hrootkey);
 	  return (lpvalue);
@@ -2847,13 +2854,13 @@ w32_get_resource (const char *key, LPDWORD lpdwtype)
       RegCloseKey (hrootkey);
     }
 
-  if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
+  if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
     {
       lpvalue = NULL;
 
-      if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
+      if (RegQueryValueEx (hrootkey, name, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
 	  && (lpvalue = xmalloc (cbData)) != NULL
-	  && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
+	  && RegQueryValueEx (hrootkey, name, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
 	{
           RegCloseKey (hrootkey);
 	  return (lpvalue);
@@ -3077,7 +3084,7 @@ #define SET_ENV_BUF_SIZE (4 * MAX_PATH)	/* to cover EMACSLOADPATH */
 	    int dont_free = 0;
 	    char bufc[SET_ENV_BUF_SIZE];
 
-	    if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
+	    if ((lpval = w32_get_resource (REG_ROOT, env_vars[i].name, &dwType)) == NULL
 		/* Also ignore empty environment variables.  */
 		|| *lpval == 0)
 	      {
diff --git a/src/w32.h b/src/w32.h
index ffa145b148..ec0f37123e 100644
--- a/src/w32.h
+++ b/src/w32.h
@@ -161,8 +161,9 @@ #define FILE_SERIAL             0x0800
 extern void reset_standard_handles (int in, int out,
 				    int err, HANDLE handles[4]);
 
-/* Return the string resource associated with KEY of type TYPE.  */
-extern LPBYTE w32_get_resource (const char * key, LPDWORD type);
+/* Query Windows Registry and return the resource associated
+   associated with KEY and NAME of type TYPE.  */
+extern LPBYTE w32_get_resource (const char * key, const char * name, LPDWORD type);
 
 extern void release_listen_threads (void);
 extern void init_ntproc (int);
diff --git a/src/w32fns.c b/src/w32fns.c
index 14d1154a2b..bcf0f50c6a 100644
--- a/src/w32fns.c
+++ b/src/w32fns.c
@@ -73,6 +73,18 @@ #define _WIN32_WINNT 0x0600
 #include <imm.h>
 #include <windowsx.h>
 
+/*
+  Internal/undocumented constants for Windows Dark mode.
+  See: https://github.com/microsoft/WindowsAppSDK/issues/41
+*/
+#define DARK_MODE_APP_NAME L"DarkMode_Explorer"
+/* For Windows 10 version 1809, 1903, 1909. */
+#define DWMWA_USE_IMMERSIVE_DARK_MODE_OLD 19
+/* For Windows 10 version 2004 and higher, and Windows 11. */
+#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE
+#define DWMWA_USE_IMMERSIVE_DARK_MODE 20
+#endif
+
 #ifndef FOF_NO_CONNECTED_ELEMENTS
 #define FOF_NO_CONNECTED_ELEMENTS 0x2000
 #endif
@@ -185,6 +197,11 @@ DECLARE_HANDLE(HMONITOR);
 typedef HRESULT (WINAPI *SetThreadDescription_Proc)
   (HANDLE hThread, PCWSTR lpThreadDescription);
 
+typedef HRESULT (WINAPI * SetWindowTheme_Proc)
+  (IN HWND hwnd, IN LPCWSTR pszSubAppName, IN LPCWSTR pszSubIdList);
+typedef HRESULT (WINAPI * DwmSetWindowAttribute_Proc)
+  (HWND hwnd, DWORD dwAttribute, IN LPCVOID pvAttribute, DWORD cbAttribute);
+
 TrackMouseEvent_Proc track_mouse_event_fn = NULL;
 ImmGetCompositionString_Proc get_composition_string_fn = NULL;
 ImmGetContext_Proc get_ime_context_fn = NULL;
@@ -199,6 +216,8 @@ DECLARE_HANDLE(HMONITOR);
 GetTitleBarInfo_Proc get_title_bar_info_fn = NULL;
 IsDebuggerPresent_Proc is_debugger_present = NULL;
 SetThreadDescription_Proc set_thread_description = NULL;
+SetWindowTheme_Proc SetWindowTheme_fn = NULL;
+DwmSetWindowAttribute_Proc DwmSetWindowAttribute_fn = NULL;
 
 extern AppendMenuW_Proc unicode_append_menu;
 
@@ -252,6 +271,9 @@ #define MENU_FREE_DELAY 1000
 int w32_minor_version;
 int w32_build_number;
 
+/* If the OS is set to use dark mode. */
+BOOL w32_darkmode = FALSE;
+
 /* Distinguish between Windows NT and Windows 95.  */
 int os_subtype;
 
@@ -2279,10 +2301,36 @@ w32_init_class (HINSTANCE hinst)
     }
 }
 
+/* Applies the Windows system theme (light or dark) to a window handle. */
+static void
+w32_applytheme (HWND hwnd)
+{
+  if (w32_darkmode)
+    {
+      /* Set window theme to that of a built-in Windows app (Explorer)
+	 because it has dark scroll bars and other UI elements. */
+      if (SetWindowTheme_fn)
+	{
+	  SetWindowTheme_fn (hwnd, DARK_MODE_APP_NAME, NULL);
+	}
+      /* Set the titlebar to system dark mode. */
+      if (DwmSetWindowAttribute_fn)
+	{
+	  /* Windows 10 version 2004 and up, Windows 11. */
+	  DWORD attr = DWMWA_USE_IMMERSIVE_DARK_MODE;
+	  /* Windows 10 older than 2004. */
+	  if (w32_build_number < 19041)
+	    attr = DWMWA_USE_IMMERSIVE_DARK_MODE_OLD;
+	  DwmSetWindowAttribute_fn
+	    (hwnd, attr, &w32_darkmode, sizeof(w32_darkmode));
+	}
+    }
+}
+
 static HWND
 w32_createvscrollbar (struct frame *f, struct scroll_bar * bar)
 {
-  return CreateWindow ("SCROLLBAR", "",
+  HWND hwnd = CreateWindow ("SCROLLBAR", "",
 		       /* Clip siblings so we don't draw over child
 			  frames.  Apparently this is not always
 			  sufficient so we also try to make bar windows
@@ -2291,12 +2339,15 @@ w32_createvscrollbar (struct frame *f, struct scroll_bar * bar)
 		       /* Position and size of scroll bar.  */
 		       bar->left, bar->top, bar->width, bar->height,
 		       FRAME_W32_WINDOW (f), NULL, hinst, NULL);
+  if (hwnd)
+    w32_applytheme (hwnd);
+  return hwnd;
 }
 
 static HWND
 w32_createhscrollbar (struct frame *f, struct scroll_bar * bar)
 {
-  return CreateWindow ("SCROLLBAR", "",
+  HWND hwnd = CreateWindow ("SCROLLBAR", "",
 		       /* Clip siblings so we don't draw over child
 			  frames.  Apparently this is not always
 			  sufficient so we also try to make bar windows
@@ -2305,6 +2356,9 @@ w32_createhscrollbar (struct frame *f, struct scroll_bar * bar)
 		       /* Position and size of scroll bar.  */
 		       bar->left, bar->top, bar->width, bar->height,
 		       FRAME_W32_WINDOW (f), NULL, hinst, NULL);
+  if (hwnd)
+    w32_applytheme (hwnd);
+  return hwnd;
 }
 
 static void
@@ -2390,6 +2444,9 @@ w32_createwindow (struct frame *f, int *coords)
       /* Enable drag-n-drop.  */
       DragAcceptFiles (hwnd, TRUE);
 
+      /* Enable system light/dark theme. */
+      w32_applytheme (hwnd);
+
       /* Do this to discard the default setting specified by our parent. */
       ShowWindow (hwnd, SW_HIDE);
 
@@ -11028,6 +11085,36 @@ globals_of_w32fns (void)
   set_thread_description = (SetThreadDescription_Proc)
     get_proc_addr (hm_kernel32, "SetThreadDescription");
 
+  /* Support OS dark mode on Windows 10 version 1809 and higher.
+     See `w32_applytheme` which uses appropriate APIs per version of Windows.
+     For future wretches who may need to understand Windows build numbers:
+     https://docs.microsoft.com/en-us/windows/release-health/release-information
+  */
+  if (w32_major_version >= 10 && w32_build_number >= 17763
+      && os_subtype == OS_SUBTYPE_NT)
+    {
+      /* Load dwmapi and uxtheme, which will be needed to set window themes. */
+      HMODULE dwmapi_lib = LoadLibrary("dwmapi.dll");
+      DwmSetWindowAttribute_fn = (DwmSetWindowAttribute_Proc)
+	get_proc_addr (dwmapi_lib, "DwmSetWindowAttribute");
+      HMODULE uxtheme_lib = LoadLibrary("uxtheme.dll");
+      SetWindowTheme_fn = (SetWindowTheme_Proc)
+	get_proc_addr (uxtheme_lib, "SetWindowTheme");
+
+      /* Check Windows Registry for system theme. DWORD set to 0 or 1.
+	 TODO: "Nice to have" would be to create a lisp setting (which
+	 defaults to this Windows Registry value), then read that lisp
+	 value here instead. This would allow the user to forcibly
+	 override the system theme (which is also user-configurable in
+	 Windows settings; see MS-Windows section in Emacs manual). */
+      LPBYTE val = w32_get_resource
+	("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
+	 "AppsUseLightTheme",
+	 NULL);
+      if (val && (DWORD)*val == 0)
+	w32_darkmode = TRUE;
+    }
+
   except_code = 0;
   except_addr = 0;
 #ifndef CYGWIN
-- 
2.33.0.windows.2


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* bug#51404: Support system dark mode on Windows 10
  2021-10-27 21:41         ` Vince Salvino
@ 2021-10-28  7:15           ` Eli Zaretskii
  2021-10-30 10:34             ` Eli Zaretskii
  0 siblings, 1 reply; 22+ messages in thread
From: Eli Zaretskii @ 2021-10-28  7:15 UTC (permalink / raw)
  To: Vince Salvino; +Cc: 51404

> From: Vince Salvino <salvino@coderedcorp.com>
> CC: "51404@debbugs.gnu.org" <51404@debbugs.gnu.org>
> Date: Wed, 27 Oct 2021 21:41:05 +0000
> 
> Update: I managed to get my hands on an 1809 system and was able to get dark mode working there as well. As far as I can tell 1809 is the absolute minimum as that is when this setting and dark mode Explorer were introduced into Windows.
> 
> The advantage is that this will now work on Windows Server 2019 and Windows LTSC 2019, which some folks may be limited to as those are the latest Server and LTSC releases.
> 
> Attached patch includes the complete change, with relevant notes etc.

Thanks.  Your legal paperwork also came through, so I will be
installing this soon.





^ permalink raw reply	[flat|nested] 22+ messages in thread

* bug#51404: Support system dark mode on Windows 10
  2021-10-28  7:15           ` Eli Zaretskii
@ 2021-10-30 10:34             ` Eli Zaretskii
  2021-10-30 17:13               ` Vince Salvino
  0 siblings, 1 reply; 22+ messages in thread
From: Eli Zaretskii @ 2021-10-30 10:34 UTC (permalink / raw)
  To: salvino; +Cc: 51404

> Date: Thu, 28 Oct 2021 10:15:40 +0300
> From: Eli Zaretskii <eliz@gnu.org>
> Cc: 51404@debbugs.gnu.org
> 
> > From: Vince Salvino <salvino@coderedcorp.com>
> > CC: "51404@debbugs.gnu.org" <51404@debbugs.gnu.org>
> > Date: Wed, 27 Oct 2021 21:41:05 +0000
> > 
> > Update: I managed to get my hands on an 1809 system and was able to get dark mode working there as well. As far as I can tell 1809 is the absolute minimum as that is when this setting and dark mode Explorer were introduced into Windows.
> > 
> > The advantage is that this will now work on Windows Server 2019 and Windows LTSC 2019, which some folks may be limited to as those are the latest Server and LTSC releases.
> > 
> > Attached patch includes the complete change, with relevant notes etc.
> 
> Thanks.  Your legal paperwork also came through, so I will be
> installing this soon.

Now done, with a few minor adaptations to our style conventions.

Please in the future accompany your changes with ChangeLog-style
commit log messages, as described in CONTRIBUTE.  (I added those for
you in this case.)

Can we now please implement the Emacs-specific user setting that will
allow users to opt in or out of this feature?  Here's what I suggest:

  . define a variable exposed to Lisp using DEFVAR_BOOL; let's call it
    w32-follow-system-theme
  . move the determination of w32_darkmode from globals_of_w32fns to
    w32_term_init, and make it depend on the value of
    w32-follow-system-theme: only set w32_darkmode if the variable is
    non-zero
  . document that users can customize w32-follow-system-theme in their
    early-init file (which is processed before window-system
    initialization that calls x-open-connection)

WDYT?

(Let me know if you need help in making any of the above happen.)

Thanks.





^ permalink raw reply	[flat|nested] 22+ messages in thread

* bug#51404: Support system dark mode on Windows 10
  2021-10-30 10:34             ` Eli Zaretskii
@ 2021-10-30 17:13               ` Vince Salvino
  2021-10-30 17:39                 ` Eli Zaretskii
  0 siblings, 1 reply; 22+ messages in thread
From: Vince Salvino @ 2021-10-30 17:13 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: 51404@debbugs.gnu.org

 > define a variable exposed to Lisp using DEFVAR_BOOL; let's call it w32-follow-system-theme

My thought would be to give the user a bit more control. Rather than saying to follow system theme or not, perhaps they could choose from 3 values: follow theme, light, or dark, e.g.:

w32-system-theme:
* nil: follow system theme (default)
* light: force light mode (the old behavior)
* dark: force dark mode

Second, could you provide an existing value from early-init that I could follow as an example? (I never knew early init was a thing, so I am going to research this - it will probably make my personal init customization a lot better too!)

Vince Salvino

^ permalink raw reply	[flat|nested] 22+ messages in thread

* bug#51404: Support system dark mode on Windows 10
  2021-10-30 17:13               ` Vince Salvino
@ 2021-10-30 17:39                 ` Eli Zaretskii
  2021-11-11  5:36                   ` bug#47291: " Lars Ingebrigtsen
  0 siblings, 1 reply; 22+ messages in thread
From: Eli Zaretskii @ 2021-10-30 17:39 UTC (permalink / raw)
  To: Vince Salvino; +Cc: 51404

> From: Vince Salvino <salvino@coderedcorp.com>
> CC: "51404@debbugs.gnu.org" <51404@debbugs.gnu.org>
> Date: Sat, 30 Oct 2021 17:13:13 +0000
> 
>  > define a variable exposed to Lisp using DEFVAR_BOOL; let's call it w32-follow-system-theme
> 
> My thought would be to give the user a bit more control. Rather than saying to follow system theme or not, perhaps they could choose from 3 values: follow theme, light, or dark, e.g.:
> 
> w32-system-theme:
> * nil: follow system theme (default)
> * light: force light mode (the old behavior)
> * dark: force dark mode

I'm not sure I understand why 'light' necessarily means the old
behavior: we didn't set any theme before this change, we just used the
Windows default.  So maybe there should be 4 values:

  nil: never follow the system theme (use Windows default)
  t: always follow the system theme
  light: force light theme (currently the same as nil)
  dark: force dark theme.

> Second, could you provide an existing value from early-init that I
> could follow as an example?

early-init is a file, called literally "early-init.el".  If you have
such a file in your ~/.emacs.d/ directory, Emacs will load it early on
during the startup.

> (I never knew early init was a thing, so I am going to research this - it will probably make my personal init customization a lot better too!)

The recommendation is to move to early-init.el only stuff that cannot
work in the normal init file.  That's because early-init is processed
when some of the infrastructure is not yet set up, so things could
fail there that will work correctly in the init file.





^ permalink raw reply	[flat|nested] 22+ messages in thread

* bug#47291: bug#51404: Support system dark mode on Windows 10
  2021-10-30 17:39                 ` Eli Zaretskii
@ 2021-11-11  5:36                   ` Lars Ingebrigtsen
  2021-11-11  7:51                     ` Eli Zaretskii
  0 siblings, 1 reply; 22+ messages in thread
From: Lars Ingebrigtsen @ 2021-11-11  5:36 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: Vince Salvino, 51404, 47291

Eli Zaretskii <eliz@gnu.org> writes:

> I'm not sure I understand why 'light' necessarily means the old
> behavior: we didn't set any theme before this change, we just used the
> Windows default.  So maybe there should be 4 values:
>
>   nil: never follow the system theme (use Windows default)
>   t: always follow the system theme
>   light: force light theme (currently the same as nil)
>   dark: force dark theme.

For a similar bug report, see bug#47291.  And we really should support
this on GNU/Linux, too, so having three different methods to support
this seems sub-optimal.

dynamic-setting.el seems like the most likely place to centralise all
this, I think?  I've had a look at what happens when you change the
theme in Gnome, and dynamic-setting-handle-config-changed-event gets
called with an

 (config-changed-event theme-name ":1")

event.  (But not what the event name is -- anybody know how to get at
that?)

-- 
(domestic pets only, the antidote for overdose, milk.)
   bloggy blog: http://lars.ingebrigtsen.no





^ permalink raw reply	[flat|nested] 22+ messages in thread

* bug#47291: bug#51404: Support system dark mode on Windows 10
  2021-11-11  5:36                   ` bug#47291: " Lars Ingebrigtsen
@ 2021-11-11  7:51                     ` Eli Zaretskii
  2021-11-11 12:15                       ` Lars Ingebrigtsen
  0 siblings, 1 reply; 22+ messages in thread
From: Eli Zaretskii @ 2021-11-11  7:51 UTC (permalink / raw)
  To: Lars Ingebrigtsen; +Cc: salvino, 51404, 47291

> From: Lars Ingebrigtsen <larsi@gnus.org>
> Cc: Vince Salvino <salvino@coderedcorp.com>,  51404@debbugs.gnu.org,
>  47291@debbugs.gnu.org
> Date: Thu, 11 Nov 2021 06:36:09 +0100
> 
> Eli Zaretskii <eliz@gnu.org> writes:
> 
> > I'm not sure I understand why 'light' necessarily means the old
> > behavior: we didn't set any theme before this change, we just used the
> > Windows default.  So maybe there should be 4 values:
> >
> >   nil: never follow the system theme (use Windows default)
> >   t: always follow the system theme
> >   light: force light theme (currently the same as nil)
> >   dark: force dark theme.
> 
> For a similar bug report, see bug#47291.  And we really should support
> this on GNU/Linux, too, so having three different methods to support
> this seems sub-optimal.

I'm not sure unification is possible here, because the functionality
is quite different, AFAICT.  At least for the functionality in this
bug report, we cannot apply the system theme to an existing frame, we
can only apply it at frame creation time.  So having a handler for
such changes will be able to affect only the frames created after the
change.  Or at least that is my understanding; the code definitely
applies the dark/light theme as part of creating a frame.

Also, having a dynamic thing that tracks changes in these settings
would on Windows mean listening and processing a special window-system
message, which seems to be WM_THEMECHANGED or maybe WM_SETTINGCHANGE.
But that's not what the code installed in this bug report does.

So the functionality seems similar, but the details differ.






^ permalink raw reply	[flat|nested] 22+ messages in thread

* bug#47291: bug#51404: Support system dark mode on Windows 10
  2021-11-11  7:51                     ` Eli Zaretskii
@ 2021-11-11 12:15                       ` Lars Ingebrigtsen
  2021-11-11 15:08                         ` Eli Zaretskii
  0 siblings, 1 reply; 22+ messages in thread
From: Lars Ingebrigtsen @ 2021-11-11 12:15 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: salvino, 51404, 47291

Eli Zaretskii <eliz@gnu.org> writes:

> I'm not sure unification is possible here, because the functionality
> is quite different, AFAICT.  At least for the functionality in this
> bug report, we cannot apply the system theme to an existing frame, we
> can only apply it at frame creation time.  So having a handler for
> such changes will be able to affect only the frames created after the
> change.  Or at least that is my understanding; the code definitely
> applies the dark/light theme as part of creating a frame.

Gtk Emacs doesn't respond to dark mode either -- so we have the
opportunity to decide how to handle these things across the board.
Perhaps in Gtk Emacs, dynamic-setting-handle-config-changed-event should
also just set something that will make the next frame creation use
different colours?

> Also, having a dynamic thing that tracks changes in these settings
> would on Windows mean listening and processing a special window-system
> message, which seems to be WM_THEMECHANGED or maybe WM_SETTINGCHANGE.
> But that's not what the code installed in this bug report does.
>
> So the functionality seems similar, but the details differ.

But perhaps Windows should be listening to those events, too?

-- 
(domestic pets only, the antidote for overdose, milk.)
   bloggy blog: http://lars.ingebrigtsen.no





^ permalink raw reply	[flat|nested] 22+ messages in thread

* bug#47291: bug#51404: Support system dark mode on Windows 10
  2021-11-11 12:15                       ` Lars Ingebrigtsen
@ 2021-11-11 15:08                         ` Eli Zaretskii
  2021-11-12  3:00                           ` Lars Ingebrigtsen
  0 siblings, 1 reply; 22+ messages in thread
From: Eli Zaretskii @ 2021-11-11 15:08 UTC (permalink / raw)
  To: Lars Ingebrigtsen; +Cc: salvino, 51404, 47291

> From: Lars Ingebrigtsen <larsi@gnus.org>
> Cc: salvino@coderedcorp.com,  51404@debbugs.gnu.org,  47291@debbugs.gnu.org
> Date: Thu, 11 Nov 2021 13:15:03 +0100
> 
> Eli Zaretskii <eliz@gnu.org> writes:
> 
> > I'm not sure unification is possible here, because the functionality
> > is quite different, AFAICT.  At least for the functionality in this
> > bug report, we cannot apply the system theme to an existing frame, we
> > can only apply it at frame creation time.  So having a handler for
> > such changes will be able to affect only the frames created after the
> > change.  Or at least that is my understanding; the code definitely
> > applies the dark/light theme as part of creating a frame.
> 
> Gtk Emacs doesn't respond to dark mode either -- so we have the
> opportunity to decide how to handle these things across the board.
> Perhaps in Gtk Emacs, dynamic-setting-handle-config-changed-event should
> also just set something that will make the next frame creation use
> different colours?

If that's what people want, sure.  I'd expect them to want Emacs to go
to dark background on all frames.

> > Also, having a dynamic thing that tracks changes in these settings
> > would on Windows mean listening and processing a special window-system
> > message, which seems to be WM_THEMECHANGED or maybe WM_SETTINGCHANGE.
> > But that's not what the code installed in this bug report does.
> >
> > So the functionality seems similar, but the details differ.
> 
> But perhaps Windows should be listening to those events, too?

Maybe.  But some expert (which is not me) will have to explain what to
do when we receive these messages, or submit patches for that.





^ permalink raw reply	[flat|nested] 22+ messages in thread

* bug#47291: bug#51404: Support system dark mode on Windows 10
  2021-11-11 15:08                         ` Eli Zaretskii
@ 2021-11-12  3:00                           ` Lars Ingebrigtsen
  2021-11-12  6:19                             ` Eli Zaretskii
  0 siblings, 1 reply; 22+ messages in thread
From: Lars Ingebrigtsen @ 2021-11-12  3:00 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: salvino, 51404, 47291

Eli Zaretskii <eliz@gnu.org> writes:

> If that's what people want, sure.  I'd expect them to want Emacs to go
> to dark background on all frames.

Possibly -- there should probably be a user option, I guess.

> Maybe.  But some expert (which is not me) will have to explain what to
> do when we receive these messages, or submit patches for that.

On the Linux side, we convert the messages to input events and then
react to that event from special-event-map, which seems like a
reasonable structure.

-- 
(domestic pets only, the antidote for overdose, milk.)
   bloggy blog: http://lars.ingebrigtsen.no





^ permalink raw reply	[flat|nested] 22+ messages in thread

* bug#51404: Support system dark mode on Windows 10
  2021-11-12  3:00                           ` Lars Ingebrigtsen
@ 2021-11-12  6:19                             ` Eli Zaretskii
  0 siblings, 0 replies; 22+ messages in thread
From: Eli Zaretskii @ 2021-11-12  6:19 UTC (permalink / raw)
  To: Lars Ingebrigtsen; +Cc: salvino, 51404, 47291

> From: Lars Ingebrigtsen <larsi@gnus.org>
> Cc: salvino@coderedcorp.com,  51404@debbugs.gnu.org,  47291@debbugs.gnu.org
> Date: Fri, 12 Nov 2021 04:00:18 +0100
> 
> > Maybe.  But some expert (which is not me) will have to explain what to
> > do when we receive these messages, or submit patches for that.
> 
> On the Linux side, we convert the messages to input events and then
> react to that event from special-event-map, which seems like a
> reasonable structure.

I mean how to tell what the message wants us to do, i.e. which parts
of the UI to change and in what way.





^ permalink raw reply	[flat|nested] 22+ messages in thread

* bug#51404: Support system dark mode on Windows 10
  2021-10-26  4:46 bug#51404: Support system dark mode on Windows 10 Vince Salvino
  2021-10-26 14:01 ` Eli Zaretskii
@ 2022-01-14  6:00 ` Vince Salvino
  2022-01-23  0:00 ` Vince Salvino
  2 siblings, 0 replies; 22+ messages in thread
From: Vince Salvino @ 2022-01-14  6:00 UTC (permalink / raw)
  To: 51404@debbugs.gnu.org

So, playing around with the idea of dynamically toggling dark/light modes on-the-fly, rather than only at program initialization as this patch currently does. I got a proof of concept working, however there is one ugly caveat. In order to change the theme, we must keep track of every window handle in existence (frame, scroll bar, other UI element) in a global.

The code for this is relatively simple, we can watch for WM_SETTINGCHANGE (in w32_wnd_proc) and then call w32_applytheme (which also needs a few modifications) to all of the HWND objects. But it seems like it would get quite messy and bloated to be storing references to all of these in globals. We would probably need some kind of array of references, and then loop through them upon receiving the signal.

The pseudo-code is something like:

	// Add every hwnd in existence to this array.
	global_hwnds = []

	w32_wnd_proc() {
		...
		case WM_SETTINGCHANGE:
			for each hwnd in global_hwnds {
				w32_applytheme(hwnd);
			}
		...
	}

Thoughts? Is it worth it?

Vince Salvino






^ permalink raw reply	[flat|nested] 22+ messages in thread

* bug#51404: Support system dark mode on Windows 10
  2021-10-26  4:46 bug#51404: Support system dark mode on Windows 10 Vince Salvino
  2021-10-26 14:01 ` Eli Zaretskii
  2022-01-14  6:00 ` Vince Salvino
@ 2022-01-23  0:00 ` Vince Salvino
  2022-01-29  3:34   ` bug#51404: " Vince Salvino
  2 siblings, 1 reply; 22+ messages in thread
From: Vince Salvino @ 2022-01-23  0:00 UTC (permalink / raw)
  To: 51404@debbugs.gnu.org

[-- Attachment #1: Type: text/plain, Size: 473 bytes --]

Attached is a patch which listens to the OS settings change, to dynamically change light/dark GUI during runtime.

Disclaimer here, I am not actually a C nor Win32 developer. I am not currently happy with the g_hwnds[256] implementation - that is purely a sloppy hack as a proof of concept. There is probably a much better way to track the window handles (all outlined in the TODO comment). However, this works if anyone wants to play around with it.

Vince Salvino


[-- Attachment #2: 0002-Support-MS-Windows-light-dark-mode-theme-change-duri.patch --]
[-- Type: application/octet-stream, Size: 7271 bytes --]

From 89ef390ca06397c21be0deea42dcc5eb0f8acfad Mon Sep 17 00:00:00 2001
From: Vince Salvino <salvino@coderedcorp.com>
Date: Sat, 22 Jan 2022 18:39:41 -0500
Subject: [PATCH] Support MS-Windows light/dark mode theme change during
 runtime. (Bug#51404)

---
 src/w32fns.c | 116 +++++++++++++++++++++++++++++++++++++++++----------
 1 file changed, 94 insertions(+), 22 deletions(-)

diff --git a/src/w32fns.c b/src/w32fns.c
index 37f9b813c6..429986051c 100644
--- a/src/w32fns.c
+++ b/src/w32fns.c
@@ -78,6 +78,7 @@ #define _WIN32_WINNT 0x0600
   See: https://github.com/microsoft/WindowsAppSDK/issues/41
 */
 #define DARK_MODE_APP_NAME L"DarkMode_Explorer"
+#define LIGHT_MODE_APP_NAME L"Explorer"
 /* For Windows 10 version 1809, 1903, 1909. */
 #ifndef DWMWA_USE_IMMERSIVE_DARK_MODE_OLD
 #define DWMWA_USE_IMMERSIVE_DARK_MODE_OLD 19
@@ -273,9 +274,25 @@ #define MENU_FREE_DELAY 1000
 int w32_minor_version;
 int w32_build_number;
 
-/* If the OS is set to use dark mode.  */
+/* If the OS supports light/dark mode. */
+BOOL w32_supports_darkmode = FALSE;
+/* If Emacs should use the OS's dark mode.  */
 BOOL w32_darkmode = FALSE;
 
+/* Track ALL window handles so they can be updated if the Windows
+   light/dark mode theme is changed. Each frame could have somehwere
+   between 1-6 HWNDs depending on which GUI features are enabled by
+   the user.
+
+   TODO: Convert this to something more dynamic:
+   * Remove upper limit (256) of HWNDs.
+   * When a HWND is destroyed it should be removed from this list
+     (just for sake of memory management cleanliness; it does not
+     actually cause a problem to make w32 calls to dead HWNDs).
+*/
+HWND g_hwnds[256];
+int g_hwnds_idx = -1;
+
 /* Distinguish between Windows NT and Windows 95.  */
 int os_subtype;
 
@@ -2303,19 +2320,50 @@ w32_init_class (HINSTANCE hinst)
     }
 }
 
+
+/* Gets the preferred Windows app mode:
+   * FALSE = Light mode (this is equivalent to the user specifying
+             Light, or the absence of any setting)
+   * TRUE = Dark mode (added in Windows 10 1809). */
+static BOOL
+w32_querydarkmode (void)
+{
+  if (w32_supports_darkmode)
+    {
+      /* Check Windows Registry for system theme.
+	 TODO: "Nice to have" would be to create a lisp setting (which
+	 defaults to this Windows Registry value), then read that lisp
+	 value here instead. This would allow the user to forcibly
+	 override the system theme (which is also user-configurable in
+	 Windows settings; see MS-Windows section in Emacs manual). */
+      LPBYTE val =
+	w32_get_resource ("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
+			  "AppsUseLightTheme",
+			  NULL);
+      return val && *val == 0;
+    }
+  return FALSE;
+}
+
 /* Applies the Windows system theme (light or dark) to the window
-   handle HWND.  */
+   handle HWND. `track` should generally be TRUE to keep a reference
+   to this HWND for future use. */
 static void
-w32_applytheme (HWND hwnd)
+w32_applytheme (HWND hwnd, bool track)
 {
-  if (w32_darkmode)
+  if (w32_supports_darkmode)
     {
       /* Set window theme to that of a built-in Windows app (Explorer),
 	 because it has dark scroll bars and other UI elements.  */
       if (SetWindowTheme_fn)
-	SetWindowTheme_fn (hwnd, DARK_MODE_APP_NAME, NULL);
+	{
+	  if (w32_darkmode)
+	    SetWindowTheme_fn (hwnd, DARK_MODE_APP_NAME, NULL);
+	  else
+	    SetWindowTheme_fn (hwnd, LIGHT_MODE_APP_NAME, NULL);
+	}
 
-      /* Set the titlebar to system dark mode.  */
+      /* Toggle darkmode titlebar on or off.  */
       if (DwmSetWindowAttribute_fn)
 	{
 	  /* Windows 10 version 2004 and up, Windows 11.  */
@@ -2323,9 +2371,26 @@ w32_applytheme (HWND hwnd)
 	  /* Windows 10 older than 2004.  */
 	  if (w32_build_number < 19041)
 	    attr = DWMWA_USE_IMMERSIVE_DARK_MODE_OLD;
+	  /* Toggle dark mode flag based on value of `w32_darkmode` */
 	  DwmSetWindowAttribute_fn (hwnd, attr,
 				    &w32_darkmode, sizeof (w32_darkmode));
 	}
+
+      /* After applying the theme, add the HWND to our global list so
+	 it can be changed later if the OS light/dark mode theme is
+	 changed. */
+      if(track)
+	{
+	  if(g_hwnds_idx < 256)
+	    {
+	      g_hwnds_idx++;
+	      g_hwnds[g_hwnds_idx] = hwnd;
+	    }
+	  else
+	    {
+	      printf("Number of window handles has exceeded capacity!");
+	    }
+	}
     }
 }
 
@@ -2342,7 +2407,7 @@ w32_createvscrollbar (struct frame *f, struct scroll_bar * bar)
 		       bar->left, bar->top, bar->width, bar->height,
 		       FRAME_W32_WINDOW (f), NULL, hinst, NULL);
   if (hwnd)
-    w32_applytheme (hwnd);
+    w32_applytheme (hwnd, TRUE);
   return hwnd;
 }
 
@@ -2359,7 +2424,7 @@ w32_createhscrollbar (struct frame *f, struct scroll_bar * bar)
 		       bar->left, bar->top, bar->width, bar->height,
 		       FRAME_W32_WINDOW (f), NULL, hinst, NULL);
   if (hwnd)
-    w32_applytheme (hwnd);
+    w32_applytheme (hwnd, TRUE);
   return hwnd;
 }
 
@@ -2447,7 +2512,7 @@ w32_createwindow (struct frame *f, int *coords)
       DragAcceptFiles (hwnd, TRUE);
 
       /* Enable system light/dark theme.  */
-      w32_applytheme (hwnd);
+      w32_applytheme (hwnd, TRUE);
 
       /* Do this to discard the default setting specified by our parent. */
       ShowWindow (hwnd, SW_HIDE);
@@ -5178,6 +5243,23 @@ w32_wnd_proc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
 	 changed, so if Emacs is interested in some of them, it could
 	 update its internal values.  */
       my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
+
+      /* Check if settings changed Light/Dark mode.
+	 Re-lookup the setting and update the HWNDs accordingly. */
+      if(w32_supports_darkmode)
+	{
+	  BOOL new_darkmode = w32_querydarkmode();
+	  if (w32_darkmode != new_darkmode)
+	    {
+	      w32_darkmode = new_darkmode;
+	      /* Loop through all known HWNDs and apply theme */
+	      for(int i=0; i<=g_hwnds_idx; i++)
+		{
+		  w32_applytheme(g_hwnds[i], false);
+		}
+	    }
+	}
+
       goto dflt;
 
     case WM_SETFOCUS:
@@ -11157,6 +11239,7 @@ globals_of_w32fns (void)
   if (os_subtype == OS_SUBTYPE_NT
       && w32_major_version >= 10 && w32_build_number >= 17763)
     {
+      w32_supports_darkmode = TRUE;
       /* Load dwmapi.dll and uxtheme.dll, which will be needed to set
 	 window themes.  */
       HMODULE dwmapi_lib = LoadLibrary("dwmapi.dll");
@@ -11165,19 +11248,8 @@ globals_of_w32fns (void)
       HMODULE uxtheme_lib = LoadLibrary("uxtheme.dll");
       SetWindowTheme_fn = (SetWindowTheme_Proc)
 	get_proc_addr (uxtheme_lib, "SetWindowTheme");
-
-      /* Check Windows Registry for system theme and set w32_darkmode.
-	 TODO: "Nice to have" would be to create a lisp setting (which
-	 defaults to this Windows Registry value), then read that lisp
-	 value here instead. This would allow the user to forcibly
-	 override the system theme (which is also user-configurable in
-	 Windows settings; see MS-Windows section in Emacs manual). */
-      LPBYTE val =
-	w32_get_resource ("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
-			  "AppsUseLightTheme",
-			  NULL);
-      if (val && *val == 0)
-	w32_darkmode = TRUE;
+      /* Set the preferred mode from OS settings. */
+      w32_darkmode = w32_querydarkmode();
     }
 
   except_code = 0;
-- 
2.34.1.windows.1


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* bug#51404: RE: Support system dark mode on Windows 10
  2022-01-23  0:00 ` Vince Salvino
@ 2022-01-29  3:34   ` Vince Salvino
  2022-01-29  8:40     ` bug#51404: " Eli Zaretskii
  0 siblings, 1 reply; 22+ messages in thread
From: Vince Salvino @ 2022-01-29  3:34 UTC (permalink / raw)
  To: 51404@debbugs.gnu.org

[-- Attachment #1: Type: text/plain, Size: 248 bytes --]

Update: I improved the previous patch to use a linked list to track the window handles during runtime, and am reasonably happy with it. If this looks good please go ahead and install the attached patch 0002 to master. Thanks!


Vince Salvino


[-- Attachment #2: 0002-Support-MS-Windows-light-dark-mode-theme-change-duri.patch --]
[-- Type: application/octet-stream, Size: 6956 bytes --]

From a8c2f353372d8f015538804e17682e72e40af222 Mon Sep 17 00:00:00 2001
From: Vince Salvino <salvino@coderedcorp.com>
Date: Fri, 28 Jan 2022 22:25:13 -0500
Subject: [PATCH] Support MS-Windows light/dark mode theme change during
 runtime. (Bug#51404)

---
 src/w32fns.c | 108 ++++++++++++++++++++++++++++++++++++++++-----------
 1 file changed, 86 insertions(+), 22 deletions(-)

diff --git a/src/w32fns.c b/src/w32fns.c
index 37f9b813c6..e1b4f4b519 100644
--- a/src/w32fns.c
+++ b/src/w32fns.c
@@ -78,6 +78,7 @@ #define _WIN32_WINNT 0x0600
   See: https://github.com/microsoft/WindowsAppSDK/issues/41
 */
 #define DARK_MODE_APP_NAME L"DarkMode_Explorer"
+#define LIGHT_MODE_APP_NAME L"Explorer"
 /* For Windows 10 version 1809, 1903, 1909. */
 #ifndef DWMWA_USE_IMMERSIVE_DARK_MODE_OLD
 #define DWMWA_USE_IMMERSIVE_DARK_MODE_OLD 19
@@ -273,9 +274,20 @@ #define MENU_FREE_DELAY 1000
 int w32_minor_version;
 int w32_build_number;
 
-/* If the OS is set to use dark mode.  */
+/* If the OS supports light/dark mode. */
+BOOL w32_supports_darkmode = FALSE;
+/* If Emacs should use the OS's dark mode.  */
 BOOL w32_darkmode = FALSE;
 
+/* Simple linked list to track window handles during runtime so they
+   can be updated if the Windows light/dark mode theme is changed. */
+struct HWND_NODE
+{
+  HWND hwnd;
+  struct HWND_NODE *next;
+};
+struct HWND_NODE *g_hwnd_root;
+
 /* Distinguish between Windows NT and Windows 95.  */
 int os_subtype;
 
@@ -2303,19 +2315,50 @@ w32_init_class (HINSTANCE hinst)
     }
 }
 
+
+/* Gets the preferred Windows app mode:
+   * FALSE = Light mode (this is equivalent to the user specifying
+             Light, or the absence of any setting)
+   * TRUE = Dark mode (added in Windows 10 1809). */
+static BOOL
+w32_querydarkmode (void)
+{
+  if (w32_supports_darkmode)
+    {
+      /* Check Windows Registry for system theme.
+	 TODO: "Nice to have" would be to create a lisp setting (which
+	 defaults to this Windows Registry value), then read that lisp
+	 value here instead. This would allow the user to forcibly
+	 override the system theme (which is also user-configurable in
+	 Windows settings; see MS-Windows section in Emacs manual). */
+      LPBYTE val =
+	w32_get_resource ("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
+			  "AppsUseLightTheme",
+			  NULL);
+      return val && *val == 0;
+    }
+  return FALSE;
+}
+
 /* Applies the Windows system theme (light or dark) to the window
-   handle HWND.  */
+   handle HWND. `track` should generally be TRUE to keep a reference
+   to this HWND for future use. */
 static void
-w32_applytheme (HWND hwnd)
+w32_applytheme (HWND hwnd, bool track)
 {
-  if (w32_darkmode)
+  if (w32_supports_darkmode)
     {
       /* Set window theme to that of a built-in Windows app (Explorer),
 	 because it has dark scroll bars and other UI elements.  */
       if (SetWindowTheme_fn)
-	SetWindowTheme_fn (hwnd, DARK_MODE_APP_NAME, NULL);
+	{
+	  if (w32_darkmode)
+	    SetWindowTheme_fn (hwnd, DARK_MODE_APP_NAME, NULL);
+	  else
+	    SetWindowTheme_fn (hwnd, LIGHT_MODE_APP_NAME, NULL);
+	}
 
-      /* Set the titlebar to system dark mode.  */
+      /* Toggle darkmode titlebar on or off.  */
       if (DwmSetWindowAttribute_fn)
 	{
 	  /* Windows 10 version 2004 and up, Windows 11.  */
@@ -2323,9 +2366,21 @@ w32_applytheme (HWND hwnd)
 	  /* Windows 10 older than 2004.  */
 	  if (w32_build_number < 19041)
 	    attr = DWMWA_USE_IMMERSIVE_DARK_MODE_OLD;
+	  /* Toggle dark mode flag based on value of `w32_darkmode` */
 	  DwmSetWindowAttribute_fn (hwnd, attr,
 				    &w32_darkmode, sizeof (w32_darkmode));
 	}
+
+      /* After applying the theme, add the HWND to our global list so
+	 it can be changed later if the OS light/dark mode theme is
+	 changed. */
+      if(track)
+	{
+	  struct HWND_NODE *curr = malloc(sizeof(struct HWND_NODE));
+	  curr->hwnd = hwnd;
+	  curr->next = g_hwnd_root;
+	  g_hwnd_root = curr;
+	}
     }
 }
 
@@ -2342,7 +2397,7 @@ w32_createvscrollbar (struct frame *f, struct scroll_bar * bar)
 		       bar->left, bar->top, bar->width, bar->height,
 		       FRAME_W32_WINDOW (f), NULL, hinst, NULL);
   if (hwnd)
-    w32_applytheme (hwnd);
+    w32_applytheme (hwnd, TRUE);
   return hwnd;
 }
 
@@ -2359,7 +2414,7 @@ w32_createhscrollbar (struct frame *f, struct scroll_bar * bar)
 		       bar->left, bar->top, bar->width, bar->height,
 		       FRAME_W32_WINDOW (f), NULL, hinst, NULL);
   if (hwnd)
-    w32_applytheme (hwnd);
+    w32_applytheme (hwnd, TRUE);
   return hwnd;
 }
 
@@ -2447,7 +2502,7 @@ w32_createwindow (struct frame *f, int *coords)
       DragAcceptFiles (hwnd, TRUE);
 
       /* Enable system light/dark theme.  */
-      w32_applytheme (hwnd);
+      w32_applytheme (hwnd, TRUE);
 
       /* Do this to discard the default setting specified by our parent. */
       ShowWindow (hwnd, SW_HIDE);
@@ -5178,6 +5233,25 @@ w32_wnd_proc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
 	 changed, so if Emacs is interested in some of them, it could
 	 update its internal values.  */
       my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
+
+      /* Check if settings changed Light/Dark mode.
+	 Re-lookup the setting and update the HWNDs accordingly. */
+      if(w32_supports_darkmode)
+	{
+	  BOOL new_darkmode = w32_querydarkmode();
+	  if (w32_darkmode != new_darkmode)
+	    {
+	      w32_darkmode = new_darkmode;
+	      /* Loop through all known HWNDs and apply theme */
+	      struct HWND_NODE *curr = g_hwnd_root;
+	      while ( curr != NULL )
+		{
+		  w32_applytheme(curr->hwnd, FALSE);
+		  curr = curr->next;
+		}
+	    }
+	}
+
       goto dflt;
 
     case WM_SETFOCUS:
@@ -11157,6 +11231,7 @@ globals_of_w32fns (void)
   if (os_subtype == OS_SUBTYPE_NT
       && w32_major_version >= 10 && w32_build_number >= 17763)
     {
+      w32_supports_darkmode = TRUE;
       /* Load dwmapi.dll and uxtheme.dll, which will be needed to set
 	 window themes.  */
       HMODULE dwmapi_lib = LoadLibrary("dwmapi.dll");
@@ -11165,19 +11240,8 @@ globals_of_w32fns (void)
       HMODULE uxtheme_lib = LoadLibrary("uxtheme.dll");
       SetWindowTheme_fn = (SetWindowTheme_Proc)
 	get_proc_addr (uxtheme_lib, "SetWindowTheme");
-
-      /* Check Windows Registry for system theme and set w32_darkmode.
-	 TODO: "Nice to have" would be to create a lisp setting (which
-	 defaults to this Windows Registry value), then read that lisp
-	 value here instead. This would allow the user to forcibly
-	 override the system theme (which is also user-configurable in
-	 Windows settings; see MS-Windows section in Emacs manual). */
-      LPBYTE val =
-	w32_get_resource ("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
-			  "AppsUseLightTheme",
-			  NULL);
-      if (val && *val == 0)
-	w32_darkmode = TRUE;
+      /* Set the preferred mode from OS settings. */
+      w32_darkmode = w32_querydarkmode();
     }
 
   except_code = 0;
-- 
2.35.0.windows.1


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* bug#51404: Support system dark mode on Windows 10
  2022-01-29  3:34   ` bug#51404: " Vince Salvino
@ 2022-01-29  8:40     ` Eli Zaretskii
  2022-01-29 20:27       ` Vince Salvino
  0 siblings, 1 reply; 22+ messages in thread
From: Eli Zaretskii @ 2022-01-29  8:40 UTC (permalink / raw)
  To: Vince Salvino; +Cc: 51404

> From: Vince Salvino <salvino@coderedcorp.com>
> CC: Eli Zaretskii <eliz@gnu.org>
> Date: Sat, 29 Jan 2022 03:34:32 +0000
> 
> Update: I improved the previous patch to use a linked list to track the window handles during runtime, and am reasonably happy with it. If this looks good please go ahead and install the attached patch 0002 to master. Thanks!

Thanks.  A few comments below, mostly about minor stylistic issues.

> From a8c2f353372d8f015538804e17682e72e40af222 Mon Sep 17 00:00:00 2001
> From: Vince Salvino <salvino@coderedcorp.com>
> Date: Fri, 28 Jan 2022 22:25:13 -0500
> Subject: [PATCH] Support MS-Windows light/dark mode theme change during
>  runtime. (Bug#51404)

Please provide a ChangeLog-style description of changes (see
CONTRIBUTE for the details of the format we prefer).

> -/* If the OS is set to use dark mode.  */
> +/* If the OS supports light/dark mode. */
                                        ^^
Our style is to leave 2 spaces after the final period of the comment
(here and elsewhere in your patch).

> +/* Simple linked list to track window handles during runtime so they
> +   can be updated if the Windows light/dark mode theme is changed. */
> +struct HWND_NODE
> +{
> +  HWND hwnd;
> +  struct HWND_NODE *next;
> +};
> +struct HWND_NODE *g_hwnd_root;

I see where you add windows to the  list, but I don't see where you
remove deleted windows from the list.  Does that mean the list will
always grow indefinitely through an Emacs session, even if windows are
deleted?

>  /* Applies the Windows system theme (light or dark) to the window
> -   handle HWND.  */
> +   handle HWND. `track` should generally be TRUE to keep a reference
                 ^^
Two spaces between sentences there.  Also, our style of quoting in
comments is 'like this', not MD-style `like this`.

> +      /* After applying the theme, add the HWND to our global list so
> +	 it can be changed later if the OS light/dark mode theme is
> +	 changed. */
> +      if(track)
> +	{
> +	  struct HWND_NODE *curr = malloc(sizeof(struct HWND_NODE));

Please use xmalloc, not malloc, to allocate memory.

Also, our style is to leave one space between a function name and the
opening parenthesis that follows it.

> +	      /* Loop through all known HWNDs and apply theme */
                                                            ^^
Each comment should end with a period (and 2 spaces).

> +	      struct HWND_NODE *curr = g_hwnd_root;
> +	      while ( curr != NULL )
                     ^^^^^^^^^^^^^^
Our style is NOT to leave a space after the opening parenthesis and
before the closing parenthesis.





^ permalink raw reply	[flat|nested] 22+ messages in thread

* bug#51404: Support system dark mode on Windows 10
  2022-01-29  8:40     ` bug#51404: " Eli Zaretskii
@ 2022-01-29 20:27       ` Vince Salvino
  0 siblings, 0 replies; 22+ messages in thread
From: Vince Salvino @ 2022-01-29 20:27 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: 51404@debbugs.gnu.org

[-- Attachment #1: Type: text/plain, Size: 1770 bytes --]

Thanks for the review. Attached is the revised patch, minus one thing specifically:

> I see where you add windows to the list, but I don't see where you remove deleted windows from the list.  Does that mean the list will always grow indefinitely through an Emacs session, even if windows are deleted?

I also had this concern but found it a bit sticky. I can't quite find a way to know if a HWND is destroyed. Windows seems to keep the HWNDs in memory, and even reuses them if a window is destroyed and new one is created. The win32 API seems to be designed around this behavior as calling functions with a HWND that is destroyed or that is not owned by the program will not have any adverse effects.

I experimented with WM_EMACS_DESTROYWINDOW but that seems to only be triggered on the titlebar destroy, not the other "windows" such as scrollbars, menu, etc.

To answer your question, yes the current implementation will grow indefinitely. Practically speaking the memory overhead is quite small though - as a marathon emacs session creating and destroying thousands of frames repeatedly might add up to few kilobytes memory overhead on supported Win 10 systems (each entry is 16 bytes). It's definitely sloppy programming, but I will have to continue to learn more about win32 to figure out the solution, given enough free time in the future.

A few items of note:
* https://stackoverflow.com/questions/2344233/validate-hwnd-using-win32-api
* I'm still digging through the code to figure out if emacs has a parent/child relationship for HWNDs, in which case this might be relevant (especially EnumChildWindows to loop through children and purge them from the list): https://docs.microsoft.com/en-us/windows/win32/winmsg/using-windows


Vince Salvino

[-- Attachment #2: 0002-Support-MS-Windows-light-dark-mode-theme-change-duri.patch --]
[-- Type: application/octet-stream, Size: 7706 bytes --]

From ab9bbf47353fcc7b55bd93eaf5d40a27e5c1eb1d Mon Sep 17 00:00:00 2001
From: Vince Salvino <salvino@coderedcorp.com>
Date: Sat, 29 Jan 2022 15:15:01 -0500
Subject: [PATCH] Support MS-Windows light/dark mode theme change during
 runtime

Track HWNDs and update them during WM_SETTINGCHANGE events (Bug#51404).
* src/w32fns.c (w32_applytheme, w32_querydarkmode, w32_wnd_proc,
  globals_of_w32fns): Track and manipulate HWND structs.
---
 src/w32fns.c | 119 ++++++++++++++++++++++++++++++++++++++++-----------
 1 file changed, 95 insertions(+), 24 deletions(-)

diff --git a/src/w32fns.c b/src/w32fns.c
index 1ea685d194..8f475cebe4 100644
--- a/src/w32fns.c
+++ b/src/w32fns.c
@@ -78,6 +78,7 @@ #define _WIN32_WINNT 0x0600
   See: https://github.com/microsoft/WindowsAppSDK/issues/41
 */
 #define DARK_MODE_APP_NAME L"DarkMode_Explorer"
+#define LIGHT_MODE_APP_NAME L"Explorer"
 /* For Windows 10 version 1809, 1903, 1909. */
 #ifndef DWMWA_USE_IMMERSIVE_DARK_MODE_OLD
 #define DWMWA_USE_IMMERSIVE_DARK_MODE_OLD 19
@@ -273,9 +274,20 @@ #define MENU_FREE_DELAY 1000
 int w32_minor_version;
 int w32_build_number;
 
-/* If the OS is set to use dark mode.  */
+/* If the OS supports light/dark mode.  */
+BOOL w32_supports_darkmode = FALSE;
+/* If Emacs should use the OS's dark mode.  */
 BOOL w32_darkmode = FALSE;
 
+/* Simple linked list to track window handles during runtime so they
+   can be updated if the Windows light/dark mode theme is changed.  */
+struct HWND_NODE
+{
+  HWND hwnd;
+  struct HWND_NODE *next;
+};
+struct HWND_NODE *g_hwnd_root;
+
 /* Distinguish between Windows NT and Windows 95.  */
 int os_subtype;
 
@@ -2303,19 +2315,58 @@ w32_init_class (HINSTANCE hinst)
     }
 }
 
-/* Applies the Windows system theme (light or dark) to the window
-   handle HWND.  */
+
+/**
+ * w32_query_darkmode:
+ *
+ * Gets the preferred Windows app mode:
+ * * FALSE = Light mode (this is equivalent to the user specifying
+ *           Light, or the absence of any setting).
+ * * TRUE = Dark mode (added in Windows 10 1809).
+ */
+static BOOL
+w32_querydarkmode (void)
+{
+  if (w32_supports_darkmode)
+    {
+      /* Check Windows Registry for system theme.
+	 TODO: "Nice to have" would be to create a lisp setting (which
+	 defaults to this Windows Registry value), then read that lisp
+	 value here instead.  This would allow the user to forcibly
+	 override the system theme (which is also user-configurable in
+	 Windows settings; see MS-Windows section in Emacs manual).  */
+      LPBYTE val =
+	w32_get_resource ("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
+			  "AppsUseLightTheme",
+			  NULL);
+      return val && *val == 0;
+    }
+  return FALSE;
+}
+
+/**
+ * w32_applytheme:
+ *
+ * Applies the Windows system theme (light or dark) to the window
+ * handle HWND.  `track' should generally be TRUE to keep a reference
+ * to this HWND for future use.
+ */
 static void
-w32_applytheme (HWND hwnd)
+w32_applytheme (HWND hwnd, BOOL track)
 {
-  if (w32_darkmode)
+  if (w32_supports_darkmode)
     {
       /* Set window theme to that of a built-in Windows app (Explorer),
 	 because it has dark scroll bars and other UI elements.  */
       if (SetWindowTheme_fn)
-	SetWindowTheme_fn (hwnd, DARK_MODE_APP_NAME, NULL);
+	{
+	  if (w32_darkmode)
+	    SetWindowTheme_fn (hwnd, DARK_MODE_APP_NAME, NULL);
+	  else
+	    SetWindowTheme_fn (hwnd, LIGHT_MODE_APP_NAME, NULL);
+	}
 
-      /* Set the titlebar to system dark mode.  */
+      /* Toggle darkmode titlebar on or off.  */
       if (DwmSetWindowAttribute_fn)
 	{
 	  /* Windows 10 version 2004 and up, Windows 11.  */
@@ -2323,9 +2374,20 @@ w32_applytheme (HWND hwnd)
 	  /* Windows 10 older than 2004.  */
 	  if (w32_build_number < 19041)
 	    attr = DWMWA_USE_IMMERSIVE_DARK_MODE_OLD;
+	  /* Toggle dark mode flag based on value of 'w32_darkmode'.  */
 	  DwmSetWindowAttribute_fn (hwnd, attr,
 				    &w32_darkmode, sizeof (w32_darkmode));
 	}
+
+      /* Add the HWND to our global list so it can be updated later if
+	 the OS light/dark mode theme is changed.  */
+      if(track)
+	{
+	  struct HWND_NODE *curr = xmalloc (sizeof (struct HWND_NODE));
+	  curr->hwnd = hwnd;
+	  curr->next = g_hwnd_root;
+	  g_hwnd_root = curr;
+	}
     }
 }
 
@@ -2342,7 +2404,7 @@ w32_createvscrollbar (struct frame *f, struct scroll_bar * bar)
 		       bar->left, bar->top, bar->width, bar->height,
 		       FRAME_W32_WINDOW (f), NULL, hinst, NULL);
   if (hwnd)
-    w32_applytheme (hwnd);
+    w32_applytheme (hwnd, TRUE);
   return hwnd;
 }
 
@@ -2359,7 +2421,7 @@ w32_createhscrollbar (struct frame *f, struct scroll_bar * bar)
 		       bar->left, bar->top, bar->width, bar->height,
 		       FRAME_W32_WINDOW (f), NULL, hinst, NULL);
   if (hwnd)
-    w32_applytheme (hwnd);
+    w32_applytheme (hwnd, TRUE);
   return hwnd;
 }
 
@@ -2447,7 +2509,7 @@ w32_createwindow (struct frame *f, int *coords)
       DragAcceptFiles (hwnd, TRUE);
 
       /* Enable system light/dark theme.  */
-      w32_applytheme (hwnd);
+      w32_applytheme (hwnd, TRUE);
 
       /* Do this to discard the default setting specified by our parent. */
       ShowWindow (hwnd, SW_HIDE);
@@ -5178,6 +5240,25 @@ w32_wnd_proc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
 	 changed, so if Emacs is interested in some of them, it could
 	 update its internal values.  */
       my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
+
+      /* Check if settings changed Light/Dark mode.
+	 Re-lookup the setting and update the HWNDs accordingly.  */
+      if(w32_supports_darkmode)
+	{
+	  BOOL new_darkmode = w32_querydarkmode();
+	  if (w32_darkmode != new_darkmode)
+	    {
+	      w32_darkmode = new_darkmode;
+	      /* Loop through all known HWNDs and apply theme.  */
+	      struct HWND_NODE *curr = g_hwnd_root;
+	      while (curr != NULL)
+		{
+		  w32_applytheme (curr->hwnd, FALSE);
+		  curr = curr->next;
+		}
+	    }
+	}
+
       goto dflt;
 
     case WM_SETFOCUS:
@@ -11150,13 +11231,14 @@ globals_of_w32fns (void)
     get_proc_addr (hm_kernel32, "SetThreadDescription");
 
   /* Support OS dark mode on Windows 10 version 1809 and higher.
-     See `w32_applytheme` which uses appropriate APIs per version of Windows.
+     See `w32_applytheme' which uses appropriate APIs per version of Windows.
      For future wretches who may need to understand Windows build numbers:
      https://docs.microsoft.com/en-us/windows/release-health/release-information
   */
   if (os_subtype == OS_SUBTYPE_NT
       && w32_major_version >= 10 && w32_build_number >= 17763)
     {
+      w32_supports_darkmode = TRUE;
       /* Load dwmapi.dll and uxtheme.dll, which will be needed to set
 	 window themes.  */
       HMODULE dwmapi_lib = LoadLibrary("dwmapi.dll");
@@ -11165,19 +11247,8 @@ globals_of_w32fns (void)
       HMODULE uxtheme_lib = LoadLibrary("uxtheme.dll");
       SetWindowTheme_fn = (SetWindowTheme_Proc)
 	get_proc_addr (uxtheme_lib, "SetWindowTheme");
-
-      /* Check Windows Registry for system theme and set w32_darkmode.
-	 TODO: "Nice to have" would be to create a lisp setting (which
-	 defaults to this Windows Registry value), then read that lisp
-	 value here instead. This would allow the user to forcibly
-	 override the system theme (which is also user-configurable in
-	 Windows settings; see MS-Windows section in Emacs manual). */
-      LPBYTE val =
-	w32_get_resource ("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
-			  "AppsUseLightTheme",
-			  NULL);
-      if (val && *val == 0)
-	w32_darkmode = TRUE;
+      /* Set the preferred mode from OS settings.  */
+      w32_darkmode = w32_querydarkmode();
     }
 
   except_code = 0;
-- 
2.35.0.windows.1


^ permalink raw reply related	[flat|nested] 22+ messages in thread

end of thread, other threads:[~2022-01-29 20:27 UTC | newest]

Thread overview: 22+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2021-10-26  4:46 bug#51404: Support system dark mode on Windows 10 Vince Salvino
2021-10-26 14:01 ` Eli Zaretskii
2021-10-26 16:18   ` Eli Zaretskii
2021-10-26 16:49   ` Vince Salvino
2021-10-26 17:05     ` Eli Zaretskii
2021-10-26 18:20       ` Vince Salvino
2021-10-27 21:41         ` Vince Salvino
2021-10-28  7:15           ` Eli Zaretskii
2021-10-30 10:34             ` Eli Zaretskii
2021-10-30 17:13               ` Vince Salvino
2021-10-30 17:39                 ` Eli Zaretskii
2021-11-11  5:36                   ` bug#47291: " Lars Ingebrigtsen
2021-11-11  7:51                     ` Eli Zaretskii
2021-11-11 12:15                       ` Lars Ingebrigtsen
2021-11-11 15:08                         ` Eli Zaretskii
2021-11-12  3:00                           ` Lars Ingebrigtsen
2021-11-12  6:19                             ` Eli Zaretskii
2022-01-14  6:00 ` Vince Salvino
2022-01-23  0:00 ` Vince Salvino
2022-01-29  3:34   ` bug#51404: " Vince Salvino
2022-01-29  8:40     ` bug#51404: " Eli Zaretskii
2022-01-29 20:27       ` Vince Salvino

Code repositories for project(s) associated with this external index

	https://git.savannah.gnu.org/cgit/emacs.git
	https://git.savannah.gnu.org/cgit/emacs/org-mode.git

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.