unofficial mirror of bug-gnu-emacs@gnu.org 
 help / color / mirror / code / Atom feed
From: Vince Salvino <salvino@coderedcorp.com>
To: Eli Zaretskii <eliz@gnu.org>
Cc: "51404@debbugs.gnu.org" <51404@debbugs.gnu.org>
Subject: bug#51404: Support system dark mode on Windows 10
Date: Tue, 26 Oct 2021 18:20:35 +0000	[thread overview]
Message-ID: <CH2PR12MB4231BF93A366641B94D7A636A5849@CH2PR12MB4231.namprd12.prod.outlook.com> (raw)
In-Reply-To: <838ryfyawv.fsf@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


  reply	other threads:[~2021-10-26 18:20 UTC|newest]

Thread overview: 22+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
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 [this message]
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

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

  List information: https://www.gnu.org/software/emacs/

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=CH2PR12MB4231BF93A366641B94D7A636A5849@CH2PR12MB4231.namprd12.prod.outlook.com \
    --to=salvino@coderedcorp.com \
    --cc=51404@debbugs.gnu.org \
    --cc=eliz@gnu.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
Code repositories for project(s) associated with this public inbox

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

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).