From 2f6784b43da06329dbec3b7f0442161a0d748ffb Mon Sep 17 00:00:00 2001 From: stu Date: Sat, 20 May 2017 10:58:07 +0000 Subject: Set demo dir at config time. --- unix/Makefile.in | 2 +- unix/configure | 14 ++++++++++++++ unix/configure.ac | 10 ++++++++++ unix/tkConfig.sh.in | 3 +++ 4 files changed, 28 insertions(+), 1 deletion(-) diff --git a/unix/Makefile.in b/unix/Makefile.in index 1b8677e..99f2284 100644 --- a/unix/Makefile.in +++ b/unix/Makefile.in @@ -95,7 +95,7 @@ HTML_INSTALL_DIR = $(INSTALL_ROOT)$(HTML_DIR) CONFIG_INSTALL_DIR = $(INSTALL_ROOT)$(libdir) # Directory in which to install the demo files: -DEMO_INSTALL_DIR = $(INSTALL_ROOT)$(TK_LIBRARY)/demos +DEMO_INSTALL_DIR = $(INSTALL_ROOT)@DEMO_DIR@ # The directory containing the Tcl sources and headers appropriate # for this version of Tk ("srcdir" will be replaced or has already diff --git a/unix/configure b/unix/configure index a02e8c4..894f7d8 100755 --- a/unix/configure +++ b/unix/configure @@ -661,6 +661,8 @@ TK_PATCH_LEVEL TK_MINOR_VERSION TK_MAJOR_VERSION TK_VERSION +TK_DEMO_DIR +DEMO_DIR UNIX_FONT_OBJS XFT_LIBS XFT_CFLAGS @@ -8794,6 +8796,18 @@ TK_STUB_LIB_PATH="${TK_STUB_LIB_DIR}/${TK_STUB_LIB_FILE}" eval "TK_INCLUDE_SPEC=\"-I${includedir}\"" #------------------------------------------------------------------------ +# Demo dir +#------------------------------------------------------------------------ + +if test x"${DEMO_DIR}" = x; then : + DEMO_DIR='$(TK_LIBRARY)/demos' +fi +eval "TK_DEMO_DIR=\"`echo ${DEMO_DIR} | tr '()' '{}'`\"" +eval "TK_DEMO_DIR=\"`echo ${TK_DEMO_DIR} | tr '()' '{}'`\"" + + + +#------------------------------------------------------------------------ # tkConfig.sh refers to this by a different name #------------------------------------------------------------------------ diff --git a/unix/configure.ac b/unix/configure.ac index a748246..9c9765f 100644 --- a/unix/configure.ac +++ b/unix/configure.ac @@ -789,6 +789,16 @@ TK_STUB_LIB_PATH="${TK_STUB_LIB_DIR}/${TK_STUB_LIB_FILE}" eval "TK_INCLUDE_SPEC=\"-I${includedir}\"" #------------------------------------------------------------------------ +# Demo dir +#------------------------------------------------------------------------ + +AS_IF([test x"${DEMO_DIR}" = x], [DEMO_DIR='$(TK_LIBRARY)/demos']) +eval "TK_DEMO_DIR=\"`echo ${DEMO_DIR} | tr '()' '{}'`\"" +eval "TK_DEMO_DIR=\"`echo ${TK_DEMO_DIR} | tr '()' '{}'`\"" +AC_SUBST(DEMO_DIR) +AC_SUBST(TK_DEMO_DIR) + +#------------------------------------------------------------------------ # tkConfig.sh refers to this by a different name #------------------------------------------------------------------------ diff --git a/unix/tkConfig.sh.in b/unix/tkConfig.sh.in index bb85ad0..e08861b 100644 --- a/unix/tkConfig.sh.in +++ b/unix/tkConfig.sh.in @@ -95,3 +95,6 @@ TK_BUILD_STUB_LIB_PATH='@TK_BUILD_STUB_LIB_PATH@' # Path to the Tk stub library in the install directory. TK_STUB_LIB_PATH='@TK_STUB_LIB_PATH@' + +# Top-level directory in which Tk's demo files are installed. +TK_DEMO_DIR='@TK_DEMO_DIR@' -- cgit v0.12 From 2afd7451e708c09b61ba7820e627a2d6fbecb3fb Mon Sep 17 00:00:00 2001 From: stu Date: Sat, 20 May 2017 11:47:46 +0000 Subject: Bring more TIP #59 to Tk.
Move ::tk::pkgconfig setup code from unix/tkUnixRFont.c to new file generic/tkPkgConfig.c.
Copied Tcl/tests/config.test into new file Tk/tests/pkgconfig.test. I believe the name 'pkgconfig.test' is better.
Adjust build system to accommodate.
Use value 'x11' for when fontsystem 'xft' unavailable.
--- generic/tkInt.h | 2 + generic/tkPkgConfig.c | 150 ++++++++++++++++++++++++++++++++++++++++++++++++++ generic/tkWindow.c | 6 ++ tests/pkgconfig.test | 60 ++++++++++++++++++++ unix/Makefile.in | 32 ++++++++++- unix/configure | 28 ++++++++++ unix/configure.ac | 6 ++ unix/tkConfig.h.in | 3 + unix/tkUnixRFont.c | 13 +---- 9 files changed, 286 insertions(+), 14 deletions(-) create mode 100644 generic/tkPkgConfig.c create mode 100644 tests/pkgconfig.test diff --git a/generic/tkInt.h b/generic/tkInt.h index 474cfb0..204cc66 100644 --- a/generic/tkInt.h +++ b/generic/tkInt.h @@ -1222,6 +1222,8 @@ MODULE_SCOPE int TkInitTkCmd(Tcl_Interp *interp, ClientData clientData); MODULE_SCOPE int TkInitFontchooser(Tcl_Interp *interp, ClientData clientData); +MODULE_SCOPE void TkInitEmbeddedConfigurationInformation( + Tcl_Interp *interp); MODULE_SCOPE void TkpWarpPointer(TkDisplay *dispPtr); MODULE_SCOPE void TkpCancelWarp(TkDisplay *dispPtr); MODULE_SCOPE int TkListCreateFrame(ClientData clientData, diff --git a/generic/tkPkgConfig.c b/generic/tkPkgConfig.c new file mode 100644 index 0000000..d913fb1 --- /dev/null +++ b/generic/tkPkgConfig.c @@ -0,0 +1,150 @@ +/* + * tkPkgConfig.c -- + * + * This file contains the configuration information to embed into the tcl + * binary library. + * + * Copyright (c) 2002 Andreas Kupries + * + * See the file "license.terms" for information on usage and redistribution of + * this file, and for a DISCLAIMER OF ALL WARRANTIES. + */ + +/* Note, the definitions in this module are influenced by the following C + * preprocessor macros: + * + * OSCMa = shortcut for "old style configuration macro activates" + * NSCMdt = shortcut for "new style configuration macro declares that" + * + * - TCL_THREADS OSCMa compilation as threaded core. + * - TCL_MEM_DEBUG OSCMa memory debugging. + * - TCL_COMPILE_DEBUG OSCMa debugging of bytecode compiler. + * - TCL_COMPILE_STATS OSCMa bytecode compiler statistics. + * + * - TCL_CFG_DO64BIT NSCMdt tk is compiled for a 64bit system. + * - NDEBUG NSCMdt tk is compiled with symbol info off. + * - TCL_CFG_OPTIMIZED NSCMdt tk is compiled with cc optimizations on + * - TCL_CFG_PROFILED NSCMdt tk is compiled with profiling info. + * - HAVE_XFT NSCMdt tk is compiled with xft font support. + * + * - CFG_RUNTIME_* Paths to various stuff at runtime. + * - CFG_INSTALL_* Paths to various stuff at installation time. + * + * - TCL_CFGVAL_ENCODING string containing the encoding used for the + * configuration values. + */ + +#include "tkInt.h" + + +#ifndef TCL_CFGVAL_ENCODING +#define TCL_CFGVAL_ENCODING "ascii" +#endif + +/* + * Use C preprocessor statements to define the various values for the embedded + * configuration information. + */ + +#ifdef TCL_THREADS +# define CFG_THREADED "1" +#else +# define CFG_THREADED "0" +#endif + +#ifdef TCL_MEM_DEBUG +# define CFG_MEMDEBUG "1" +#else +# define CFG_MEMDEBUG "0" +#endif + +#ifdef TCL_COMPILE_DEBUG +# define CFG_COMPILE_DEBUG "1" +#else +# define CFG_COMPILE_DEBUG "0" +#endif + +#ifdef TCL_COMPILE_STATS +# define CFG_COMPILE_STATS "1" +#else +# define CFG_COMPILE_STATS "0" +#endif + +#ifdef TCL_CFG_DO64BIT +# define CFG_64 "1" +#else +# define CFG_64 "0" +#endif + +#ifndef NDEBUG +# define CFG_DEBUG "1" +#else +# define CFG_DEBUG "0" +#endif + +#ifdef TCL_CFG_OPTIMIZED +# define CFG_OPTIMIZED "1" +#else +# define CFG_OPTIMIZED "0" +#endif + +#ifdef TCL_CFG_PROFILED +# define CFG_PROFILED "1" +#else +# define CFG_PROFILED "0" +#endif + +#ifdef HAVE_XFT +# define CFG_FONTSYSTEM "xft" +#else +# define CFG_FONTSYSTEM "x11" +#endif + +static Tcl_Config const cfg[] = { + {"debug", CFG_DEBUG}, + {"threaded", CFG_THREADED}, + {"profiled", CFG_PROFILED}, + {"64bit", CFG_64}, + {"optimized", CFG_OPTIMIZED}, + {"mem_debug", CFG_MEMDEBUG}, + {"compile_debug", CFG_COMPILE_DEBUG}, + {"compile_stats", CFG_COMPILE_STATS}, + {"fontsystem", CFG_FONTSYSTEM}, + + /* Runtime paths to various stuff */ + + {"libdir,runtime", CFG_RUNTIME_LIBDIR}, + {"bindir,runtime", CFG_RUNTIME_BINDIR}, + {"scriptdir,runtime", CFG_RUNTIME_SCRDIR}, + {"includedir,runtime", CFG_RUNTIME_INCDIR}, + {"docdir,runtime", CFG_RUNTIME_DOCDIR}, + {"demodir,runtime", CFG_RUNTIME_DEMODIR}, + + /* Installation paths to various stuff */ + + {"libdir,install", CFG_INSTALL_LIBDIR}, + {"bindir,install", CFG_INSTALL_BINDIR}, + {"scriptdir,install", CFG_INSTALL_SCRDIR}, + {"includedir,install", CFG_INSTALL_INCDIR}, + {"docdir,install", CFG_INSTALL_DOCDIR}, + {"demodir,install", CFG_INSTALL_DEMODIR}, + + /* Last entry, closes the array */ + {NULL, NULL} +}; + +void +TkInitEmbeddedConfigurationInformation( + Tcl_Interp *interp) /* Interpreter the configuration command is + * registered in. */ +{ + Tcl_RegisterConfig(interp, "tk", cfg, TCL_CFGVAL_ENCODING); +} + +/* + * Local Variables: + * mode: c + * c-basic-offset: 4 + * fill-column: 78 + * End: + */ diff --git a/generic/tkWindow.c b/generic/tkWindow.c index d9b5dec..4368e7e 100644 --- a/generic/tkWindow.c +++ b/generic/tkWindow.c @@ -3052,6 +3052,12 @@ Initialize( } /* + * TIP #59: Make embedded configuration information available. + */ + + TkInitEmbeddedConfigurationInformation(interp); + + /* * Ensure that our obj-types are registered with the Tcl runtime. */ diff --git a/tests/pkgconfig.test b/tests/pkgconfig.test new file mode 100644 index 0000000..5cb5081 --- /dev/null +++ b/tests/pkgconfig.test @@ -0,0 +1,60 @@ +# -*- tcl -*- +# Commands covered: pkgconfig +# +# This file contains a collection of tests for one or more of the Tk +# built-in commands. Sourcing this file into Tk runs the tests and +# generates output for errors. No output means no errors were found. +# +# Copyright (c) 1991-1993 The Regents of the University of California. +# Copyright (c) 1994-1996 Sun Microsystems, Inc. +# Copyright (c) 1998-1999 by Scriptics Corporation. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. + +package require tcltest 2.2 +namespace import ::tcltest::* +eval tcltest::configure $argv +tcltest::loadTestedCommands + +test pkgconfig-1.1 {query keys} { + lsort [::tk::pkgconfig list] +} {64bit bindir,install bindir,runtime compile_debug compile_stats debug demodir,install demodir,runtime docdir,install docdir,runtime fontsystem includedir,install includedir,runtime libdir,install libdir,runtime mem_debug optimized profiled scriptdir,install scriptdir,runtime threaded} +test pkgconfig-1.2 {query keys multiple times} { + string compare [::tk::pkgconfig list] [::tk::pkgconfig list] +} 0 +test pkgconfig-1.3 {query value multiple times} { + string compare \ + [::tk::pkgconfig get bindir,install] \ + [::tk::pkgconfig get bindir,install] +} 0 + + +test pkgconfig-2.0 {error: missing subcommand} { + catch {::tk::pkgconfig} msg + set msg +} {wrong # args: should be "::tk::pkgconfig subcommand ?arg?"} +test pkgconfig-2.1 {error: illegal subcommand} { + catch {::tk::pkgconfig foo} msg + set msg +} {bad subcommand "foo": must be get or list} +test pkgconfig-2.2 {error: list with arguments} { + catch {::tk::pkgconfig list foo} msg + set msg +} {wrong # args: should be "::tk::pkgconfig list"} +test pkgconfig-2.3 {error: get without arguments} { + catch {::tk::pkgconfig get} msg + set msg +} {wrong # args: should be "::tk::pkgconfig get key"} +test pkgconfig-2.4 {error: query unknown key} { + catch {::tk::pkgconfig get foo} msg + set msg +} {key not known} +test pkgconfig-2.5 {error: query with to many arguments} { + catch {::tk::pkgconfig get foo bar} msg + set msg +} {wrong # args: should be "::tk::pkgconfig subcommand ?arg?"} + +# cleanup +cleanupTests +return diff --git a/unix/Makefile.in b/unix/Makefile.in index 99f2284..e71005e 100644 --- a/unix/Makefile.in +++ b/unix/Makefile.in @@ -369,8 +369,9 @@ GENERIC_OBJS = tk3d.o tkArgv.o tkAtom.o tkBind.o tkBitmap.o tkBusy.o \ tkClipboard.o \ tkCmds.o tkColor.o tkConfig.o tkConsole.o tkCursor.o tkError.o \ tkEvent.o tkFocus.o tkFont.o tkGet.o tkGC.o tkGeometry.o tkGrab.o \ - tkGrid.o tkMain.o tkObj.o tkOldConfig.o tkOption.o tkPack.o tkPlace.o \ - tkSelect.o tkStyle.o tkUndo.o tkUtil.o tkVisual.o tkWindow.o + tkGrid.o tkMain.o tkObj.o tkOldConfig.o tkOption.o tkPack.o \ + tkPkgConfig.o tkPlace.o tkSelect.o tkStyle.o tkUndo.o tkUtil.o \ + tkVisual.o tkWindow.o TTK_OBJS = \ ttkBlink.o ttkButton.o ttkCache.o ttkClamTheme.o ttkClassicTheme.o \ @@ -431,6 +432,7 @@ GENERIC_SRCS = \ $(GENERIC_DIR)/tkGrid.c $(GENERIC_DIR)/tkConsole.c \ $(GENERIC_DIR)/tkMain.c $(GENERIC_DIR)/tkOption.c \ $(GENERIC_DIR)/tkPack.c $(GENERIC_DIR)/tkPlace.c \ + $(GENERIC_DIR)/tkPkgConfig.c \ $(GENERIC_DIR)/tkSelect.c $(GENERIC_DIR)/tkStyle.c \ $(GENERIC_DIR)/tkUndo.c $(GENERIC_DIR)/tkUtil.c \ $(GENERIC_DIR)/tkVisual.c $(GENERIC_DIR)/tkWindow.c \ @@ -1009,6 +1011,32 @@ tkOption.o: $(GENERIC_DIR)/tkOption.c tkPack.o: $(GENERIC_DIR)/tkPack.c $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkPack.c +# TIP #59, embedding of configuration information into the binary library. +# +# Part of Tk's configuration information are the paths where it was installed +# and where it will look for its libraries (which can be different). We derive +# this information from the variables which can be overridden by the user. As +# every path can be configured separately we do not remember one general +# prefix/exec_prefix but all the different paths individually. + +tkPkgConfig.o: $(GENERIC_DIR)/tkPkgConfig.c + $(CC) -c $(CC_SWITCHES) \ + -DCFG_INSTALL_LIBDIR="\"$(LIB_INSTALL_DIR)\"" \ + -DCFG_INSTALL_BINDIR="\"$(BIN_INSTALL_DIR)\"" \ + -DCFG_INSTALL_SCRDIR="\"$(SCRIPT_INSTALL_DIR)\"" \ + -DCFG_INSTALL_INCDIR="\"$(INCLUDE_INSTALL_DIR)\"" \ + -DCFG_INSTALL_DOCDIR="\"$(MAN_INSTALL_DIR)\"" \ + -DCFG_INSTALL_DEMODIR="\"$(DEMO_INSTALL_DIR)\"" \ + \ + -DCFG_RUNTIME_LIBDIR="\"$(libdir)\"" \ + -DCFG_RUNTIME_BINDIR="\"$(bindir)\"" \ + -DCFG_RUNTIME_SCRDIR="\"$(TK_LIBRARY)\"" \ + -DCFG_RUNTIME_INCDIR="\"$(includedir)\"" \ + -DCFG_RUNTIME_DOCDIR="\"$(mandir)\"" \ + -DCFG_RUNTIME_DEMODIR="\"$(DEMO_INSTALL_DIR)\"" \ + \ + $(GENERIC_DIR)/tkPkgConfig.c + tkPlace.o: $(GENERIC_DIR)/tkPlace.c $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkPlace.c diff --git a/unix/configure b/unix/configure index 894f7d8..e8fb0d4 100755 --- a/unix/configure +++ b/unix/configure @@ -766,6 +766,7 @@ with_tcl enable_man_symlinks enable_man_compression enable_man_suffix +with_encoding enable_threads enable_shared enable_64bit @@ -1430,6 +1431,8 @@ Optional Packages: --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) --with-tcl directory containing tcl configuration (tclConfig.sh) + --with-encoding encoding for configuration values (default: + iso8859-1) --with-x use the X Window System Some influential environment variables: @@ -3950,6 +3953,31 @@ $as_echo "$tcl_cv_cc_pipe" >&6; } fi #------------------------------------------------------------------------ +# Embedded configuration information, encoding to use for the values, TIP #59 +#------------------------------------------------------------------------ + + + +# Check whether --with-encoding was given. +if test "${with_encoding+set}" = set; then : + withval=$with_encoding; with_tcencoding=${withval} +fi + + + if test x"${with_tcencoding}" != x ; then + +cat >>confdefs.h <<_ACEOF +#define TCL_CFGVAL_ENCODING "${with_tcencoding}" +_ACEOF + + else + +$as_echo "#define TCL_CFGVAL_ENCODING \"iso8859-1\"" >>confdefs.h + + fi + + +#------------------------------------------------------------------------ # Threads support - this auto-enables if Tcl was compiled threaded #------------------------------------------------------------------------ diff --git a/unix/configure.ac b/unix/configure.ac index 9c9765f..59c7601 100644 --- a/unix/configure.ac +++ b/unix/configure.ac @@ -111,6 +111,12 @@ if test -z "$no_pipe" && test -n "$GCC"; then fi #------------------------------------------------------------------------ +# Embedded configuration information, encoding to use for the values, TIP #59 +#------------------------------------------------------------------------ + +SC_TCL_CFG_ENCODING + +#------------------------------------------------------------------------ # Threads support - this auto-enables if Tcl was compiled threaded #------------------------------------------------------------------------ diff --git a/unix/tkConfig.h.in b/unix/tkConfig.h.in index 4fd7726..99e87f9 100644 --- a/unix/tkConfig.h.in +++ b/unix/tkConfig.h.in @@ -136,6 +136,9 @@ /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS +/* What encoding should be used for embedded configuration info? */ +#undef TCL_CFGVAL_ENCODING + /* Is this a 64-bit build? */ #undef TCL_CFG_DO64BIT diff --git a/unix/tkUnixRFont.c b/unix/tkUnixRFont.c index 9c1116d..379af05 100644 --- a/unix/tkUnixRFont.c +++ b/unix/tkUnixRFont.c @@ -57,24 +57,13 @@ static Tcl_ThreadDataKey dataKey; /* * Package initialization: - * Nothing to do here except register the fact that we're using Xft in - * the TIP 59 configuration database. + * Nothing to do! */ -#ifndef TCL_CFGVAL_ENCODING -#define TCL_CFGVAL_ENCODING "ascii" -#endif - void TkpFontPkgInit( TkMainInfo *mainPtr) /* The application being created. */ { - static const Tcl_Config cfg[] = { - { "fontsystem", "xft" }, - { 0,0 } - }; - - Tcl_RegisterConfig(mainPtr->interp, "tk", cfg, TCL_CFGVAL_ENCODING); } static XftFont * -- cgit v0.12 From 15635ac20ae6cee1f9b080035266e2ef544c32cf Mon Sep 17 00:00:00 2001 From: stu Date: Sat, 20 May 2017 11:55:43 +0000 Subject: Add demo dir to tk.pc? --- unix/tk.pc.in | 1 + 1 file changed, 1 insertion(+) diff --git a/unix/tk.pc.in b/unix/tk.pc.in index 68f2130..f1e7acd 100644 --- a/unix/tk.pc.in +++ b/unix/tk.pc.in @@ -4,6 +4,7 @@ prefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ +demodir=@TK_DEMO_DIR@ Name: The Tk Toolkit Description: Tk is a cross-platform graphical user interface toolkit, the standard GUI not only for Tcl, but for many other dynamic languages as well. -- cgit v0.12 From 3a06e5165e7010bc5b3aea3f020d02304c136af7 Mon Sep 17 00:00:00 2001 From: stu Date: Tue, 7 Nov 2017 22:39:08 +0000 Subject: Add fontsystem values for Win and Mac. --- generic/tkPkgConfig.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/generic/tkPkgConfig.c b/generic/tkPkgConfig.c index d913fb1..8ea2c29 100644 --- a/generic/tkPkgConfig.c +++ b/generic/tkPkgConfig.c @@ -94,7 +94,11 @@ # define CFG_PROFILED "0" #endif -#ifdef HAVE_XFT +#if defined(_WIN32) || defined(__CYGWIN__) +# define CFG_FONTSYSTEM "gdi" +#elif defined(MAC_OSX_TK) +# define CFG_FONTSYSTEM "xft" +#elif defined(HAVE_XFT) # define CFG_FONTSYSTEM "xft" #else # define CFG_FONTSYSTEM "x11" -- cgit v0.12 From 9d7183d31ce425ef36ddaea52f8e0977cd999a7a Mon Sep 17 00:00:00 2001 From: stu Date: Wed, 8 Nov 2017 02:47:33 +0000 Subject: Use ::tk::pkgconfig to get the demo directory on MacOSX. --- macosx/tkMacOSXMenus.c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/macosx/tkMacOSXMenus.c b/macosx/tkMacOSXMenus.c index f8f00a6..91fbd1f 100644 --- a/macosx/tkMacOSXMenus.c +++ b/macosx/tkMacOSXMenus.c @@ -287,6 +287,7 @@ EDIT_ACTION(redo, Redo) *---------------------------------------------------------------------- */ +#if 0 static Tcl_Obj * GetWidgetDemoPath( Tcl_Interp *interp) @@ -306,6 +307,26 @@ GetWidgetDemoPath( } return result; } +#else +static Tcl_Obj * +GetWidgetDemoPath( + Tcl_Interp *interp) +{ + Tcl_Obj *result = NULL; + + if (Tcl_EvalEx(interp, "::tk::pkgconfig get demodir,runtime", + -1, TCL_EVAL_GLOBAL) == TCL_OK) { + Tcl_Obj *libpath, *demo[1] = { Tcl_NewStringObj("widget", 6) }; + + libpath = Tcl_GetObjResult(interp); + Tcl_IncrRefCount(libpath); + result = Tcl_FSJoinToPath(libpath, 1, demo); + Tcl_DecrRefCount(libpath); + } + Tcl_ResetResult(interp); + return result; +} +#endif /* *---------------------------------------------------------------------- -- cgit v0.12 From 2e3c80f974dcfc0fc773d6dbdb5e95ef0eee658a Mon Sep 17 00:00:00 2001 From: stu Date: Tue, 21 Nov 2017 18:48:49 +0000 Subject: Use macos comment for TkpFontPkgInit. --- unix/tkUnixRFont.c | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/unix/tkUnixRFont.c b/unix/tkUnixRFont.c index e357338..a2191dc 100644 --- a/unix/tkUnixRFont.c +++ b/unix/tkUnixRFont.c @@ -56,8 +56,22 @@ typedef struct ThreadSpecificData { static Tcl_ThreadDataKey dataKey; /* - * Package initialization: - * Nothing to do! + *------------------------------------------------------------------------- + * + * TkpFontPkgInit -- + * + * This procedure is called when an application is created. It + * initializes all the structures that are used by the + * platform-dependant code on a per application basis. + * Note that this is called before TkpInit() ! + * + * Results: + * None. + * + * Side effects: + * None. + * + *------------------------------------------------------------------------- */ void -- cgit v0.12 From e6032ebc5625554d828c05f7613453e0d03fccf4 Mon Sep 17 00:00:00 2001 From: stu Date: Wed, 22 Nov 2017 16:20:30 +0000 Subject: Remove unrelated ::tk::pkgconfig variables: compile_debug and compile_stats. Adjust test. Add copyright. --- generic/tkPkgConfig.c | 24 ++++++------------------ tests/pkgconfig.test | 8 +++++++- 2 files changed, 13 insertions(+), 19 deletions(-) diff --git a/generic/tkPkgConfig.c b/generic/tkPkgConfig.c index 8ea2c29..56aa106 100644 --- a/generic/tkPkgConfig.c +++ b/generic/tkPkgConfig.c @@ -5,6 +5,7 @@ * binary library. * * Copyright (c) 2002 Andreas Kupries + * Copyright (c) 2017 Stuart Cassoff * * See the file "license.terms" for information on usage and redistribution of * this file, and for a DISCLAIMER OF ALL WARRANTIES. @@ -16,16 +17,17 @@ * OSCMa = shortcut for "old style configuration macro activates" * NSCMdt = shortcut for "new style configuration macro declares that" * - * - TCL_THREADS OSCMa compilation as threaded core. + * - TCL_THREADS OSCMa compilation as threaded. * - TCL_MEM_DEBUG OSCMa memory debugging. - * - TCL_COMPILE_DEBUG OSCMa debugging of bytecode compiler. - * - TCL_COMPILE_STATS OSCMa bytecode compiler statistics. * * - TCL_CFG_DO64BIT NSCMdt tk is compiled for a 64bit system. * - NDEBUG NSCMdt tk is compiled with symbol info off. * - TCL_CFG_OPTIMIZED NSCMdt tk is compiled with cc optimizations on * - TCL_CFG_PROFILED NSCMdt tk is compiled with profiling info. - * - HAVE_XFT NSCMdt tk is compiled with xft font support. + * + * - _WIN32 || __CYGWIN__ The value for the fontsytem key will be + * MAC_OSX_TK chosen based on these macros/defines. + * HAVE_XFT NSCMdt xft font support was requested. * * - CFG_RUNTIME_* Paths to various stuff at runtime. * - CFG_INSTALL_* Paths to various stuff at installation time. @@ -58,18 +60,6 @@ # define CFG_MEMDEBUG "0" #endif -#ifdef TCL_COMPILE_DEBUG -# define CFG_COMPILE_DEBUG "1" -#else -# define CFG_COMPILE_DEBUG "0" -#endif - -#ifdef TCL_COMPILE_STATS -# define CFG_COMPILE_STATS "1" -#else -# define CFG_COMPILE_STATS "0" -#endif - #ifdef TCL_CFG_DO64BIT # define CFG_64 "1" #else @@ -111,8 +101,6 @@ static Tcl_Config const cfg[] = { {"64bit", CFG_64}, {"optimized", CFG_OPTIMIZED}, {"mem_debug", CFG_MEMDEBUG}, - {"compile_debug", CFG_COMPILE_DEBUG}, - {"compile_stats", CFG_COMPILE_STATS}, {"fontsystem", CFG_FONTSYSTEM}, /* Runtime paths to various stuff */ diff --git a/tests/pkgconfig.test b/tests/pkgconfig.test index 5cb5081..1694eea 100644 --- a/tests/pkgconfig.test +++ b/tests/pkgconfig.test @@ -8,6 +8,7 @@ # Copyright (c) 1991-1993 The Regents of the University of California. # Copyright (c) 1994-1996 Sun Microsystems, Inc. # Copyright (c) 1998-1999 by Scriptics Corporation. +# Copyright (c) 2017 Stuart Cassoff # # See the file "license.terms" for information on usage and redistribution # of this file, and for a DISCLAIMER OF ALL WARRANTIES. @@ -19,7 +20,12 @@ tcltest::loadTestedCommands test pkgconfig-1.1 {query keys} { lsort [::tk::pkgconfig list] -} {64bit bindir,install bindir,runtime compile_debug compile_stats debug demodir,install demodir,runtime docdir,install docdir,runtime fontsystem includedir,install includedir,runtime libdir,install libdir,runtime mem_debug optimized profiled scriptdir,install scriptdir,runtime threaded} +} [list \ + 64bit bindir,install bindir,runtime debug demodir,install demodir,runtime \ + docdir,install docdir,runtime fontsystem includedir,install includedir,runtime \ + libdir,install libdir,runtime mem_debug optimized profiled \ + scriptdir,install scriptdir,runtime threaded \ +] test pkgconfig-1.2 {query keys multiple times} { string compare [::tk::pkgconfig list] [::tk::pkgconfig list] } 0 -- cgit v0.12 From 30a9d67a0b9143300d7c3d929b76afd2fafed397 Mon Sep 17 00:00:00 2001 From: fvogel Date: Tue, 15 May 2018 19:30:35 +0000 Subject: =?UTF-8?q?Implementation=20of=20TIP=20#507:=20Include=20simple=20?= =?UTF-8?q?svg=20support=20with=20nanosvg.=20Files=20as=20provided=20by=20?= =?UTF-8?q?Ren=C3=A9=20Zaumseil.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- generic/tkInt.h | 1 + generic/tkWindow.c | 1 + unix/Makefile.in | 6 +++++- win/Makefile.in | 1 + 4 files changed, 8 insertions(+), 1 deletion(-) diff --git a/generic/tkInt.h b/generic/tkInt.h index 12c5f88..9b639ac 100644 --- a/generic/tkInt.h +++ b/generic/tkInt.h @@ -949,6 +949,7 @@ MODULE_SCOPE void (*tkHandleEventProc) (XEvent* eventPtr); MODULE_SCOPE Tk_PhotoImageFormat tkImgFmtDefault; MODULE_SCOPE Tk_PhotoImageFormat tkImgFmtPNG; MODULE_SCOPE Tk_PhotoImageFormat tkImgFmtPPM; +MODULE_SCOPE Tk_PhotoImageFormat tkImgFmtSVGnano; MODULE_SCOPE TkMainInfo *tkMainWindowList; MODULE_SCOPE Tk_ImageType tkPhotoImageType; MODULE_SCOPE Tcl_HashTable tkPredefBitmapTable; diff --git a/generic/tkWindow.c b/generic/tkWindow.c index ef06a5b..e4d2281 100644 --- a/generic/tkWindow.c +++ b/generic/tkWindow.c @@ -340,6 +340,7 @@ CreateTopLevelWindow( Tk_CreatePhotoImageFormat(&tkImgFmtGIF); Tk_CreatePhotoImageFormat(&tkImgFmtPNG); Tk_CreatePhotoImageFormat(&tkImgFmtPPM); + Tk_CreatePhotoImageFormat(&tkImgFmtSVGnano); } if ((parent != NULL) && (screenName != NULL) && (screenName[0] == '\0')) { diff --git a/unix/Makefile.in b/unix/Makefile.in index 225a8f7..4b629af 100644 --- a/unix/Makefile.in +++ b/unix/Makefile.in @@ -356,7 +356,7 @@ CANV_OBJS = tkCanvas.o tkCanvArc.o tkCanvBmap.o tkCanvImg.o \ tkCanvUtil.o tkCanvWind.o tkRectOval.o tkTrig.o IMAGE_OBJS = tkImage.o tkImgBmap.o tkImgGIF.o tkImgPNG.o tkImgPPM.o \ - tkImgPhoto.o tkImgPhInstance.o tkImgListFormat.o + tkImgPhoto.o tkImgPhInstance.o tkImgListFormat.o tkImgSVGnano.o TEXT_OBJS = tkText.o tkTextBTree.o tkTextDisp.o tkTextImage.o tkTextIndex.o \ tkTextMark.o tkTextTag.o tkTextWind.o @@ -449,6 +449,7 @@ GENERIC_SRCS = \ $(GENERIC_DIR)/tkTrig.c $(GENERIC_DIR)/tkImage.c \ $(GENERIC_DIR)/tkImgBmap.c $(GENERIC_DIR)/tkImgGIF.c \ $(GENERIC_DIR)/tkImgPNG.c $(GENERIC_DIR)/tkImgPPM.c \ + $(GENERIC_DIR)/tkImgSVGnano.c $(GENERIC_DIR)/tkImgSVGnano.c \ $(GENERIC_DIR)/tkImgPhoto.c $(GENERIC_DIR)/tkImgPhInstance.c \ $(GENERIC_DIR)/tkImgListFormat.c $(GENERIC_DIR)/tkText.c \ $(GENERIC_DIR)/tkTextBTree.c $(GENERIC_DIR)/tkTextDisp.c \ @@ -1118,6 +1119,9 @@ tkImgPNG.o: $(GENERIC_DIR)/tkImgPNG.c tkImgPPM.o: $(GENERIC_DIR)/tkImgPPM.c $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkImgPPM.c +tkImgSVGnano.o: $(GENERIC_DIR)/tkImgSVGnano.c + $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkImgSVGnano.c + tkImgPhoto.o: $(GENERIC_DIR)/tkImgPhoto.c $(GENERIC_DIR)/tkImgPhoto.h $(CC) -c $(CC_SWITCHES) $(GENERIC_DIR)/tkImgPhoto.c diff --git a/win/Makefile.in b/win/Makefile.in index 3c1c9e3..5bf0deb 100644 --- a/win/Makefile.in +++ b/win/Makefile.in @@ -321,6 +321,7 @@ TK_OBJS = \ tkImgGIF.$(OBJEXT) \ tkImgPNG.$(OBJEXT) \ tkImgPPM.$(OBJEXT) \ + tkImgSVGnano.$(OBJEXT) \ tkImgPhoto.$(OBJEXT) \ tkImgPhInstance.$(OBJEXT) \ tkImgUtil.$(OBJEXT) \ -- cgit v0.12 From a7048fe8fec1e93713cefba5214cfa6a200761f8 Mon Sep 17 00:00:00 2001 From: fvogel Date: Tue, 15 May 2018 19:32:12 +0000 Subject: =?UTF-8?q?Add=20missing=20files,=20as=20provided=20by=20Ren=C3=A9?= =?UTF-8?q?=20Zaumseil.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- generic/nanosvg.h | 3055 ++++++++++++++++++++++++++++++++++++++++++++++++ generic/nanosvgrast.h | 1467 +++++++++++++++++++++++ generic/tkImgSVGnano.c | 703 +++++++++++ 3 files changed, 5225 insertions(+) create mode 100644 generic/nanosvg.h create mode 100644 generic/nanosvgrast.h create mode 100644 generic/tkImgSVGnano.c diff --git a/generic/nanosvg.h b/generic/nanosvg.h new file mode 100644 index 0000000..8cdb728 --- /dev/null +++ b/generic/nanosvg.h @@ -0,0 +1,3055 @@ +/* + * Copyright (c) 2013-14 Mikko Mononen memon@inside.org + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + * + * The SVG parser is based on Anti-Grain Geometry 2.4 SVG example + * Copyright (C) 2002-2004 Maxim Shemanarev (McSeem) (http://www.antigrain.com/) + * + * Arc calculation code based on canvg (https://code.google.com/p/canvg/) + * + * Bounding box calculation based on http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html + * + */ + +#ifndef NANOSVG_H +#define NANOSVG_H + +#ifdef __cplusplus +extern "C" { +#endif + +// NanoSVG is a simple stupid single-header-file SVG parse. The output of the parser is a list of cubic bezier shapes. +// +// The library suits well for anything from rendering scalable icons in your editor application to prototyping a game. +// +// NanoSVG supports a wide range of SVG features, but something may be missing, feel free to create a pull request! +// +// The shapes in the SVG images are transformed by the viewBox and converted to specified units. +// That is, you should get the same looking data as your designed in your favorite app. +// +// NanoSVG can return the paths in few different units. For example if you want to render an image, you may choose +// to get the paths in pixels, or if you are feeding the data into a CNC-cutter, you may want to use millimeters. +// +// The units passed to NanoVG should be one of: 'px', 'pt', 'pc' 'mm', 'cm', or 'in'. +// DPI (dots-per-inch) controls how the unit conversion is done. +// +// If you don't know or care about the units stuff, "px" and 96 should get you going. + + +/* Example Usage: + // Load + NSVGImage* image; + image = nsvgParseFromFile("test.svg", "px", 96); + printf("size: %f x %f\n", image->width, image->height); + // Use... + for (NSVGshape *shape = image->shapes; shape != NULL; shape = shape->next) { + for (NSVGpath *path = shape->paths; path != NULL; path = path->next) { + for (int i = 0; i < path->npts-1; i += 3) { + float* p = &path->pts[i*2]; + drawCubicBez(p[0],p[1], p[2],p[3], p[4],p[5], p[6],p[7]); + } + } + } + // Delete + nsvgDelete(image); +*/ + +#ifndef NANOSVG_SCOPE +#define NANOSVG_SCOPE +#endif + +#ifndef NANOSVG_malloc +#define NANOSVG_malloc malloc +#endif + +#ifndef NANOSVG_realloc +#define NANOSVG_realloc realloc +#endif + +#ifndef NANOSVG_free +#define NANOSVG_free free +#endif + +enum NSVGpaintType { + NSVG_PAINT_NONE = 0, + NSVG_PAINT_COLOR = 1, + NSVG_PAINT_LINEAR_GRADIENT = 2, + NSVG_PAINT_RADIAL_GRADIENT = 3 +}; + +enum NSVGspreadType { + NSVG_SPREAD_PAD = 0, + NSVG_SPREAD_REFLECT = 1, + NSVG_SPREAD_REPEAT = 2 +}; + +enum NSVGlineJoin { + NSVG_JOIN_MITER = 0, + NSVG_JOIN_ROUND = 1, + NSVG_JOIN_BEVEL = 2 +}; + +enum NSVGlineCap { + NSVG_CAP_BUTT = 0, + NSVG_CAP_ROUND = 1, + NSVG_CAP_SQUARE = 2 +}; + +enum NSVGfillRule { + NSVG_FILLRULE_NONZERO = 0, + NSVG_FILLRULE_EVENODD = 1 +}; + +enum NSVGflags { + NSVG_FLAGS_VISIBLE = 0x01 +}; + +typedef struct NSVGgradientStop { + unsigned int color; + float offset; +} NSVGgradientStop; + +typedef struct NSVGgradient { + float xform[6]; + char spread; + float fx, fy; + int nstops; + NSVGgradientStop stops[1]; +} NSVGgradient; + +typedef struct NSVGpaint { + char type; + union { + unsigned int color; + NSVGgradient* gradient; + }; +} NSVGpaint; + +typedef struct NSVGpath +{ + float* pts; // Cubic bezier points: x0,y0, [cpx1,cpx1,cpx2,cpy2,x1,y1], ... + int npts; // Total number of bezier points. + char closed; // Flag indicating if shapes should be treated as closed. + float bounds[4]; // Tight bounding box of the shape [minx,miny,maxx,maxy]. + struct NSVGpath* next; // Pointer to next path, or NULL if last element. +} NSVGpath; + +typedef struct NSVGshape +{ + char id[64]; // Optional 'id' attr of the shape or its group + NSVGpaint fill; // Fill paint + NSVGpaint stroke; // Stroke paint + float opacity; // Opacity of the shape. + float strokeWidth; // Stroke width (scaled). + float strokeDashOffset; // Stroke dash offset (scaled). + float strokeDashArray[8]; // Stroke dash array (scaled). + char strokeDashCount; // Number of dash values in dash array. + char strokeLineJoin; // Stroke join type. + char strokeLineCap; // Stroke cap type. + float miterLimit; // Miter limit + char fillRule; // Fill rule, see NSVGfillRule. + unsigned char flags; // Logical or of NSVG_FLAGS_* flags + float bounds[4]; // Tight bounding box of the shape [minx,miny,maxx,maxy]. + NSVGpath* paths; // Linked list of paths in the image. + struct NSVGshape* next; // Pointer to next shape, or NULL if last element. +} NSVGshape; + +typedef struct NSVGimage +{ + float width; // Width of the image. + float height; // Height of the image. + NSVGshape* shapes; // Linked list of shapes in the image. +} NSVGimage; + +// Parses SVG file from a file, returns SVG image as paths. +NANOSVG_SCOPE NSVGimage* nsvgParseFromFile(const char* filename, const char* units, float dpi); + +// Parses SVG file from a null terminated string, returns SVG image as paths. +// Important note: changes the string. +NANOSVG_SCOPE NSVGimage* nsvgParse(char* input, const char* units, float dpi); + +// Deletes list of paths. +NANOSVG_SCOPE void nsvgDelete(NSVGimage* image); + +#ifdef __cplusplus +} +#endif + +#endif // NANOSVG_H + +#ifdef NANOSVG_IMPLEMENTATION + +#include +#include +#include + +#define NSVG_PI (3.14159265358979323846264338327f) +#define NSVG_KAPPA90 (0.5522847493f) // Length proportional to radius of a cubic bezier handle for 90deg arcs. + +#define NSVG_ALIGN_MIN 0 +#define NSVG_ALIGN_MID 1 +#define NSVG_ALIGN_MAX 2 +#define NSVG_ALIGN_NONE 0 +#define NSVG_ALIGN_MEET 1 +#define NSVG_ALIGN_SLICE 2 + +#define NSVG_NOTUSED(v) do { (void)(1 ? (void)0 : ( (void)(v) ) ); } while(0) +#define NSVG_RGB(r, g, b) (((unsigned int)r) | ((unsigned int)g << 8) | ((unsigned int)b << 16)) + +#ifdef _MSC_VER + #pragma warning (disable: 4996) // Switch off security warnings + #pragma warning (disable: 4100) // Switch off unreferenced formal parameter warnings + #ifdef __cplusplus + #define NSVG_INLINE inline + #else + #define NSVG_INLINE + #endif +#else + #define NSVG_INLINE inline +#endif + + +static int nsvg__isspace(char c) +{ + return strchr(" \t\n\v\f\r", c) != 0; +} + +static int nsvg__isdigit(char c) +{ + return c >= '0' && c <= '9'; +} + +static int nsvg__isnum(char c) +{ + return strchr("0123456789+-.eE", c) != 0; +} + +static NSVG_INLINE float nsvg__minf(float a, float b) { return a < b ? a : b; } +static NSVG_INLINE float nsvg__maxf(float a, float b) { return a > b ? a : b; } + + +// Simple XML parser + +#define NSVG_XML_TAG 1 +#define NSVG_XML_CONTENT 2 +#define NSVG_XML_MAX_ATTRIBS 256 + +static void nsvg__parseContent(char* s, + void (*contentCb)(void* ud, const char* s), + void* ud) +{ + // Trim start white spaces + while (*s && nsvg__isspace(*s)) s++; + if (!*s) return; + + if (contentCb) + (*contentCb)(ud, s); +} + +static void nsvg__parseElement(char* s, + void (*startelCb)(void* ud, const char* el, const char** attr), + void (*endelCb)(void* ud, const char* el), + void* ud) +{ + const char* attr[NSVG_XML_MAX_ATTRIBS]; + int nattr = 0; + char* name; + int start = 0; + int end = 0; + char quote; + + // Skip white space after the '<' + while (*s && nsvg__isspace(*s)) s++; + + // Check if the tag is end tag + if (*s == '/') { + s++; + end = 1; + } else { + start = 1; + } + + // Skip comments, data and preprocessor stuff. + if (!*s || *s == '?' || *s == '!') + return; + + // Get tag name + name = s; + while (*s && !nsvg__isspace(*s)) s++; + if (*s) { *s++ = '\0'; } + + // Get attribs + while (!end && *s && nattr < NSVG_XML_MAX_ATTRIBS-3) { + char* name = NULL; + char* value = NULL; + + // Skip white space before the attrib name + while (*s && nsvg__isspace(*s)) s++; + if (!*s) break; + if (*s == '/') { + end = 1; + break; + } + name = s; + // Find end of the attrib name. + while (*s && !nsvg__isspace(*s) && *s != '=') s++; + if (*s) { *s++ = '\0'; } + // Skip until the beginning of the value. + while (*s && *s != '\"' && *s != '\'') s++; + if (!*s) break; + quote = *s; + s++; + // Store value and find the end of it. + value = s; + while (*s && *s != quote) s++; + if (*s) { *s++ = '\0'; } + + // Store only well formed attributes + if (name && value) { + attr[nattr++] = name; + attr[nattr++] = value; + } + } + + // List terminator + attr[nattr++] = 0; + attr[nattr++] = 0; + + // Call callbacks. + if (start && startelCb) + (*startelCb)(ud, name, attr); + if (end && endelCb) + (*endelCb)(ud, name); +} + +NANOSVG_SCOPE +int nsvg__parseXML(char* input, + void (*startelCb)(void* ud, const char* el, const char** attr), + void (*endelCb)(void* ud, const char* el), + void (*contentCb)(void* ud, const char* s), + void* ud) +{ + char* s = input; + char* mark = s; + int state = NSVG_XML_CONTENT; + while (*s) { + if (*s == '<' && state == NSVG_XML_CONTENT) { + // Start of a tag + *s++ = '\0'; + nsvg__parseContent(mark, contentCb, ud); + mark = s; + state = NSVG_XML_TAG; + } else if (*s == '>' && state == NSVG_XML_TAG) { + // Start of a content or new tag. + *s++ = '\0'; + nsvg__parseContent(mark, contentCb, ud); + nsvg__parseElement(mark, startelCb, endelCb, ud); + mark = s; + state = NSVG_XML_CONTENT; + } else { + s++; + } + } + + return 1; +} + + +/* Simple SVG parser. */ + +#define NSVG_MAX_ATTR 128 + +enum NSVGgradientUnits { + NSVG_USER_SPACE = 0, + NSVG_OBJECT_SPACE = 1 +}; + +#define NSVG_MAX_DASHES 8 + +enum NSVGunits { + NSVG_UNITS_USER, + NSVG_UNITS_PX, + NSVG_UNITS_PT, + NSVG_UNITS_PC, + NSVG_UNITS_MM, + NSVG_UNITS_CM, + NSVG_UNITS_IN, + NSVG_UNITS_PERCENT, + NSVG_UNITS_EM, + NSVG_UNITS_EX +}; + +enum NSVGvisible { + NSVG_VIS_DISPLAY = 1, + NSVG_VIS_VISIBLE = 2 +}; + +typedef struct NSVGcoordinate { + float value; + int units; +} NSVGcoordinate; + +typedef struct NSVGlinearData { + NSVGcoordinate x1, y1, x2, y2; +} NSVGlinearData; + +typedef struct NSVGradialData { + NSVGcoordinate cx, cy, r, fx, fy; +} NSVGradialData; + +typedef struct NSVGgradientData +{ + char id[64]; + char ref[64]; + char type; + union { + NSVGlinearData linear; + NSVGradialData radial; + }; + char spread; + char units; + float xform[6]; + int nstops; + NSVGgradientStop* stops; + struct NSVGgradientData* next; +} NSVGgradientData; + +typedef struct NSVGattrib +{ + char id[64]; + float xform[6]; + unsigned int fillColor; + unsigned int strokeColor; + float opacity; + float fillOpacity; + float strokeOpacity; + char fillGradient[64]; + char strokeGradient[64]; + float strokeWidth; + float strokeDashOffset; + float strokeDashArray[NSVG_MAX_DASHES]; + int strokeDashCount; + char strokeLineJoin; + char strokeLineCap; + float miterLimit; + char fillRule; + float fontSize; + unsigned int stopColor; + float stopOpacity; + float stopOffset; + char hasFill; + char hasStroke; + char visible; +} NSVGattrib; + +typedef struct NSVGstyles +{ + char* name; + char* description; + struct NSVGstyles* next; +} NSVGstyles; + +typedef struct NSVGparser +{ + NSVGattrib attr[NSVG_MAX_ATTR]; + int attrHead; + float* pts; + int npts; + int cpts; + NSVGpath* plist; + NSVGimage* image; + NSVGstyles* styles; + NSVGgradientData* gradients; + NSVGshape* shapesTail; + float viewMinx, viewMiny, viewWidth, viewHeight; + int alignX, alignY, alignType; + float dpi; + char pathFlag; + char defsFlag; + char styleFlag; +} NSVGparser; + +static void nsvg__xformIdentity(float* t) +{ + t[0] = 1.0f; t[1] = 0.0f; + t[2] = 0.0f; t[3] = 1.0f; + t[4] = 0.0f; t[5] = 0.0f; +} + +static void nsvg__xformSetTranslation(float* t, float tx, float ty) +{ + t[0] = 1.0f; t[1] = 0.0f; + t[2] = 0.0f; t[3] = 1.0f; + t[4] = tx; t[5] = ty; +} + +static void nsvg__xformSetScale(float* t, float sx, float sy) +{ + t[0] = sx; t[1] = 0.0f; + t[2] = 0.0f; t[3] = sy; + t[4] = 0.0f; t[5] = 0.0f; +} + +static void nsvg__xformSetSkewX(float* t, float a) +{ + t[0] = 1.0f; t[1] = 0.0f; + t[2] = tanf(a); t[3] = 1.0f; + t[4] = 0.0f; t[5] = 0.0f; +} + +static void nsvg__xformSetSkewY(float* t, float a) +{ + t[0] = 1.0f; t[1] = tanf(a); + t[2] = 0.0f; t[3] = 1.0f; + t[4] = 0.0f; t[5] = 0.0f; +} + +static void nsvg__xformSetRotation(float* t, float a) +{ + float cs = cosf(a), sn = sinf(a); + t[0] = cs; t[1] = sn; + t[2] = -sn; t[3] = cs; + t[4] = 0.0f; t[5] = 0.0f; +} + +static void nsvg__xformMultiply(float* t, float* s) +{ + float t0 = t[0] * s[0] + t[1] * s[2]; + float t2 = t[2] * s[0] + t[3] * s[2]; + float t4 = t[4] * s[0] + t[5] * s[2] + s[4]; + t[1] = t[0] * s[1] + t[1] * s[3]; + t[3] = t[2] * s[1] + t[3] * s[3]; + t[5] = t[4] * s[1] + t[5] * s[3] + s[5]; + t[0] = t0; + t[2] = t2; + t[4] = t4; +} + +static void nsvg__xformInverse(float* inv, float* t) +{ + double invdet, det = (double)t[0] * t[3] - (double)t[2] * t[1]; + if (det > -1e-6 && det < 1e-6) { + nsvg__xformIdentity(t); + return; + } + invdet = 1.0 / det; + inv[0] = (float)(t[3] * invdet); + inv[2] = (float)(-t[2] * invdet); + inv[4] = (float)(((double)t[2] * t[5] - (double)t[3] * t[4]) * invdet); + inv[1] = (float)(-t[1] * invdet); + inv[3] = (float)(t[0] * invdet); + inv[5] = (float)(((double)t[1] * t[4] - (double)t[0] * t[5]) * invdet); +} + +static void nsvg__xformPremultiply(float* t, float* s) +{ + float s2[6]; + memcpy(s2, s, sizeof(float)*6); + nsvg__xformMultiply(s2, t); + memcpy(t, s2, sizeof(float)*6); +} + +static void nsvg__xformPoint(float* dx, float* dy, float x, float y, float* t) +{ + *dx = x*t[0] + y*t[2] + t[4]; + *dy = x*t[1] + y*t[3] + t[5]; +} + +static void nsvg__xformVec(float* dx, float* dy, float x, float y, float* t) +{ + *dx = x*t[0] + y*t[2]; + *dy = x*t[1] + y*t[3]; +} + +#define NSVG_EPSILON (1e-12) + +static int nsvg__ptInBounds(float* pt, float* bounds) +{ + return pt[0] >= bounds[0] && pt[0] <= bounds[2] && pt[1] >= bounds[1] && pt[1] <= bounds[3]; +} + + +static double nsvg__evalBezier(double t, double p0, double p1, double p2, double p3) +{ + double it = 1.0-t; + return it*it*it*p0 + 3.0*it*it*t*p1 + 3.0*it*t*t*p2 + t*t*t*p3; +} + +static void nsvg__curveBounds(float* bounds, float* curve) +{ + int i, j, count; + double roots[2], a, b, c, b2ac, t, v; + float* v0 = &curve[0]; + float* v1 = &curve[2]; + float* v2 = &curve[4]; + float* v3 = &curve[6]; + + // Start the bounding box by end points + bounds[0] = nsvg__minf(v0[0], v3[0]); + bounds[1] = nsvg__minf(v0[1], v3[1]); + bounds[2] = nsvg__maxf(v0[0], v3[0]); + bounds[3] = nsvg__maxf(v0[1], v3[1]); + + // Bezier curve fits inside the convex hull of it's control points. + // If control points are inside the bounds, we're done. + if (nsvg__ptInBounds(v1, bounds) && nsvg__ptInBounds(v2, bounds)) + return; + + // Add bezier curve inflection points in X and Y. + for (i = 0; i < 2; i++) { + a = -3.0 * v0[i] + 9.0 * v1[i] - 9.0 * v2[i] + 3.0 * v3[i]; + b = 6.0 * v0[i] - 12.0 * v1[i] + 6.0 * v2[i]; + c = 3.0 * v1[i] - 3.0 * v0[i]; + count = 0; + if (fabs(a) < NSVG_EPSILON) { + if (fabs(b) > NSVG_EPSILON) { + t = -c / b; + if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON) + roots[count++] = t; + } + } else { + b2ac = b*b - 4.0*c*a; + if (b2ac > NSVG_EPSILON) { + t = (-b + sqrt(b2ac)) / (2.0 * a); + if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON) + roots[count++] = t; + t = (-b - sqrt(b2ac)) / (2.0 * a); + if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON) + roots[count++] = t; + } + } + for (j = 0; j < count; j++) { + v = nsvg__evalBezier(roots[j], v0[i], v1[i], v2[i], v3[i]); + bounds[0+i] = nsvg__minf(bounds[0+i], (float)v); + bounds[2+i] = nsvg__maxf(bounds[2+i], (float)v); + } + } +} + +static NSVGparser* nsvg__createParser() +{ + NSVGparser* p; + p = (NSVGparser*)NANOSVG_malloc(sizeof(NSVGparser)); + if (p == NULL) goto error; + memset(p, 0, sizeof(NSVGparser)); + + p->image = (NSVGimage*)NANOSVG_malloc(sizeof(NSVGimage)); + if (p->image == NULL) goto error; + memset(p->image, 0, sizeof(NSVGimage)); + + // Init style + nsvg__xformIdentity(p->attr[0].xform); + memset(p->attr[0].id, 0, sizeof p->attr[0].id); + p->attr[0].fillColor = NSVG_RGB(0,0,0); + p->attr[0].strokeColor = NSVG_RGB(0,0,0); + p->attr[0].opacity = 1; + p->attr[0].fillOpacity = 1; + p->attr[0].strokeOpacity = 1; + p->attr[0].stopOpacity = 1; + p->attr[0].strokeWidth = 1; + p->attr[0].strokeLineJoin = NSVG_JOIN_MITER; + p->attr[0].strokeLineCap = NSVG_CAP_BUTT; + p->attr[0].miterLimit = 4; + p->attr[0].fillRule = NSVG_FILLRULE_NONZERO; + p->attr[0].hasFill = 1; + p->attr[0].visible = NSVG_VIS_DISPLAY | NSVG_VIS_VISIBLE; + + return p; + +error: + if (p) { + if (p->image) NANOSVG_free(p->image); + NANOSVG_free(p); + } + return NULL; +} + +static void nsvg__deleteStyles(NSVGstyles* style) { + while (style) { + NSVGstyles *next = style->next; + if (style->name!= NULL) + free(style->name); + if (style->description != NULL) + free(style->description); + free(style); + style = next; + } +} + +static void nsvg__deletePaths(NSVGpath* path) +{ + while (path) { + NSVGpath *next = path->next; + if (path->pts != NULL) + NANOSVG_free(path->pts); + NANOSVG_free(path); + path = next; + } +} + +static void nsvg__deletePaint(NSVGpaint* paint) +{ + if (paint->type == NSVG_PAINT_LINEAR_GRADIENT || paint->type == NSVG_PAINT_RADIAL_GRADIENT) + NANOSVG_free(paint->gradient); +} + +static void nsvg__deleteGradientData(NSVGgradientData* grad) +{ + NSVGgradientData* next; + while (grad != NULL) { + next = grad->next; + NANOSVG_free(grad->stops); + NANOSVG_free(grad); + grad = next; + } +} + +static void nsvg__deleteParser(NSVGparser* p) +{ + if (p != NULL) { + nsvg__deleteStyles(p->styles); + nsvg__deletePaths(p->plist); + nsvg__deleteGradientData(p->gradients); + nsvgDelete(p->image); + NANOSVG_free(p->pts); + NANOSVG_free(p); + } +} + +static void nsvg__resetPath(NSVGparser* p) +{ + p->npts = 0; +} + +static void nsvg__addPoint(NSVGparser* p, float x, float y) +{ + if (p->npts+1 > p->cpts) { + p->cpts = p->cpts ? p->cpts*2 : 8; + p->pts = (float*)NANOSVG_realloc(p->pts, p->cpts*2*sizeof(float)); + if (!p->pts) return; + } + p->pts[p->npts*2+0] = x; + p->pts[p->npts*2+1] = y; + p->npts++; +} + +static void nsvg__moveTo(NSVGparser* p, float x, float y) +{ + if (p->npts > 0) { + p->pts[(p->npts-1)*2+0] = x; + p->pts[(p->npts-1)*2+1] = y; + } else { + nsvg__addPoint(p, x, y); + } +} + +static void nsvg__lineTo(NSVGparser* p, float x, float y) +{ + float px,py, dx,dy; + if (p->npts > 0) { + px = p->pts[(p->npts-1)*2+0]; + py = p->pts[(p->npts-1)*2+1]; + dx = x - px; + dy = y - py; + nsvg__addPoint(p, px + dx/3.0f, py + dy/3.0f); + nsvg__addPoint(p, x - dx/3.0f, y - dy/3.0f); + nsvg__addPoint(p, x, y); + } +} + +static void nsvg__cubicBezTo(NSVGparser* p, float cpx1, float cpy1, float cpx2, float cpy2, float x, float y) +{ + nsvg__addPoint(p, cpx1, cpy1); + nsvg__addPoint(p, cpx2, cpy2); + nsvg__addPoint(p, x, y); +} + +static NSVGattrib* nsvg__getAttr(NSVGparser* p) +{ + return &p->attr[p->attrHead]; +} + +static void nsvg__pushAttr(NSVGparser* p) +{ + if (p->attrHead < NSVG_MAX_ATTR-1) { + p->attrHead++; + memcpy(&p->attr[p->attrHead], &p->attr[p->attrHead-1], sizeof(NSVGattrib)); + } +} + +static void nsvg__popAttr(NSVGparser* p) +{ + if (p->attrHead > 0) + p->attrHead--; +} + +static float nsvg__actualOrigX(NSVGparser* p) +{ + return p->viewMinx; +} + +static float nsvg__actualOrigY(NSVGparser* p) +{ + return p->viewMiny; +} + +static float nsvg__actualWidth(NSVGparser* p) +{ + return p->viewWidth; +} + +static float nsvg__actualHeight(NSVGparser* p) +{ + return p->viewHeight; +} + +static float nsvg__actualLength(NSVGparser* p) +{ + float w = nsvg__actualWidth(p), h = nsvg__actualHeight(p); + return sqrtf(w*w + h*h) / sqrtf(2.0f); +} + +static float nsvg__convertToPixels(NSVGparser* p, NSVGcoordinate c, float orig, float length) +{ + NSVGattrib* attr = nsvg__getAttr(p); + switch (c.units) { + case NSVG_UNITS_USER: return c.value; + case NSVG_UNITS_PX: return c.value; + case NSVG_UNITS_PT: return c.value / 72.0f * p->dpi; + case NSVG_UNITS_PC: return c.value / 6.0f * p->dpi; + case NSVG_UNITS_MM: return c.value / 25.4f * p->dpi; + case NSVG_UNITS_CM: return c.value / 2.54f * p->dpi; + case NSVG_UNITS_IN: return c.value * p->dpi; + case NSVG_UNITS_EM: return c.value * attr->fontSize; + case NSVG_UNITS_EX: return c.value * attr->fontSize * 0.52f; // x-height of Helvetica. + case NSVG_UNITS_PERCENT: return orig + c.value / 100.0f * length; + default: return c.value; + } + return c.value; +} + +static NSVGgradientData* nsvg__findGradientData(NSVGparser* p, const char* id) +{ + NSVGgradientData* grad = p->gradients; + while (grad) { + if (strcmp(grad->id, id) == 0) + return grad; + grad = grad->next; + } + return NULL; +} + +static NSVGgradient* nsvg__createGradient(NSVGparser* p, const char* id, const float* localBounds, char* paintType) +{ + NSVGattrib* attr = nsvg__getAttr(p); + NSVGgradientData* data = NULL; + NSVGgradientData* ref = NULL; + NSVGgradientStop* stops = NULL; + NSVGgradient* grad; + float ox, oy, sw, sh, sl; + int nstops = 0; + + data = nsvg__findGradientData(p, id); + if (data == NULL) return NULL; + + // TODO: use ref to fill in all unset values too. + ref = data; + while (ref != NULL) { + if (stops == NULL && ref->stops != NULL) { + stops = ref->stops; + nstops = ref->nstops; + break; + } + ref = nsvg__findGradientData(p, ref->ref); + } + if (stops == NULL) return NULL; + + grad = (NSVGgradient*)NANOSVG_malloc(sizeof(NSVGgradient) + sizeof(NSVGgradientStop)*(nstops-1)); + if (grad == NULL) return NULL; + + // The shape width and height. + if (data->units == NSVG_OBJECT_SPACE) { + ox = localBounds[0]; + oy = localBounds[1]; + sw = localBounds[2] - localBounds[0]; + sh = localBounds[3] - localBounds[1]; + } else { + ox = nsvg__actualOrigX(p); + oy = nsvg__actualOrigY(p); + sw = nsvg__actualWidth(p); + sh = nsvg__actualHeight(p); + } + sl = sqrtf(sw*sw + sh*sh) / sqrtf(2.0f); + + if (data->type == NSVG_PAINT_LINEAR_GRADIENT) { + float x1, y1, x2, y2, dx, dy; + x1 = nsvg__convertToPixels(p, data->linear.x1, ox, sw); + y1 = nsvg__convertToPixels(p, data->linear.y1, oy, sh); + x2 = nsvg__convertToPixels(p, data->linear.x2, ox, sw); + y2 = nsvg__convertToPixels(p, data->linear.y2, oy, sh); + // Calculate transform aligned to the line + dx = x2 - x1; + dy = y2 - y1; + grad->xform[0] = dy; grad->xform[1] = -dx; + grad->xform[2] = dx; grad->xform[3] = dy; + grad->xform[4] = x1; grad->xform[5] = y1; + } else { + float cx, cy, fx, fy, r; + cx = nsvg__convertToPixels(p, data->radial.cx, ox, sw); + cy = nsvg__convertToPixels(p, data->radial.cy, oy, sh); + fx = nsvg__convertToPixels(p, data->radial.fx, ox, sw); + fy = nsvg__convertToPixels(p, data->radial.fy, oy, sh); + r = nsvg__convertToPixels(p, data->radial.r, 0, sl); + // Calculate transform aligned to the circle + grad->xform[0] = r; grad->xform[1] = 0; + grad->xform[2] = 0; grad->xform[3] = r; + grad->xform[4] = cx; grad->xform[5] = cy; + grad->fx = fx / r; + grad->fy = fy / r; + } + + nsvg__xformMultiply(grad->xform, data->xform); + nsvg__xformMultiply(grad->xform, attr->xform); + + grad->spread = data->spread; + memcpy(grad->stops, stops, nstops*sizeof(NSVGgradientStop)); + grad->nstops = nstops; + + *paintType = data->type; + + return grad; +} + +static float nsvg__getAverageScale(float* t) +{ + float sx = sqrtf(t[0]*t[0] + t[2]*t[2]); + float sy = sqrtf(t[1]*t[1] + t[3]*t[3]); + return (sx + sy) * 0.5f; +} + +static void nsvg__getLocalBounds(float* bounds, NSVGshape *shape, float* xform) +{ + NSVGpath* path; + float curve[4*2], curveBounds[4]; + int i, first = 1; + for (path = shape->paths; path != NULL; path = path->next) { + nsvg__xformPoint(&curve[0], &curve[1], path->pts[0], path->pts[1], xform); + for (i = 0; i < path->npts-1; i += 3) { + nsvg__xformPoint(&curve[2], &curve[3], path->pts[(i+1)*2], path->pts[(i+1)*2+1], xform); + nsvg__xformPoint(&curve[4], &curve[5], path->pts[(i+2)*2], path->pts[(i+2)*2+1], xform); + nsvg__xformPoint(&curve[6], &curve[7], path->pts[(i+3)*2], path->pts[(i+3)*2+1], xform); + nsvg__curveBounds(curveBounds, curve); + if (first) { + bounds[0] = curveBounds[0]; + bounds[1] = curveBounds[1]; + bounds[2] = curveBounds[2]; + bounds[3] = curveBounds[3]; + first = 0; + } else { + bounds[0] = nsvg__minf(bounds[0], curveBounds[0]); + bounds[1] = nsvg__minf(bounds[1], curveBounds[1]); + bounds[2] = nsvg__maxf(bounds[2], curveBounds[2]); + bounds[3] = nsvg__maxf(bounds[3], curveBounds[3]); + } + curve[0] = curve[6]; + curve[1] = curve[7]; + } + } +} + +static void nsvg__addShape(NSVGparser* p) +{ + NSVGattrib* attr = nsvg__getAttr(p); + float scale = 1.0f; + NSVGshape* shape; + NSVGpath* path; + int i; + + if (p->plist == NULL) + return; + + shape = (NSVGshape*)NANOSVG_malloc(sizeof(NSVGshape)); + if (shape == NULL) goto error; + memset(shape, 0, sizeof(NSVGshape)); + + memcpy(shape->id, attr->id, sizeof shape->id); + scale = nsvg__getAverageScale(attr->xform); + shape->strokeWidth = attr->strokeWidth * scale; + shape->strokeDashOffset = attr->strokeDashOffset * scale; + shape->strokeDashCount = (char)attr->strokeDashCount; + for (i = 0; i < attr->strokeDashCount; i++) + shape->strokeDashArray[i] = attr->strokeDashArray[i] * scale; + shape->strokeLineJoin = attr->strokeLineJoin; + shape->strokeLineCap = attr->strokeLineCap; + shape->miterLimit = attr->miterLimit; + shape->fillRule = attr->fillRule; + shape->opacity = attr->opacity; + + shape->paths = p->plist; + p->plist = NULL; + + // Calculate shape bounds + shape->bounds[0] = shape->paths->bounds[0]; + shape->bounds[1] = shape->paths->bounds[1]; + shape->bounds[2] = shape->paths->bounds[2]; + shape->bounds[3] = shape->paths->bounds[3]; + for (path = shape->paths->next; path != NULL; path = path->next) { + shape->bounds[0] = nsvg__minf(shape->bounds[0], path->bounds[0]); + shape->bounds[1] = nsvg__minf(shape->bounds[1], path->bounds[1]); + shape->bounds[2] = nsvg__maxf(shape->bounds[2], path->bounds[2]); + shape->bounds[3] = nsvg__maxf(shape->bounds[3], path->bounds[3]); + } + + // Set fill + if (attr->hasFill == 0) { + shape->fill.type = NSVG_PAINT_NONE; + } else if (attr->hasFill == 1) { + shape->fill.type = NSVG_PAINT_COLOR; + shape->fill.color = attr->fillColor; + shape->fill.color |= (unsigned int)(attr->fillOpacity*255) << 24; + } else if (attr->hasFill == 2) { + float inv[6], localBounds[4]; + nsvg__xformInverse(inv, attr->xform); + nsvg__getLocalBounds(localBounds, shape, inv); + shape->fill.gradient = nsvg__createGradient(p, attr->fillGradient, localBounds, &shape->fill.type); + if (shape->fill.gradient == NULL) { + shape->fill.type = NSVG_PAINT_NONE; + } + } + + // Set stroke + if (attr->hasStroke == 0) { + shape->stroke.type = NSVG_PAINT_NONE; + } else if (attr->hasStroke == 1) { + shape->stroke.type = NSVG_PAINT_COLOR; + shape->stroke.color = attr->strokeColor; + shape->stroke.color |= (unsigned int)(attr->strokeOpacity*255) << 24; + } else if (attr->hasStroke == 2) { + float inv[6], localBounds[4]; + nsvg__xformInverse(inv, attr->xform); + nsvg__getLocalBounds(localBounds, shape, inv); + shape->stroke.gradient = nsvg__createGradient(p, attr->strokeGradient, localBounds, &shape->stroke.type); + if (shape->stroke.gradient == NULL) + shape->stroke.type = NSVG_PAINT_NONE; + } + + // Set flags + shape->flags = ((attr->visible & NSVG_VIS_DISPLAY) && (attr->visible & NSVG_VIS_VISIBLE) ? NSVG_FLAGS_VISIBLE : 0x00); + + // Add to tail + if (p->image->shapes == NULL) + p->image->shapes = shape; + else + p->shapesTail->next = shape; + p->shapesTail = shape; + + return; + +error: + if (shape) NANOSVG_free(shape); +} + +static void nsvg__addPath(NSVGparser* p, char closed) +{ + NSVGattrib* attr = nsvg__getAttr(p); + NSVGpath* path = NULL; + float bounds[4]; + float* curve; + int i; + + if (p->npts < 4) + return; + + if (closed) + nsvg__lineTo(p, p->pts[0], p->pts[1]); + + path = (NSVGpath*)NANOSVG_malloc(sizeof(NSVGpath)); + if (path == NULL) goto error; + memset(path, 0, sizeof(NSVGpath)); + + path->pts = (float*)NANOSVG_malloc(p->npts*2*sizeof(float)); + if (path->pts == NULL) goto error; + path->closed = closed; + path->npts = p->npts; + + // Transform path. + for (i = 0; i < p->npts; ++i) + nsvg__xformPoint(&path->pts[i*2], &path->pts[i*2+1], p->pts[i*2], p->pts[i*2+1], attr->xform); + + // Find bounds + for (i = 0; i < path->npts-1; i += 3) { + curve = &path->pts[i*2]; + nsvg__curveBounds(bounds, curve); + if (i == 0) { + path->bounds[0] = bounds[0]; + path->bounds[1] = bounds[1]; + path->bounds[2] = bounds[2]; + path->bounds[3] = bounds[3]; + } else { + path->bounds[0] = nsvg__minf(path->bounds[0], bounds[0]); + path->bounds[1] = nsvg__minf(path->bounds[1], bounds[1]); + path->bounds[2] = nsvg__maxf(path->bounds[2], bounds[2]); + path->bounds[3] = nsvg__maxf(path->bounds[3], bounds[3]); + } + } + + path->next = p->plist; + p->plist = path; + + return; + +error: + if (path != NULL) { + if (path->pts != NULL) NANOSVG_free(path->pts); + NANOSVG_free(path); + } +} + +// We roll our own string to float because the std library one uses locale and messes things up. +static double nsvg__atof(const char* s) +{ + char* cur = (char*)s; + char* end = NULL; + double res = 0.0, sign = 1.0; + long long intPart = 0, fracPart = 0; + char hasIntPart = 0, hasFracPart = 0; + + // Parse optional sign + if (*cur == '+') { + cur++; + } else if (*cur == '-') { + sign = -1; + cur++; + } + + // Parse integer part + if (nsvg__isdigit(*cur)) { + // Parse digit sequence + intPart = (double)strtoll(cur, &end, 10); + if (cur != end) { + res = (double)intPart; + hasIntPart = 1; + cur = end; + } + } + + // Parse fractional part. + if (*cur == '.') { + cur++; // Skip '.' + if (nsvg__isdigit(*cur)) { + // Parse digit sequence + fracPart = strtoll(cur, &end, 10); + if (cur != end) { + res += (double)fracPart / pow(10.0, (double)(end - cur)); + hasFracPart = 1; + cur = end; + } + } + } + + // A valid number should have integer or fractional part. + if (!hasIntPart && !hasFracPart) + return 0.0; + + // Parse optional exponent + if (*cur == 'e' || *cur == 'E') { + int expPart = 0; + cur++; // skip 'E' + expPart = strtol(cur, &end, 10); // Parse digit sequence with sign + if (cur != end) { + res *= pow(10.0, (double)expPart); + } + } + + return res * sign; +} + + +static const char* nsvg__parseNumber(const char* s, char* it, const int size) +{ + const int last = size-1; + int i = 0; + + // sign + if (*s == '-' || *s == '+') { + if (i < last) it[i++] = *s; + s++; + } + // integer part + while (*s && nsvg__isdigit(*s)) { + if (i < last) it[i++] = *s; + s++; + } + if (*s == '.') { + // decimal point + if (i < last) it[i++] = *s; + s++; + // fraction part + while (*s && nsvg__isdigit(*s)) { + if (i < last) it[i++] = *s; + s++; + } + } + // exponent + if (*s == 'e' || *s == 'E') { + if (i < last) it[i++] = *s; + s++; + if (*s == '-' || *s == '+') { + if (i < last) it[i++] = *s; + s++; + } + while (*s && nsvg__isdigit(*s)) { + if (i < last) it[i++] = *s; + s++; + } + } + it[i] = '\0'; + + return s; +} + +static const char* nsvg__getNextPathItem(const char* s, char* it) +{ + it[0] = '\0'; + // Skip white spaces and commas + while (*s && (nsvg__isspace(*s) || *s == ',')) s++; + if (!*s) return s; + if (*s == '-' || *s == '+' || *s == '.' || nsvg__isdigit(*s)) { + s = nsvg__parseNumber(s, it, 64); + } else { + // Parse command + it[0] = *s++; + it[1] = '\0'; + return s; + } + + return s; +} + +static unsigned int nsvg__parseColorHex(const char* str) +{ + unsigned int c = 0, r = 0, g = 0, b = 0; + int n = 0; + str++; // skip # + // Calculate number of characters. + while(str[n] && !nsvg__isspace(str[n])) + n++; + if (n == 6) { + sscanf(str, "%x", &c); + } else if (n == 3) { + sscanf(str, "%x", &c); + c = (c&0xf) | ((c&0xf0) << 4) | ((c&0xf00) << 8); + c |= c<<4; + } + r = (c >> 16) & 0xff; + g = (c >> 8) & 0xff; + b = c & 0xff; + return NSVG_RGB(r,g,b); +} + +static unsigned int nsvg__parseColorRGB(const char* str) +{ + int r = -1, g = -1, b = -1; + char s1[32]="", s2[32]=""; + sscanf(str + 4, "%d%[%%, \t]%d%[%%, \t]%d", &r, s1, &g, s2, &b); + if (strchr(s1, '%')) { + return NSVG_RGB((r*255)/100,(g*255)/100,(b*255)/100); + } else { + return NSVG_RGB(r,g,b); + } +} + +typedef struct NSVGNamedColor { + const char* name; + unsigned int color; +} NSVGNamedColor; + +NSVGNamedColor nsvg__colors[] = { + + { "red", NSVG_RGB(255, 0, 0) }, + { "green", NSVG_RGB( 0, 128, 0) }, + { "blue", NSVG_RGB( 0, 0, 255) }, + { "yellow", NSVG_RGB(255, 255, 0) }, + { "cyan", NSVG_RGB( 0, 255, 255) }, + { "magenta", NSVG_RGB(255, 0, 255) }, + { "black", NSVG_RGB( 0, 0, 0) }, + { "grey", NSVG_RGB(128, 128, 128) }, + { "gray", NSVG_RGB(128, 128, 128) }, + { "white", NSVG_RGB(255, 255, 255) }, + +#ifdef NANOSVG_ALL_COLOR_KEYWORDS + { "aliceblue", NSVG_RGB(240, 248, 255) }, + { "antiquewhite", NSVG_RGB(250, 235, 215) }, + { "aqua", NSVG_RGB( 0, 255, 255) }, + { "aquamarine", NSVG_RGB(127, 255, 212) }, + { "azure", NSVG_RGB(240, 255, 255) }, + { "beige", NSVG_RGB(245, 245, 220) }, + { "bisque", NSVG_RGB(255, 228, 196) }, + { "blanchedalmond", NSVG_RGB(255, 235, 205) }, + { "blueviolet", NSVG_RGB(138, 43, 226) }, + { "brown", NSVG_RGB(165, 42, 42) }, + { "burlywood", NSVG_RGB(222, 184, 135) }, + { "cadetblue", NSVG_RGB( 95, 158, 160) }, + { "chartreuse", NSVG_RGB(127, 255, 0) }, + { "chocolate", NSVG_RGB(210, 105, 30) }, + { "coral", NSVG_RGB(255, 127, 80) }, + { "cornflowerblue", NSVG_RGB(100, 149, 237) }, + { "cornsilk", NSVG_RGB(255, 248, 220) }, + { "crimson", NSVG_RGB(220, 20, 60) }, + { "darkblue", NSVG_RGB( 0, 0, 139) }, + { "darkcyan", NSVG_RGB( 0, 139, 139) }, + { "darkgoldenrod", NSVG_RGB(184, 134, 11) }, + { "darkgray", NSVG_RGB(169, 169, 169) }, + { "darkgreen", NSVG_RGB( 0, 100, 0) }, + { "darkgrey", NSVG_RGB(169, 169, 169) }, + { "darkkhaki", NSVG_RGB(189, 183, 107) }, + { "darkmagenta", NSVG_RGB(139, 0, 139) }, + { "darkolivegreen", NSVG_RGB( 85, 107, 47) }, + { "darkorange", NSVG_RGB(255, 140, 0) }, + { "darkorchid", NSVG_RGB(153, 50, 204) }, + { "darkred", NSVG_RGB(139, 0, 0) }, + { "darksalmon", NSVG_RGB(233, 150, 122) }, + { "darkseagreen", NSVG_RGB(143, 188, 143) }, + { "darkslateblue", NSVG_RGB( 72, 61, 139) }, + { "darkslategray", NSVG_RGB( 47, 79, 79) }, + { "darkslategrey", NSVG_RGB( 47, 79, 79) }, + { "darkturquoise", NSVG_RGB( 0, 206, 209) }, + { "darkviolet", NSVG_RGB(148, 0, 211) }, + { "deeppink", NSVG_RGB(255, 20, 147) }, + { "deepskyblue", NSVG_RGB( 0, 191, 255) }, + { "dimgray", NSVG_RGB(105, 105, 105) }, + { "dimgrey", NSVG_RGB(105, 105, 105) }, + { "dodgerblue", NSVG_RGB( 30, 144, 255) }, + { "firebrick", NSVG_RGB(178, 34, 34) }, + { "floralwhite", NSVG_RGB(255, 250, 240) }, + { "forestgreen", NSVG_RGB( 34, 139, 34) }, + { "fuchsia", NSVG_RGB(255, 0, 255) }, + { "gainsboro", NSVG_RGB(220, 220, 220) }, + { "ghostwhite", NSVG_RGB(248, 248, 255) }, + { "gold", NSVG_RGB(255, 215, 0) }, + { "goldenrod", NSVG_RGB(218, 165, 32) }, + { "greenyellow", NSVG_RGB(173, 255, 47) }, + { "honeydew", NSVG_RGB(240, 255, 240) }, + { "hotpink", NSVG_RGB(255, 105, 180) }, + { "indianred", NSVG_RGB(205, 92, 92) }, + { "indigo", NSVG_RGB( 75, 0, 130) }, + { "ivory", NSVG_RGB(255, 255, 240) }, + { "khaki", NSVG_RGB(240, 230, 140) }, + { "lavender", NSVG_RGB(230, 230, 250) }, + { "lavenderblush", NSVG_RGB(255, 240, 245) }, + { "lawngreen", NSVG_RGB(124, 252, 0) }, + { "lemonchiffon", NSVG_RGB(255, 250, 205) }, + { "lightblue", NSVG_RGB(173, 216, 230) }, + { "lightcoral", NSVG_RGB(240, 128, 128) }, + { "lightcyan", NSVG_RGB(224, 255, 255) }, + { "lightgoldenrodyellow", NSVG_RGB(250, 250, 210) }, + { "lightgray", NSVG_RGB(211, 211, 211) }, + { "lightgreen", NSVG_RGB(144, 238, 144) }, + { "lightgrey", NSVG_RGB(211, 211, 211) }, + { "lightpink", NSVG_RGB(255, 182, 193) }, + { "lightsalmon", NSVG_RGB(255, 160, 122) }, + { "lightseagreen", NSVG_RGB( 32, 178, 170) }, + { "lightskyblue", NSVG_RGB(135, 206, 250) }, + { "lightslategray", NSVG_RGB(119, 136, 153) }, + { "lightslategrey", NSVG_RGB(119, 136, 153) }, + { "lightsteelblue", NSVG_RGB(176, 196, 222) }, + { "lightyellow", NSVG_RGB(255, 255, 224) }, + { "lime", NSVG_RGB( 0, 255, 0) }, + { "limegreen", NSVG_RGB( 50, 205, 50) }, + { "linen", NSVG_RGB(250, 240, 230) }, + { "maroon", NSVG_RGB(128, 0, 0) }, + { "mediumaquamarine", NSVG_RGB(102, 205, 170) }, + { "mediumblue", NSVG_RGB( 0, 0, 205) }, + { "mediumorchid", NSVG_RGB(186, 85, 211) }, + { "mediumpurple", NSVG_RGB(147, 112, 219) }, + { "mediumseagreen", NSVG_RGB( 60, 179, 113) }, + { "mediumslateblue", NSVG_RGB(123, 104, 238) }, + { "mediumspringgreen", NSVG_RGB( 0, 250, 154) }, + { "mediumturquoise", NSVG_RGB( 72, 209, 204) }, + { "mediumvioletred", NSVG_RGB(199, 21, 133) }, + { "midnightblue", NSVG_RGB( 25, 25, 112) }, + { "mintcream", NSVG_RGB(245, 255, 250) }, + { "mistyrose", NSVG_RGB(255, 228, 225) }, + { "moccasin", NSVG_RGB(255, 228, 181) }, + { "navajowhite", NSVG_RGB(255, 222, 173) }, + { "navy", NSVG_RGB( 0, 0, 128) }, + { "oldlace", NSVG_RGB(253, 245, 230) }, + { "olive", NSVG_RGB(128, 128, 0) }, + { "olivedrab", NSVG_RGB(107, 142, 35) }, + { "orange", NSVG_RGB(255, 165, 0) }, + { "orangered", NSVG_RGB(255, 69, 0) }, + { "orchid", NSVG_RGB(218, 112, 214) }, + { "palegoldenrod", NSVG_RGB(238, 232, 170) }, + { "palegreen", NSVG_RGB(152, 251, 152) }, + { "paleturquoise", NSVG_RGB(175, 238, 238) }, + { "palevioletred", NSVG_RGB(219, 112, 147) }, + { "papayawhip", NSVG_RGB(255, 239, 213) }, + { "peachpuff", NSVG_RGB(255, 218, 185) }, + { "peru", NSVG_RGB(205, 133, 63) }, + { "pink", NSVG_RGB(255, 192, 203) }, + { "plum", NSVG_RGB(221, 160, 221) }, + { "powderblue", NSVG_RGB(176, 224, 230) }, + { "purple", NSVG_RGB(128, 0, 128) }, + { "rosybrown", NSVG_RGB(188, 143, 143) }, + { "royalblue", NSVG_RGB( 65, 105, 225) }, + { "saddlebrown", NSVG_RGB(139, 69, 19) }, + { "salmon", NSVG_RGB(250, 128, 114) }, + { "sandybrown", NSVG_RGB(244, 164, 96) }, + { "seagreen", NSVG_RGB( 46, 139, 87) }, + { "seashell", NSVG_RGB(255, 245, 238) }, + { "sienna", NSVG_RGB(160, 82, 45) }, + { "silver", NSVG_RGB(192, 192, 192) }, + { "skyblue", NSVG_RGB(135, 206, 235) }, + { "slateblue", NSVG_RGB(106, 90, 205) }, + { "slategray", NSVG_RGB(112, 128, 144) }, + { "slategrey", NSVG_RGB(112, 128, 144) }, + { "snow", NSVG_RGB(255, 250, 250) }, + { "springgreen", NSVG_RGB( 0, 255, 127) }, + { "steelblue", NSVG_RGB( 70, 130, 180) }, + { "tan", NSVG_RGB(210, 180, 140) }, + { "teal", NSVG_RGB( 0, 128, 128) }, + { "thistle", NSVG_RGB(216, 191, 216) }, + { "tomato", NSVG_RGB(255, 99, 71) }, + { "turquoise", NSVG_RGB( 64, 224, 208) }, + { "violet", NSVG_RGB(238, 130, 238) }, + { "wheat", NSVG_RGB(245, 222, 179) }, + { "whitesmoke", NSVG_RGB(245, 245, 245) }, + { "yellowgreen", NSVG_RGB(154, 205, 50) }, +#endif +}; + +static unsigned int nsvg__parseColorName(const char* str) +{ + int i, ncolors = sizeof(nsvg__colors) / sizeof(NSVGNamedColor); + + for (i = 0; i < ncolors; i++) { + if (strcmp(nsvg__colors[i].name, str) == 0) { + return nsvg__colors[i].color; + } + } + + return NSVG_RGB(128, 128, 128); +} + +static unsigned int nsvg__parseColor(const char* str) +{ + size_t len = 0; + while(*str == ' ') ++str; + len = strlen(str); + if (len >= 1 && *str == '#') + return nsvg__parseColorHex(str); + else if (len >= 4 && str[0] == 'r' && str[1] == 'g' && str[2] == 'b' && str[3] == '(') + return nsvg__parseColorRGB(str); + return nsvg__parseColorName(str); +} + +static float nsvg__parseOpacity(const char* str) +{ + float val = 0; + sscanf(str, "%f", &val); + if (val < 0.0f) val = 0.0f; + if (val > 1.0f) val = 1.0f; + return val; +} + +static float nsvg__parseMiterLimit(const char* str) +{ + float val = 0; + sscanf(str, "%f", &val); + if (val < 0.0f) val = 0.0f; + return val; +} + +static int nsvg__parseUnits(const char* units) +{ + if (units[0] == 'p' && units[1] == 'x') + return NSVG_UNITS_PX; + else if (units[0] == 'p' && units[1] == 't') + return NSVG_UNITS_PT; + else if (units[0] == 'p' && units[1] == 'c') + return NSVG_UNITS_PC; + else if (units[0] == 'm' && units[1] == 'm') + return NSVG_UNITS_MM; + else if (units[0] == 'c' && units[1] == 'm') + return NSVG_UNITS_CM; + else if (units[0] == 'i' && units[1] == 'n') + return NSVG_UNITS_IN; + else if (units[0] == '%') + return NSVG_UNITS_PERCENT; + else if (units[0] == 'e' && units[1] == 'm') + return NSVG_UNITS_EM; + else if (units[0] == 'e' && units[1] == 'x') + return NSVG_UNITS_EX; + return NSVG_UNITS_USER; +} + +static NSVGcoordinate nsvg__parseCoordinateRaw(const char* str) +{ + NSVGcoordinate coord = {0, NSVG_UNITS_USER}; + char units[32]=""; + sscanf(str, "%f%s", &coord.value, units); + coord.units = nsvg__parseUnits(units); + return coord; +} + +static NSVGcoordinate nsvg__coord(float v, int units) +{ + NSVGcoordinate coord = {v, units}; + return coord; +} + +static float nsvg__parseCoordinate(NSVGparser* p, const char* str, float orig, float length) +{ + NSVGcoordinate coord = nsvg__parseCoordinateRaw(str); + return nsvg__convertToPixels(p, coord, orig, length); +} + +static int nsvg__parseTransformArgs(const char* str, float* args, int maxNa, int* na) +{ + const char* end; + const char* ptr; + char it[64]; + + *na = 0; + ptr = str; + while (*ptr && *ptr != '(') ++ptr; + if (*ptr == 0) + return 1; + end = ptr; + while (*end && *end != ')') ++end; + if (*end == 0) + return 1; + + while (ptr < end) { + if (*ptr == '-' || *ptr == '+' || *ptr == '.' || nsvg__isdigit(*ptr)) { + if (*na >= maxNa) return 0; + ptr = nsvg__parseNumber(ptr, it, 64); + args[(*na)++] = (float)nsvg__atof(it); + } else { + ++ptr; + } + } + return (int)(end - str); +} + + +static int nsvg__parseMatrix(float* xform, const char* str) +{ + float t[6]; + int na = 0; + int len = nsvg__parseTransformArgs(str, t, 6, &na); + if (na != 6) return len; + memcpy(xform, t, sizeof(float)*6); + return len; +} + +static int nsvg__parseTranslate(float* xform, const char* str) +{ + float args[2]; + float t[6]; + int na = 0; + int len = nsvg__parseTransformArgs(str, args, 2, &na); + if (na == 1) args[1] = 0.0; + + nsvg__xformSetTranslation(t, args[0], args[1]); + memcpy(xform, t, sizeof(float)*6); + return len; +} + +static int nsvg__parseScale(float* xform, const char* str) +{ + float args[2]; + int na = 0; + float t[6]; + int len = nsvg__parseTransformArgs(str, args, 2, &na); + if (na == 1) args[1] = args[0]; + nsvg__xformSetScale(t, args[0], args[1]); + memcpy(xform, t, sizeof(float)*6); + return len; +} + +static int nsvg__parseSkewX(float* xform, const char* str) +{ + float args[1]; + int na = 0; + float t[6]; + int len = nsvg__parseTransformArgs(str, args, 1, &na); + nsvg__xformSetSkewX(t, args[0]/180.0f*NSVG_PI); + memcpy(xform, t, sizeof(float)*6); + return len; +} + +static int nsvg__parseSkewY(float* xform, const char* str) +{ + float args[1]; + int na = 0; + float t[6]; + int len = nsvg__parseTransformArgs(str, args, 1, &na); + nsvg__xformSetSkewY(t, args[0]/180.0f*NSVG_PI); + memcpy(xform, t, sizeof(float)*6); + return len; +} + +static int nsvg__parseRotate(float* xform, const char* str) +{ + float args[3]; + int na = 0; + float m[6]; + float t[6]; + int len = nsvg__parseTransformArgs(str, args, 3, &na); + if (na == 1) + args[1] = args[2] = 0.0f; + nsvg__xformIdentity(m); + + if (na > 1) { + nsvg__xformSetTranslation(t, -args[1], -args[2]); + nsvg__xformMultiply(m, t); + } + + nsvg__xformSetRotation(t, args[0]/180.0f*NSVG_PI); + nsvg__xformMultiply(m, t); + + if (na > 1) { + nsvg__xformSetTranslation(t, args[1], args[2]); + nsvg__xformMultiply(m, t); + } + + memcpy(xform, m, sizeof(float)*6); + + return len; +} + +static void nsvg__parseTransform(float* xform, const char* str) +{ + float t[6]; + nsvg__xformIdentity(xform); + while (*str) + { + if (strncmp(str, "matrix", 6) == 0) + str += nsvg__parseMatrix(t, str); + else if (strncmp(str, "translate", 9) == 0) + str += nsvg__parseTranslate(t, str); + else if (strncmp(str, "scale", 5) == 0) + str += nsvg__parseScale(t, str); + else if (strncmp(str, "rotate", 6) == 0) + str += nsvg__parseRotate(t, str); + else if (strncmp(str, "skewX", 5) == 0) + str += nsvg__parseSkewX(t, str); + else if (strncmp(str, "skewY", 5) == 0) + str += nsvg__parseSkewY(t, str); + else{ + ++str; + continue; + } + + nsvg__xformPremultiply(xform, t); + } +} + +static void nsvg__parseUrl(char* id, const char* str) +{ + int i = 0; + str += 4; // "url("; + if (*str == '#') + str++; + while (i < 63 && *str != ')') { + id[i] = *str++; + i++; + } + id[i] = '\0'; +} + +static char nsvg__parseLineCap(const char* str) +{ + if (strcmp(str, "butt") == 0) + return NSVG_CAP_BUTT; + else if (strcmp(str, "round") == 0) + return NSVG_CAP_ROUND; + else if (strcmp(str, "square") == 0) + return NSVG_CAP_SQUARE; + // TODO: handle inherit. + return NSVG_CAP_BUTT; +} + +static char nsvg__parseLineJoin(const char* str) +{ + if (strcmp(str, "miter") == 0) + return NSVG_JOIN_MITER; + else if (strcmp(str, "round") == 0) + return NSVG_JOIN_ROUND; + else if (strcmp(str, "bevel") == 0) + return NSVG_JOIN_BEVEL; + // TODO: handle inherit. + return NSVG_JOIN_MITER; +} + +static char nsvg__parseFillRule(const char* str) +{ + if (strcmp(str, "nonzero") == 0) + return NSVG_FILLRULE_NONZERO; + else if (strcmp(str, "evenodd") == 0) + return NSVG_FILLRULE_EVENODD; + // TODO: handle inherit. + return NSVG_FILLRULE_NONZERO; +} + +static const char* nsvg__getNextDashItem(const char* s, char* it) +{ + int n = 0; + it[0] = '\0'; + // Skip white spaces and commas + while (*s && (nsvg__isspace(*s) || *s == ',')) s++; + // Advance until whitespace, comma or end. + while (*s && (!nsvg__isspace(*s) && *s != ',')) { + if (n < 63) + it[n++] = *s; + s++; + } + it[n++] = '\0'; + return s; +} + +static int nsvg__parseStrokeDashArray(NSVGparser* p, const char* str, float* strokeDashArray) +{ + char item[64]; + int count = 0, i; + float sum = 0.0f; + + // Handle "none" + if (str[0] == 'n') + return 0; + + // Parse dashes + while (*str) { + str = nsvg__getNextDashItem(str, item); + if (!*item) break; + if (count < NSVG_MAX_DASHES) + strokeDashArray[count++] = fabsf(nsvg__parseCoordinate(p, item, 0.0f, nsvg__actualLength(p))); + } + + for (i = 0; i < count; i++) + sum += strokeDashArray[i]; + if (sum <= 1e-6f) + count = 0; + + return count; +} + +static void nsvg__parseStyle(NSVGparser* p, const char* str); + +static int nsvg__parseAttr(NSVGparser* p, const char* name, const char* value) +{ + float xform[6]; + NSVGattrib* attr = nsvg__getAttr(p); + if (!attr) return 0; + + if (strcmp(name, "style") == 0) { + nsvg__parseStyle(p, value); + } else if (strcmp(name, "display") == 0) { + if (strcmp(value, "none") == 0) + attr->visible &= ~NSVG_VIS_DISPLAY; + // Don't reset ->visible on display:inline, one display:none hides the whole subtree + + } else if (strcmp(name, "visibility") == 0) { + if (strcmp(value, "hidden") == 0) { + attr->visible &= ~NSVG_VIS_VISIBLE; + } else if (strcmp(value, "visible") == 0) { + attr->visible |= NSVG_VIS_VISIBLE; + } + } else if (strcmp(name, "fill") == 0) { + if (strcmp(value, "none") == 0) { + attr->hasFill = 0; + } else if (strncmp(value, "url(", 4) == 0) { + attr->hasFill = 2; + nsvg__parseUrl(attr->fillGradient, value); + } else { + attr->hasFill = 1; + attr->fillColor = nsvg__parseColor(value); + } + } else if (strcmp(name, "opacity") == 0) { + attr->opacity = nsvg__parseOpacity(value); + } else if (strcmp(name, "fill-opacity") == 0) { + attr->fillOpacity = nsvg__parseOpacity(value); + } else if (strcmp(name, "stroke") == 0) { + if (strcmp(value, "none") == 0) { + attr->hasStroke = 0; + } else if (strncmp(value, "url(", 4) == 0) { + attr->hasStroke = 2; + nsvg__parseUrl(attr->strokeGradient, value); + } else { + attr->hasStroke = 1; + attr->strokeColor = nsvg__parseColor(value); + } + } else if (strcmp(name, "stroke-width") == 0) { + attr->strokeWidth = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p)); + } else if (strcmp(name, "stroke-dasharray") == 0) { + attr->strokeDashCount = nsvg__parseStrokeDashArray(p, value, attr->strokeDashArray); + } else if (strcmp(name, "stroke-dashoffset") == 0) { + attr->strokeDashOffset = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p)); + } else if (strcmp(name, "stroke-opacity") == 0) { + attr->strokeOpacity = nsvg__parseOpacity(value); + } else if (strcmp(name, "stroke-linecap") == 0) { + attr->strokeLineCap = nsvg__parseLineCap(value); + } else if (strcmp(name, "stroke-linejoin") == 0) { + attr->strokeLineJoin = nsvg__parseLineJoin(value); + } else if (strcmp(name, "stroke-miterlimit") == 0) { + attr->miterLimit = nsvg__parseMiterLimit(value); + } else if (strcmp(name, "fill-rule") == 0) { + attr->fillRule = nsvg__parseFillRule(value); + } else if (strcmp(name, "font-size") == 0) { + attr->fontSize = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p)); + } else if (strcmp(name, "transform") == 0) { + nsvg__parseTransform(xform, value); + nsvg__xformPremultiply(attr->xform, xform); + } else if (strcmp(name, "stop-color") == 0) { + attr->stopColor = nsvg__parseColor(value); + } else if (strcmp(name, "stop-opacity") == 0) { + attr->stopOpacity = nsvg__parseOpacity(value); + } else if (strcmp(name, "offset") == 0) { + attr->stopOffset = nsvg__parseCoordinate(p, value, 0.0f, 1.0f); + } else if (strcmp(name, "id") == 0) { + strncpy(attr->id, value, 63); + attr->id[63] = '\0'; + } else if (strcmp(name, "class") == 0) { + NSVGstyles* style = p->styles; + while (style) { + if (strcmp(style->name + 1, value) == 0) { + break; + } + style = style->next; + } + if (style) { + nsvg__parseStyle(p, style->description); + } + } else { + return 0; + } + return 1; +} + +static int nsvg__parseNameValue(NSVGparser* p, const char* start, const char* end) +{ + const char* str; + const char* val; + char name[512]; + char value[512]; + int n; + + str = start; + while (str < end && *str != ':') ++str; + + val = str; + + // Right Trim + while (str > start && (*str == ':' || nsvg__isspace(*str))) --str; + ++str; + + n = (int)(str - start); + if (n > 511) n = 511; + if (n) memcpy(name, start, n); + name[n] = 0; + + while (val < end && (*val == ':' || nsvg__isspace(*val))) ++val; + + n = (int)(end - val); + if (n > 511) n = 511; + if (n) memcpy(value, val, n); + value[n] = 0; + + return nsvg__parseAttr(p, name, value); +} + +static void nsvg__parseStyle(NSVGparser* p, const char* str) +{ + const char* start; + const char* end; + + while (*str) { + // Left Trim + while(*str && nsvg__isspace(*str)) ++str; + start = str; + while(*str && *str != ';') ++str; + end = str; + + // Right Trim + while (end > start && (*end == ';' || nsvg__isspace(*end))) --end; + ++end; + + nsvg__parseNameValue(p, start, end); + if (*str) ++str; + } +} + +static void nsvg__parseAttribs(NSVGparser* p, const char** attr) +{ + int i; + for (i = 0; attr[i]; i += 2) + { + if (strcmp(attr[i], "style") == 0) + nsvg__parseStyle(p, attr[i + 1]); + else + nsvg__parseAttr(p, attr[i], attr[i + 1]); + } +} + +static int nsvg__getArgsPerElement(char cmd) +{ + switch (cmd) { + case 'v': + case 'V': + case 'h': + case 'H': + return 1; + case 'm': + case 'M': + case 'l': + case 'L': + case 't': + case 'T': + return 2; + case 'q': + case 'Q': + case 's': + case 'S': + return 4; + case 'c': + case 'C': + return 6; + case 'a': + case 'A': + return 7; + } + return 0; +} + +static void nsvg__pathMoveTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) +{ + if (rel) { + *cpx += args[0]; + *cpy += args[1]; + } else { + *cpx = args[0]; + *cpy = args[1]; + } + nsvg__moveTo(p, *cpx, *cpy); +} + +static void nsvg__pathLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) +{ + if (rel) { + *cpx += args[0]; + *cpy += args[1]; + } else { + *cpx = args[0]; + *cpy = args[1]; + } + nsvg__lineTo(p, *cpx, *cpy); +} + +static void nsvg__pathHLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) +{ + if (rel) + *cpx += args[0]; + else + *cpx = args[0]; + nsvg__lineTo(p, *cpx, *cpy); +} + +static void nsvg__pathVLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) +{ + if (rel) + *cpy += args[0]; + else + *cpy = args[0]; + nsvg__lineTo(p, *cpx, *cpy); +} + +static void nsvg__pathCubicBezTo(NSVGparser* p, float* cpx, float* cpy, + float* cpx2, float* cpy2, float* args, int rel) +{ + float x2, y2, cx1, cy1, cx2, cy2; + + if (rel) { + cx1 = *cpx + args[0]; + cy1 = *cpy + args[1]; + cx2 = *cpx + args[2]; + cy2 = *cpy + args[3]; + x2 = *cpx + args[4]; + y2 = *cpy + args[5]; + } else { + cx1 = args[0]; + cy1 = args[1]; + cx2 = args[2]; + cy2 = args[3]; + x2 = args[4]; + y2 = args[5]; + } + + nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); + + *cpx2 = cx2; + *cpy2 = cy2; + *cpx = x2; + *cpy = y2; +} + +static void nsvg__pathCubicBezShortTo(NSVGparser* p, float* cpx, float* cpy, + float* cpx2, float* cpy2, float* args, int rel) +{ + float x1, y1, x2, y2, cx1, cy1, cx2, cy2; + + x1 = *cpx; + y1 = *cpy; + if (rel) { + cx2 = *cpx + args[0]; + cy2 = *cpy + args[1]; + x2 = *cpx + args[2]; + y2 = *cpy + args[3]; + } else { + cx2 = args[0]; + cy2 = args[1]; + x2 = args[2]; + y2 = args[3]; + } + + cx1 = 2*x1 - *cpx2; + cy1 = 2*y1 - *cpy2; + + nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); + + *cpx2 = cx2; + *cpy2 = cy2; + *cpx = x2; + *cpy = y2; +} + +static void nsvg__pathQuadBezTo(NSVGparser* p, float* cpx, float* cpy, + float* cpx2, float* cpy2, float* args, int rel) +{ + float x1, y1, x2, y2, cx, cy; + float cx1, cy1, cx2, cy2; + + x1 = *cpx; + y1 = *cpy; + if (rel) { + cx = *cpx + args[0]; + cy = *cpy + args[1]; + x2 = *cpx + args[2]; + y2 = *cpy + args[3]; + } else { + cx = args[0]; + cy = args[1]; + x2 = args[2]; + y2 = args[3]; + } + + // Convert to cubic bezier + cx1 = x1 + 2.0f/3.0f*(cx - x1); + cy1 = y1 + 2.0f/3.0f*(cy - y1); + cx2 = x2 + 2.0f/3.0f*(cx - x2); + cy2 = y2 + 2.0f/3.0f*(cy - y2); + + nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); + + *cpx2 = cx; + *cpy2 = cy; + *cpx = x2; + *cpy = y2; +} + +static void nsvg__pathQuadBezShortTo(NSVGparser* p, float* cpx, float* cpy, + float* cpx2, float* cpy2, float* args, int rel) +{ + float x1, y1, x2, y2, cx, cy; + float cx1, cy1, cx2, cy2; + + x1 = *cpx; + y1 = *cpy; + if (rel) { + x2 = *cpx + args[0]; + y2 = *cpy + args[1]; + } else { + x2 = args[0]; + y2 = args[1]; + } + + cx = 2*x1 - *cpx2; + cy = 2*y1 - *cpy2; + + // Convert to cubix bezier + cx1 = x1 + 2.0f/3.0f*(cx - x1); + cy1 = y1 + 2.0f/3.0f*(cy - y1); + cx2 = x2 + 2.0f/3.0f*(cx - x2); + cy2 = y2 + 2.0f/3.0f*(cy - y2); + + nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); + + *cpx2 = cx; + *cpy2 = cy; + *cpx = x2; + *cpy = y2; +} + +static float nsvg__sqr(float x) { return x*x; } +static float nsvg__vmag(float x, float y) { return sqrtf(x*x + y*y); } + +static float nsvg__vecrat(float ux, float uy, float vx, float vy) +{ + return (ux*vx + uy*vy) / (nsvg__vmag(ux,uy) * nsvg__vmag(vx,vy)); +} + +static float nsvg__vecang(float ux, float uy, float vx, float vy) +{ + float r = nsvg__vecrat(ux,uy, vx,vy); + if (r < -1.0f) r = -1.0f; + if (r > 1.0f) r = 1.0f; + return ((ux*vy < uy*vx) ? -1.0f : 1.0f) * acosf(r); +} + +static void nsvg__pathArcTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) +{ + // Ported from canvg (https://code.google.com/p/canvg/) + float rx, ry, rotx; + float x1, y1, x2, y2, cx, cy, dx, dy, d; + float x1p, y1p, cxp, cyp, s, sa, sb; + float ux, uy, vx, vy, a1, da; + float x, y, tanx, tany, a, px = 0, py = 0, ptanx = 0, ptany = 0, t[6]; + float sinrx, cosrx; + int fa, fs; + int i, ndivs; + float hda, kappa; + + rx = fabsf(args[0]); // y radius + ry = fabsf(args[1]); // x radius + rotx = args[2] / 180.0f * NSVG_PI; // x rotation angle + fa = fabsf(args[3]) > 1e-6 ? 1 : 0; // Large arc + fs = fabsf(args[4]) > 1e-6 ? 1 : 0; // Sweep direction + x1 = *cpx; // start point + y1 = *cpy; + if (rel) { // end point + x2 = *cpx + args[5]; + y2 = *cpy + args[6]; + } else { + x2 = args[5]; + y2 = args[6]; + } + + dx = x1 - x2; + dy = y1 - y2; + d = sqrtf(dx*dx + dy*dy); + if (d < 1e-6f || rx < 1e-6f || ry < 1e-6f) { + // The arc degenerates to a line + nsvg__lineTo(p, x2, y2); + *cpx = x2; + *cpy = y2; + return; + } + + sinrx = sinf(rotx); + cosrx = cosf(rotx); + + // Convert to center point parameterization. + // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes + // 1) Compute x1', y1' + x1p = cosrx * dx / 2.0f + sinrx * dy / 2.0f; + y1p = -sinrx * dx / 2.0f + cosrx * dy / 2.0f; + d = nsvg__sqr(x1p)/nsvg__sqr(rx) + nsvg__sqr(y1p)/nsvg__sqr(ry); + if (d > 1) { + d = sqrtf(d); + rx *= d; + ry *= d; + } + // 2) Compute cx', cy' + s = 0.0f; + sa = nsvg__sqr(rx)*nsvg__sqr(ry) - nsvg__sqr(rx)*nsvg__sqr(y1p) - nsvg__sqr(ry)*nsvg__sqr(x1p); + sb = nsvg__sqr(rx)*nsvg__sqr(y1p) + nsvg__sqr(ry)*nsvg__sqr(x1p); + if (sa < 0.0f) sa = 0.0f; + if (sb > 0.0f) + s = sqrtf(sa / sb); + if (fa == fs) + s = -s; + cxp = s * rx * y1p / ry; + cyp = s * -ry * x1p / rx; + + // 3) Compute cx,cy from cx',cy' + cx = (x1 + x2)/2.0f + cosrx*cxp - sinrx*cyp; + cy = (y1 + y2)/2.0f + sinrx*cxp + cosrx*cyp; + + // 4) Calculate theta1, and delta theta. + ux = (x1p - cxp) / rx; + uy = (y1p - cyp) / ry; + vx = (-x1p - cxp) / rx; + vy = (-y1p - cyp) / ry; + a1 = nsvg__vecang(1.0f,0.0f, ux,uy); // Initial angle + da = nsvg__vecang(ux,uy, vx,vy); // Delta angle + +// if (vecrat(ux,uy,vx,vy) <= -1.0f) da = NSVG_PI; +// if (vecrat(ux,uy,vx,vy) >= 1.0f) da = 0; + + if (fs == 0 && da > 0) + da -= 2 * NSVG_PI; + else if (fs == 1 && da < 0) + da += 2 * NSVG_PI; + + // Approximate the arc using cubic spline segments. + t[0] = cosrx; t[1] = sinrx; + t[2] = -sinrx; t[3] = cosrx; + t[4] = cx; t[5] = cy; + + // Split arc into max 90 degree segments. + // The loop assumes an iteration per end point (including start and end), this +1. + ndivs = (int)(fabsf(da) / (NSVG_PI*0.5f) + 1.0f); + hda = (da / (float)ndivs) / 2.0f; + kappa = fabsf(4.0f / 3.0f * (1.0f - cosf(hda)) / sinf(hda)); + if (da < 0.0f) + kappa = -kappa; + + for (i = 0; i <= ndivs; i++) { + a = a1 + da * ((float)i/(float)ndivs); + dx = cosf(a); + dy = sinf(a); + nsvg__xformPoint(&x, &y, dx*rx, dy*ry, t); // position + nsvg__xformVec(&tanx, &tany, -dy*rx * kappa, dx*ry * kappa, t); // tangent + if (i > 0) + nsvg__cubicBezTo(p, px+ptanx,py+ptany, x-tanx, y-tany, x, y); + px = x; + py = y; + ptanx = tanx; + ptany = tany; + } + + *cpx = x2; + *cpy = y2; +} + +static void nsvg__parsePath(NSVGparser* p, const char** attr) +{ + const char* s = NULL; + char cmd = '\0'; + float args[10]; + int nargs; + int rargs = 0; + float cpx, cpy, cpx2, cpy2; + const char* tmp[4]; + char closedFlag; + int i; + char item[64]; + + for (i = 0; attr[i]; i += 2) { + if (strcmp(attr[i], "d") == 0) { + s = attr[i + 1]; + } else { + tmp[0] = attr[i]; + tmp[1] = attr[i + 1]; + tmp[2] = 0; + tmp[3] = 0; + nsvg__parseAttribs(p, tmp); + } + } + + if (s) { + nsvg__resetPath(p); + cpx = 0; cpy = 0; + cpx2 = 0; cpy2 = 0; + closedFlag = 0; + nargs = 0; + + while (*s) { + s = nsvg__getNextPathItem(s, item); + if (!*item) break; + if (nsvg__isnum(item[0])) { + if (nargs < 10) + args[nargs++] = (float)nsvg__atof(item); + if (nargs >= rargs) { + switch (cmd) { + case 'm': + case 'M': + nsvg__pathMoveTo(p, &cpx, &cpy, args, cmd == 'm' ? 1 : 0); + // Moveto can be followed by multiple coordinate pairs, + // which should be treated as linetos. + cmd = (cmd == 'm') ? 'l' : 'L'; + rargs = nsvg__getArgsPerElement(cmd); + cpx2 = cpx; cpy2 = cpy; + break; + case 'l': + case 'L': + nsvg__pathLineTo(p, &cpx, &cpy, args, cmd == 'l' ? 1 : 0); + cpx2 = cpx; cpy2 = cpy; + break; + case 'H': + case 'h': + nsvg__pathHLineTo(p, &cpx, &cpy, args, cmd == 'h' ? 1 : 0); + cpx2 = cpx; cpy2 = cpy; + break; + case 'V': + case 'v': + nsvg__pathVLineTo(p, &cpx, &cpy, args, cmd == 'v' ? 1 : 0); + cpx2 = cpx; cpy2 = cpy; + break; + case 'C': + case 'c': + nsvg__pathCubicBezTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 'c' ? 1 : 0); + break; + case 'S': + case 's': + nsvg__pathCubicBezShortTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 's' ? 1 : 0); + break; + case 'Q': + case 'q': + nsvg__pathQuadBezTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 'q' ? 1 : 0); + break; + case 'T': + case 't': + nsvg__pathQuadBezShortTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 't' ? 1 : 0); + break; + case 'A': + case 'a': + nsvg__pathArcTo(p, &cpx, &cpy, args, cmd == 'a' ? 1 : 0); + cpx2 = cpx; cpy2 = cpy; + break; + default: + if (nargs >= 2) { + cpx = args[nargs-2]; + cpy = args[nargs-1]; + cpx2 = cpx; cpy2 = cpy; + } + break; + } + nargs = 0; + } + } else { + cmd = item[0]; + rargs = nsvg__getArgsPerElement(cmd); + if (cmd == 'M' || cmd == 'm') { + // Commit path. + if (p->npts > 0) + nsvg__addPath(p, closedFlag); + // Start new subpath. + nsvg__resetPath(p); + closedFlag = 0; + nargs = 0; + } else if (cmd == 'Z' || cmd == 'z') { + closedFlag = 1; + // Commit path. + if (p->npts > 0) { + // Move current point to first point + cpx = p->pts[0]; + cpy = p->pts[1]; + cpx2 = cpx; cpy2 = cpy; + nsvg__addPath(p, closedFlag); + } + // Start new subpath. + nsvg__resetPath(p); + nsvg__moveTo(p, cpx, cpy); + closedFlag = 0; + nargs = 0; + } + } + } + // Commit path. + if (p->npts) + nsvg__addPath(p, closedFlag); + } + + nsvg__addShape(p); +} + +static void nsvg__parseRect(NSVGparser* p, const char** attr) +{ + float x = 0.0f; + float y = 0.0f; + float w = 0.0f; + float h = 0.0f; + float rx = -1.0f; // marks not set + float ry = -1.0f; + int i; + + for (i = 0; attr[i]; i += 2) { + if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "x") == 0) x = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); + if (strcmp(attr[i], "y") == 0) y = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); + if (strcmp(attr[i], "width") == 0) w = nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p)); + if (strcmp(attr[i], "height") == 0) h = nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p)); + if (strcmp(attr[i], "rx") == 0) rx = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p))); + if (strcmp(attr[i], "ry") == 0) ry = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p))); + } + } + + if (rx < 0.0f && ry > 0.0f) rx = ry; + if (ry < 0.0f && rx > 0.0f) ry = rx; + if (rx < 0.0f) rx = 0.0f; + if (ry < 0.0f) ry = 0.0f; + if (rx > w/2.0f) rx = w/2.0f; + if (ry > h/2.0f) ry = h/2.0f; + + if (w != 0.0f && h != 0.0f) { + nsvg__resetPath(p); + + if (rx < 0.00001f || ry < 0.0001f) { + nsvg__moveTo(p, x, y); + nsvg__lineTo(p, x+w, y); + nsvg__lineTo(p, x+w, y+h); + nsvg__lineTo(p, x, y+h); + } else { + // Rounded rectangle + nsvg__moveTo(p, x+rx, y); + nsvg__lineTo(p, x+w-rx, y); + nsvg__cubicBezTo(p, x+w-rx*(1-NSVG_KAPPA90), y, x+w, y+ry*(1-NSVG_KAPPA90), x+w, y+ry); + nsvg__lineTo(p, x+w, y+h-ry); + nsvg__cubicBezTo(p, x+w, y+h-ry*(1-NSVG_KAPPA90), x+w-rx*(1-NSVG_KAPPA90), y+h, x+w-rx, y+h); + nsvg__lineTo(p, x+rx, y+h); + nsvg__cubicBezTo(p, x+rx*(1-NSVG_KAPPA90), y+h, x, y+h-ry*(1-NSVG_KAPPA90), x, y+h-ry); + nsvg__lineTo(p, x, y+ry); + nsvg__cubicBezTo(p, x, y+ry*(1-NSVG_KAPPA90), x+rx*(1-NSVG_KAPPA90), y, x+rx, y); + } + + nsvg__addPath(p, 1); + + nsvg__addShape(p); + } +} + +static void nsvg__parseCircle(NSVGparser* p, const char** attr) +{ + float cx = 0.0f; + float cy = 0.0f; + float r = 0.0f; + int i; + + for (i = 0; attr[i]; i += 2) { + if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "cx") == 0) cx = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); + if (strcmp(attr[i], "cy") == 0) cy = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); + if (strcmp(attr[i], "r") == 0) r = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualLength(p))); + } + } + + if (r > 0.0f) { + nsvg__resetPath(p); + + nsvg__moveTo(p, cx+r, cy); + nsvg__cubicBezTo(p, cx+r, cy+r*NSVG_KAPPA90, cx+r*NSVG_KAPPA90, cy+r, cx, cy+r); + nsvg__cubicBezTo(p, cx-r*NSVG_KAPPA90, cy+r, cx-r, cy+r*NSVG_KAPPA90, cx-r, cy); + nsvg__cubicBezTo(p, cx-r, cy-r*NSVG_KAPPA90, cx-r*NSVG_KAPPA90, cy-r, cx, cy-r); + nsvg__cubicBezTo(p, cx+r*NSVG_KAPPA90, cy-r, cx+r, cy-r*NSVG_KAPPA90, cx+r, cy); + + nsvg__addPath(p, 1); + + nsvg__addShape(p); + } +} + +static void nsvg__parseEllipse(NSVGparser* p, const char** attr) +{ + float cx = 0.0f; + float cy = 0.0f; + float rx = 0.0f; + float ry = 0.0f; + int i; + + for (i = 0; attr[i]; i += 2) { + if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "cx") == 0) cx = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); + if (strcmp(attr[i], "cy") == 0) cy = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); + if (strcmp(attr[i], "rx") == 0) rx = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p))); + if (strcmp(attr[i], "ry") == 0) ry = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p))); + } + } + + if (rx > 0.0f && ry > 0.0f) { + + nsvg__resetPath(p); + + nsvg__moveTo(p, cx+rx, cy); + nsvg__cubicBezTo(p, cx+rx, cy+ry*NSVG_KAPPA90, cx+rx*NSVG_KAPPA90, cy+ry, cx, cy+ry); + nsvg__cubicBezTo(p, cx-rx*NSVG_KAPPA90, cy+ry, cx-rx, cy+ry*NSVG_KAPPA90, cx-rx, cy); + nsvg__cubicBezTo(p, cx-rx, cy-ry*NSVG_KAPPA90, cx-rx*NSVG_KAPPA90, cy-ry, cx, cy-ry); + nsvg__cubicBezTo(p, cx+rx*NSVG_KAPPA90, cy-ry, cx+rx, cy-ry*NSVG_KAPPA90, cx+rx, cy); + + nsvg__addPath(p, 1); + + nsvg__addShape(p); + } +} + +static void nsvg__parseLine(NSVGparser* p, const char** attr) +{ + float x1 = 0.0; + float y1 = 0.0; + float x2 = 0.0; + float y2 = 0.0; + int i; + + for (i = 0; attr[i]; i += 2) { + if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "x1") == 0) x1 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); + if (strcmp(attr[i], "y1") == 0) y1 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); + if (strcmp(attr[i], "x2") == 0) x2 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); + if (strcmp(attr[i], "y2") == 0) y2 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); + } + } + + nsvg__resetPath(p); + + nsvg__moveTo(p, x1, y1); + nsvg__lineTo(p, x2, y2); + + nsvg__addPath(p, 0); + + nsvg__addShape(p); +} + +static void nsvg__parsePoly(NSVGparser* p, const char** attr, int closeFlag) +{ + int i; + const char* s; + float args[2]; + int nargs, npts = 0; + char item[64]; + + nsvg__resetPath(p); + + for (i = 0; attr[i]; i += 2) { + if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "points") == 0) { + s = attr[i + 1]; + nargs = 0; + while (*s) { + s = nsvg__getNextPathItem(s, item); + args[nargs++] = (float)nsvg__atof(item); + if (nargs >= 2) { + if (npts == 0) + nsvg__moveTo(p, args[0], args[1]); + else + nsvg__lineTo(p, args[0], args[1]); + nargs = 0; + npts++; + } + } + } + } + } + + nsvg__addPath(p, (char)closeFlag); + + nsvg__addShape(p); +} + +static void nsvg__parseSVG(NSVGparser* p, const char** attr) +{ + int i; + for (i = 0; attr[i]; i += 2) { + if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "width") == 0) { + p->image->width = nsvg__parseCoordinate(p, attr[i + 1], 0.0f, 0.0f); + } else if (strcmp(attr[i], "height") == 0) { + p->image->height = nsvg__parseCoordinate(p, attr[i + 1], 0.0f, 0.0f); + } else if (strcmp(attr[i], "viewBox") == 0) { + sscanf(attr[i + 1], "%f%*[%%, \t]%f%*[%%, \t]%f%*[%%, \t]%f", &p->viewMinx, &p->viewMiny, &p->viewWidth, &p->viewHeight); + } else if (strcmp(attr[i], "preserveAspectRatio") == 0) { + if (strstr(attr[i + 1], "none") != 0) { + // No uniform scaling + p->alignType = NSVG_ALIGN_NONE; + } else { + // Parse X align + if (strstr(attr[i + 1], "xMin") != 0) + p->alignX = NSVG_ALIGN_MIN; + else if (strstr(attr[i + 1], "xMid") != 0) + p->alignX = NSVG_ALIGN_MID; + else if (strstr(attr[i + 1], "xMax") != 0) + p->alignX = NSVG_ALIGN_MAX; + // Parse X align + if (strstr(attr[i + 1], "yMin") != 0) + p->alignY = NSVG_ALIGN_MIN; + else if (strstr(attr[i + 1], "yMid") != 0) + p->alignY = NSVG_ALIGN_MID; + else if (strstr(attr[i + 1], "yMax") != 0) + p->alignY = NSVG_ALIGN_MAX; + // Parse meet/slice + p->alignType = NSVG_ALIGN_MEET; + if (strstr(attr[i + 1], "slice") != 0) + p->alignType = NSVG_ALIGN_SLICE; + } + } + } + } +} + +static void nsvg__parseGradient(NSVGparser* p, const char** attr, char type) +{ + int i; + NSVGgradientData* grad = (NSVGgradientData*)NANOSVG_malloc(sizeof(NSVGgradientData)); + if (grad == NULL) return; + memset(grad, 0, sizeof(NSVGgradientData)); + grad->units = NSVG_OBJECT_SPACE; + grad->type = type; + if (grad->type == NSVG_PAINT_LINEAR_GRADIENT) { + grad->linear.x1 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT); + grad->linear.y1 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT); + grad->linear.x2 = nsvg__coord(100.0f, NSVG_UNITS_PERCENT); + grad->linear.y2 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT); + } else if (grad->type == NSVG_PAINT_RADIAL_GRADIENT) { + grad->radial.cx = nsvg__coord(50.0f, NSVG_UNITS_PERCENT); + grad->radial.cy = nsvg__coord(50.0f, NSVG_UNITS_PERCENT); + grad->radial.r = nsvg__coord(50.0f, NSVG_UNITS_PERCENT); + } + + nsvg__xformIdentity(grad->xform); + + for (i = 0; attr[i]; i += 2) { + if (strcmp(attr[i], "id") == 0) { + strncpy(grad->id, attr[i+1], 63); + grad->id[63] = '\0'; + } else if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "gradientUnits") == 0) { + if (strcmp(attr[i+1], "objectBoundingBox") == 0) + grad->units = NSVG_OBJECT_SPACE; + else + grad->units = NSVG_USER_SPACE; + } else if (strcmp(attr[i], "gradientTransform") == 0) { + nsvg__parseTransform(grad->xform, attr[i + 1]); + } else if (strcmp(attr[i], "cx") == 0) { + grad->radial.cx = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "cy") == 0) { + grad->radial.cy = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "r") == 0) { + grad->radial.r = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "fx") == 0) { + grad->radial.fx = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "fy") == 0) { + grad->radial.fy = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "x1") == 0) { + grad->linear.x1 = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "y1") == 0) { + grad->linear.y1 = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "x2") == 0) { + grad->linear.x2 = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "y2") == 0) { + grad->linear.y2 = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "spreadMethod") == 0) { + if (strcmp(attr[i+1], "pad") == 0) + grad->spread = NSVG_SPREAD_PAD; + else if (strcmp(attr[i+1], "reflect") == 0) + grad->spread = NSVG_SPREAD_REFLECT; + else if (strcmp(attr[i+1], "repeat") == 0) + grad->spread = NSVG_SPREAD_REPEAT; + } else if (strcmp(attr[i], "xlink:href") == 0) { + const char *href = attr[i+1]; + strncpy(grad->ref, href+1, 62); + grad->ref[62] = '\0'; + } + } + } + + grad->next = p->gradients; + p->gradients = grad; +} + +static void nsvg__parseGradientStop(NSVGparser* p, const char** attr) +{ + NSVGattrib* curAttr = nsvg__getAttr(p); + NSVGgradientData* grad; + NSVGgradientStop* stop; + int i, idx; + + curAttr->stopOffset = 0; + curAttr->stopColor = 0; + curAttr->stopOpacity = 1.0f; + + for (i = 0; attr[i]; i += 2) { + nsvg__parseAttr(p, attr[i], attr[i + 1]); + } + + // Add stop to the last gradient. + grad = p->gradients; + if (grad == NULL) return; + + grad->nstops++; + grad->stops = (NSVGgradientStop*)NANOSVG_realloc(grad->stops, sizeof(NSVGgradientStop)*grad->nstops); + if (grad->stops == NULL) return; + + // Insert + idx = grad->nstops-1; + for (i = 0; i < grad->nstops-1; i++) { + if (curAttr->stopOffset < grad->stops[i].offset) { + idx = i; + break; + } + } + if (idx != grad->nstops-1) { + for (i = grad->nstops-1; i > idx; i--) + grad->stops[i] = grad->stops[i-1]; + } + + stop = &grad->stops[idx]; + stop->color = curAttr->stopColor; + stop->color |= (unsigned int)(curAttr->stopOpacity*255) << 24; + stop->offset = curAttr->stopOffset; +} + +static void nsvg__startElement(void* ud, const char* el, const char** attr) +{ + NSVGparser* p = (NSVGparser*)ud; + + if (p->defsFlag) { + // Skip everything but gradients in defs + if (strcmp(el, "linearGradient") == 0) { + nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT); + } else if (strcmp(el, "radialGradient") == 0) { + nsvg__parseGradient(p, attr, NSVG_PAINT_RADIAL_GRADIENT); + } else if (strcmp(el, "stop") == 0) { + nsvg__parseGradientStop(p, attr); + } + return; + } + + if (strcmp(el, "g") == 0) { + nsvg__pushAttr(p); + nsvg__parseAttribs(p, attr); + } else if (strcmp(el, "path") == 0) { + if (p->pathFlag) // Do not allow nested paths. + return; + nsvg__pushAttr(p); + nsvg__parsePath(p, attr); + nsvg__popAttr(p); + } else if (strcmp(el, "rect") == 0) { + nsvg__pushAttr(p); + nsvg__parseRect(p, attr); + nsvg__popAttr(p); + } else if (strcmp(el, "circle") == 0) { + nsvg__pushAttr(p); + nsvg__parseCircle(p, attr); + nsvg__popAttr(p); + } else if (strcmp(el, "ellipse") == 0) { + nsvg__pushAttr(p); + nsvg__parseEllipse(p, attr); + nsvg__popAttr(p); + } else if (strcmp(el, "line") == 0) { + nsvg__pushAttr(p); + nsvg__parseLine(p, attr); + nsvg__popAttr(p); + } else if (strcmp(el, "polyline") == 0) { + nsvg__pushAttr(p); + nsvg__parsePoly(p, attr, 0); + nsvg__popAttr(p); + } else if (strcmp(el, "polygon") == 0) { + nsvg__pushAttr(p); + nsvg__parsePoly(p, attr, 1); + nsvg__popAttr(p); + } else if (strcmp(el, "linearGradient") == 0) { + nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT); + } else if (strcmp(el, "radialGradient") == 0) { + nsvg__parseGradient(p, attr, NSVG_PAINT_RADIAL_GRADIENT); + } else if (strcmp(el, "stop") == 0) { + nsvg__parseGradientStop(p, attr); + } else if (strcmp(el, "defs") == 0) { + p->defsFlag = 1; + } else if (strcmp(el, "svg") == 0) { + nsvg__parseSVG(p, attr); + } else if (strcmp(el, "style") == 0) { + p->styleFlag = 1; + } +} + +static void nsvg__endElement(void* ud, const char* el) +{ + NSVGparser* p = (NSVGparser*)ud; + + if (strcmp(el, "g") == 0) { + nsvg__popAttr(p); + } else if (strcmp(el, "path") == 0) { + p->pathFlag = 0; + } else if (strcmp(el, "defs") == 0) { + p->defsFlag = 0; + } else if (strcmp(el, "style") == 0) { + p->styleFlag = 0; + } +} + +static char *nsvg__strndup(const char *s, size_t n) +{ + char *result; + size_t len = strlen(s); + + if (n < len) + len = n; + + result = (char*)NANOSVG_malloc(len+1); + if (!result) + return 0; + + result[len] = '\0'; + return (char *)memcpy(result, s, len); +} + +static void nsvg__content(void* ud, const char* s) +{ + NSVGparser* p = (NSVGparser*)ud; + if (p->styleFlag) { + + int state = 0; + const char* start = NULL; + while (*s) { + char c = *s; + if (nsvg__isspace(c) || c == '{') { + if (state == 1) { + NSVGstyles* next = p->styles; + + p->styles = (NSVGstyles*)malloc(sizeof(NSVGstyles)); + p->styles->next = next; + p->styles->name = nsvg__strndup(start, (size_t)(s - start)); + start = s + 1; + state = 2; + } + } else if (state == 2 && c == '}') { + p->styles->description = nsvg__strndup(start, (size_t)(s - start)); + state = 0; + } + else if (state == 0) { + start = s; + state = 1; + } + s++; + /* + if (*s == '{' && state == NSVG_XML_CONTENT) { + // Start of a tag + *s++ = '\0'; + nsvg__parseContent(mark, contentCb, ud); + mark = s; + state = NSVG_XML_TAG; + } + else if (*s == '>' && state == NSVG_XML_TAG) { + // Start of a content or new tag. + *s++ = '\0'; + nsvg__parseElement(mark, startelCb, endelCb, ud); + mark = s; + state = NSVG_XML_CONTENT; + } + else { + s++; + } + */ + } + + } +} + +static void nsvg__imageBounds(NSVGparser* p, float* bounds) +{ + NSVGshape* shape; + shape = p->image->shapes; + if (shape == NULL) { + bounds[0] = bounds[1] = bounds[2] = bounds[3] = 0.0; + return; + } + bounds[0] = shape->bounds[0]; + bounds[1] = shape->bounds[1]; + bounds[2] = shape->bounds[2]; + bounds[3] = shape->bounds[3]; + for (shape = shape->next; shape != NULL; shape = shape->next) { + bounds[0] = nsvg__minf(bounds[0], shape->bounds[0]); + bounds[1] = nsvg__minf(bounds[1], shape->bounds[1]); + bounds[2] = nsvg__maxf(bounds[2], shape->bounds[2]); + bounds[3] = nsvg__maxf(bounds[3], shape->bounds[3]); + } +} + +static float nsvg__viewAlign(float content, float container, int type) +{ + if (type == NSVG_ALIGN_MIN) + return 0; + else if (type == NSVG_ALIGN_MAX) + return container - content; + // mid + return (container - content) * 0.5f; +} + +static void nsvg__scaleGradient(NSVGgradient* grad, float tx, float ty, float sx, float sy) +{ + float t[6]; + nsvg__xformSetTranslation(t, tx, ty); + nsvg__xformMultiply (grad->xform, t); + + nsvg__xformSetScale(t, sx, sy); + nsvg__xformMultiply (grad->xform, t); +} + +static void nsvg__scaleToViewbox(NSVGparser* p, const char* units) +{ + NSVGshape* shape; + NSVGpath* path; + float tx, ty, sx, sy, us, bounds[4], t[6], avgs; + int i; + float* pt; + + // Guess image size if not set completely. + nsvg__imageBounds(p, bounds); + + if (p->viewWidth == 0) { + if (p->image->width > 0) { + p->viewWidth = p->image->width; + } else { + p->viewMinx = bounds[0]; + p->viewWidth = bounds[2] - bounds[0]; + } + } + if (p->viewHeight == 0) { + if (p->image->height > 0) { + p->viewHeight = p->image->height; + } else { + p->viewMiny = bounds[1]; + p->viewHeight = bounds[3] - bounds[1]; + } + } + if (p->image->width == 0) + p->image->width = p->viewWidth; + if (p->image->height == 0) + p->image->height = p->viewHeight; + + tx = -p->viewMinx; + ty = -p->viewMiny; + sx = p->viewWidth > 0 ? p->image->width / p->viewWidth : 0; + sy = p->viewHeight > 0 ? p->image->height / p->viewHeight : 0; + // Unit scaling + us = 1.0f / nsvg__convertToPixels(p, nsvg__coord(1.0f, nsvg__parseUnits(units)), 0.0f, 1.0f); + + // Fix aspect ratio + if (p->alignType == NSVG_ALIGN_MEET) { + // fit whole image into viewbox + sx = sy = nsvg__minf(sx, sy); + tx += nsvg__viewAlign(p->viewWidth*sx, p->image->width, p->alignX) / sx; + ty += nsvg__viewAlign(p->viewHeight*sy, p->image->height, p->alignY) / sy; + } else if (p->alignType == NSVG_ALIGN_SLICE) { + // fill whole viewbox with image + sx = sy = nsvg__maxf(sx, sy); + tx += nsvg__viewAlign(p->viewWidth*sx, p->image->width, p->alignX) / sx; + ty += nsvg__viewAlign(p->viewHeight*sy, p->image->height, p->alignY) / sy; + } + + // Transform + sx *= us; + sy *= us; + avgs = (sx+sy) / 2.0f; + for (shape = p->image->shapes; shape != NULL; shape = shape->next) { + shape->bounds[0] = (shape->bounds[0] + tx) * sx; + shape->bounds[1] = (shape->bounds[1] + ty) * sy; + shape->bounds[2] = (shape->bounds[2] + tx) * sx; + shape->bounds[3] = (shape->bounds[3] + ty) * sy; + for (path = shape->paths; path != NULL; path = path->next) { + path->bounds[0] = (path->bounds[0] + tx) * sx; + path->bounds[1] = (path->bounds[1] + ty) * sy; + path->bounds[2] = (path->bounds[2] + tx) * sx; + path->bounds[3] = (path->bounds[3] + ty) * sy; + for (i =0; i < path->npts; i++) { + pt = &path->pts[i*2]; + pt[0] = (pt[0] + tx) * sx; + pt[1] = (pt[1] + ty) * sy; + } + } + + if (shape->fill.type == NSVG_PAINT_LINEAR_GRADIENT || shape->fill.type == NSVG_PAINT_RADIAL_GRADIENT) { + nsvg__scaleGradient(shape->fill.gradient, tx,ty, sx,sy); + memcpy(t, shape->fill.gradient->xform, sizeof(float)*6); + nsvg__xformInverse(shape->fill.gradient->xform, t); + } + if (shape->stroke.type == NSVG_PAINT_LINEAR_GRADIENT || shape->stroke.type == NSVG_PAINT_RADIAL_GRADIENT) { + nsvg__scaleGradient(shape->stroke.gradient, tx,ty, sx,sy); + memcpy(t, shape->stroke.gradient->xform, sizeof(float)*6); + nsvg__xformInverse(shape->stroke.gradient->xform, t); + } + + shape->strokeWidth *= avgs; + shape->strokeDashOffset *= avgs; + for (i = 0; i < shape->strokeDashCount; i++) + shape->strokeDashArray[i] *= avgs; + } +} + +NANOSVG_SCOPE +NSVGimage* nsvgParse(char* input, const char* units, float dpi) +{ + NSVGparser* p; + NSVGimage* ret = 0; + + p = nsvg__createParser(); + if (p == NULL) { + return NULL; + } + p->dpi = dpi; + + nsvg__parseXML(input, nsvg__startElement, nsvg__endElement, nsvg__content, p); + + // Scale to viewBox + nsvg__scaleToViewbox(p, units); + + ret = p->image; + p->image = NULL; + + nsvg__deleteParser(p); + + return ret; +} + +NANOSVG_SCOPE +NSVGimage* nsvgParseFromFile(const char* filename, const char* units, float dpi) +{ + FILE* fp = NULL; + size_t size; + char* data = NULL; + NSVGimage* image = NULL; + + fp = fopen(filename, "rb"); + if (!fp) goto error; + fseek(fp, 0, SEEK_END); + size = ftell(fp); + fseek(fp, 0, SEEK_SET); + data = (char*)NANOSVG_malloc(size+1); + if (data == NULL) goto error; + if (fread(data, 1, size, fp) != size) goto error; + data[size] = '\0'; // Must be null terminated. + fclose(fp); + image = nsvgParse(data, units, dpi); + NANOSVG_free(data); + + return image; + +error: + if (fp) fclose(fp); + if (data) NANOSVG_free(data); + if (image) nsvgDelete(image); + return NULL; +} + +NANOSVG_SCOPE +void nsvgDelete(NSVGimage* image) +{ + NSVGshape *snext, *shape; + if (image == NULL) return; + shape = image->shapes; + while (shape != NULL) { + snext = shape->next; + nsvg__deletePaths(shape->paths); + nsvg__deletePaint(&shape->fill); + nsvg__deletePaint(&shape->stroke); + NANOSVG_free(shape); + shape = snext; + } + NANOSVG_free(image); +} + +#endif diff --git a/generic/nanosvgrast.h b/generic/nanosvgrast.h new file mode 100644 index 0000000..37636fe --- /dev/null +++ b/generic/nanosvgrast.h @@ -0,0 +1,1467 @@ +/* + * Copyright (c) 2013-14 Mikko Mononen memon@inside.org + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + * + * The polygon rasterization is heavily based on stb_truetype rasterizer + * by Sean Barrett - http://nothings.org/ + * + */ + +#ifndef NANOSVGRAST_H +#define NANOSVGRAST_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef NANOSVG_SCOPE +#define NANOSVG_SCOPE +#endif + +#ifndef NANOSVG_malloc +#define NANOSVG_malloc malloc +#endif + +#ifndef NANOSVG_realloc +#define NANOSVG_realloc realloc +#endif + +#ifndef NANOSVG_free +#define NANOSVG_free free +#endif + +typedef struct NSVGrasterizer NSVGrasterizer; + +/* Example Usage: + // Load SVG + struct SNVGImage* image = nsvgParseFromFile("test.svg."); + + // Create rasterizer (can be used to render multiple images). + struct NSVGrasterizer* rast = nsvgCreateRasterizer(); + // Allocate memory for image + unsigned char* img = malloc(w*h*4); + // Rasterize + nsvgRasterize(rast, image, 0,0,1, img, w, h, w*4); +*/ + +// Allocated rasterizer context. +NANOSVG_SCOPE NSVGrasterizer* nsvgCreateRasterizer(); + +// Rasterizes SVG image, returns RGBA image (non-premultiplied alpha) +// r - pointer to rasterizer context +// image - pointer to image to rasterize +// tx,ty - image offset (applied after scaling) +// scale - image scale +// dst - pointer to destination image data, 4 bytes per pixel (RGBA) +// w - width of the image to render +// h - height of the image to render +// stride - number of bytes per scaleline in the destination buffer +NANOSVG_SCOPE void nsvgRasterize(NSVGrasterizer* r, + NSVGimage* image, float tx, float ty, float scale, + unsigned char* dst, int w, int h, int stride); + +// Deletes rasterizer context. +NANOSVG_SCOPE void nsvgDeleteRasterizer(NSVGrasterizer*); + + +#ifdef __cplusplus +} +#endif + +#endif // NANOSVGRAST_H + +#ifdef NANOSVGRAST_IMPLEMENTATION + +#include + +#define NSVG__SUBSAMPLES 5 +#define NSVG__FIXSHIFT 10 +#define NSVG__FIX (1 << NSVG__FIXSHIFT) +#define NSVG__FIXMASK (NSVG__FIX-1) +#define NSVG__MEMPAGE_SIZE 1024 + +typedef struct NSVGedge { + float x0,y0, x1,y1; + int dir; + struct NSVGedge* next; +} NSVGedge; + +typedef struct NSVGpoint { + float x, y; + float dx, dy; + float len; + float dmx, dmy; + unsigned char flags; +} NSVGpoint; + +typedef struct NSVGactiveEdge { + int x,dx; + float ey; + int dir; + struct NSVGactiveEdge *next; +} NSVGactiveEdge; + +typedef struct NSVGmemPage { + unsigned char mem[NSVG__MEMPAGE_SIZE]; + int size; + struct NSVGmemPage* next; +} NSVGmemPage; + +typedef struct NSVGcachedPaint { + char type; + char spread; + float xform[6]; + unsigned int colors[256]; +} NSVGcachedPaint; + +struct NSVGrasterizer +{ + float px, py; + + float tessTol; + float distTol; + + NSVGedge* edges; + int nedges; + int cedges; + + NSVGpoint* points; + int npoints; + int cpoints; + + NSVGpoint* points2; + int npoints2; + int cpoints2; + + NSVGactiveEdge* freelist; + NSVGmemPage* pages; + NSVGmemPage* curpage; + + unsigned char* scanline; + int cscanline; + + unsigned char* bitmap; + int width, height, stride; +}; + +NANOSVG_SCOPE +NSVGrasterizer* nsvgCreateRasterizer() +{ + NSVGrasterizer* r = (NSVGrasterizer*)NANOSVG_malloc(sizeof(NSVGrasterizer)); + if (r == NULL) goto error; + memset(r, 0, sizeof(NSVGrasterizer)); + + r->tessTol = 0.25f; + r->distTol = 0.01f; + + return r; + +error: + nsvgDeleteRasterizer(r); + return NULL; +} + +NANOSVG_SCOPE +void nsvgDeleteRasterizer(NSVGrasterizer* r) +{ + NSVGmemPage* p; + + if (r == NULL) return; + + p = r->pages; + while (p != NULL) { + NSVGmemPage* next = p->next; + NANOSVG_free(p); + p = next; + } + + if (r->edges) NANOSVG_free(r->edges); + if (r->points) NANOSVG_free(r->points); + if (r->points2) NANOSVG_free(r->points2); + if (r->scanline) NANOSVG_free(r->scanline); + + NANOSVG_free(r); +} + +static NSVGmemPage* nsvg__nextPage(NSVGrasterizer* r, NSVGmemPage* cur) +{ + NSVGmemPage *newp; + + // If using existing chain, return the next page in chain + if (cur != NULL && cur->next != NULL) { + return cur->next; + } + + // Alloc new page + newp = (NSVGmemPage*)NANOSVG_malloc(sizeof(NSVGmemPage)); + if (newp == NULL) return NULL; + memset(newp, 0, sizeof(NSVGmemPage)); + + // Add to linked list + if (cur != NULL) + cur->next = newp; + else + r->pages = newp; + + return newp; +} + +static void nsvg__resetPool(NSVGrasterizer* r) +{ + NSVGmemPage* p = r->pages; + while (p != NULL) { + p->size = 0; + p = p->next; + } + r->curpage = r->pages; +} + +static unsigned char* nsvg__alloc(NSVGrasterizer* r, int size) +{ + unsigned char* buf; + if (size > NSVG__MEMPAGE_SIZE) return NULL; + if (r->curpage == NULL || r->curpage->size+size > NSVG__MEMPAGE_SIZE) { + r->curpage = nsvg__nextPage(r, r->curpage); + } + buf = &r->curpage->mem[r->curpage->size]; + r->curpage->size += size; + return buf; +} + +static int nsvg__ptEquals(float x1, float y1, float x2, float y2, float tol) +{ + float dx = x2 - x1; + float dy = y2 - y1; + return dx*dx + dy*dy < tol*tol; +} + +static void nsvg__addPathPoint(NSVGrasterizer* r, float x, float y, int flags) +{ + NSVGpoint* pt; + + if (r->npoints > 0) { + pt = &r->points[r->npoints-1]; + if (nsvg__ptEquals(pt->x,pt->y, x,y, r->distTol)) { + pt->flags = (unsigned char)(pt->flags | flags); + return; + } + } + + if (r->npoints+1 > r->cpoints) { + r->cpoints = r->cpoints > 0 ? r->cpoints * 2 : 64; + r->points = (NSVGpoint*)NANOSVG_realloc(r->points, sizeof(NSVGpoint) * r->cpoints); + if (r->points == NULL) return; + } + + pt = &r->points[r->npoints]; + pt->x = x; + pt->y = y; + pt->flags = (unsigned char)flags; + r->npoints++; +} + +static void nsvg__appendPathPoint(NSVGrasterizer* r, NSVGpoint pt) +{ + if (r->npoints+1 > r->cpoints) { + r->cpoints = r->cpoints > 0 ? r->cpoints * 2 : 64; + r->points = (NSVGpoint*)NANOSVG_realloc(r->points, sizeof(NSVGpoint) * r->cpoints); + if (r->points == NULL) return; + } + r->points[r->npoints] = pt; + r->npoints++; +} + +static void nsvg__duplicatePoints(NSVGrasterizer* r) +{ + if (r->npoints > r->cpoints2) { + r->cpoints2 = r->npoints; + r->points2 = (NSVGpoint*)NANOSVG_realloc(r->points2, sizeof(NSVGpoint) * r->cpoints2); + if (r->points2 == NULL) return; + } + + memcpy(r->points2, r->points, sizeof(NSVGpoint) * r->npoints); + r->npoints2 = r->npoints; +} + +static void nsvg__addEdge(NSVGrasterizer* r, float x0, float y0, float x1, float y1) +{ + NSVGedge* e; + + // Skip horizontal edges + if (y0 == y1) + return; + + if (r->nedges+1 > r->cedges) { + r->cedges = r->cedges > 0 ? r->cedges * 2 : 64; + r->edges = (NSVGedge*)NANOSVG_realloc(r->edges, sizeof(NSVGedge) * r->cedges); + if (r->edges == NULL) return; + } + + e = &r->edges[r->nedges]; + r->nedges++; + + if (y0 < y1) { + e->x0 = x0; + e->y0 = y0; + e->x1 = x1; + e->y1 = y1; + e->dir = 1; + } else { + e->x0 = x1; + e->y0 = y1; + e->x1 = x0; + e->y1 = y0; + e->dir = -1; + } +} + +static float nsvg__normalize(float *x, float* y) +{ + float d = sqrtf((*x)*(*x) + (*y)*(*y)); + if (d > 1e-6f) { + float id = 1.0f / d; + *x *= id; + *y *= id; + } + return d; +} + +static float nsvg__absf(float x) { return x < 0 ? -x : x; } + +static void nsvg__flattenCubicBez(NSVGrasterizer* r, + float x1, float y1, float x2, float y2, + float x3, float y3, float x4, float y4, + int level, int type) +{ + float x12,y12,x23,y23,x34,y34,x123,y123,x234,y234,x1234,y1234; + float dx,dy,d2,d3; + + if (level > 10) return; + + x12 = (x1+x2)*0.5f; + y12 = (y1+y2)*0.5f; + x23 = (x2+x3)*0.5f; + y23 = (y2+y3)*0.5f; + x34 = (x3+x4)*0.5f; + y34 = (y3+y4)*0.5f; + x123 = (x12+x23)*0.5f; + y123 = (y12+y23)*0.5f; + + dx = x4 - x1; + dy = y4 - y1; + d2 = nsvg__absf(((x2 - x4) * dy - (y2 - y4) * dx)); + d3 = nsvg__absf(((x3 - x4) * dy - (y3 - y4) * dx)); + + if ((d2 + d3)*(d2 + d3) < r->tessTol * (dx*dx + dy*dy)) { + nsvg__addPathPoint(r, x4, y4, type); + return; + } + + x234 = (x23+x34)*0.5f; + y234 = (y23+y34)*0.5f; + x1234 = (x123+x234)*0.5f; + y1234 = (y123+y234)*0.5f; + + nsvg__flattenCubicBez(r, x1,y1, x12,y12, x123,y123, x1234,y1234, level+1, 0); + nsvg__flattenCubicBez(r, x1234,y1234, x234,y234, x34,y34, x4,y4, level+1, type); +} + +static void nsvg__flattenShape(NSVGrasterizer* r, NSVGshape* shape, float scale) +{ + int i, j; + NSVGpath* path; + + for (path = shape->paths; path != NULL; path = path->next) { + r->npoints = 0; + // Flatten path + nsvg__addPathPoint(r, path->pts[0]*scale, path->pts[1]*scale, 0); + for (i = 0; i < path->npts-1; i += 3) { + float* p = &path->pts[i*2]; + nsvg__flattenCubicBez(r, p[0]*scale,p[1]*scale, p[2]*scale,p[3]*scale, p[4]*scale,p[5]*scale, p[6]*scale,p[7]*scale, 0, 0); + } + // Close path + nsvg__addPathPoint(r, path->pts[0]*scale, path->pts[1]*scale, 0); + // Build edges + for (i = 0, j = r->npoints-1; i < r->npoints; j = i++) + nsvg__addEdge(r, r->points[j].x, r->points[j].y, r->points[i].x, r->points[i].y); + } +} + +enum NSVGpointFlags +{ + NSVG_PT_CORNER = 0x01, + NSVG_PT_BEVEL = 0x02, + NSVG_PT_LEFT = 0x04 +}; + +static void nsvg__initClosed(NSVGpoint* left, NSVGpoint* right, NSVGpoint* p0, NSVGpoint* p1, float lineWidth) +{ + float w = lineWidth * 0.5f; + float dx = p1->x - p0->x; + float dy = p1->y - p0->y; + float len = nsvg__normalize(&dx, &dy); + float px = p0->x + dx*len*0.5f, py = p0->y + dy*len*0.5f; + float dlx = dy, dly = -dx; + float lx = px - dlx*w, ly = py - dly*w; + float rx = px + dlx*w, ry = py + dly*w; + left->x = lx; left->y = ly; + right->x = rx; right->y = ry; +} + +static void nsvg__buttCap(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p, float dx, float dy, float lineWidth, int connect) +{ + float w = lineWidth * 0.5f; + float px = p->x, py = p->y; + float dlx = dy, dly = -dx; + float lx = px - dlx*w, ly = py - dly*w; + float rx = px + dlx*w, ry = py + dly*w; + + nsvg__addEdge(r, lx, ly, rx, ry); + + if (connect) { + nsvg__addEdge(r, left->x, left->y, lx, ly); + nsvg__addEdge(r, rx, ry, right->x, right->y); + } + left->x = lx; left->y = ly; + right->x = rx; right->y = ry; +} + +static void nsvg__squareCap(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p, float dx, float dy, float lineWidth, int connect) +{ + float w = lineWidth * 0.5f; + float px = p->x - dx*w, py = p->y - dy*w; + float dlx = dy, dly = -dx; + float lx = px - dlx*w, ly = py - dly*w; + float rx = px + dlx*w, ry = py + dly*w; + + nsvg__addEdge(r, lx, ly, rx, ry); + + if (connect) { + nsvg__addEdge(r, left->x, left->y, lx, ly); + nsvg__addEdge(r, rx, ry, right->x, right->y); + } + left->x = lx; left->y = ly; + right->x = rx; right->y = ry; +} + +#ifndef NSVG_PI +#define NSVG_PI (3.14159265358979323846264338327f) +#endif + +static void nsvg__roundCap(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p, float dx, float dy, float lineWidth, int ncap, int connect) +{ + int i; + float w = lineWidth * 0.5f; + float px = p->x, py = p->y; + float dlx = dy, dly = -dx; + float lx = 0, ly = 0, rx = 0, ry = 0, prevx = 0, prevy = 0; + + for (i = 0; i < ncap; i++) { + float a = (float)i/(float)(ncap-1)*NSVG_PI; + float ax = cosf(a) * w, ay = sinf(a) * w; + float x = px - dlx*ax - dx*ay; + float y = py - dly*ax - dy*ay; + + if (i > 0) + nsvg__addEdge(r, prevx, prevy, x, y); + + prevx = x; + prevy = y; + + if (i == 0) { + lx = x; ly = y; + } else if (i == ncap-1) { + rx = x; ry = y; + } + } + + if (connect) { + nsvg__addEdge(r, left->x, left->y, lx, ly); + nsvg__addEdge(r, rx, ry, right->x, right->y); + } + + left->x = lx; left->y = ly; + right->x = rx; right->y = ry; +} + +static void nsvg__bevelJoin(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p0, NSVGpoint* p1, float lineWidth) +{ + float w = lineWidth * 0.5f; + float dlx0 = p0->dy, dly0 = -p0->dx; + float dlx1 = p1->dy, dly1 = -p1->dx; + float lx0 = p1->x - (dlx0 * w), ly0 = p1->y - (dly0 * w); + float rx0 = p1->x + (dlx0 * w), ry0 = p1->y + (dly0 * w); + float lx1 = p1->x - (dlx1 * w), ly1 = p1->y - (dly1 * w); + float rx1 = p1->x + (dlx1 * w), ry1 = p1->y + (dly1 * w); + + nsvg__addEdge(r, lx0, ly0, left->x, left->y); + nsvg__addEdge(r, lx1, ly1, lx0, ly0); + + nsvg__addEdge(r, right->x, right->y, rx0, ry0); + nsvg__addEdge(r, rx0, ry0, rx1, ry1); + + left->x = lx1; left->y = ly1; + right->x = rx1; right->y = ry1; +} + +static void nsvg__miterJoin(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p0, NSVGpoint* p1, float lineWidth) +{ + float w = lineWidth * 0.5f; + float dlx0 = p0->dy, dly0 = -p0->dx; + float dlx1 = p1->dy, dly1 = -p1->dx; + float lx0, rx0, lx1, rx1; + float ly0, ry0, ly1, ry1; + + if (p1->flags & NSVG_PT_LEFT) { + lx0 = lx1 = p1->x - p1->dmx * w; + ly0 = ly1 = p1->y - p1->dmy * w; + nsvg__addEdge(r, lx1, ly1, left->x, left->y); + + rx0 = p1->x + (dlx0 * w); + ry0 = p1->y + (dly0 * w); + rx1 = p1->x + (dlx1 * w); + ry1 = p1->y + (dly1 * w); + nsvg__addEdge(r, right->x, right->y, rx0, ry0); + nsvg__addEdge(r, rx0, ry0, rx1, ry1); + } else { + lx0 = p1->x - (dlx0 * w); + ly0 = p1->y - (dly0 * w); + lx1 = p1->x - (dlx1 * w); + ly1 = p1->y - (dly1 * w); + nsvg__addEdge(r, lx0, ly0, left->x, left->y); + nsvg__addEdge(r, lx1, ly1, lx0, ly0); + + rx0 = rx1 = p1->x + p1->dmx * w; + ry0 = ry1 = p1->y + p1->dmy * w; + nsvg__addEdge(r, right->x, right->y, rx1, ry1); + } + + left->x = lx1; left->y = ly1; + right->x = rx1; right->y = ry1; +} + +static void nsvg__roundJoin(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p0, NSVGpoint* p1, float lineWidth, int ncap) +{ + int i, n; + float w = lineWidth * 0.5f; + float dlx0 = p0->dy, dly0 = -p0->dx; + float dlx1 = p1->dy, dly1 = -p1->dx; + float a0 = atan2f(dly0, dlx0); + float a1 = atan2f(dly1, dlx1); + float da = a1 - a0; + float lx, ly, rx, ry; + + if (da < NSVG_PI) da += NSVG_PI*2; + if (da > NSVG_PI) da -= NSVG_PI*2; + + n = (int)ceilf((nsvg__absf(da) / NSVG_PI) * (float)ncap); + if (n < 2) n = 2; + if (n > ncap) n = ncap; + + lx = left->x; + ly = left->y; + rx = right->x; + ry = right->y; + + for (i = 0; i < n; i++) { + float u = (float)i/(float)(n-1); + float a = a0 + u*da; + float ax = cosf(a) * w, ay = sinf(a) * w; + float lx1 = p1->x - ax, ly1 = p1->y - ay; + float rx1 = p1->x + ax, ry1 = p1->y + ay; + + nsvg__addEdge(r, lx1, ly1, lx, ly); + nsvg__addEdge(r, rx, ry, rx1, ry1); + + lx = lx1; ly = ly1; + rx = rx1; ry = ry1; + } + + left->x = lx; left->y = ly; + right->x = rx; right->y = ry; +} + +static void nsvg__straightJoin(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p1, float lineWidth) +{ + float w = lineWidth * 0.5f; + float lx = p1->x - (p1->dmx * w), ly = p1->y - (p1->dmy * w); + float rx = p1->x + (p1->dmx * w), ry = p1->y + (p1->dmy * w); + + nsvg__addEdge(r, lx, ly, left->x, left->y); + nsvg__addEdge(r, right->x, right->y, rx, ry); + + left->x = lx; left->y = ly; + right->x = rx; right->y = ry; +} + +static int nsvg__curveDivs(float r, float arc, float tol) +{ + float da = acosf(r / (r + tol)) * 2.0f; + int divs = (int)ceilf(arc / da); + if (divs < 2) divs = 2; + return divs; +} + +static void nsvg__expandStroke(NSVGrasterizer* r, NSVGpoint* points, int npoints, int closed, int lineJoin, int lineCap, float lineWidth) +{ + int ncap = nsvg__curveDivs(lineWidth*0.5f, NSVG_PI, r->tessTol); // Calculate divisions per half circle. + NSVGpoint left = {0,0,0,0,0,0,0,0}, right = {0,0,0,0,0,0,0,0}, firstLeft = {0,0,0,0,0,0,0,0}, firstRight = {0,0,0,0,0,0,0,0}; + NSVGpoint* p0, *p1; + int j, s, e; + + // Build stroke edges + if (closed) { + // Looping + p0 = &points[npoints-1]; + p1 = &points[0]; + s = 0; + e = npoints; + } else { + // Add cap + p0 = &points[0]; + p1 = &points[1]; + s = 1; + e = npoints-1; + } + + if (closed) { + nsvg__initClosed(&left, &right, p0, p1, lineWidth); + firstLeft = left; + firstRight = right; + } else { + // Add cap + float dx = p1->x - p0->x; + float dy = p1->y - p0->y; + nsvg__normalize(&dx, &dy); + if (lineCap == NSVG_CAP_BUTT) + nsvg__buttCap(r, &left, &right, p0, dx, dy, lineWidth, 0); + else if (lineCap == NSVG_CAP_SQUARE) + nsvg__squareCap(r, &left, &right, p0, dx, dy, lineWidth, 0); + else if (lineCap == NSVG_CAP_ROUND) + nsvg__roundCap(r, &left, &right, p0, dx, dy, lineWidth, ncap, 0); + } + + for (j = s; j < e; ++j) { + if (p1->flags & NSVG_PT_CORNER) { + if (lineJoin == NSVG_JOIN_ROUND) + nsvg__roundJoin(r, &left, &right, p0, p1, lineWidth, ncap); + else if (lineJoin == NSVG_JOIN_BEVEL || (p1->flags & NSVG_PT_BEVEL)) + nsvg__bevelJoin(r, &left, &right, p0, p1, lineWidth); + else + nsvg__miterJoin(r, &left, &right, p0, p1, lineWidth); + } else { + nsvg__straightJoin(r, &left, &right, p1, lineWidth); + } + p0 = p1++; + } + + if (closed) { + // Loop it + nsvg__addEdge(r, firstLeft.x, firstLeft.y, left.x, left.y); + nsvg__addEdge(r, right.x, right.y, firstRight.x, firstRight.y); + } else { + // Add cap + float dx = p1->x - p0->x; + float dy = p1->y - p0->y; + nsvg__normalize(&dx, &dy); + if (lineCap == NSVG_CAP_BUTT) + nsvg__buttCap(r, &right, &left, p1, -dx, -dy, lineWidth, 1); + else if (lineCap == NSVG_CAP_SQUARE) + nsvg__squareCap(r, &right, &left, p1, -dx, -dy, lineWidth, 1); + else if (lineCap == NSVG_CAP_ROUND) + nsvg__roundCap(r, &right, &left, p1, -dx, -dy, lineWidth, ncap, 1); + } +} + +static void nsvg__prepareStroke(NSVGrasterizer* r, float miterLimit, int lineJoin) +{ + int i, j; + NSVGpoint* p0, *p1; + + p0 = &r->points[r->npoints-1]; + p1 = &r->points[0]; + for (i = 0; i < r->npoints; i++) { + // Calculate segment direction and length + p0->dx = p1->x - p0->x; + p0->dy = p1->y - p0->y; + p0->len = nsvg__normalize(&p0->dx, &p0->dy); + // Advance + p0 = p1++; + } + + // calculate joins + p0 = &r->points[r->npoints-1]; + p1 = &r->points[0]; + for (j = 0; j < r->npoints; j++) { + float dlx0, dly0, dlx1, dly1, dmr2, cross; + dlx0 = p0->dy; + dly0 = -p0->dx; + dlx1 = p1->dy; + dly1 = -p1->dx; + // Calculate extrusions + p1->dmx = (dlx0 + dlx1) * 0.5f; + p1->dmy = (dly0 + dly1) * 0.5f; + dmr2 = p1->dmx*p1->dmx + p1->dmy*p1->dmy; + if (dmr2 > 0.000001f) { + float s2 = 1.0f / dmr2; + if (s2 > 600.0f) { + s2 = 600.0f; + } + p1->dmx *= s2; + p1->dmy *= s2; + } + + // Clear flags, but keep the corner. + p1->flags = (p1->flags & NSVG_PT_CORNER) ? NSVG_PT_CORNER : 0; + + // Keep track of left turns. + cross = p1->dx * p0->dy - p0->dx * p1->dy; + if (cross > 0.0f) + p1->flags |= NSVG_PT_LEFT; + + // Check to see if the corner needs to be beveled. + if (p1->flags & NSVG_PT_CORNER) { + if ((dmr2 * miterLimit*miterLimit) < 1.0f || lineJoin == NSVG_JOIN_BEVEL || lineJoin == NSVG_JOIN_ROUND) { + p1->flags |= NSVG_PT_BEVEL; + } + } + + p0 = p1++; + } +} + +static void nsvg__flattenShapeStroke(NSVGrasterizer* r, NSVGshape* shape, float scale) +{ + int i, j, closed; + NSVGpath* path; + NSVGpoint* p0, *p1; + float miterLimit = shape->miterLimit; + int lineJoin = shape->strokeLineJoin; + int lineCap = shape->strokeLineCap; + float lineWidth = shape->strokeWidth * scale; + + for (path = shape->paths; path != NULL; path = path->next) { + // Flatten path + r->npoints = 0; + nsvg__addPathPoint(r, path->pts[0]*scale, path->pts[1]*scale, NSVG_PT_CORNER); + for (i = 0; i < path->npts-1; i += 3) { + float* p = &path->pts[i*2]; + nsvg__flattenCubicBez(r, p[0]*scale,p[1]*scale, p[2]*scale,p[3]*scale, p[4]*scale,p[5]*scale, p[6]*scale,p[7]*scale, 0, NSVG_PT_CORNER); + } + if (r->npoints < 2) + continue; + + closed = path->closed; + + // If the first and last points are the same, remove the last, mark as closed path. + p0 = &r->points[r->npoints-1]; + p1 = &r->points[0]; + if (nsvg__ptEquals(p0->x,p0->y, p1->x,p1->y, r->distTol)) { + r->npoints--; + p0 = &r->points[r->npoints-1]; + closed = 1; + } + + if (shape->strokeDashCount > 0) { + int idash = 0, dashState = 1; + float totalDist = 0, dashLen, allDashLen, dashOffset; + NSVGpoint cur; + + if (closed) + nsvg__appendPathPoint(r, r->points[0]); + + // Duplicate points -> points2. + nsvg__duplicatePoints(r); + + r->npoints = 0; + cur = r->points2[0]; + nsvg__appendPathPoint(r, cur); + + // Figure out dash offset. + allDashLen = 0; + for (j = 0; j < shape->strokeDashCount; j++) + allDashLen += shape->strokeDashArray[j]; + if (shape->strokeDashCount & 1) + allDashLen *= 2.0f; + // Find location inside pattern + dashOffset = fmodf(shape->strokeDashOffset, allDashLen); + if (dashOffset < 0.0f) + dashOffset += allDashLen; + + while (dashOffset > shape->strokeDashArray[idash]) { + dashOffset -= shape->strokeDashArray[idash]; + idash = (idash + 1) % shape->strokeDashCount; + } + dashLen = (shape->strokeDashArray[idash] - dashOffset) * scale; + + for (j = 1; j < r->npoints2; ) { + float dx = r->points2[j].x - cur.x; + float dy = r->points2[j].y - cur.y; + float dist = sqrtf(dx*dx + dy*dy); + + if ((totalDist + dist) > dashLen) { + // Calculate intermediate point + float d = (dashLen - totalDist) / dist; + float x = cur.x + dx * d; + float y = cur.y + dy * d; + nsvg__addPathPoint(r, x, y, NSVG_PT_CORNER); + + // Stroke + if (r->npoints > 1 && dashState) { + nsvg__prepareStroke(r, miterLimit, lineJoin); + nsvg__expandStroke(r, r->points, r->npoints, 0, lineJoin, lineCap, lineWidth); + } + // Advance dash pattern + dashState = !dashState; + idash = (idash+1) % shape->strokeDashCount; + dashLen = shape->strokeDashArray[idash] * scale; + // Restart + cur.x = x; + cur.y = y; + cur.flags = NSVG_PT_CORNER; + totalDist = 0.0f; + r->npoints = 0; + nsvg__appendPathPoint(r, cur); + } else { + totalDist += dist; + cur = r->points2[j]; + nsvg__appendPathPoint(r, cur); + j++; + } + } + // Stroke any leftover path + if (r->npoints > 1 && dashState) + nsvg__expandStroke(r, r->points, r->npoints, 0, lineJoin, lineCap, lineWidth); + } else { + nsvg__prepareStroke(r, miterLimit, lineJoin); + nsvg__expandStroke(r, r->points, r->npoints, closed, lineJoin, lineCap, lineWidth); + } + } +} + +static int nsvg__cmpEdge(const void *p, const void *q) +{ + const NSVGedge* a = (const NSVGedge*)p; + const NSVGedge* b = (const NSVGedge*)q; + + if (a->y0 < b->y0) return -1; + if (a->y0 > b->y0) return 1; + return 0; +} + + +static NSVGactiveEdge* nsvg__addActive(NSVGrasterizer* r, NSVGedge* e, float startPoint) +{ + NSVGactiveEdge* z; + float dxdy; + + if (r->freelist != NULL) { + // Restore from freelist. + z = r->freelist; + r->freelist = z->next; + } else { + // Alloc new edge. + z = (NSVGactiveEdge*)nsvg__alloc(r, sizeof(NSVGactiveEdge)); + if (z == NULL) return NULL; + } + + dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); +// STBTT_assert(e->y0 <= start_point); + // round dx down to avoid going too far + if (dxdy < 0) + z->dx = (int)(-floorf(NSVG__FIX * -dxdy)); + else + z->dx = (int)floorf(NSVG__FIX * dxdy); + z->x = (int)floorf(NSVG__FIX * (e->x0 + dxdy * (startPoint - e->y0))); +// z->x -= off_x * FIX; + z->ey = e->y1; + z->next = 0; + z->dir = e->dir; + + return z; +} + +static void nsvg__freeActive(NSVGrasterizer* r, NSVGactiveEdge* z) +{ + z->next = r->freelist; + r->freelist = z; +} + +static void nsvg__fillScanline(unsigned char* scanline, int len, int x0, int x1, int maxWeight, int* xmin, int* xmax) +{ + int i = x0 >> NSVG__FIXSHIFT; + int j = x1 >> NSVG__FIXSHIFT; + if (i < *xmin) *xmin = i; + if (j > *xmax) *xmax = j; + if (i < len && j >= 0) { + if (i == j) { + // x0,x1 are the same pixel, so compute combined coverage + scanline[i] = (unsigned char)(scanline[i] + ((x1 - x0) * maxWeight >> NSVG__FIXSHIFT)); + } else { + if (i >= 0) // add antialiasing for x0 + scanline[i] = (unsigned char)(scanline[i] + (((NSVG__FIX - (x0 & NSVG__FIXMASK)) * maxWeight) >> NSVG__FIXSHIFT)); + else + i = -1; // clip + + if (j < len) // add antialiasing for x1 + scanline[j] = (unsigned char)(scanline[j] + (((x1 & NSVG__FIXMASK) * maxWeight) >> NSVG__FIXSHIFT)); + else + j = len; // clip + + for (++i; i < j; ++i) // fill pixels between x0 and x1 + scanline[i] = (unsigned char)(scanline[i] + maxWeight); + } + } +} + +// note: this routine clips fills that extend off the edges... ideally this +// wouldn't happen, but it could happen if the truetype glyph bounding boxes +// are wrong, or if the user supplies a too-small bitmap +static void nsvg__fillActiveEdges(unsigned char* scanline, int len, NSVGactiveEdge* e, int maxWeight, int* xmin, int* xmax, char fillRule) +{ + // non-zero winding fill + int x0 = 0, w = 0; + + if (fillRule == NSVG_FILLRULE_NONZERO) { + // Non-zero + while (e != NULL) { + if (w == 0) { + // if we're currently at zero, we need to record the edge start point + x0 = e->x; w += e->dir; + } else { + int x1 = e->x; w += e->dir; + // if we went to zero, we need to draw + if (w == 0) + nsvg__fillScanline(scanline, len, x0, x1, maxWeight, xmin, xmax); + } + e = e->next; + } + } else if (fillRule == NSVG_FILLRULE_EVENODD) { + // Even-odd + while (e != NULL) { + if (w == 0) { + // if we're currently at zero, we need to record the edge start point + x0 = e->x; w = 1; + } else { + int x1 = e->x; w = 0; + nsvg__fillScanline(scanline, len, x0, x1, maxWeight, xmin, xmax); + } + e = e->next; + } + } +} + +static float nsvg__clampf(float a, float mn, float mx) { return a < mn ? mn : (a > mx ? mx : a); } + +static unsigned int nsvg__RGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a) +{ + return (r) | (g << 8) | (b << 16) | (a << 24); +} + +static unsigned int nsvg__lerpRGBA(unsigned int c0, unsigned int c1, float u) +{ + int iu = (int)(nsvg__clampf(u, 0.0f, 1.0f) * 256.0f); + int r = (((c0) & 0xff)*(256-iu) + (((c1) & 0xff)*iu)) >> 8; + int g = (((c0>>8) & 0xff)*(256-iu) + (((c1>>8) & 0xff)*iu)) >> 8; + int b = (((c0>>16) & 0xff)*(256-iu) + (((c1>>16) & 0xff)*iu)) >> 8; + int a = (((c0>>24) & 0xff)*(256-iu) + (((c1>>24) & 0xff)*iu)) >> 8; + return nsvg__RGBA((unsigned char)r, (unsigned char)g, (unsigned char)b, (unsigned char)a); +} + +static unsigned int nsvg__applyOpacity(unsigned int c, float u) +{ + int iu = (int)(nsvg__clampf(u, 0.0f, 1.0f) * 256.0f); + int r = (c) & 0xff; + int g = (c>>8) & 0xff; + int b = (c>>16) & 0xff; + int a = (((c>>24) & 0xff)*iu) >> 8; + return nsvg__RGBA((unsigned char)r, (unsigned char)g, (unsigned char)b, (unsigned char)a); +} + +static inline int nsvg__div255(int x) +{ + return ((x+1) * 257) >> 16; +} + +static void nsvg__scanlineSolid(unsigned char* dst, int count, unsigned char* cover, int x, int y, + float tx, float ty, float scale, NSVGcachedPaint* cache) +{ + + if (cache->type == NSVG_PAINT_COLOR) { + int i, cr, cg, cb, ca; + cr = cache->colors[0] & 0xff; + cg = (cache->colors[0] >> 8) & 0xff; + cb = (cache->colors[0] >> 16) & 0xff; + ca = (cache->colors[0] >> 24) & 0xff; + + for (i = 0; i < count; i++) { + int r,g,b; + int a = nsvg__div255((int)cover[0] * ca); + int ia = 255 - a; + // Premultiply + r = nsvg__div255(cr * a); + g = nsvg__div255(cg * a); + b = nsvg__div255(cb * a); + + // Blend over + r += nsvg__div255(ia * (int)dst[0]); + g += nsvg__div255(ia * (int)dst[1]); + b += nsvg__div255(ia * (int)dst[2]); + a += nsvg__div255(ia * (int)dst[3]); + + dst[0] = (unsigned char)r; + dst[1] = (unsigned char)g; + dst[2] = (unsigned char)b; + dst[3] = (unsigned char)a; + + cover++; + dst += 4; + } + } else if (cache->type == NSVG_PAINT_LINEAR_GRADIENT) { + // TODO: spread modes. + // TODO: plenty of opportunities to optimize. + float fx, fy, dx, gy; + float* t = cache->xform; + int i, cr, cg, cb, ca; + unsigned int c; + + fx = ((float)x - tx) / scale; + fy = ((float)y - ty) / scale; + dx = 1.0f / scale; + + for (i = 0; i < count; i++) { + int r,g,b,a,ia; + gy = fx*t[1] + fy*t[3] + t[5]; + c = cache->colors[(int)nsvg__clampf(gy*255.0f, 0, 255.0f)]; + cr = (c) & 0xff; + cg = (c >> 8) & 0xff; + cb = (c >> 16) & 0xff; + ca = (c >> 24) & 0xff; + + a = nsvg__div255((int)cover[0] * ca); + ia = 255 - a; + + // Premultiply + r = nsvg__div255(cr * a); + g = nsvg__div255(cg * a); + b = nsvg__div255(cb * a); + + // Blend over + r += nsvg__div255(ia * (int)dst[0]); + g += nsvg__div255(ia * (int)dst[1]); + b += nsvg__div255(ia * (int)dst[2]); + a += nsvg__div255(ia * (int)dst[3]); + + dst[0] = (unsigned char)r; + dst[1] = (unsigned char)g; + dst[2] = (unsigned char)b; + dst[3] = (unsigned char)a; + + cover++; + dst += 4; + fx += dx; + } + } else if (cache->type == NSVG_PAINT_RADIAL_GRADIENT) { + // TODO: spread modes. + // TODO: plenty of opportunities to optimize. + // TODO: focus (fx,fy) + float fx, fy, dx, gx, gy, gd; + float* t = cache->xform; + int i, cr, cg, cb, ca; + unsigned int c; + + fx = ((float)x - tx) / scale; + fy = ((float)y - ty) / scale; + dx = 1.0f / scale; + + for (i = 0; i < count; i++) { + int r,g,b,a,ia; + gx = fx*t[0] + fy*t[2] + t[4]; + gy = fx*t[1] + fy*t[3] + t[5]; + gd = sqrtf(gx*gx + gy*gy); + c = cache->colors[(int)nsvg__clampf(gd*255.0f, 0, 255.0f)]; + cr = (c) & 0xff; + cg = (c >> 8) & 0xff; + cb = (c >> 16) & 0xff; + ca = (c >> 24) & 0xff; + + a = nsvg__div255((int)cover[0] * ca); + ia = 255 - a; + + // Premultiply + r = nsvg__div255(cr * a); + g = nsvg__div255(cg * a); + b = nsvg__div255(cb * a); + + // Blend over + r += nsvg__div255(ia * (int)dst[0]); + g += nsvg__div255(ia * (int)dst[1]); + b += nsvg__div255(ia * (int)dst[2]); + a += nsvg__div255(ia * (int)dst[3]); + + dst[0] = (unsigned char)r; + dst[1] = (unsigned char)g; + dst[2] = (unsigned char)b; + dst[3] = (unsigned char)a; + + cover++; + dst += 4; + fx += dx; + } + } +} + +static void nsvg__rasterizeSortedEdges(NSVGrasterizer *r, float tx, float ty, float scale, NSVGcachedPaint* cache, char fillRule) +{ + NSVGactiveEdge *active = NULL; + int y, s; + int e = 0; + int maxWeight = (255 / NSVG__SUBSAMPLES); // weight per vertical scanline + int xmin, xmax; + + for (y = 0; y < r->height; y++) { + memset(r->scanline, 0, r->width); + xmin = r->width; + xmax = 0; + for (s = 0; s < NSVG__SUBSAMPLES; ++s) { + // find center of pixel for this scanline + float scany = (float)(y*NSVG__SUBSAMPLES + s) + 0.5f; + NSVGactiveEdge **step = &active; + + // update all active edges; + // remove all active edges that terminate before the center of this scanline + while (*step) { + NSVGactiveEdge *z = *step; + if (z->ey <= scany) { + *step = z->next; // delete from list +// NSVG__assert(z->valid); + nsvg__freeActive(r, z); + } else { + z->x += z->dx; // advance to position for current scanline + step = &((*step)->next); // advance through list + } + } + + // resort the list if needed + for (;;) { + int changed = 0; + step = &active; + while (*step && (*step)->next) { + if ((*step)->x > (*step)->next->x) { + NSVGactiveEdge* t = *step; + NSVGactiveEdge* q = t->next; + t->next = q->next; + q->next = t; + *step = q; + changed = 1; + } + step = &(*step)->next; + } + if (!changed) break; + } + + // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline + while (e < r->nedges && r->edges[e].y0 <= scany) { + if (r->edges[e].y1 > scany) { + NSVGactiveEdge* z = nsvg__addActive(r, &r->edges[e], scany); + if (z == NULL) break; + // find insertion point + if (active == NULL) { + active = z; + } else if (z->x < active->x) { + // insert at front + z->next = active; + active = z; + } else { + // find thing to insert AFTER + NSVGactiveEdge* p = active; + while (p->next && p->next->x < z->x) + p = p->next; + // at this point, p->next->x is NOT < z->x + z->next = p->next; + p->next = z; + } + } + e++; + } + + // now process all active edges in non-zero fashion + if (active != NULL) + nsvg__fillActiveEdges(r->scanline, r->width, active, maxWeight, &xmin, &xmax, fillRule); + } + // Blit + if (xmin < 0) xmin = 0; + if (xmax > r->width-1) xmax = r->width-1; + if (xmin <= xmax) { + nsvg__scanlineSolid(&r->bitmap[y * r->stride] + xmin*4, xmax-xmin+1, &r->scanline[xmin], xmin, y, tx,ty, scale, cache); + } + } + +} + +static void nsvg__unpremultiplyAlpha(unsigned char* image, int w, int h, int stride) +{ + int x,y; + + // Unpremultiply + for (y = 0; y < h; y++) { + unsigned char *row = &image[y*stride]; + for (x = 0; x < w; x++) { + int r = row[0], g = row[1], b = row[2], a = row[3]; + if (a != 0) { + row[0] = (unsigned char)(r*255/a); + row[1] = (unsigned char)(g*255/a); + row[2] = (unsigned char)(b*255/a); + } + row += 4; + } + } + + // Defringe + for (y = 0; y < h; y++) { + unsigned char *row = &image[y*stride]; + for (x = 0; x < w; x++) { + int r = 0, g = 0, b = 0, a = row[3], n = 0; + if (a == 0) { + if (x-1 > 0 && row[-1] != 0) { + r += row[-4]; + g += row[-3]; + b += row[-2]; + n++; + } + if (x+1 < w && row[7] != 0) { + r += row[4]; + g += row[5]; + b += row[6]; + n++; + } + if (y-1 > 0 && row[-stride+3] != 0) { + r += row[-stride]; + g += row[-stride+1]; + b += row[-stride+2]; + n++; + } + if (y+1 < h && row[stride+3] != 0) { + r += row[stride]; + g += row[stride+1]; + b += row[stride+2]; + n++; + } + if (n > 0) { + row[0] = (unsigned char)(r/n); + row[1] = (unsigned char)(g/n); + row[2] = (unsigned char)(b/n); + } + } + row += 4; + } + } +} + + +static void nsvg__initPaint(NSVGcachedPaint* cache, NSVGpaint* paint, float opacity) +{ + int i, j; + NSVGgradient* grad; + + cache->type = paint->type; + + if (paint->type == NSVG_PAINT_COLOR) { + cache->colors[0] = nsvg__applyOpacity(paint->color, opacity); + return; + } + + grad = paint->gradient; + + cache->spread = grad->spread; + memcpy(cache->xform, grad->xform, sizeof(float)*6); + + if (grad->nstops == 0) { + for (i = 0; i < 256; i++) + cache->colors[i] = 0; + } if (grad->nstops == 1) { + for (i = 0; i < 256; i++) + cache->colors[i] = nsvg__applyOpacity(grad->stops[i].color, opacity); + } else { + unsigned int ca, cb = 0; + float ua, ub, du, u; + int ia, ib, count; + + ca = nsvg__applyOpacity(grad->stops[0].color, opacity); + ua = nsvg__clampf(grad->stops[0].offset, 0, 1); + ub = nsvg__clampf(grad->stops[grad->nstops-1].offset, ua, 1); + ia = (int)(ua * 255.0f); + ib = (int)(ub * 255.0f); + for (i = 0; i < ia; i++) { + cache->colors[i] = ca; + } + + for (i = 0; i < grad->nstops-1; i++) { + ca = nsvg__applyOpacity(grad->stops[i].color, opacity); + cb = nsvg__applyOpacity(grad->stops[i+1].color, opacity); + ua = nsvg__clampf(grad->stops[i].offset, 0, 1); + ub = nsvg__clampf(grad->stops[i+1].offset, 0, 1); + ia = (int)(ua * 255.0f); + ib = (int)(ub * 255.0f); + count = ib - ia; + if (count <= 0) continue; + u = 0; + du = 1.0f / (float)count; + for (j = 0; j < count; j++) { + cache->colors[ia+j] = nsvg__lerpRGBA(ca,cb,u); + u += du; + } + } + + for (i = ib; i < 256; i++) + cache->colors[i] = cb; + } + +} + +/* +static void dumpEdges(NSVGrasterizer* r, const char* name) +{ + float xmin = 0, xmax = 0, ymin = 0, ymax = 0; + NSVGedge *e = NULL; + int i; + if (r->nedges == 0) return; + FILE* fp = fopen(name, "w"); + if (fp == NULL) return; + + xmin = xmax = r->edges[0].x0; + ymin = ymax = r->edges[0].y0; + for (i = 0; i < r->nedges; i++) { + e = &r->edges[i]; + xmin = nsvg__minf(xmin, e->x0); + xmin = nsvg__minf(xmin, e->x1); + xmax = nsvg__maxf(xmax, e->x0); + xmax = nsvg__maxf(xmax, e->x1); + ymin = nsvg__minf(ymin, e->y0); + ymin = nsvg__minf(ymin, e->y1); + ymax = nsvg__maxf(ymax, e->y0); + ymax = nsvg__maxf(ymax, e->y1); + } + + fprintf(fp, "", xmin, ymin, (xmax - xmin), (ymax - ymin)); + + for (i = 0; i < r->nedges; i++) { + e = &r->edges[i]; + fprintf(fp ,"", e->x0,e->y0, e->x1,e->y1); + } + + for (i = 0; i < r->npoints; i++) { + if (i+1 < r->npoints) + fprintf(fp ,"", r->points[i].x, r->points[i].y, r->points[i+1].x, r->points[i+1].y); + fprintf(fp ,"", r->points[i].x, r->points[i].y, r->points[i].flags == 0 ? "#f00" : "#0f0"); + } + + fprintf(fp, ""); + fclose(fp); +} +*/ + +NANOSVG_SCOPE +void nsvgRasterize(NSVGrasterizer* r, + NSVGimage* image, float tx, float ty, float scale, + unsigned char* dst, int w, int h, int stride) +{ + NSVGshape *shape = NULL; + NSVGedge *e = NULL; + NSVGcachedPaint cache; + int i; + + r->bitmap = dst; + r->width = w; + r->height = h; + r->stride = stride; + + if (w > r->cscanline) { + r->cscanline = w; + r->scanline = (unsigned char*)NANOSVG_realloc(r->scanline, w); + if (r->scanline == NULL) return; + } + + for (i = 0; i < h; i++) + memset(&dst[i*stride], 0, w*4); + + for (shape = image->shapes; shape != NULL; shape = shape->next) { + if (!(shape->flags & NSVG_FLAGS_VISIBLE)) + continue; + + if (shape->fill.type != NSVG_PAINT_NONE) { + nsvg__resetPool(r); + r->freelist = NULL; + r->nedges = 0; + + nsvg__flattenShape(r, shape, scale); + + // Scale and translate edges + for (i = 0; i < r->nedges; i++) { + e = &r->edges[i]; + e->x0 = tx + e->x0; + e->y0 = (ty + e->y0) * NSVG__SUBSAMPLES; + e->x1 = tx + e->x1; + e->y1 = (ty + e->y1) * NSVG__SUBSAMPLES; + } + + // Rasterize edges + qsort(r->edges, r->nedges, sizeof(NSVGedge), nsvg__cmpEdge); + + // now, traverse the scanlines and find the intersections on each scanline, use non-zero rule + nsvg__initPaint(&cache, &shape->fill, shape->opacity); + + nsvg__rasterizeSortedEdges(r, tx,ty,scale, &cache, shape->fillRule); + } + if (shape->stroke.type != NSVG_PAINT_NONE && (shape->strokeWidth * scale) > 0.01f) { + nsvg__resetPool(r); + r->freelist = NULL; + r->nedges = 0; + + nsvg__flattenShapeStroke(r, shape, scale); + +// dumpEdges(r, "edge.svg"); + + // Scale and translate edges + for (i = 0; i < r->nedges; i++) { + e = &r->edges[i]; + e->x0 = tx + e->x0; + e->y0 = (ty + e->y0) * NSVG__SUBSAMPLES; + e->x1 = tx + e->x1; + e->y1 = (ty + e->y1) * NSVG__SUBSAMPLES; + } + + // Rasterize edges + qsort(r->edges, r->nedges, sizeof(NSVGedge), nsvg__cmpEdge); + + // now, traverse the scanlines and find the intersections on each scanline, use non-zero rule + nsvg__initPaint(&cache, &shape->stroke, shape->opacity); + + nsvg__rasterizeSortedEdges(r, tx,ty,scale, &cache, NSVG_FILLRULE_NONZERO); + } + } + + nsvg__unpremultiplyAlpha(dst, w, h, stride); + + r->bitmap = NULL; + r->width = 0; + r->height = 0; + r->stride = 0; +} + +#endif diff --git a/generic/tkImgSVGnano.c b/generic/tkImgSVGnano.c new file mode 100644 index 0000000..26236da --- /dev/null +++ b/generic/tkImgSVGnano.c @@ -0,0 +1,703 @@ +/* + * tkImgSVGnano.c + * + * A photo file handler for SVG files. + * + * Copyright (c) 2013-14 Mikko Mononen memon@inside.org + * Copyright (c) 2018 Christian Gollwitzer auriocus@gmx.de + * Copyright (c) 2018 Rene Zaumseil r.zaumseil@freenet.de + * + * See the file "license.terms" for information on usage and redistribution of + * this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * This handler is build using the original nanosvg library files from + * https://github.com/memononen/nanosvg and the tcl extension files from + * https://github.com/auriocus/tksvg + * + */ + +#include "tkInt.h" +#define NANOSVG_malloc ckalloc +#define NANOSVG_realloc ckrealloc +#define NANOSVG_free ckfree +#define NANOSVG_SCOPE MODULE_SCOPE +#define NANOSVG_ALL_COLOR_KEYWORDS +#define NANOSVG_IMPLEMENTATION +#include "nanosvg.h" +#define NANOSVGRAST_IMPLEMENTATION +#include "nanosvgrast.h" + +/* Additional parameters to nsvgRasterize() */ + +typedef struct { + double x; + double y; + double scale; +} RastOpts; + +/* + * The format record for the SVG nano file format: + */ + +Tk_PhotoImageFormat tkImgFmtSVGnano = { + "svgnano", /* name */ + FileMatchSVG, /* fileMatchProc */ + StringMatchSVG, /* stringMatchProc */ + FileReadSVG, /* fileReadProc */ + StringReadSVG, /* stringReadProc */ + NULL, /* fileWriteProc */ + NULL, /* stringWriteProc */ + NULL +}; + +/* + * Per interp cache of last NSVGimage which was matched to + * be immediately rasterized after the match. This helps to + * eliminate double parsing of the SVG file/string. + */ + +typedef struct { + ClientData dataOrChan; + Tcl_DString formatString; + NSVGimage *nsvgImage; + RastOpts ropts; +} NSVGcache; + +static int FileMatchSVG(Tcl_Channel chan, const char *fileName, + Tcl_Obj *format, int *widthPtr, int *heightPtr, + Tcl_Interp *interp); +static int FileReadSVG(Tcl_Interp *interp, Tcl_Channel chan, + const char *fileName, Tcl_Obj *format, + Tk_PhotoHandle imageHandle, int destX, int destY, + int width, int height, int srcX, int srcY); +static int StringMatchSVG(Tcl_Obj *dataObj, Tcl_Obj *format, + int *widthPtr, int *heightPtr, Tcl_Interp *interp); +static int StringReadSVG(Tcl_Interp *interp, Tcl_Obj *dataObj, + Tcl_Obj *format, Tk_PhotoHandle imageHandle, + int destX, int destY, int width, int height, + int srcX, int srcY); +static NSVGimage * ParseSVGWithOptions(Tcl_Interp *interp, + const char *input, int length, Tcl_Obj *format, + RastOpts *ropts); +static int RasterizeSVG(Tcl_Interp *interp, + Tk_PhotoHandle imageHandle, NSVGimage *nsvgImage, + int destX, int destY, int width, int height, + int srcX, int srcY, RastOpts *ropts); +static NSVGcache * GetCachePtr(Tcl_Interp *interp); +static int CacheSVG(Tcl_Interp *interp, ClientData dataOrChan, + Tcl_Obj *formatObj, NSVGimage *nsvgImage, + RastOpts *ropts); +static NSVGimage * GetCachedSVG(Tcl_Interp *interp, ClientData dataOrChan, + Tcl_Obj *formatObj, RastOpts *ropts); +static void CleanCache(Tcl_Interp *interp); +static void FreeCache(ClientData clientData, Tcl_Interp *interp); + +/* + *---------------------------------------------------------------------- + * + * FileMatchSVG -- + * + * This function is invoked by the photo image type to see if a file + * contains image data in SVG format. + * + * Results: + * The return value is >0 if the file can be successfully parsed, + * and 0 otherwise. + * + * Side effects: + * The file is saved in the internal cache for further use. + * + *---------------------------------------------------------------------- + */ + +static int +FileMatchSVG( + Tcl_Channel chan, + const char *fileName, + Tcl_Obj *formatObj, + int *widthPtr, int *heightPtr, + Tcl_Interp *interp) +{ + int length; + Tcl_Obj *dataObj = Tcl_NewObj(); + const char *data; + RastOpts ropts; + NSVGimage *nsvgImage; + + CleanCache(interp); + if (Tcl_ReadChars(chan, dataObj, -1, 0) == -1) { + /* in case of an error reading the file */ + Tcl_DecrRefCount(dataObj); + return 0; + } + data = Tcl_GetStringFromObj(dataObj, &length); + nsvgImage = ParseSVGWithOptions(interp, data, length, formatObj, &ropts); + Tcl_DecrRefCount(dataObj); + if (nsvgImage != NULL) { + *widthPtr = ceil(nsvgImage->width * ropts.scale); + *heightPtr = ceil(nsvgImage->height * ropts.scale); + if ((*widthPtr <= 0) || (*heightPtr <= 0)) { + nsvgDelete(nsvgImage); + return 0; + } + if (!CacheSVG(interp, chan, formatObj, nsvgImage, &ropts)) { + nsvgDelete(nsvgImage); + } + return 1; + } + return 0; +} + +/* + *---------------------------------------------------------------------- + * + * FileReadSVG -- + * + * This function is called by the photo image type to read SVG format + * data from a file and write it into a given photo image. + * + * Results: + * A standard TCL completion code. If TCL_ERROR is returned then an error + * message is left in the interp's result. + * + * Side effects: + * The access position in file f is changed, and new data is added to the + * image given by imageHandle. + * + *---------------------------------------------------------------------- + */ + +static int +FileReadSVG( + Tcl_Interp *interp, + Tcl_Channel chan, + const char *fileName, + Tcl_Obj *formatObj, + Tk_PhotoHandle imageHandle, + int destX, int destY, + int width, int height, + int srcX, int srcY) +{ + int length; + const char *data; + RastOpts ropts; + NSVGimage *nsvgImage = GetCachedSVG(interp, chan, formatObj, &ropts); + + if (nsvgImage == NULL) { + Tcl_Obj *dataObj = Tcl_NewObj(); + + if (Tcl_ReadChars(chan, dataObj, -1, 0) == -1) { + /* in case of an error reading the file */ + Tcl_DecrRefCount(dataObj); + Tcl_SetResult(interp, "read error", TCL_STATIC); + Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "READ_ERROR", NULL); + return TCL_ERROR; + } + data = Tcl_GetStringFromObj(dataObj, &length); + nsvgImage = ParseSVGWithOptions(interp, data, length, formatObj, + &ropts); + Tcl_DecrRefCount(dataObj); + if (nsvgImage == NULL) { + return TCL_ERROR; + } + } + return RasterizeSVG(interp, imageHandle, nsvgImage, destX, destY, + width, height, srcX, srcY, &ropts); +} + +/* + *---------------------------------------------------------------------- + * + * StringMatchSVG -- + * + * This function is invoked by the photo image type to see if a string + * contains image data in SVG format. + * + * Results: + * The return value is >0 if the file can be successfully parsed, + * and 0 otherwise. + * + * Side effects: + * The file is saved in the internal cache for further use. + * + *---------------------------------------------------------------------- + */ + +static int +StringMatchSVG( + Tcl_Obj *dataObj, + Tcl_Obj *formatObj, + int *widthPtr, int *heightPtr, + Tcl_Interp *interp) +{ + int length; + const char *data; + RastOpts ropts; + NSVGimage *nsvgImage; + + CleanCache(interp); + data = Tcl_GetStringFromObj(dataObj, &length); + nsvgImage = ParseSVGWithOptions(interp, data, length, formatObj, &ropts); + if (nsvgImage != NULL) { + *widthPtr = ceil(nsvgImage->width * ropts.scale); + *heightPtr = ceil(nsvgImage->height * ropts.scale); + if (!CacheSVG(interp, dataObj, formatObj, nsvgImage, &ropts)) { + nsvgDelete(nsvgImage); + } + return 1; + } + return 0; +} + +/* + *---------------------------------------------------------------------- + * + * StringReadSVG -- + * + * This function is called by the photo image type to read SVG format + * data from a string and write it into a given photo image. + * + * Results: + * A standard TCL completion code. If TCL_ERROR is returned then an error + * message is left in the interp's result. + * + * Side effects: + * New data is added to the image given by imageHandle. + * + *---------------------------------------------------------------------- + */ + +static int +StringReadSVG( + Tcl_Interp *interp, + Tcl_Obj *dataObj, + Tcl_Obj *formatObj, + Tk_PhotoHandle imageHandle, + int destX, int destY, + int width, int height, + int srcX, int srcY) +{ + int length; + const char *data; + RastOpts ropts; + NSVGimage *nsvgImage = GetCachedSVG(interp, dataObj, formatObj, &ropts); + + if (nsvgImage == NULL) { + data = Tcl_GetStringFromObj(dataObj, &length); + nsvgImage = ParseSVGWithOptions(interp, data, length, formatObj, + &ropts); + } + if (nsvgImage == NULL) { + return TCL_ERROR; + } + return RasterizeSVG(interp, imageHandle, nsvgImage, destX, destY, + width, height, srcX, srcY, &ropts); +} + +/* + *---------------------------------------------------------------------- + * + * ParseSVGWithOptions -- + * + * This function is called to parse the given input string as SVG. + * + * Results: + * Return a newly create NSVGimage on success, and NULL otherwise. + * + * Side effects: + * + *---------------------------------------------------------------------- + */ + +static NSVGimage * +ParseSVGWithOptions( + Tcl_Interp *interp, + const char *input, + int length, + Tcl_Obj *formatObj, + RastOpts *ropts) +{ + Tcl_Obj **objv = NULL; + int objc = 0; + double dpi = 96.0; + char unit[3], *p; + char *inputCopy = NULL; + NSVGimage *nsvgImage; + static const char *const fmtOptions[] = { + "-dpi", "-scale", "-unit", "-x", "-y", NULL + }; + enum fmtOptions { + OPT_DPI, OPT_SCALE, OPT_UNIT, OPT_X, OPT_Y + }; + + /* + * The parser destroys the original input string, + * therefore first duplicate. + */ + + inputCopy = attemptckalloc(length+1); + if (inputCopy == NULL) { + Tcl_SetResult(interp, "cannot alloc data buffer", TCL_STATIC); + Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "OUT_OF_MEMORY", NULL); + goto error; + } + memcpy(inputCopy, input, length); + inputCopy[length] = '\0'; + + /* + * Process elements of format specification as a list. + */ + + strcpy(unit, "px"); + ropts->x = ropts->y = 0.0; + ropts->scale = 1.0; + if ((formatObj != NULL) && + Tcl_ListObjGetElements(interp, formatObj, &objc, &objv) != TCL_OK) { + goto error; + } + for (; objc > 0 ; objc--, objv++) { + int optIndex; + + /* + * Ignore the "svg" part of the format specification. + */ + + if (!strcasecmp(Tcl_GetString(objv[0]), "svg")) { + continue; + } + + if (Tcl_GetIndexFromObjStruct(interp, objv[0], fmtOptions, + sizeof(char *), "option", 0, &optIndex) == TCL_ERROR) { + goto error; + } + + if (objc < 2) { + ckfree(inputCopy); + Tcl_WrongNumArgs(interp, 1, objv, "value"); + goto error; + } + + objc--; + objv++; + + switch ((enum fmtOptions) optIndex) { + case OPT_DPI: + if (Tcl_GetDoubleFromObj(interp, objv[0], &dpi) == TCL_ERROR) { + goto error; + } + if (dpi < 0.0) { + Tcl_SetObjResult(interp, Tcl_NewStringObj( + "-dpi value must be positive", -1)); + Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "BAD_DPI", + NULL); + goto error; + } + break; + case OPT_SCALE: + if (Tcl_GetDoubleFromObj(interp, objv[0], &ropts->scale) == + TCL_ERROR) { + goto error; + } + if (ropts->scale <= 0.0) { + Tcl_SetObjResult(interp, Tcl_NewStringObj( + "-scale value must be positive", -1)); + Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "BAD_SCALE", + NULL); + goto error; + } + break; + case OPT_UNIT: + p = Tcl_GetString(objv[0]); + if ((p != NULL) && (p[0])) { + strncpy(unit, p, 3); + unit[2] = '\0'; + } + break; + case OPT_X: + if (Tcl_GetDoubleFromObj(interp, objv[0], &ropts->x) == TCL_ERROR) { + goto error; + } + break; + case OPT_Y: + if (Tcl_GetDoubleFromObj(interp, objv[0], &ropts->y) == TCL_ERROR) { + goto error; + } + break; + } + } + + nsvgImage = nsvgParse(inputCopy, unit, dpi); + if (nsvgImage == NULL) { + Tcl_SetResult(interp, "cannot parse SVG image", TCL_STATIC); + Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "PARSE_ERROR", NULL); + goto error; + } + ckfree(inputCopy); + return nsvgImage; + +error: + if (inputCopy != NULL) { + ckfree(inputCopy); + } + return NULL; +} + +/* + *---------------------------------------------------------------------- + * + * RasterizeSVG -- + * + * This function is called to rasterize the given nsvgImage and + * fill the imageHandle with data. + * + * Results: + * A standard TCL completion code. If TCL_ERROR is returned then an error + * message is left in the interp's result. + * + * + * Side effects: + * On error the given nsvgImage will be deleted. + * + *---------------------------------------------------------------------- + */ + +static int +RasterizeSVG( + Tcl_Interp *interp, + Tk_PhotoHandle imageHandle, + NSVGimage *nsvgImage, + int destX, int destY, + int width, int height, + int srcX, int srcY, + RastOpts *ropts) +{ + int w, h, c; + NSVGrasterizer *rast; + unsigned char *imgData; + Tk_PhotoImageBlock svgblock; + + w = ceil(nsvgImage->width * ropts->scale); + h = ceil(nsvgImage->height * ropts->scale); + rast = nsvgCreateRasterizer(); + if (rast == NULL) { + Tcl_SetResult(interp, "cannot initialize rasterizer", TCL_STATIC); + Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "RASTERIZER_ERROR", + NULL); + goto cleanAST; + } + imgData = attemptckalloc(w * h *4); + if (imgData == NULL) { + Tcl_SetResult(interp, "cannot alloc image buffer", TCL_STATIC); + Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "OUT_OF_MEMORY", NULL); + goto cleanRAST; + } + nsvgRasterize(rast, nsvgImage, ropts->x, ropts->y, + ropts->scale, imgData, w, h, w * 4); + /* transfer the data to a photo block */ + svgblock.pixelPtr = imgData; + svgblock.width = w; + svgblock.height = h; + svgblock.pitch = w * 4; + svgblock.pixelSize = 4; + for (c = 0; c <= 3; c++) { + svgblock.offset[c] = c; + } + if (Tk_PhotoExpand(interp, imageHandle, + destX + width, destY + height) != TCL_OK) { + goto cleanRAST; + } + if (Tk_PhotoPutBlock(interp, imageHandle, &svgblock, destX, destY, + width, height, TK_PHOTO_COMPOSITE_SET) != TCL_OK) { + goto cleanimg; + } + ckfree(imgData); + nsvgDeleteRasterizer(rast); + nsvgDelete(nsvgImage); + return TCL_OK; + +cleanimg: + ckfree(imgData); + +cleanRAST: + nsvgDeleteRasterizer(rast); + +cleanAST: + nsvgDelete(nsvgImage); + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * GetCachePtr -- + * + * This function is called to get the per interpreter used + * svg image cache. + * + * Results: + * Return a pointer to the used cache. + * + * Side effects: + * Initialize the cache on the first call. + * + *---------------------------------------------------------------------- + */ + +static NSVGcache * +GetCachePtr( + Tcl_Interp *interp +) { + NSVGcache *cachePtr = Tcl_GetAssocData(interp, "tksvgnano", NULL); + if (cachePtr == NULL) { + cachePtr = ckalloc(sizeof(NSVGcache)); + cachePtr->dataOrChan = NULL; + Tcl_DStringInit(&cachePtr->formatString); + cachePtr->nsvgImage = NULL; + Tcl_SetAssocData(interp, "tksvgnano", FreeCache, cachePtr); + } + return cachePtr; +} + +/* + *---------------------------------------------------------------------- + * + * CacheSVG -- + * + * Add the given svg image informations to the cache for further usage. + * + * Results: + * Return 1 on success, and 0 otherwise. + * + * Side effects: + * + *---------------------------------------------------------------------- + */ + +static int +CacheSVG( + Tcl_Interp *interp, + ClientData dataOrChan, + Tcl_Obj *formatObj, + NSVGimage *nsvgImage, + RastOpts *ropts) +{ + int length; + const char *data; + NSVGcache *cachePtr = GetCachePtr(interp); + + if (cachePtr != NULL) { + cachePtr->dataOrChan = dataOrChan; + if (formatObj != NULL) { + data = Tcl_GetStringFromObj(formatObj, &length); + Tcl_DStringAppend(&cachePtr->formatString, data, length); + } + cachePtr->nsvgImage = nsvgImage; + cachePtr->ropts = *ropts; + return 1; + } + return 0; +} + +/* + *---------------------------------------------------------------------- + * + * GetCachedSVG -- + * + * Try to get the NSVGimage from the internal cache. + * + * Results: + * Return the found NSVGimage on success, and NULL otherwise. + * + * Side effects: + * Calls the CleanCache() function. + * + *---------------------------------------------------------------------- + */ + +static NSVGimage * +GetCachedSVG( + Tcl_Interp *interp, + ClientData dataOrChan, + Tcl_Obj *formatObj, + RastOpts *ropts) +{ + int length; + const char *data; + NSVGcache *cachePtr = GetCachePtr(interp); + NSVGimage *nsvgImage = NULL; + + if ((cachePtr != NULL) && (cachePtr->nsvgImage != NULL) && + (cachePtr->dataOrChan == dataOrChan)) { + if (formatObj != NULL) { + data = Tcl_GetStringFromObj(formatObj, &length); + if (strcmp(data, Tcl_DStringValue(&cachePtr->formatString)) == 0) { + nsvgImage = cachePtr->nsvgImage; + *ropts = cachePtr->ropts; + cachePtr->nsvgImage = NULL; + } + } else if (Tcl_DStringLength(&cachePtr->formatString) == 0) { + nsvgImage = cachePtr->nsvgImage; + *ropts = cachePtr->ropts; + cachePtr->nsvgImage = NULL; + } + } + CleanCache(interp); + return nsvgImage; +} + +/* + *---------------------------------------------------------------------- + * + * CleanCache -- + * + * Reset the cache and delete the saved image in it. + * + * Results: + * + * Side effects: + * + *---------------------------------------------------------------------- + */ + +static void +CleanCache(Tcl_Interp *interp) +{ + NSVGcache *cachePtr = GetCachePtr(interp); + + if (cachePtr != NULL) { + cachePtr->dataOrChan = NULL; + Tcl_DStringSetLength(&cachePtr->formatString, 0); + if (cachePtr->nsvgImage != NULL) { + nsvgDelete(cachePtr->nsvgImage); + cachePtr->nsvgImage = NULL; + } + } +} + +/* + *---------------------------------------------------------------------- + * + * FreeCache -- + * + * This function is called to clean up the internal cache data. + * + * Results: + * + * Side effects: + * Existing image data in the cache and the cache will be deleted. + * + *---------------------------------------------------------------------- + */ + +static void +FreeCache(ClientData clientData, Tcl_Interp *interp) +{ + NSVGcache *cachePtr = clientData; + + Tcl_DStringFree(&cachePtr->formatString); + if (cachePtr->nsvgImage != NULL) { + nsvgDelete(cachePtr->nsvgImage); + } + ckfree(cachePtr); +} + -- cgit v0.12 From 6836803d2ce10a72b5bf56444fcaf0dfbfa5e96f Mon Sep 17 00:00:00 2001 From: fvogel Date: Tue, 15 May 2018 19:35:34 +0000 Subject: Add missing bit to makefile.vc to try to make it compile with MSVC --- win/makefile.vc | 1 + 1 file changed, 1 insertion(+) diff --git a/win/makefile.vc b/win/makefile.vc index 2382cad..6bed72d 100644 --- a/win/makefile.vc +++ b/win/makefile.vc @@ -219,6 +219,7 @@ TKOBJS = \ $(TMP_DIR)\tkImgGIF.obj \ $(TMP_DIR)\tkImgPNG.obj \ $(TMP_DIR)\tkImgPPM.obj \ + $(TMP_DIR)\tkImgSVGnano.obj \ $(TMP_DIR)\tkImgPhoto.obj \ $(TMP_DIR)\tkImgPhInstance.obj \ $(TMP_DIR)\tkImgUtil.obj \ -- cgit v0.12 From d36fcadcbbefb8f2d0c188cded43e2dd32610252 Mon Sep 17 00:00:00 2001 From: fvogel Date: Wed, 16 May 2018 18:16:33 +0000 Subject: =?UTF-8?q?New=20files=20provided=20by=20Ren=C3=A9=20Zaumseil?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- generic/tkImgSVGnano.c | 66 ++++++++++++++++++++++++++------------------------ tests/imgSVGnano.test | 65 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+), 31 deletions(-) create mode 100644 tests/imgSVGnano.test diff --git a/generic/tkImgSVGnano.c b/generic/tkImgSVGnano.c index 26236da..73044c0 100644 --- a/generic/tkImgSVGnano.c +++ b/generic/tkImgSVGnano.c @@ -36,21 +36,6 @@ typedef struct { } RastOpts; /* - * The format record for the SVG nano file format: - */ - -Tk_PhotoImageFormat tkImgFmtSVGnano = { - "svgnano", /* name */ - FileMatchSVG, /* fileMatchProc */ - StringMatchSVG, /* stringMatchProc */ - FileReadSVG, /* fileReadProc */ - StringReadSVG, /* stringReadProc */ - NULL, /* fileWriteProc */ - NULL, /* stringWriteProc */ - NULL -}; - -/* * Per interp cache of last NSVGimage which was matched to * be immediately rasterized after the match. This helps to * eliminate double parsing of the SVG file/string. @@ -93,6 +78,21 @@ static void CleanCache(Tcl_Interp *interp); static void FreeCache(ClientData clientData, Tcl_Interp *interp); /* + * The format record for the SVG nano file format: + */ + +Tk_PhotoImageFormat tkImgFmtSVGnano = { + "svgnano", /* name */ + FileMatchSVG, /* fileMatchProc */ + StringMatchSVG, /* stringMatchProc */ + FileReadSVG, /* fileReadProc */ + StringReadSVG, /* stringReadProc */ + NULL, /* fileWriteProc */ + NULL, /* stringWriteProc */ + NULL +}; + +/* *---------------------------------------------------------------------- * * FileMatchSVG -- @@ -134,8 +134,8 @@ FileMatchSVG( nsvgImage = ParseSVGWithOptions(interp, data, length, formatObj, &ropts); Tcl_DecrRefCount(dataObj); if (nsvgImage != NULL) { - *widthPtr = ceil(nsvgImage->width * ropts.scale); - *heightPtr = ceil(nsvgImage->height * ropts.scale); + *widthPtr = (int) ceil(nsvgImage->width * ropts.scale); + *heightPtr = (int) ceil(nsvgImage->height * ropts.scale); if ((*widthPtr <= 0) || (*heightPtr <= 0)) { nsvgDelete(nsvgImage); return 0; @@ -189,7 +189,7 @@ FileReadSVG( if (Tcl_ReadChars(chan, dataObj, -1, 0) == -1) { /* in case of an error reading the file */ Tcl_DecrRefCount(dataObj); - Tcl_SetResult(interp, "read error", TCL_STATIC); + Tcl_SetObjResult(interp, Tcl_NewStringObj("read error", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "READ_ERROR", NULL); return TCL_ERROR; } @@ -239,8 +239,12 @@ StringMatchSVG( data = Tcl_GetStringFromObj(dataObj, &length); nsvgImage = ParseSVGWithOptions(interp, data, length, formatObj, &ropts); if (nsvgImage != NULL) { - *widthPtr = ceil(nsvgImage->width * ropts.scale); - *heightPtr = ceil(nsvgImage->height * ropts.scale); + *widthPtr = (int) ceil(nsvgImage->width * ropts.scale); + *heightPtr = (int) ceil(nsvgImage->height * ropts.scale); + if ((*widthPtr <= 0) || (*heightPtr <= 0)) { + nsvgDelete(nsvgImage); + return 0; + } if (!CacheSVG(interp, dataObj, formatObj, nsvgImage, &ropts)) { nsvgDelete(nsvgImage); } @@ -337,7 +341,7 @@ ParseSVGWithOptions( inputCopy = attemptckalloc(length+1); if (inputCopy == NULL) { - Tcl_SetResult(interp, "cannot alloc data buffer", TCL_STATIC); + Tcl_SetObjResult(interp, Tcl_NewStringObj("cannot alloc data buffer", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "OUT_OF_MEMORY", NULL); goto error; } @@ -359,10 +363,10 @@ ParseSVGWithOptions( int optIndex; /* - * Ignore the "svg" part of the format specification. + * Ignore the "svgnano" part of the format specification. */ - if (!strcasecmp(Tcl_GetString(objv[0]), "svg")) { + if (!strcasecmp(Tcl_GetString(objv[0]), "svgnano")) { continue; } @@ -426,9 +430,9 @@ ParseSVGWithOptions( } } - nsvgImage = nsvgParse(inputCopy, unit, dpi); + nsvgImage = nsvgParse(inputCopy, unit, (float) dpi); if (nsvgImage == NULL) { - Tcl_SetResult(interp, "cannot parse SVG image", TCL_STATIC); + Tcl_SetObjResult(interp, Tcl_NewStringObj("cannot parse SVG image", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "PARSE_ERROR", NULL); goto error; } @@ -476,23 +480,23 @@ RasterizeSVG( unsigned char *imgData; Tk_PhotoImageBlock svgblock; - w = ceil(nsvgImage->width * ropts->scale); - h = ceil(nsvgImage->height * ropts->scale); + w = (int) ceil(nsvgImage->width * ropts->scale); + h = (int) ceil(nsvgImage->height * ropts->scale); rast = nsvgCreateRasterizer(); if (rast == NULL) { - Tcl_SetResult(interp, "cannot initialize rasterizer", TCL_STATIC); + Tcl_SetObjResult(interp, Tcl_NewStringObj("cannot initialize rasterizer", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "RASTERIZER_ERROR", NULL); goto cleanAST; } imgData = attemptckalloc(w * h *4); if (imgData == NULL) { - Tcl_SetResult(interp, "cannot alloc image buffer", TCL_STATIC); + Tcl_SetObjResult(interp, Tcl_NewStringObj("cannot alloc image buffer", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "SVG", "OUT_OF_MEMORY", NULL); goto cleanRAST; } - nsvgRasterize(rast, nsvgImage, ropts->x, ropts->y, - ropts->scale, imgData, w, h, w * 4); + nsvgRasterize(rast, nsvgImage, (float) ropts->x, (float) ropts->y, + (float) ropts->scale, imgData, w, h, w * 4); /* transfer the data to a photo block */ svgblock.pixelPtr = imgData; svgblock.width = w; diff --git a/tests/imgSVGnano.test b/tests/imgSVGnano.test new file mode 100644 index 0000000..499a36f --- /dev/null +++ b/tests/imgSVGnano.test @@ -0,0 +1,65 @@ +# This file is a Tcl script to test out the code in tkImgSVGnano.c, which reads +# and write SVG-format image files for photo widgets. The files is organized +# in the standard fashion for Tcl tests. +# +# Copyright (c) 2018 Rene Zaumseil +# All rights reserved. + +package require tcltest 2.2 +namespace import ::tcltest::* +eval tcltest::configure $argv +tcltest::loadTestedCommands +imageInit + +namespace eval svgnano { + variable data + set data(plus) { + + + + + + + + +} + set data(bad) { +} + +test imgSVGnano-1.1 {reading simple image} -setup { + catch {rename foo ""} +} -body { + image create photo foo -data $data(plus) + list [image width foo] [image height foo] +} -cleanup { + rename foo "" +} -result {100 100} + +test imgSVGnano-1.2 {simple image with options} -setup { + catch {rename foo ""} +} -body { + image create photo foo -data $data(plus) -format {svgnano -dpi 100 -scale 3} + list [image width foo] [image height foo] +} -cleanup { + rename foo "" +} -result {300 300} + +test imgSVGnano-2.1 {reading a bad image} -body { + image create photo foo -format svgnano -data $data(bad) +} -returnCodes error -result {couldn't recognize image data} +test imgSVGnano-2.2 {using bad option} -body { + image create photo -data $data(plus) -format {svgnano -scale 0} +} -returnCodes error -result {couldn't recognize image data} + +};# end of namespace svgnano + +namespace delete svgnano +imageFinish +cleanupTests +return + +# Local Variables: +# mode: tcl +# fill-column: 78 +# End: -- cgit v0.12 From 37349167bfe39cd913f76d7fee2b58829833ca5b Mon Sep 17 00:00:00 2001 From: fvogel Date: Mon, 4 Jun 2018 21:03:04 +0000 Subject: =?UTF-8?q?Ren=C3=A9=20Zaumseil=20fixed=20a=20crash?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- generic/tkImgSVGnano.c | 1 + 1 file changed, 1 insertion(+) diff --git a/generic/tkImgSVGnano.c b/generic/tkImgSVGnano.c index 73044c0..d27016c 100644 --- a/generic/tkImgSVGnano.c +++ b/generic/tkImgSVGnano.c @@ -377,6 +377,7 @@ ParseSVGWithOptions( if (objc < 2) { ckfree(inputCopy); + inputCopy = NULL; Tcl_WrongNumArgs(interp, 1, objv, "value"); goto error; } -- cgit v0.12 From 27830e63ff84b223f0fde6d1039b18e7f9099ba7 Mon Sep 17 00:00:00 2001 From: fvogel Date: Mon, 4 Jun 2018 21:04:10 +0000 Subject: =?UTF-8?q?Test=20added=20by=20Ren=C3=A9=20Zaumseil=20for=20the=20?= =?UTF-8?q?crash=20he=20just=20fixed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/imgSVGnano.test | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/tests/imgSVGnano.test b/tests/imgSVGnano.test index 499a36f..82ea693 100644 --- a/tests/imgSVGnano.test +++ b/tests/imgSVGnano.test @@ -45,6 +45,17 @@ test imgSVGnano-1.2 {simple image with options} -setup { rename foo "" } -result {300 300} +# test on crash found by Koen Danckaert +test imgSVGnano-1.3 {reformat image options} -setup { + catch {rename foo ""} +} -body { + image create photo foo -data $data(plus) + foo configure -format {svgnano -scale} + list {} +} -cleanup { + rename foo "" +} -result {} + test imgSVGnano-2.1 {reading a bad image} -body { image create photo foo -format svgnano -data $data(bad) } -returnCodes error -result {couldn't recognize image data} -- cgit v0.12 From ae80940d633d4e743adb865a60c82318a74d3a57 Mon Sep 17 00:00:00 2001 From: fvogel Date: Wed, 6 Jun 2018 18:13:15 +0000 Subject: Make branch compile with MSVC 2008 (Express Edition) --- generic/nanosvg.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/generic/nanosvg.h b/generic/nanosvg.h index 8cdb728..1f2f71f 100644 --- a/generic/nanosvg.h +++ b/generic/nanosvg.h @@ -219,6 +219,9 @@ NANOSVG_SCOPE void nsvgDelete(NSVGimage* image); #else #define NSVG_INLINE #endif + #if !defined(strtoll) // old MSVC versions do not have strtoll() + #define strtoll _strtoi64 + #endif #else #define NSVG_INLINE inline #endif @@ -1140,7 +1143,7 @@ static double nsvg__atof(const char* s) // Parse integer part if (nsvg__isdigit(*cur)) { // Parse digit sequence - intPart = (double)strtoll(cur, &end, 10); + intPart = strtoll(cur, &end, 10); if (cur != end) { res = (double)intPart; hasIntPart = 1; -- cgit v0.12 From b8e5f4ebd4ba3018ee6bd0b30cdd30b7aec8ded0 Mon Sep 17 00:00:00 2001 From: fvogel Date: Wed, 13 Jun 2018 11:30:11 +0000 Subject: =?UTF-8?q?New=20files=20provided=20by=20Ren=C3=A9=20Zaumseil:=20p?= =?UTF-8?q?hoto.n=20man=20page=20updated,=20and=20tests=20refined.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- doc/photo.n | 9 +++++++++ tests/imgSVGnano.test | 22 ++++++++++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/doc/photo.n b/doc/photo.n index d875098..d7ad93d 100644 --- a/doc/photo.n +++ b/doc/photo.n @@ -551,6 +551,15 @@ an additional alpha filtering for the overall image, which allows the background on which the image is displayed to show through. This usually also has the effect of desaturating the image. The \fIalphaValue\fR must be between 0.0 and 1.0. +\fBsvgnano \-dpi\fI dpiValue\fR \-scale\fI scaleValue\fR \-unit\fI unitValue\fR \-x\fI xValue\fR \-y\fI yValue\fR +. +\fIdpiValue\fR is used in conversion between given coordinates and screen resolution. The value must be greater then 0.0. The default value is 96. +\fIscaleValue\fR is used to scale the resulting image. The value must be greater then 0.0. The default value is 1. +\fIunitValue\fR is the unit of all coordinates in the svg data. Available units are px (default, coordinates in pixel), mm , cm and in. +\fxValue\fR is used to move the created image in x-direction. The default value is 0. +\fyValue\fR is used to move the created image in y-direction. The default value is 0. +. +The svgnano format supports a wide range of SVG features, but something may be missing for instance text. .VE 8.6 .VS 8.7 .SH "COLOR FORMATS" diff --git a/tests/imgSVGnano.test b/tests/imgSVGnano.test index 82ea693..ec93f0a 100644 --- a/tests/imgSVGnano.test +++ b/tests/imgSVGnano.test @@ -50,11 +50,29 @@ test imgSVGnano-1.3 {reformat image options} -setup { catch {rename foo ""} } -body { image create photo foo -data $data(plus) - foo configure -format {svgnano -scale} + catch {foo configure -format {svgnano -scale}} list {} } -cleanup { rename foo "" -} -result {} +} -result {{}} + +test imgSVGnano-1.4 {image options} -setup { + catch {rename foo ""} +} -body { + image create photo foo -data $data(plus) + foo configure -format {svgnano -scale 2} + foo configure -format {svgnano -x 20 -y -10} + foo configure -format {svgnano -unit pt} + foo configure -format {svgnano -unit mm} + foo configure -format {svgnano -unit cm} + foo configure -format {svgnano -unit in} + foo configure -format {svgnano -unit px} + foo configure -format {svgnano -dpi 600} + list [image width foo] [image height foo] +} -cleanup { + rename foo "" +} -result {100 100} + test imgSVGnano-2.1 {reading a bad image} -body { image create photo foo -format svgnano -data $data(bad) -- cgit v0.12 From 11648c96884595e922b50bc13695d882171a8a73 Mon Sep 17 00:00:00 2001 From: oehhar Date: Fri, 15 Jun 2018 08:30:07 +0000 Subject: Make svg compile with MS VC++ 6 - attention - strtoll is replaced by strtol which has lower resolution. --- generic/nanosvg.h | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) mode change 100644 => 100755 generic/nanosvg.h diff --git a/generic/nanosvg.h b/generic/nanosvg.h old mode 100644 new mode 100755 index 1f2f71f..7e74f99 --- a/generic/nanosvg.h +++ b/generic/nanosvg.h @@ -85,6 +85,20 @@ extern "C" { #define NANOSVG_free free #endif +// float emulation for MS VC6++ compiler +#if (_MSC_VER == 1200) +#define tanf(a) (float)tan(a) +#define cosf(a) (float)cos(a) +#define sinf(a) (float)sin(a) +#define sqrtf(a) (float)sqrt(a) +#define fabsf(a) (float)abs(a) +#define acosf(a) (float)acos(a) +#define atan2f(a,b) (float)atan2(a,b) +#define ceilf(a) (float)ceil(a) +#define fmodf(a,b) (float)fmod(a,b) +#define floorf(a) (float)floor(a) +#endif + enum NSVGpaintType { NSVG_PAINT_NONE = 0, NSVG_PAINT_COLOR = 1, @@ -1129,7 +1143,11 @@ static double nsvg__atof(const char* s) char* cur = (char*)s; char* end = NULL; double res = 0.0, sign = 1.0; +#if (_MSC_VER == 1200) + __int64 intPart = 0, fracPart = 0; +#else long long intPart = 0, fracPart = 0; +#endif char hasIntPart = 0, hasFracPart = 0; // Parse optional sign @@ -1143,7 +1161,11 @@ static double nsvg__atof(const char* s) // Parse integer part if (nsvg__isdigit(*cur)) { // Parse digit sequence +#if (_MSC_VER == 1200) + intPart = strtol(cur, &end, 10); +#else intPart = strtoll(cur, &end, 10); +#endif if (cur != end) { res = (double)intPart; hasIntPart = 1; @@ -1156,7 +1178,11 @@ static double nsvg__atof(const char* s) cur++; // Skip '.' if (nsvg__isdigit(*cur)) { // Parse digit sequence +#if (_MSC_VER == 1200) + fracPart = strtol(cur, &end, 10); +#else fracPart = strtoll(cur, &end, 10); +#endif if (cur != end) { res += (double)fracPart / pow(10.0, (double)(end - cur)); hasFracPart = 1; -- cgit v0.12 From 621e67ddd5f49faa263d089410e8addac2ccdc9c Mon Sep 17 00:00:00 2001 From: stu Date: Wed, 4 Jul 2018 09:33:47 +0000 Subject: Changes based on recommendations in http://code.activestate.com/lists/tcl-core/19816/. Cleanup old code. --- generic/tkPkgConfig.c | 2 +- macosx/tkMacOSXMenus.c | 22 ---------------------- 2 files changed, 1 insertion(+), 23 deletions(-) diff --git a/generic/tkPkgConfig.c b/generic/tkPkgConfig.c index 56aa106..8019ac9 100644 --- a/generic/tkPkgConfig.c +++ b/generic/tkPkgConfig.c @@ -87,7 +87,7 @@ #if defined(_WIN32) || defined(__CYGWIN__) # define CFG_FONTSYSTEM "gdi" #elif defined(MAC_OSX_TK) -# define CFG_FONTSYSTEM "xft" +# define CFG_FONTSYSTEM "cocoa" #elif defined(HAVE_XFT) # define CFG_FONTSYSTEM "xft" #else diff --git a/macosx/tkMacOSXMenus.c b/macosx/tkMacOSXMenus.c index 91fbd1f..6fb889d 100644 --- a/macosx/tkMacOSXMenus.c +++ b/macosx/tkMacOSXMenus.c @@ -287,27 +287,6 @@ EDIT_ACTION(redo, Redo) *---------------------------------------------------------------------- */ -#if 0 -static Tcl_Obj * -GetWidgetDemoPath( - Tcl_Interp *interp) -{ - Tcl_Obj *libpath, *result = NULL; - - libpath = Tcl_GetVar2Ex(interp, "tk_library", NULL, TCL_GLOBAL_ONLY); - if (libpath) { - Tcl_Obj *demo[2] = { Tcl_NewStringObj("demos", 5), - Tcl_NewStringObj("widget", 6) }; - - Tcl_IncrRefCount(libpath); - result = Tcl_FSJoinToPath(libpath, 2, demo); - Tcl_DecrRefCount(libpath); - } else { - Tcl_ResetResult(interp); - } - return result; -} -#else static Tcl_Obj * GetWidgetDemoPath( Tcl_Interp *interp) @@ -326,7 +305,6 @@ GetWidgetDemoPath( Tcl_ResetResult(interp); return result; } -#endif /* *---------------------------------------------------------------------- -- cgit v0.12 From 4e79eb4b84580b3f9a303174e2771e8a3ad0105c Mon Sep 17 00:00:00 2001 From: fvogel Date: Thu, 6 Sep 2018 07:56:35 +0000 Subject: Make photo.n compile to html again by fixing syntax errors. Also, reword a bit the documentation for the svgnano format. --- doc/photo.n | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/doc/photo.n b/doc/photo.n index d7ad93d..d84c33d 100644 --- a/doc/photo.n +++ b/doc/photo.n @@ -551,15 +551,24 @@ an additional alpha filtering for the overall image, which allows the background on which the image is displayed to show through. This usually also has the effect of desaturating the image. The \fIalphaValue\fR must be between 0.0 and 1.0. -\fBsvgnano \-dpi\fI dpiValue\fR \-scale\fI scaleValue\fR \-unit\fI unitValue\fR \-x\fI xValue\fR \-y\fI yValue\fR -. -\fIdpiValue\fR is used in conversion between given coordinates and screen resolution. The value must be greater then 0.0. The default value is 96. -\fIscaleValue\fR is used to scale the resulting image. The value must be greater then 0.0. The default value is 1. -\fIunitValue\fR is the unit of all coordinates in the svg data. Available units are px (default, coordinates in pixel), mm , cm and in. -\fxValue\fR is used to move the created image in x-direction. The default value is 0. -\fyValue\fR is used to move the created image in y-direction. The default value is 0. -. -The svgnano format supports a wide range of SVG features, but something may be missing for instance text. +.TP +\fBsvgnano \-dpi\fI dpiValue\fB \-scale\fI scaleValue\fB \-unit\fI unitValue\fB \-x\fI xValue\fB \-y\fI yValue\fR +. +\fIdpiValue\fR is used in conversion between given coordinates and +screen resolution. The value must be greater than 0 and the default +value is 96. +\fIscaleValue\fR is used to scale the resulting image. The value must +be greater than 0 and the default value is 1. +\fIunitValue\fR is the unit of all coordinates in the SVG data. +Available units are px (default, coordinates in pixel), mm , cm and +in. +\fIxValue\fR and \fIyValue\fR are used to move the created image +respectively in x-direction and y-direction. The default value is 0 +for both. +. +The svgnano format supports a wide range of SVG features, but the +full SVG standard is not available, for instance the 'text' feature +is missing. .VE 8.6 .VS 8.7 .SH "COLOR FORMATS" -- cgit v0.12 From a6e11187e0005e79278bcc7f9192f11062dee7b0 Mon Sep 17 00:00:00 2001 From: fvogel Date: Sat, 22 Sep 2018 14:38:42 +0000 Subject: Add some more info about the svgnano format in the photo.n man page --- doc/photo.n | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/photo.n b/doc/photo.n index d84c33d..a904f6a 100644 --- a/doc/photo.n +++ b/doc/photo.n @@ -560,8 +560,8 @@ value is 96. \fIscaleValue\fR is used to scale the resulting image. The value must be greater than 0 and the default value is 1. \fIunitValue\fR is the unit of all coordinates in the SVG data. -Available units are px (default, coordinates in pixel), mm , cm and -in. +Available units are px (default, coordinates in pixel), pt (1/72 inch), +pc (12 pt), mm , cm and in. \fIxValue\fR and \fIyValue\fR are used to move the created image respectively in x-direction and y-direction. The default value is 0 for both. @@ -569,6 +569,10 @@ for both. The svgnano format supports a wide range of SVG features, but the full SVG standard is not available, for instance the 'text' feature is missing. +. +Currently only SVG images reading and conversion into (pixel-based +format) photos is supported: Tk does not (yet) support bundling photo +images in SVG vector graphics. .VE 8.6 .VS 8.7 .SH "COLOR FORMATS" -- cgit v0.12 From 70faead3ab7c265f9117593c313450f0f8eb4497 Mon Sep 17 00:00:00 2001 From: fvogel Date: Mon, 3 Dec 2018 19:06:39 +0000 Subject: =?UTF-8?q?New=20files=20from=20Ren=C3=A9=20Zaumseil?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- doc/photo.n | 45 ++++++++++++++++++++++++++++++++++++++------- generic/tkImgSVGnano.c | 20 +++++--------------- 2 files changed, 43 insertions(+), 22 deletions(-) diff --git a/doc/photo.n b/doc/photo.n index a904f6a..a2601bd 100644 --- a/doc/photo.n +++ b/doc/photo.n @@ -552,7 +552,7 @@ background on which the image is displayed to show through. This usually also has the effect of desaturating the image. The \fIalphaValue\fR must be between 0.0 and 1.0. .TP -\fBsvgnano \-dpi\fI dpiValue\fB \-scale\fI scaleValue\fB \-unit\fI unitValue\fB \-x\fI xValue\fB \-y\fI yValue\fR +\fBsvg \-dpi\fI dpiValue\fB \-scale\fI scaleValue\fB \-unit\fI unitValue\fR . \fIdpiValue\fR is used in conversion between given coordinates and screen resolution. The value must be greater than 0 and the default @@ -562,13 +562,44 @@ be greater than 0 and the default value is 1. \fIunitValue\fR is the unit of all coordinates in the SVG data. Available units are px (default, coordinates in pixel), pt (1/72 inch), pc (12 pt), mm , cm and in. -\fIxValue\fR and \fIyValue\fR are used to move the created image -respectively in x-direction and y-direction. The default value is 0 -for both. -. -The svgnano format supports a wide range of SVG features, but the +The svg format supports a wide range of SVG features, but the full SVG standard is not available, for instance the 'text' feature -is missing. +is missing and silently ignores when reading the SVG data. +The supported SVG features are: +. +.RS +\fB elements:\fR g, path, rect, circle, ellipse, line, polyline, polygon, +linearGradient, radialGradient, stop, defs, svg, style \fR +. +\fB attributes:\fR width, height, viewBox, +preserveAspectRatio with none, xMin, xMid, xMax, yMin, yMid, yMax, slice +. +\fB gradient attributes:\fR gradientUnits with objectBoundingBox, +gradientTransform, cx, cy, r fx, fy x1, y1, x2, y2 +spreadMethod with pad, reflect or repeat, +xlink:href +. +\fB poly attibutes: \fR points +. +\fB line attibutes: \fR x1, y1, x2, y2 +. +\fB ellipse attibutes: \fR cx, cy, rx, ry +. +\fB circle attibutes: \fR cx, cy, r +. +\fB rectangle attibutes: \fR x, y, width, height, rx, ry +. +\fB path attibutes: \fR d with m, M, l, L, h, H, v, V, c, C, s, S, q, Q, t, T, a, A, z, Z +. +\fB style attibutes: \fR display with none, visibility, hidden, visible, +fill with nonzero and evenodd, opacity, fill-opacity, +stroke, stroke-width, stroke-dasharray, stroke-dashoffset, stroke-opacity, +stroke-linecap with butt, round and square, +stroke-linejoin with miter, round and bevel, stroke-miterlimit +fill-rule, font-size, +transform with matrix, translate, scale, rotate, skewX and skewY, +stop-color, stop-opacity, offset, id, class +.RE . Currently only SVG images reading and conversion into (pixel-based format) photos is supported: Tk does not (yet) support bundling photo diff --git a/generic/tkImgSVGnano.c b/generic/tkImgSVGnano.c index d27016c..f86c45e 100644 --- a/generic/tkImgSVGnano.c +++ b/generic/tkImgSVGnano.c @@ -82,7 +82,7 @@ static void FreeCache(ClientData clientData, Tcl_Interp *interp); */ Tk_PhotoImageFormat tkImgFmtSVGnano = { - "svgnano", /* name */ + "svg", /* name */ FileMatchSVG, /* fileMatchProc */ StringMatchSVG, /* stringMatchProc */ FileReadSVG, /* fileReadProc */ @@ -328,10 +328,10 @@ ParseSVGWithOptions( char *inputCopy = NULL; NSVGimage *nsvgImage; static const char *const fmtOptions[] = { - "-dpi", "-scale", "-unit", "-x", "-y", NULL + "-dpi", "-scale", "-unit", NULL }; enum fmtOptions { - OPT_DPI, OPT_SCALE, OPT_UNIT, OPT_X, OPT_Y + OPT_DPI, OPT_SCALE, OPT_UNIT }; /* @@ -363,10 +363,10 @@ ParseSVGWithOptions( int optIndex; /* - * Ignore the "svgnano" part of the format specification. + * Ignore the "svg" part of the format specification. */ - if (!strcasecmp(Tcl_GetString(objv[0]), "svgnano")) { + if (!strcasecmp(Tcl_GetString(objv[0]), "svg")) { continue; } @@ -418,16 +418,6 @@ ParseSVGWithOptions( unit[2] = '\0'; } break; - case OPT_X: - if (Tcl_GetDoubleFromObj(interp, objv[0], &ropts->x) == TCL_ERROR) { - goto error; - } - break; - case OPT_Y: - if (Tcl_GetDoubleFromObj(interp, objv[0], &ropts->y) == TCL_ERROR) { - goto error; - } - break; } } -- cgit v0.12 From 6827b7524eabe58dc7973ab7cbb9197271627eab Mon Sep 17 00:00:00 2001 From: fvogel Date: Mon, 3 Dec 2018 19:10:21 +0000 Subject: Fix syntax in photo.n so that the html help builds --- doc/photo.n | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/photo.n b/doc/photo.n index a2601bd..7df6e3c 100644 --- a/doc/photo.n +++ b/doc/photo.n @@ -569,7 +569,7 @@ The supported SVG features are: . .RS \fB elements:\fR g, path, rect, circle, ellipse, line, polyline, polygon, -linearGradient, radialGradient, stop, defs, svg, style \fR +linearGradient, radialGradient, stop, defs, svg, style . \fB attributes:\fR width, height, viewBox, preserveAspectRatio with none, xMin, xMid, xMax, yMin, yMid, yMax, slice -- cgit v0.12 From c14733a8c0255097c66badda7e20fad95a69dfd6 Mon Sep 17 00:00:00 2001 From: fvogel Date: Tue, 4 Dec 2018 21:12:56 +0000 Subject: Fix rendering of photo.n a bit --- doc/photo.n | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/doc/photo.n b/doc/photo.n index 7df6e3c..2f6076e 100644 --- a/doc/photo.n +++ b/doc/photo.n @@ -570,28 +570,28 @@ The supported SVG features are: .RS \fB elements:\fR g, path, rect, circle, ellipse, line, polyline, polygon, linearGradient, radialGradient, stop, defs, svg, style -. +.PP \fB attributes:\fR width, height, viewBox, preserveAspectRatio with none, xMin, xMid, xMax, yMin, yMid, yMax, slice -. +.PP \fB gradient attributes:\fR gradientUnits with objectBoundingBox, gradientTransform, cx, cy, r fx, fy x1, y1, x2, y2 spreadMethod with pad, reflect or repeat, xlink:href -. -\fB poly attibutes: \fR points -. -\fB line attibutes: \fR x1, y1, x2, y2 -. -\fB ellipse attibutes: \fR cx, cy, rx, ry -. -\fB circle attibutes: \fR cx, cy, r -. -\fB rectangle attibutes: \fR x, y, width, height, rx, ry -. -\fB path attibutes: \fR d with m, M, l, L, h, H, v, V, c, C, s, S, q, Q, t, T, a, A, z, Z -. -\fB style attibutes: \fR display with none, visibility, hidden, visible, +.PP +\fB poly attributes: \fR points +.PP +\fB line attributes: \fR x1, y1, x2, y2 +.PP +\fB ellipse attributes: \fR cx, cy, rx, ry +.PP +\fB circle attributes: \fR cx, cy, r +.PP +\fB rectangle attributes: \fR x, y, width, height, rx, ry +.PP +\fB path attributes: \fR d with m, M, l, L, h, H, v, V, c, C, s, S, q, Q, t, T, a, A, z, Z +.PP +\fB style attributes: \fR display with none, visibility, hidden, visible, fill with nonzero and evenodd, opacity, fill-opacity, stroke, stroke-width, stroke-dasharray, stroke-dashoffset, stroke-opacity, stroke-linecap with butt, round and square, -- cgit v0.12 From c059c056e55ab968ac7c513bbd96720655e06da3 Mon Sep 17 00:00:00 2001 From: fvogel Date: Mon, 31 Dec 2018 13:27:01 +0000 Subject: Fix proposal by Simon Geard for [6ce6e74635]: TIP415 implementation does not handle small arcs correctly --- generic/tkCanvArc.c | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/generic/tkCanvArc.c b/generic/tkCanvArc.c index 8bc1781..02deebe 100644 --- a/generic/tkCanvArc.c +++ b/generic/tkCanvArc.c @@ -13,6 +13,8 @@ #include "tkInt.h" #include "tkCanvas.h" +#include "float.h" + /* * The structure below defines the record for each arc item. */ @@ -183,7 +185,7 @@ static void ComputeArcBbox(Tk_Canvas canvas, ArcItem *arcPtr); static int ConfigureArc(Tcl_Interp *interp, Tk_Canvas canvas, Tk_Item *itemPtr, int objc, Tcl_Obj *const objv[], int flags); -static void ComputeArcFromHeight(ArcItem *arcPtr); +static int ComputeArcFromHeight(ArcItem *arcPtr); static int CreateArc(Tcl_Interp *interp, Tk_Canvas canvas, struct Tk_Item *itemPtr, int objc, Tcl_Obj *const objv[]); @@ -473,7 +475,14 @@ ConfigureArc( * overridden. */ if (arcPtr->height != 0) { - ComputeArcFromHeight(arcPtr); + int ret = ComputeArcFromHeight(arcPtr); + if (ret != TCL_OK) { + Tcl_SetObjResult(interp, Tcl_ObjPrintf( + "coordinates too close to define a chord")); + Tcl_SetErrorCode(interp, "TK", "CANVAS", "COORDS", "ARC", + NULL); + return ret; + } ComputeArcBbox(canvas, arcPtr); } @@ -593,7 +602,7 @@ ConfigureArc( * end-point and height (!= 0). * * Results: - * None. + * TCL_ERROR if the chord length is zero, TCL_OK otherwise. * * Side effects: * The height parameter is set to 0 on exit. @@ -601,7 +610,7 @@ ConfigureArc( *-------------------------------------------------------------- */ -static void +static int ComputeArcFromHeight( ArcItem* arcPtr) { @@ -613,6 +622,10 @@ ComputeArcFromHeight( chordLen = hypot(arcPtr->endPoint[1] - arcPtr->startPoint[1], arcPtr->startPoint[0] - arcPtr->endPoint[0]); + + if (chordLen < DBL_EPSILON) + return TCL_ERROR; + chordDir[0] = (arcPtr->endPoint[0] - arcPtr->startPoint[0]) / chordLen; chordDir[1] = (arcPtr->endPoint[1] - arcPtr->startPoint[1]) / chordLen; chordCen[0] = (arcPtr->startPoint[0] + arcPtr->endPoint[0]) / 2; @@ -666,6 +679,8 @@ ComputeArcFromHeight( */ arcPtr->height = 0; + + return TCL_OK; } /* -- cgit v0.12 From 8550ff36184d6cbc3f17c5ed7843337b6cc2349e Mon Sep 17 00:00:00 2001 From: fvogel Date: Mon, 21 Jan 2019 07:06:14 +0000 Subject: Fix formatting --- generic/tkCanvArc.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/generic/tkCanvArc.c b/generic/tkCanvArc.c index 07813ea..ead03bf 100644 --- a/generic/tkCanvArc.c +++ b/generic/tkCanvArc.c @@ -476,13 +476,13 @@ ConfigureArc( */ if (arcPtr->height != 0) { int ret = ComputeArcFromHeight(arcPtr); - if (ret != TCL_OK) { - Tcl_SetObjResult(interp, Tcl_ObjPrintf( - "coordinates too close to define a chord")); - Tcl_SetErrorCode(interp, "TK", "CANVAS", "COORDS", "ARC", - NULL); - return ret; - } + if (ret != TCL_OK) { + Tcl_SetObjResult(interp, Tcl_ObjPrintf( + "coordinates too close to define a chord")); + Tcl_SetErrorCode(interp, "TK", "CANVAS", "COORDS", "ARC", + NULL); + return ret; + } ComputeArcBbox(canvas, arcPtr); } @@ -806,7 +806,7 @@ ComputeArcBbox( ComputeArcOutline(canvas,arcPtr); /* - * To compute the bounding box, start with the the bbox formed by the two + * To compute the bounding box, start with the bbox formed by the two * endpoints of the arc. Then add in the center of the arc's oval (if * relevant) and the 3-o'clock, 6-o'clock, 9-o'clock, and 12-o'clock * positions, if they are relevant. -- cgit v0.12 From 4dc6002eb8151fd593fca4ec98db71109fcda126 Mon Sep 17 00:00:00 2001 From: culler Date: Fri, 8 Mar 2019 18:54:30 +0000 Subject: Fix bug [9286526144]: incorrect menu locations for ttk menubuttons. --- library/menu.tcl | 9 --- library/ttk/menubutton.tcl | 134 ++++++++++++++++++++++++++++++++++----------- 2 files changed, 101 insertions(+), 42 deletions(-) diff --git a/library/menu.tcl b/library/menu.tcl index 8d06868..9d6370a 100644 --- a/library/menu.tcl +++ b/library/menu.tcl @@ -1178,15 +1178,6 @@ if {[tk windowingsystem] eq "aqua"} { set entry 0 } } - if {$entry ne ""} { - if {$entry == [$menu index last]} { - set entryHeight [expr {[winfo reqheight $menu] \ - - [$menu yposition $entry]}] - } else { - set entryHeight [expr {[$menu yposition [expr {$entry+1}]] \ - - [$menu yposition $entry]}] - } - } set x [winfo rootx $button] set y [winfo rooty $button] switch [$button cget -direction] { diff --git a/library/ttk/menubutton.tcl b/library/ttk/menubutton.tcl index 2be064c..9d12b05 100644 --- a/library/ttk/menubutton.tcl +++ b/library/ttk/menubutton.tcl @@ -61,43 +61,106 @@ if {[tk windowingsystem] eq "x11"} { } # PostPosition -- -# Returns the x and y coordinates where the menu -# should be posted, based on the menubutton and menu size -# and -direction option. +# Returns x and y coordinates and a menu item index. +# If the index is not an empty string the menu should +# be posted so that the upper left corner of the indexed +# menu item is located at the point (x, y). Otherwise +# the top left corner of the menu itself should be located +# at that point. # # TODO: adjust menu width to be at least as wide as the button # for -direction above, below. # -proc ttk::menubutton::PostPosition {mb menu} { - set x [winfo rootx $mb] - set y [winfo rooty $mb] - set dir [$mb cget -direction] - set bw [winfo width $mb] - set bh [winfo height $mb] - set mw [winfo reqwidth $menu] - set mh [winfo reqheight $menu] - set sw [expr {[winfo screenwidth $menu] - $bw - $mw}] - set sh [expr {[winfo screenheight $menu] - $bh - $mh}] - - switch -- $dir { - above { if {$y >= $mh} { incr y -$mh } { incr y $bh } } - below { if {$y <= $sh} { incr y $bh } { incr y -$mh } } - left { if {$x >= $mw} { incr x -$mw } { incr x $bw } } - right { if {$x <= $sw} { incr x $bw } { incr x -$mw } } - flush { - # post menu atop menubutton. - # If there's a menu entry whose label matches the - # menubutton -text, assume this is an optionmenu - # and place that entry over the menubutton. - set index [FindMenuEntry $menu [$mb cget -text]] - if {$index ne ""} { - incr y -[$menu yposition $index] +if {[tk windowingsystem] eq "aqua"} { + proc ::ttk::menubutton::PostPosition {mb menu} { + set mh [expr {[winfo reqheight $menu] - 6}] + set bh [expr {[winfo height $mb] + 1}] + set mw [expr {[winfo reqwidth $menu] - 2}] + set bw [expr {[winfo width $mb] -1}] + set dF [expr {[winfo width $mb] - [winfo reqwidth $menu] -9}] + set entry "" + set entry [::tk::MenuFindName $menu [$mb cget -text]] + if {$entry eq ""} { + set entry 0 + } + set x [winfo rootx $mb] + set y [expr {2 + [winfo rooty $mb]}] + switch [$mb cget -direction] { + above { + set entry "" + incr y -$mh + } + below { + set entry "" + incr y $bh + } + left { + incr x -$mw + } + right { + incr x $bw + } + default { + incr x $dF } } + return [list $x $y $entry] + } +} else { + proc ::ttk::menubutton::PostPosition {mb menu} { + set mh [expr {[winfo reqheight $menu]}] + set bh [expr {[winfo height $mb]}] + set mw [expr {[winfo reqwidth $menu]}] + set bw [expr {[winfo width $mb]}] + set dF [expr {[winfo width $mb] - [winfo reqwidth $menu]}] + if {[tk windowingsystem] eq "win32"} { + incr mh 6 + incr mw 16 + } + set entry {} + set entry [::tk::MenuFindName $menu [$mb cget -text]] + if {$entry eq {}} { + set entry 0 + } + set x [winfo rootx $mb] + set y [winfo rooty $mb] + switch [$mb cget -direction] { + above { + set entry {} + incr y -$mh + # if we go offscreen to the top, show as 'below' + if {$y < [winfo vrooty $mb]} { + set y [expr {[winfo vrooty $mb] + [winfo rooty $mb]\ + + [winfo reqheight $mb]}] + } + } + below { + set entry {} + incr y $bh + # if we go offscreen to the bottom, show as 'above' + if {($y + $mh) > ([winfo vrooty $mb] + [winfo vrootheight $mb])} { + set y [expr {[winfo vrooty $mb] + [winfo vrootheight $mb] \ + + [winfo rooty $mb] - $mh}] + } + } + left { + incr x -$mw + } + right { + incr x $bw + } + default { + if {[$mb cget -style] eq ""} { + incr x [expr {([winfo width $mb] - \ + [winfo reqwidth $menu])/ 2}] + } else { + incr y $bh + } + } + } + return [list $x $y $entry] } - - return [list $x $y] } # Popdown -- @@ -107,8 +170,8 @@ proc ttk::menubutton::Popdown {mb} { if {[$mb instate disabled] || [set menu [$mb cget -menu]] eq ""} { return } - foreach {x y} [PostPosition $mb $menu] { break } - tk_popup $menu $x $y + foreach {x y entry} [PostPosition $mb $menu] { break } + tk_popup $menu $x $y $entry } # Pulldown (X11 only) -- @@ -121,13 +184,17 @@ proc ttk::menubutton::Pulldown {mb} { if {[$mb instate disabled] || [set menu [$mb cget -menu]] eq ""} { return } - foreach {x y} [PostPosition $mb $menu] { break } set State(pulldown) 1 set State(oldcursor) [$mb cget -cursor] $mb state pressed $mb configure -cursor [$menu cget -cursor] - $menu post $x $y + foreach {x y entry} [PostPosition $mb $menu] { break } + if {$entry ne {}} { + $menu post $x $y $entry + } else { + $menu post $x $y + } tk_menuSetFocus $menu } @@ -143,6 +210,7 @@ proc ttk::menubutton::TransferGrab {mb} { set State(pulldown) 0 set menu [$mb cget -menu] + foreach {x y entry} [PostPosition $mb $menu] { break } tk_popup $menu [winfo rootx $menu] [winfo rooty $menu] } } -- cgit v0.12 From aa019c08a152fc9d3fd124aa780af6c90f7c68ad Mon Sep 17 00:00:00 2001 From: dkf Date: Mon, 11 Mar 2019 09:43:35 +0000 Subject: Basic implementation of TIP 164: [$canvas rotate] --- generic/tk.h | 6 ++- generic/tkCanvas.c | 110 +++++++++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 104 insertions(+), 12 deletions(-) diff --git a/generic/tk.h b/generic/tk.h index f106f1c..b5be2ce 100644 --- a/generic/tk.h +++ b/generic/tk.h @@ -1034,6 +1034,8 @@ typedef int (Tk_ItemAreaProc)(Tk_Canvas canvas, Tk_Item *itemPtr, double *rectPtr); typedef int (Tk_ItemPostscriptProc)(Tcl_Interp *interp, Tk_Canvas canvas, Tk_Item *itemPtr, int prepass); +typedef void (Tk_ItemRotateProc)(Tk_Canvas canvas, Tk_Item *itemPtr, + double originX, double originY, double angleRadians); typedef void (Tk_ItemScaleProc)(Tk_Canvas canvas, Tk_Item *itemPtr, double originX, double originY, double scaleX, double scaleY); @@ -1117,7 +1119,9 @@ typedef struct Tk_ItemType { /* Procedure to delete characters from an * item. */ struct Tk_ItemType *nextPtr;/* Used to link types together into a list. */ - char *reserved1; /* Reserved for future extension. */ + Tk_ItemRotateProc *rotateProc; + /* Procedure to rotate an item's coordinates + * about a point. */ int reserved2; /* Carefully compatible with */ char *reserved3; /* Jan Nijtmans dash patch */ char *reserved4; diff --git a/generic/tkCanvas.c b/generic/tkCanvas.c index f3778a6..8a05c86 100644 --- a/generic/tkCanvas.c +++ b/generic/tkCanvas.c @@ -560,6 +560,71 @@ ItemTranslate( itemPtr->typePtr->translateProc((Tk_Canvas) canvasPtr, itemPtr, xDelta, yDelta); } + +static inline void +ItemRotate( + TkCanvas *canvasPtr, + Tk_Item *itemPtr, + double x, + double y, + double angle) +{ + if (itemPtr->typePtr->rotateProc != NULL) { + itemPtr->typePtr->rotateProc((Tk_Canvas) canvasPtr, + itemPtr, x, y, angle); + } else { + int objc, i, ok = 1; + Tcl_Obj **objv; + double *coordv; + double s = sin(angle); + double c = cos(angle); + Tcl_Interp *interp = canvasPtr->interp; + + if (ItemCoords(canvasPtr, itemPtr, 0, NULL) == TCL_OK && + Tcl_ListObjGetElements(NULL, Tcl_GetObjResult(interp), + &objc, &objv) == TCL_OK) { + coordv = (double *) Tcl_Alloc(sizeof(double) * objc); + for (i=0 ; iflags |= REPICK_NEEDED; + } + break; + } case CANV_SCALE: { double xOrigin, yOrigin, xScale, yScale; -- cgit v0.12 From 6e2eb1fb209467279ed4ff451956fa1e58bac93c Mon Sep 17 00:00:00 2001 From: dkf Date: Mon, 11 Mar 2019 10:19:12 +0000 Subject: Starting to build out the per-item implementations --- generic/tkCanvArc.c | 57 ++++++++++++++++++++++- generic/tkCanvBmap.c | 45 ++++++++++++++++++- generic/tkCanvas.c | 124 ++++++++++++++++++++++++++++++++------------------- 3 files changed, 179 insertions(+), 47 deletions(-) diff --git a/generic/tkCanvArc.c b/generic/tkCanvArc.c index d2daa17..ca9ef34 100644 --- a/generic/tkCanvArc.c +++ b/generic/tkCanvArc.c @@ -214,6 +214,8 @@ static int HorizLineToArc(double x1, double x2, static int VertLineToArc(double x, double y1, double y2, double rx, double ry, double start, double extent); +static void RotateArc(Tk_Canvas canvas, Tk_Item *itemPtr, + double originX, double originY, double angleRad); /* * The structures below defines the arc item types by means of functions that @@ -241,7 +243,8 @@ Tk_ItemType tkArcType = { NULL, /* insertProc */ NULL, /* dTextProc */ NULL, /* nextPtr */ - NULL, 0, NULL, NULL + RotateArc, /* rotateProc */ + 0, NULL, NULL }; /* @@ -1493,6 +1496,58 @@ ScaleArc( /* *-------------------------------------------------------------- * + * RotateArc -- + * + * This function is called to rotate an arc by a given amount. + * + * Results: + * None. + * + * Side effects: + * The position of the arc is rotated by angleRad radians about (originX, + * originY), and the bounding box is updated in the generic part of the + * item structure. + * + *-------------------------------------------------------------- + */ + +static void +RotateArc( + Tk_Canvas canvas, + Tk_Item *itemPtr, + double originX, + double originY, + double angleRad) +{ + ArcItem *arcPtr = (ArcItem *) itemPtr; + double x, y, nx, ny; + double s = sin(angleRad); + double c = cos(angleRad); + + x = arcPtr->bbox[0] - originX; + y = arcPtr->bbox[1] - originY; + nx = x * c - y * s; + ny = x * s + y * c; + arcPtr->bbox[0] = nx + originX; + arcPtr->bbox[1] = ny + originY; + + x = arcPtr->bbox[2] - originX; + y = arcPtr->bbox[3] - originY; + nx = x * c - y * s; + ny = x * s + y * c; + arcPtr->bbox[2] = nx + originX; + arcPtr->bbox[3] = ny + originY; + + /* + * TODO: update the arc endpoints? + */ + + ComputeArcBbox(canvas, arcPtr); +} + +/* + *-------------------------------------------------------------- + * * TranslateArc -- * * This function is called to move an arc by a given amount. diff --git a/generic/tkCanvBmap.c b/generic/tkCanvBmap.c index b9de07b..948379d 100644 --- a/generic/tkCanvBmap.c +++ b/generic/tkCanvBmap.c @@ -105,6 +105,8 @@ static void DeleteBitmap(Tk_Canvas canvas, static void DisplayBitmap(Tk_Canvas canvas, Tk_Item *itemPtr, Display *display, Drawable dst, int x, int y, int width, int height); +static void RotateBitmap(Tk_Canvas canvas, Tk_Item *itemPtr, + double originX, double originY, double angleRad); static void ScaleBitmap(Tk_Canvas canvas, Tk_Item *itemPtr, double originX, double originY, double scaleX, double scaleY); @@ -137,7 +139,8 @@ Tk_ItemType tkBitmapType = { NULL, /* insertProc */ NULL, /* dTextProc */ NULL, /* nextPtr */ - NULL, 0, NULL, NULL + RotateBitmap, /* rotateProc */ + 0, NULL, NULL }; /* @@ -790,6 +793,46 @@ ScaleBitmap( /* *-------------------------------------------------------------- * + * RotateBitmap -- + * + * This function is called to rotate a bitmap's origin by a given amount. + * + * Results: + * None. + * + * Side effects: + * The position of the bitmap is rotated by angleRad radians about + * (originX, originY), and the bounding box is updated in the generic + * part of the item structure. + * + *-------------------------------------------------------------- + */ + +static void +RotateBitmap( + Tk_Canvas canvas, + Tk_Item *itemPtr, + double originX, + double originY, + double angleRad) +{ + BitmapItem *bmapPtr = (BitmapItem *) itemPtr; + double x, y, nx, ny; + double s = sin(angleRad); + double c = cos(angleRad); + + x = bmapPtr->x - originX; + y = bmapPtr->y - originY; + nx = x * c - y * s; + ny = x * s + y * c; + bmapPtr->x = nx + originX; + bmapPtr->y = ny + originY; + ComputeBitmapBbox(canvas, bmapPtr); +} + +/* + *-------------------------------------------------------------- + * * TranslateBitmap -- * * This function is called to move an item by a given amount. diff --git a/generic/tkCanvas.c b/generic/tkCanvas.c index 8a05c86..9e5ec3e 100644 --- a/generic/tkCanvas.c +++ b/generic/tkCanvas.c @@ -241,6 +241,9 @@ static void CanvasWorldChanged(ClientData instanceData); static int ConfigureCanvas(Tcl_Interp *interp, TkCanvas *canvasPtr, int argc, Tcl_Obj *const *argv, int flags); +static void DefaultRotateImplementation(TkCanvas *canvasPtr, + Tk_Item *itemPtr, double x, double y, + double angleRadians); static void DestroyCanvas(void *memPtr); static int DrawCanvas(Tcl_Interp *interp, ClientData clientData, Tk_PhotoHandle photohandle, int subsample, int zoom); static void DisplayCanvas(ClientData clientData); @@ -567,63 +570,94 @@ ItemRotate( Tk_Item *itemPtr, double x, double y, - double angle) + double angleRadians) { if (itemPtr->typePtr->rotateProc != NULL) { itemPtr->typePtr->rotateProc((Tk_Canvas) canvasPtr, - itemPtr, x, y, angle); + itemPtr, x, y, angleRadians); } else { - int objc, i, ok = 1; - Tcl_Obj **objv; - double *coordv; - double s = sin(angle); - double c = cos(angle); - Tcl_Interp *interp = canvasPtr->interp; - - if (ItemCoords(canvasPtr, itemPtr, 0, NULL) == TCL_OK && - Tcl_ListObjGetElements(NULL, Tcl_GetObjResult(interp), - &objc, &objv) == TCL_OK) { - coordv = (double *) Tcl_Alloc(sizeof(double) * objc); - for (i=0 ; iinterp; + + /* + * Get the coordinates out of the item. + */ + + if (ItemCoords(canvasPtr, itemPtr, 0, NULL) == TCL_OK && + Tcl_ListObjGetElements(NULL, Tcl_GetObjResult(interp), + &objc, &objv) == TCL_OK) { + coordv = (double *) Tcl_Alloc(sizeof(double) * objc); + for (i=0 ; i Date: Mon, 11 Mar 2019 20:32:17 +0000 Subject: More item types --- generic/tkCanvImg.c | 46 ++++++++++++++++++++++++++++++++++- generic/tkCanvLine.c | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++- generic/tkCanvPoly.c | 51 ++++++++++++++++++++++++++++++++++++--- generic/tkCanvText.c | 41 ++++++++++++++++++++++++++++++- generic/tkCanvWind.c | 42 +++++++++++++++++++++++++++++++- 5 files changed, 241 insertions(+), 7 deletions(-) diff --git a/generic/tkCanvImg.c b/generic/tkCanvImg.c index 70b9c79..20fcd52 100644 --- a/generic/tkCanvImg.c +++ b/generic/tkCanvImg.c @@ -94,6 +94,8 @@ static void DeleteImage(Tk_Canvas canvas, static void DisplayImage(Tk_Canvas canvas, Tk_Item *itemPtr, Display *display, Drawable dst, int x, int y, int width, int height); +static void RotateImage(Tk_Canvas canvas, Tk_Item *itemPtr, + double originX, double originY, double angleRad); static void ScaleImage(Tk_Canvas canvas, Tk_Item *itemPtr, double originX, double originY, double scaleX, double scaleY); @@ -126,7 +128,8 @@ Tk_ItemType tkImageType = { NULL, /* insertProc */ NULL, /* dTextProc */ NULL, /* nextPtr */ - NULL, 0, NULL, NULL + RotateImage, /* rotateProc */ + 0, NULL, NULL }; /* @@ -761,6 +764,47 @@ ImageToPostscript( /* *-------------------------------------------------------------- * + * RotateImage -- + * + * This function is called to rotate an image's origin by a given amount. + * This does *not* rotate the contents of the image. + * + * Results: + * None. + * + * Side effects: + * The position of the image anchor is rotated by angleRad radians about + * (originX, originY), and the bounding box is updated in the generic + * part of the item structure. + * + *-------------------------------------------------------------- + */ + +static void +RotateImage( + Tk_Canvas canvas, + Tk_Item *itemPtr, + double originX, + double originY, + double angleRad) +{ + ImageItem *imgPtr = (ImageItem *) itemPtr; + double x, y, nx, ny; + double s = sin(angleRad); + double c = cos(angleRad); + + x = imgPtr->x - originX; + y = imgPtr->y - originY; + nx = x * c - y * s; + ny = x * s + y * c; + imgPtr->x = nx + originX; + imgPtr->y = ny + originY; + ComputeImageBbox(canvas, imgPtr); +} + +/* + *-------------------------------------------------------------- + * * ScaleImage -- * * This function is invoked to rescale an item. diff --git a/generic/tkCanvLine.c b/generic/tkCanvLine.c index b6c845d..ce4d40d 100644 --- a/generic/tkCanvLine.c +++ b/generic/tkCanvLine.c @@ -117,6 +117,8 @@ static int ParseArrowShape(ClientData clientData, static const char * PrintArrowShape(ClientData clientData, Tk_Window tkwin, char *recordPtr, int offset, Tcl_FreeProc **freeProcPtr); +static void RotateLine(Tk_Canvas canvas, Tk_Item *itemPtr, + double originX, double originY, double angleRad); static void ScaleLine(Tk_Canvas canvas, Tk_Item *itemPtr, double originX, double originY, double scaleX, double scaleY); @@ -239,7 +241,8 @@ Tk_ItemType tkLineType = { LineInsert, /* insertProc */ LineDeleteCoords, /* dTextProc */ NULL, /* nextPtr */ - NULL, 0, NULL, NULL + RotateLine, /* rotateProc */ + 0, NULL, NULL }; /* @@ -1856,6 +1859,69 @@ TranslateLine( /* *-------------------------------------------------------------- * + * RotateLine -- + * + * This function is called to rotate a line by a given amount about a + * point. + * + * Results: + * None. + * + * Side effects: + * The position of the line is rotated by angleRad about (originX, + * originY), and the bounding box is updated in the generic part of the + * item structure. + * + *-------------------------------------------------------------- + */ + +static inline void +DoRotate( + double originX, double originY, + double sine, double cosine, + double *xPtr, double *yPtr) +{ + double x = *xPtr - originX; + double y = *yPtr - originY; + + *xPtr = originX + x * cosine - y * sine; + *yPtr = originY + x * sine + y * cosine; +} + +static void +RotateLine( + Tk_Canvas canvas, /* Canvas containing item. */ + Tk_Item *itemPtr, /* Item that is being moved. */ + double originX, double originY, + double angleRad) /* Amount by which item is to be rotated. */ +{ + LineItem *linePtr = (LineItem *) itemPtr; + double *coordPtr; + int i; + double s = sin(angleRad), c = cos(angleRad); + + for (i = 0, coordPtr = linePtr->coordPtr; i < linePtr->numPoints; + i++, coordPtr += 2) { + DoRotate(originX, originY, s, c, &coordPtr[0], &coordPtr[1]); + } + if (linePtr->firstArrowPtr != NULL) { + for (i = 0, coordPtr = linePtr->firstArrowPtr; i < PTS_IN_ARROW; + i++, coordPtr += 2) { + DoRotate(originX, originY, s, c, &coordPtr[0], &coordPtr[1]); + } + } + if (linePtr->lastArrowPtr != NULL) { + for (i = 0, coordPtr = linePtr->lastArrowPtr; i < PTS_IN_ARROW; + i++, coordPtr += 2) { + DoRotate(originX, originY, s, c, &coordPtr[0], &coordPtr[1]); + } + } + ComputeLineBbox(canvas, linePtr); +} + +/* + *-------------------------------------------------------------- + * * ParseArrowShape -- * * This function is called back during option parsing to parse arrow diff --git a/generic/tkCanvPoly.c b/generic/tkCanvPoly.c index 6a8f865..ae18067 100644 --- a/generic/tkCanvPoly.c +++ b/generic/tkCanvPoly.c @@ -176,6 +176,8 @@ static double PolygonToPoint(Tk_Canvas canvas, Tk_Item *itemPtr, double *pointPtr); static int PolygonToPostscript(Tcl_Interp *interp, Tk_Canvas canvas, Tk_Item *itemPtr, int prepass); +static void RotatePolygon(Tk_Canvas canvas, Tk_Item *itemPtr, + double originX, double originY, double angleRad); static void ScalePolygon(Tk_Canvas canvas, Tk_Item *itemPtr, double originX, double originY, double scaleX, double scaleY); @@ -202,13 +204,14 @@ Tk_ItemType tkPolygonType = { PolygonToPostscript, /* postscriptProc */ ScalePolygon, /* scaleProc */ TranslatePolygon, /* translateProc */ - GetPolygonIndex, /* indexProc */ + GetPolygonIndex, /* indexProc */ NULL, /* icursorProc */ NULL, /* selectionProc */ - PolygonInsert, /* insertProc */ + PolygonInsert, /* insertProc */ PolygonDeleteCoords, /* dTextProc */ NULL, /* nextPtr */ - NULL, 0, NULL, NULL + RotatePolygon, /* rotateProc */ + 0, NULL, NULL }; /* @@ -1738,6 +1741,48 @@ GetPolygonIndex( /* *-------------------------------------------------------------- * + * RotatePolygon -- + * + * This function is called to rotate a polygon by a given amount about a + * point. + * + * Results: + * None. + * + * Side effects: + * The position of the polygon is rotated by angleRad about (originX, + * originY), and the bounding box is updated in the generic part of the + * item structure. + * + *-------------------------------------------------------------- + */ + +static void +RotatePolygon( + Tk_Canvas canvas, /* Canvas containing item. */ + Tk_Item *itemPtr, /* Item that is being moved. */ + double originX, double originY, + double angleRad) /* Amount by which item is to be rotated. */ +{ + PolygonItem *polyPtr = (PolygonItem *) itemPtr; + double *coordPtr; + int i; + double s = sin(angleRad), c = cos(angleRad); + + for (i = 0, coordPtr = polyPtr->coordPtr; i < polyPtr->numPoints; + i++, coordPtr += 2) { + double x = coordPtr[0] - originX; + double y = coordPtr[1] - originY; + + coordPtr[0] = originX + x * c - y * s; + coordPtr[1] = originY + x * s + y * c; + } + ComputePolygonBbox(canvas, polyPtr); +} + +/* + *-------------------------------------------------------------- + * * TranslatePolygon -- * * This function is called to move a polygon by a given amount. diff --git a/generic/tkCanvText.c b/generic/tkCanvText.c index c918399..22b6dea 100644 --- a/generic/tkCanvText.c +++ b/generic/tkCanvText.c @@ -170,6 +170,8 @@ static double TextToPoint(Tk_Canvas canvas, Tk_Item *itemPtr, double *pointPtr); static int TextToPostscript(Tcl_Interp *interp, Tk_Canvas canvas, Tk_Item *itemPtr, int prepass); +static void RotateText(Tk_Canvas canvas, Tk_Item *itemPtr, + double originX, double originY, double angleRad); static void TranslateText(Tk_Canvas canvas, Tk_Item *itemPtr, double deltaX, double deltaY); @@ -199,7 +201,8 @@ Tk_ItemType tkTextType = { TextInsert, /* insertProc */ TextDeleteChars, /* dTextProc */ NULL, /* nextPtr */ - NULL, 0, NULL, NULL + RotateText, /* rotateProc */ + 0, NULL, NULL }; #define ROUND(d) ((int) floor((d) + 0.5)) @@ -1250,6 +1253,42 @@ TextToArea( /* *-------------------------------------------------------------- * + * RotateText -- + * + * This function is called to rotate a text item by a given amount about a + * point. Note that this does *not* rotate the text of the item. + * + * Results: + * None. + * + * Side effects: + * The position of the text anchor is rotated by angleRad about (originX, + * originY), and the bounding box is updated in the generic part of the + * item structure. + * + *-------------------------------------------------------------- + */ + +static void +RotateText( + Tk_Canvas canvas, /* Canvas containing item. */ + Tk_Item *itemPtr, /* Item that is being rotated. */ + double originX, double originY, + double angleRad) /* Amount by which item is to be rotated. */ +{ + TextItem *textPtr = (TextItem *) itemPtr; + double s = sin(angleRad), c = cos(angleRad); + double x = textPtr->x - originX; + double y = textPtr->y - originY; + + textPtr->x = originX + x * c - y * s; + textPtr->y = originY + x * s + y * c; + ComputeTextBbox(canvas, textPtr); +} + +/* + *-------------------------------------------------------------- + * * ScaleText -- * * This function is invoked to rescale a text item. diff --git a/generic/tkCanvWind.c b/generic/tkCanvWind.c index f73546f..8c44a6c 100644 --- a/generic/tkCanvWind.c +++ b/generic/tkCanvWind.c @@ -77,6 +77,8 @@ static void DeleteWinItem(Tk_Canvas canvas, static void DisplayWinItem(Tk_Canvas canvas, Tk_Item *itemPtr, Display *display, Drawable dst, int x, int y, int width, int height); +static void RotateWinItem(Tk_Canvas canvas, Tk_Item *itemPtr, + double originX, double originY, double angleRad); static void ScaleWinItem(Tk_Canvas canvas, Tk_Item *itemPtr, double originX, double originY, double scaleX, double scaleY); @@ -130,7 +132,8 @@ Tk_ItemType tkWindowType = { NULL, /* insertProc */ NULL, /* dTextProc */ NULL, /* nextPtr */ - NULL, 0, NULL, NULL + RotateWinItem, /* rotateProc */ + 0, NULL, NULL }; /* @@ -915,6 +918,43 @@ CanvasPsWindow( /* *-------------------------------------------------------------- * + * RotateWinItem -- + * + * This function is called to rotate a window item by a given amount + * about a point. Note that this does *not* rotate the window of the + * item. + * + * Results: + * None. + * + * Side effects: + * The position of the window anchor is rotated by angleRad about (originX, + * originY), and the bounding box is updated in the generic part of the + * item structure. + * + *-------------------------------------------------------------- + */ + +static void +RotateWinItem( + Tk_Canvas canvas, /* Canvas containing item. */ + Tk_Item *itemPtr, /* Item that is being rotated. */ + double originX, double originY, + double angleRad) /* Amount by which item is to be rotated. */ +{ + WindowItem *winItemPtr = (WindowItem *) itemPtr; + double s = sin(angleRad), c = cos(angleRad); + double x = winItemPtr->x - originX; + double y = winItemPtr->y - originY; + + winItemPtr->x = originX + x * c - y * s; + winItemPtr->y = originY + x * s + y * c; + ComputeWindowBbox(canvas, winItemPtr); +} + +/* + *-------------------------------------------------------------- + * * ScaleWinItem -- * * This function is invoked to rescale a window item. -- cgit v0.12 From 87a95ec0329c9fd676ed4a5d9d10247eb245a4ec Mon Sep 17 00:00:00 2001 From: dkf Date: Mon, 11 Mar 2019 21:30:39 +0000 Subject: All standard item types now have rotation proc callbacks. --- generic/tkRectOval.c | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/generic/tkRectOval.c b/generic/tkRectOval.c index 359d3ef..b1bce7b 100644 --- a/generic/tkRectOval.c +++ b/generic/tkRectOval.c @@ -148,6 +148,8 @@ static int RectToArea(Tk_Canvas canvas, Tk_Item *itemPtr, double *areaPtr); static double RectToPoint(Tk_Canvas canvas, Tk_Item *itemPtr, double *pointPtr); +static void RotateRectOval(Tk_Canvas canvas, Tk_Item *itemPtr, + double originX, double originY, double angleRad); static void ScaleRectOval(Tk_Canvas canvas, Tk_Item *itemPtr, double originX, double originY, double scaleX, double scaleY); @@ -180,7 +182,8 @@ Tk_ItemType tkRectangleType = { NULL, /* insertProc */ NULL, /* dTextProc */ NULL, /* nextPtr */ - NULL, 0, NULL, NULL + RotateRectOval, /* rotateProc */ + 0, NULL, NULL }; Tk_ItemType tkOvalType = { @@ -204,7 +207,8 @@ Tk_ItemType tkOvalType = { NULL, /* insertProc */ NULL, /* dTextProc */ NULL, /* nextPtr */ - NULL, 0, NULL, NULL + RotateRectOval, /* rotateProc */ + 0, NULL, NULL }; /* @@ -1285,6 +1289,56 @@ OvalToArea( /* *-------------------------------------------------------------- * + * RotateRectOval -- + * + * This function is invoked to rotate a rectangle or oval item's + * coordinates. It's probably unwise to rotate these by anything other + * than 90-degree increments. + * + * Results: + * None. + * + * Side effects: + * The position of the rectangle or oval is rotated by angleRad about + * (originX, originY), and the bounding box is updated in the generic + * part of the item structure. + * + *-------------------------------------------------------------- + */ + +static inline void +DoRotate( + double originX, double originY, + double sine, double cosine, + double *xPtr, double *yPtr) +{ + double x = *xPtr - originX; + double y = *yPtr - originY; + + *xPtr = originX + x * cosine - y * sine; + *yPtr = originY + x * sine + y * cosine; +} + +static void +RotateRectOval( + Tk_Canvas canvas, /* Canvas containing rectangle. */ + Tk_Item *itemPtr, /* Rectangle to be scaled. */ + double originX, double originY, + /* Origin about which to rotate rect. */ + double angleRad) /* Amount to scale in X direction. */ +{ + RectOvalItem *rectOvalPtr = (RectOvalItem *) itemPtr; + double s = sin(angleRad), c = cos(angleRad); + double *coords = rectOvalPtr->bbox; + + DoRotate(originX, originY, s, c, &coords[0], &coords[1]); + DoRotate(originX, originY, s, c, &coords[2], &coords[3]); + ComputeRectOvalBbox(canvas, rectOvalPtr); +} + +/* + *-------------------------------------------------------------- + * * ScaleRectOval -- * * This function is invoked to rescale a rectangle or oval item. -- cgit v0.12 From 913c2ffec66a261d7cea357c21cdcda60132c0a5 Mon Sep 17 00:00:00 2001 From: dkf Date: Wed, 13 Mar 2019 19:16:12 +0000 Subject: Document. Factor out basic rotation function. --- doc/CrtItemType.3 | 43 +++++++++++++++++++++++++++++++++++++++++++ doc/canvas.n | 38 ++++++++++++++++++++++++++++---------- generic/tkCanvArc.c | 32 +++++++++++++++----------------- generic/tkCanvBmap.c | 13 +++---------- generic/tkCanvImg.c | 13 +++---------- generic/tkCanvLine.c | 19 +++---------------- generic/tkCanvPoly.c | 6 +----- generic/tkCanvText.c | 7 ++----- generic/tkCanvUtil.c | 38 +++++++++++++++++++++++++++++++++++++- generic/tkCanvWind.c | 7 ++----- generic/tkInt.h | 3 +++ generic/tkRectOval.c | 29 +++++++++++++---------------- 12 files changed, 153 insertions(+), 95 deletions(-) diff --git a/doc/CrtItemType.3 b/doc/CrtItemType.3 index f9198f3..1bfb20f 100644 --- a/doc/CrtItemType.3 +++ b/doc/CrtItemType.3 @@ -83,6 +83,9 @@ typedef struct Tk_ItemType { Tk_ItemInsertProc *\fIinsertProc\fR; Tk_ItemDCharsProc *\fIdCharsProc\fR; Tk_ItemType *\fInextPtr\fR; +.VS "8.7, TIP164" + Tk_ItemRotateProc *\fIrotateProc\fR; +.VE "8.7, TIP164" } \fBTk_ItemType\fR; .CE .PP @@ -549,6 +552,46 @@ and \fIdeltaX\fR and \fIdeltaY\fR give the amounts that should be added to each x and y coordinate within the item. The type manager should adjust the item's coordinates and update the bounding box in the item's header. +.SS ROTATEPROC +.VS "8.7, TIP164" +.PP +\fItypePtr\->rotateProc\fR is invoked by Tk to rotate a canvas item +during the \fBrotate\fR widget command. +The procedure must match the following prototype: +.PP +.CS +typedef void \fBTk_ItemRotateProc\fR( + Tk_Canvas \fIcanvas\fR, + Tk_Item *\fIitemPtr\fR, + double \fIoriginX\fR, + double \fIoriginY\fR, + double \fIangleRad\fR); +.CE +.PP +The \fIcanvas\fR and \fIitemPtr\fR arguments have the usual meaning. +\fIoriginX\fR and \fIoriginY\fR specify an origin relative to which +the item is to be rotated, and \fIangleRad\fR gives the anticlockwise +rotation to be applied in radians. +The item should adjust the coordinates of its control points so that where +they used to have coordinates \fIx\fR and \fIy\fR, they will have new +coordinates \fIx\(fm\fR and \fIy\(fm\fR, where +.PP +.CS +\fIrelX\fR = \fIx\fR - \fIoriginX\fR +\fIrelY\fR = \fIy\fR - \fIoriginY\fR +\fIx\(fm\fR = \fIoriginX\fR + \fIrelX\fR \(mu cos(\fIangleRad\fR) + \fIrelY\fR \(mu sin(\fIangleRad\fR) +\fIy\(fm\fR = \fIoriginY\fR \(mi \fIrelX\fR \(mu sin(\fIangleRad\fR) + \fIrelY\fR \(mu cos(\fIangleRad\fR) +.CE +.PP +The control points for an item are not necessarily the coordinates provided to +the item when it is created (or via the \fItypePtr\->coordProc\fR), but could +instead be derived from them. +\fIrotateProc\fR must also update the bounding box in the item's header. +.PP +Item types do not need to provide a \fItypePtr\->rotateProc\fR. If the +\fItypePtr\->rotateProc\fR is NULL, the \fItypePtr\->coordProc\fR will be +used instead to retrieve and update the list of coordinates. +.VE "8.7, TIP164" .SS INDEXPROC .PP \fItypePtr\->indexProc\fR is invoked by Tk to translate a string diff --git a/doc/canvas.n b/doc/canvas.n index fa7843d..bcd4991 100644 --- a/doc/canvas.n +++ b/doc/canvas.n @@ -220,8 +220,12 @@ for scrolling. Canvases do not support scaling or rotation of the canvas coordinate system relative to the window coordinate system. .PP -Individual items may be moved or scaled using widget commands -described below, but they may not be rotated. +Individual items may be moved, scaled +.VS "8.7, TIP164" +or rotated +.VE "8.7, TIP164" +using widget commands +described below. .PP Note that the default origin of the canvas's visible area is coincident with the origin for the whole window as that makes bindings @@ -674,13 +678,12 @@ mapped. This command returns an empty string. .TP \fIpathName \fBimove \fItagOrId index x y\fR -.VS 8.6 +. This command causes the \fIindex\fR'th coordinate of each of the items indicated by \fItagOrId\fR to be relocated to the location (\fIx\fR,\fIy\fR). Each item interprets \fIindex\fR independently according to the rules described in \fBINDICES\fR above. Out of the standard set of items, only line and polygon items may have their coordinates relocated this way. -.VE 8.6 .TP \fIpathName \fBindex \fItagOrId index\fR . @@ -766,7 +769,7 @@ each point associated with the item. This command returns an empty string. .TP \fIpathName \fBmoveto \fItagOrId xPos yPos\fR -.VS 8.6 +. Move the items given by \fItagOrId\fR in the canvas coordinate space so that the first coordinate pair of the bottommost item with tag \fItagOrId\fR is located at @@ -775,7 +778,6 @@ the empty string, in which case the corresponding coordinate will be unchanged. All items matching \fItagOrId\fR remain in the same positions relative to each other. This command returns an empty string. -.VE 8.6 .TP \fIpathName \fBpostscript \fR?\fIoption value option value ...\fR? . @@ -961,7 +963,7 @@ determined by the \fBraise\fR command and \fBlower\fR command, not the .RE .TP \fIpathName \fBrchars \fItagOrId first last string\fR -.VS 8.6 +. This command causes the text or coordinates between \fIfirst\fR and \fIlast\fR for each of the items indicated by \fItagOrId\fR to be replaced by \fIstring\fR. Each item interprets \fIfirst\fR and \fIlast\fR independently @@ -970,7 +972,24 @@ set of items, text items support this operation by altering their text as directed, and line and polygon items support this operation by altering their coordinate list (in which case \fIstring\fR should be a list of coordinates to use as a replacement). The other items ignore this operation. -.VE 8.6 +.TP +\fIpathName \fBrotate \fItagOrId xOrigin yOrigin angle\fR +.VS "8.7, TIP164" +Rotate the coordinates of all of the items given by \fItagOrId\fR in canvas +coordinate space. +\fIXOrigin\fR and \fIyOrigin\fR identify the origin for the rotation +operation and \fIangle\fR identifies the amount to rotate the coordinates +anticlockwise, in degrees. (Negative values rotate clockwise.) +This command returns an empty string. +.RS +.PP +Implementation note: not all item types work well with rotations. In +particular, the \fBarc\fR, \fBoval\fR and \fBrectangle\fR types are very +unlikely to work as you expect. Several other item types only have a single +coordinate; this command can move that anchor point, but will not rotate the +item about that anchor point. +.RE +.VE "8.7, TIP164" .TP \fIpathName \fBscale \fItagOrId xOrigin yOrigin xScale yScale\fR . @@ -1834,13 +1853,12 @@ The following standard options are supported by text items: The following extra options are supported for text items: .TP \fB\-angle \fIrotationDegrees\fR -.VS 8.6 +. \fIRotationDegrees\fR tells how many degrees to rotate the text anticlockwise about the positioning point for the text; it may have any floating-point value from 0.0 to 360.0. For example, if \fIrotationDegrees\fR is \fB90\fR, then the text will be drawn vertically from bottom to top. This option defaults to \fB0.0\fR. -.VE 8.6 .TP \fB\-font \fIfontName\fR Specifies the font to use for the text item. diff --git a/generic/tkCanvArc.c b/generic/tkCanvArc.c index ca9ef34..3741829 100644 --- a/generic/tkCanvArc.c +++ b/generic/tkCanvArc.c @@ -1520,23 +1520,21 @@ RotateArc( double angleRad) { ArcItem *arcPtr = (ArcItem *) itemPtr; - double x, y, nx, ny; - double s = sin(angleRad); - double c = cos(angleRad); - - x = arcPtr->bbox[0] - originX; - y = arcPtr->bbox[1] - originY; - nx = x * c - y * s; - ny = x * s + y * c; - arcPtr->bbox[0] = nx + originX; - arcPtr->bbox[1] = ny + originY; - - x = arcPtr->bbox[2] - originX; - y = arcPtr->bbox[3] - originY; - nx = x * c - y * s; - ny = x * s + y * c; - arcPtr->bbox[2] = nx + originX; - arcPtr->bbox[3] = ny + originY; + double s = sin(angleRad), c = cos(angleRad); + double coords[4]; + + memcpy(coords, arcPtr->bbox, sizeof(coords)); + TkRotatePoint(originX, originY, s, c, &coords[0], &coords[1]); + TkRotatePoint(originX, originY, s, c, &coords[2], &coords[3]); + + /* + * Sort the points for the bounding box. + */ + + arcPtr->bbox[0] = (coords[0] < coords[2]) ? coords[0] : coords[2]; + arcPtr->bbox[1] = (coords[1] < coords[3]) ? coords[1] : coords[3]; + arcPtr->bbox[2] = (coords[0] < coords[2]) ? coords[2] : coords[0]; + arcPtr->bbox[3] = (coords[1] < coords[3]) ? coords[3] : coords[1]; /* * TODO: update the arc endpoints? diff --git a/generic/tkCanvBmap.c b/generic/tkCanvBmap.c index 948379d..34c74f3 100644 --- a/generic/tkCanvBmap.c +++ b/generic/tkCanvBmap.c @@ -817,16 +817,9 @@ RotateBitmap( double angleRad) { BitmapItem *bmapPtr = (BitmapItem *) itemPtr; - double x, y, nx, ny; - double s = sin(angleRad); - double c = cos(angleRad); - - x = bmapPtr->x - originX; - y = bmapPtr->y - originY; - nx = x * c - y * s; - ny = x * s + y * c; - bmapPtr->x = nx + originX; - bmapPtr->y = ny + originY; + + TkRotatePoint(originX, originY, sin(angleRad), cos(angleRad), + &bmapPtr->x, &bmapPtr->y); ComputeBitmapBbox(canvas, bmapPtr); } diff --git a/generic/tkCanvImg.c b/generic/tkCanvImg.c index 20fcd52..f2b73a6 100644 --- a/generic/tkCanvImg.c +++ b/generic/tkCanvImg.c @@ -789,16 +789,9 @@ RotateImage( double angleRad) { ImageItem *imgPtr = (ImageItem *) itemPtr; - double x, y, nx, ny; - double s = sin(angleRad); - double c = cos(angleRad); - - x = imgPtr->x - originX; - y = imgPtr->y - originY; - nx = x * c - y * s; - ny = x * s + y * c; - imgPtr->x = nx + originX; - imgPtr->y = ny + originY; + + TkRotatePoint(originX, originY, sin(angleRad), cos(angleRad), + &imgPtr->x, &imgPtr->y); ComputeImageBbox(canvas, imgPtr); } diff --git a/generic/tkCanvLine.c b/generic/tkCanvLine.c index ce4d40d..3f8f5c1 100644 --- a/generic/tkCanvLine.c +++ b/generic/tkCanvLine.c @@ -1875,19 +1875,6 @@ TranslateLine( *-------------------------------------------------------------- */ -static inline void -DoRotate( - double originX, double originY, - double sine, double cosine, - double *xPtr, double *yPtr) -{ - double x = *xPtr - originX; - double y = *yPtr - originY; - - *xPtr = originX + x * cosine - y * sine; - *yPtr = originY + x * sine + y * cosine; -} - static void RotateLine( Tk_Canvas canvas, /* Canvas containing item. */ @@ -1902,18 +1889,18 @@ RotateLine( for (i = 0, coordPtr = linePtr->coordPtr; i < linePtr->numPoints; i++, coordPtr += 2) { - DoRotate(originX, originY, s, c, &coordPtr[0], &coordPtr[1]); + TkRotatePoint(originX, originY, s, c, &coordPtr[0], &coordPtr[1]); } if (linePtr->firstArrowPtr != NULL) { for (i = 0, coordPtr = linePtr->firstArrowPtr; i < PTS_IN_ARROW; i++, coordPtr += 2) { - DoRotate(originX, originY, s, c, &coordPtr[0], &coordPtr[1]); + TkRotatePoint(originX, originY, s, c, &coordPtr[0], &coordPtr[1]); } } if (linePtr->lastArrowPtr != NULL) { for (i = 0, coordPtr = linePtr->lastArrowPtr; i < PTS_IN_ARROW; i++, coordPtr += 2) { - DoRotate(originX, originY, s, c, &coordPtr[0], &coordPtr[1]); + TkRotatePoint(originX, originY, s, c, &coordPtr[0], &coordPtr[1]); } } ComputeLineBbox(canvas, linePtr); diff --git a/generic/tkCanvPoly.c b/generic/tkCanvPoly.c index ae18067..1677bbb 100644 --- a/generic/tkCanvPoly.c +++ b/generic/tkCanvPoly.c @@ -1771,11 +1771,7 @@ RotatePolygon( for (i = 0, coordPtr = polyPtr->coordPtr; i < polyPtr->numPoints; i++, coordPtr += 2) { - double x = coordPtr[0] - originX; - double y = coordPtr[1] - originY; - - coordPtr[0] = originX + x * c - y * s; - coordPtr[1] = originY + x * s + y * c; + TkRotatePoint(originX, originY, s, c, &coordPtr[0], &coordPtr[1]); } ComputePolygonBbox(canvas, polyPtr); } diff --git a/generic/tkCanvText.c b/generic/tkCanvText.c index 22b6dea..4f446ec 100644 --- a/generic/tkCanvText.c +++ b/generic/tkCanvText.c @@ -1277,12 +1277,9 @@ RotateText( double angleRad) /* Amount by which item is to be rotated. */ { TextItem *textPtr = (TextItem *) itemPtr; - double s = sin(angleRad), c = cos(angleRad); - double x = textPtr->x - originX; - double y = textPtr->y - originY; - textPtr->x = originX + x * c - y * s; - textPtr->y = originY + x * s + y * c; + TkRotatePoint(originX, originY, sin(angleRad), cos(angleRad), + &textPtr->x, &textPtr->y); ComputeTextBbox(canvas, textPtr); } diff --git a/generic/tkCanvUtil.c b/generic/tkCanvUtil.c index 6ce671d..52d7bf6 100644 --- a/generic/tkCanvUtil.c +++ b/generic/tkCanvUtil.c @@ -1265,7 +1265,6 @@ Tk_ChangeOutlineGC( } return 0; } - /* *-------------------------------------------------------------- @@ -1865,6 +1864,43 @@ TkCanvTranslatePath( } /* + *-------------------------------------------------------------- + * + * TkRotatePoint -- + * + * Rotate a point about another point. The angle should be converted into + * its sine and cosine before calling this function. + * + * Results: + * None + * + * Side effects: + * The point in (*xPtr,*yPtr) is updated to be rotated about + * (originX,originY) by the amount given by the sine and cosine of the + * angle to rotate. + * + *-------------------------------------------------------------- + */ + +void +TkRotatePoint( + double originX, double originY, /* The point about which to rotate. */ + double sine, double cosine, /* How much to rotate? */ + double *xPtr, double *yPtr) /* The point to be rotated. (INOUT) */ +{ + double x = *xPtr - originX; + double y = *yPtr - originY; + + /* + * Beware! The canvas coordinate space is flipped vertically, so rotations + * go the "wrong" way with respect to mathematics. + */ + + *xPtr = originX + x * cosine + y * sine; + *yPtr = originY - x * sine + y * cosine; +} + +/* * Local Variables: * mode: c * c-basic-offset: 4 diff --git a/generic/tkCanvWind.c b/generic/tkCanvWind.c index 8c44a6c..9f38932 100644 --- a/generic/tkCanvWind.c +++ b/generic/tkCanvWind.c @@ -943,12 +943,9 @@ RotateWinItem( double angleRad) /* Amount by which item is to be rotated. */ { WindowItem *winItemPtr = (WindowItem *) itemPtr; - double s = sin(angleRad), c = cos(angleRad); - double x = winItemPtr->x - originX; - double y = winItemPtr->y - originY; - winItemPtr->x = originX + x * c - y * s; - winItemPtr->y = originY + x * s + y * c; + TkRotatePoint(originX, originY, sin(angleRad), cos(angleRad), + &winItemPtr->x, &winItemPtr->y); ComputeWindowBbox(canvas, winItemPtr); } diff --git a/generic/tkInt.h b/generic/tkInt.h index 767bbbb..9c6a28f 100644 --- a/generic/tkInt.h +++ b/generic/tkInt.h @@ -1259,6 +1259,9 @@ MODULE_SCOPE void TkpCancelWarp(TkDisplay *dispPtr); MODULE_SCOPE int TkListCreateFrame(ClientData clientData, Tcl_Interp *interp, Tcl_Obj *listObj, int toplevel, Tcl_Obj *nameObj); +MODULE_SCOPE void TkRotatePoint(double originX, double originY, + double sine, double cosine, double *xPtr, + double *yPtr); #ifdef _WIN32 #define TkParseColor XParseColor diff --git a/generic/tkRectOval.c b/generic/tkRectOval.c index b1bce7b..279e89e 100644 --- a/generic/tkRectOval.c +++ b/generic/tkRectOval.c @@ -1306,19 +1306,6 @@ OvalToArea( *-------------------------------------------------------------- */ -static inline void -DoRotate( - double originX, double originY, - double sine, double cosine, - double *xPtr, double *yPtr) -{ - double x = *xPtr - originX; - double y = *yPtr - originY; - - *xPtr = originX + x * cosine - y * sine; - *yPtr = originY + x * sine + y * cosine; -} - static void RotateRectOval( Tk_Canvas canvas, /* Canvas containing rectangle. */ @@ -1329,10 +1316,20 @@ RotateRectOval( { RectOvalItem *rectOvalPtr = (RectOvalItem *) itemPtr; double s = sin(angleRad), c = cos(angleRad); - double *coords = rectOvalPtr->bbox; + double coords[4]; + + memcpy(coords, rectOvalPtr->bbox, sizeof(coords)); + TkRotatePoint(originX, originY, s, c, &coords[0], &coords[1]); + TkRotatePoint(originX, originY, s, c, &coords[2], &coords[3]); + + /* + * Sort the points for the bounding box. + */ - DoRotate(originX, originY, s, c, &coords[0], &coords[1]); - DoRotate(originX, originY, s, c, &coords[2], &coords[3]); + rectOvalPtr->bbox[0] = (coords[0] < coords[2]) ? coords[0] : coords[2]; + rectOvalPtr->bbox[1] = (coords[1] < coords[3]) ? coords[1] : coords[3]; + rectOvalPtr->bbox[2] = (coords[0] < coords[2]) ? coords[2] : coords[0]; + rectOvalPtr->bbox[3] = (coords[1] < coords[3]) ? coords[3] : coords[1]; ComputeRectOvalBbox(canvas, rectOvalPtr); } -- cgit v0.12 From fd50ed0534e4f513c14e01475e5dbfa992ae0c2a Mon Sep 17 00:00:00 2001 From: dkf Date: Fri, 15 Mar 2019 18:41:23 +0000 Subject: Make some items have a virtual centre point to move. Much saner behaviour. --- doc/canvas.n | 13 ++++++++----- generic/tkCanvArc.c | 24 ++++++++++++++---------- generic/tkRectOval.c | 28 ++++++++++++++++------------ 3 files changed, 38 insertions(+), 27 deletions(-) diff --git a/doc/canvas.n b/doc/canvas.n index bcd4991..424c3ca 100644 --- a/doc/canvas.n +++ b/doc/canvas.n @@ -983,11 +983,14 @@ anticlockwise, in degrees. (Negative values rotate clockwise.) This command returns an empty string. .RS .PP -Implementation note: not all item types work well with rotations. In -particular, the \fBarc\fR, \fBoval\fR and \fBrectangle\fR types are very -unlikely to work as you expect. Several other item types only have a single -coordinate; this command can move that anchor point, but will not rotate the -item about that anchor point. +Implementation note: not all item types work the same with rotations. In +particular,\fB bitmap\fR,\fB image\fR,\fB text\fR and\fB window\fR items only +rotate their anchor points and do not rotate the items themselves about those +points, and the \fBarc\fR, \fBoval\fR and \fBrectangle\fR types rotate about a +computed center point instead of moving the bounding box coordinates directly. +.PP +Some items (currently \fBarc\R and\fB text\fR) have angles in their options; +this command \fIdoes not\fR affect those options. .RE .VE "8.7, TIP164" .TP diff --git a/generic/tkCanvArc.c b/generic/tkCanvArc.c index 3741829..c6d6890 100644 --- a/generic/tkCanvArc.c +++ b/generic/tkCanvArc.c @@ -1520,21 +1520,25 @@ RotateArc( double angleRad) { ArcItem *arcPtr = (ArcItem *) itemPtr; - double s = sin(angleRad), c = cos(angleRad); - double coords[4]; + double newX, newY, oldX, oldY; - memcpy(coords, arcPtr->bbox, sizeof(coords)); - TkRotatePoint(originX, originY, s, c, &coords[0], &coords[1]); - TkRotatePoint(originX, originY, s, c, &coords[2], &coords[3]); + /* + * Compute the centre of the box, then rotate that about the origin. + */ + + newX = oldX = (arcPtr->bbox[0] + arcPtr->bbox[2]) / 2.0; + newY = oldY = (arcPtr->bbox[1] + arcPtr->bbox[3]) / 2.0; + TkRotatePoint(originX, originY, sin(angleRad), cos(angleRad), + &newX, &newY); /* - * Sort the points for the bounding box. + * Apply the translation to the box. */ - arcPtr->bbox[0] = (coords[0] < coords[2]) ? coords[0] : coords[2]; - arcPtr->bbox[1] = (coords[1] < coords[3]) ? coords[1] : coords[3]; - arcPtr->bbox[2] = (coords[0] < coords[2]) ? coords[2] : coords[0]; - arcPtr->bbox[3] = (coords[1] < coords[3]) ? coords[3] : coords[1]; + arcPtr->bbox[0] += newX - oldX; + arcPtr->bbox[1] += newY - oldY; + arcPtr->bbox[2] += newX - oldX; + arcPtr->bbox[3] += newY - oldY; /* * TODO: update the arc endpoints? diff --git a/generic/tkRectOval.c b/generic/tkRectOval.c index 279e89e..b40814e 100644 --- a/generic/tkRectOval.c +++ b/generic/tkRectOval.c @@ -1292,8 +1292,8 @@ OvalToArea( * RotateRectOval -- * * This function is invoked to rotate a rectangle or oval item's - * coordinates. It's probably unwise to rotate these by anything other - * than 90-degree increments. + * coordinates. It works by rotating a computed point in the centre of + * the bounding box, NOT by rotating the corners of the bounding box. * * Results: * None. @@ -1315,21 +1315,25 @@ RotateRectOval( double angleRad) /* Amount to scale in X direction. */ { RectOvalItem *rectOvalPtr = (RectOvalItem *) itemPtr; - double s = sin(angleRad), c = cos(angleRad); - double coords[4]; + double newX, newY, oldX, oldY; - memcpy(coords, rectOvalPtr->bbox, sizeof(coords)); - TkRotatePoint(originX, originY, s, c, &coords[0], &coords[1]); - TkRotatePoint(originX, originY, s, c, &coords[2], &coords[3]); + /* + * Compute the centre of the box, then rotate that about the origin. + */ + + newX = oldX = (rectOvalPtr->bbox[0] + rectOvalPtr->bbox[2]) / 2.0; + newY = oldY = (rectOvalPtr->bbox[1] + rectOvalPtr->bbox[3]) / 2.0; + TkRotatePoint(originX, originY, sin(angleRad), cos(angleRad), + &newX, &newY); /* - * Sort the points for the bounding box. + * Apply the translation to the box. */ - rectOvalPtr->bbox[0] = (coords[0] < coords[2]) ? coords[0] : coords[2]; - rectOvalPtr->bbox[1] = (coords[1] < coords[3]) ? coords[1] : coords[3]; - rectOvalPtr->bbox[2] = (coords[0] < coords[2]) ? coords[2] : coords[0]; - rectOvalPtr->bbox[3] = (coords[1] < coords[3]) ? coords[3] : coords[1]; + rectOvalPtr->bbox[0] += newX - oldX; + rectOvalPtr->bbox[1] += newY - oldY; + rectOvalPtr->bbox[2] += newX - oldX; + rectOvalPtr->bbox[3] += newY - oldY; ComputeRectOvalBbox(canvas, rectOvalPtr); } -- cgit v0.12 From c69576ab77387471caceaf4dfd952904dbd5d421 Mon Sep 17 00:00:00 2001 From: dkf Date: Sat, 16 Mar 2019 14:54:15 +0000 Subject: Tests of rotation --- tests/canvas.test | 183 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 183 insertions(+) diff --git a/tests/canvas.test b/tests/canvas.test index e8dc332..100fea1 100644 --- a/tests/canvas.test +++ b/tests/canvas.test @@ -1040,6 +1040,189 @@ test canvas-20.3 {canvas image with subsample and zoom} -setup { image delete testimage } -result 1 +destroy .c +test canvas-21.1 {canvas rotate} -setup { + pack [canvas .c] +} -body { + .c create line 50 50 50 100 100 100 + .c rotate all 75 75 90 + lmap c [.c coords all] {format %.2f $c} +} -cleanup { + destroy .c +} -result {50.00 100.00 100.00 100.00 100.00 50.00} +test canvas-21.2 {canvas rotate} -setup { + pack [canvas .c] +} -body { + .c create line 50 50 50 100 100 100 + .c rotate all 75 75 -10 + lmap c [.c coords all] {format %.2f $c} +} -cleanup { + destroy .c +} -result {54.72 46.04 46.04 95.28 95.28 103.96} +test canvas-21.3 {canvas rotate: syntax} -setup { + pack [canvas .c] +} -body { + .c rotate all 75 75 +} -returnCodes error -cleanup { + destroy .c +} -result {wrong # args: should be ".c rotate tagOrId x y angle"} +test canvas-21.4 {canvas rotate: syntax} -setup { + pack [canvas .c] +} -body { + .c rotate all 75 75 123 123 +} -returnCodes error -cleanup { + destroy .c +} -result {wrong # args: should be ".c rotate tagOrId x y angle"} +test canvas-21.5 {canvas rotate: syntax} -setup { + pack [canvas .c] +} -body { + .c rotate {!} 1 1 1 +} -returnCodes error -cleanup { + destroy .c +} -result {missing tag in tag search expression} +test canvas-21.6 {canvas rotate: syntax} -setup { + pack [canvas .c] +} -body { + .c rotate all x 1 1 +} -returnCodes error -cleanup { + destroy .c +} -result {bad screen distance "x"} +test canvas-21.7 {canvas rotate: syntax} -setup { + pack [canvas .c] +} -body { + .c rotate all 1 x 1 +} -returnCodes error -cleanup { + destroy .c +} -result {bad screen distance "x"} +test canvas-21.8 {canvas rotate: syntax} -setup { + pack [canvas .c] +} -body { + .c rotate all 1 1 x +} -returnCodes error -cleanup { + destroy .c +} -result {expected floating-point number but got "x"} +test canvas-21.9 {canvas rotate: nothing to rotate} -setup { + pack [canvas .c] +} -body { + .c rotate all 75 75 10 +} -cleanup { + destroy .c +} -result {} +test canvas-21.10 {canvas rotate: multiple things to rotate} -setup { + pack [canvas .c] +} -body { + .c create line 50 50 50 100 -tag a + .c create line 50 50 100 50 -tag b + .c rotate all 75 75 45 + list [lmap c [.c coords a] {format %.2f $c}] [lmap c [.c coords b] {format %.2f $c}] +} -cleanup { + destroy .c +} -result {{39.64 75.00 75.00 110.36} {39.64 75.00 75.00 39.64}} + +test canvas-22.1 {canvas rotate: arc item rotation behaviour} -setup { + pack [canvas .c] +} -body { + .c create arc 50 50 75 75 -start 45 -extent 90 + .c rotate all 100 100 90 + list [lmap c [.c coords all] {format %.2f $c}] \ + [lmap o {-start -extent} {.c itemcget all $o}] \ + [.c bbox all] +} -cleanup { + destroy .c +} -result {{50.00 125.00 75.00 150.00} {45.0 90.0} {52 123 73 140}} +test canvas-22.2 {canvas rotate: bitmap item rotation behaviour} -setup { + pack [canvas .c] +} -body { + .c create bitmap 50 50 -bitmap info -anchor se + .c rotate all 100 100 90 + list [lmap c [.c coords all] {format %.2f $c}] \ + [lmap o {-bitmap -anchor} {.c itemcget all $o}] \ + [.c bbox all] +} -cleanup { + destroy .c +} -result {{50.00 150.00} {info se} {42 129 50 150}} +test canvas-22.3 {canvas rotate: image item rotation behaviour} -setup { + pack [canvas .c] + image create photo dummy -width 50 -height 50 +} -body { + .c create image 50 50 -image dummy -anchor se + .c rotate all 100 100 90 + list [lmap c [.c coords all] {format %.2f $c}] \ + [lmap o {-image -anchor} {.c itemcget all $o}] \ + [.c bbox all] +} -cleanup { + destroy .c + image delete dummy +} -result {{50.00 150.00} {dummy se} {0 100 50 150}} +test canvas-22.4 {canvas rotate: line item rotation behaviour} -setup { + pack [canvas .c] +} -body { + .c create line 50 50 75 50 50 75 75 75 + .c rotate all 100 100 90 + list [lmap c [.c coords all] {format %.2f $c}] \ + [lmap o {} {.c itemcget all $o}] \ + [.c bbox all] +} -cleanup { + destroy .c +} -result {{50.00 150.00 50.00 125.00 75.00 150.00 75.00 125.00} {} {48 123 77 152}} +test canvas-22.5 {canvas rotate: oval item rotation behaviour} -setup { + pack [canvas .c] +} -body { + .c create oval 50 50 65 85 + .c rotate all 100 100 90 + list [lmap c [.c coords all] {format %.2f $c}] \ + [lmap o {} {.c itemcget all $o}] \ + [.c bbox all] +} -cleanup { + destroy .c +} -result {{60.00 125.00 75.00 160.00} {} {59 124 76 161}} +test canvas-22.6 {canvas rotate: polygon item rotation behaviour} -setup { + pack [canvas .c] +} -body { + .c create polygon 50 50 75 50 50 75 75 75 + .c rotate all 100 100 90 + list [lmap c [.c coords all] {format %.2f $c}] \ + [lmap o {} {.c itemcget all $o}] \ + [.c bbox all] +} -cleanup { + destroy .c +} -result {{50.00 150.00 50.00 125.00 75.00 150.00 75.00 125.00} {} {49 124 76 151}} +test canvas-22.7 {canvas rotate: rectangle item rotation behaviour} -setup { + pack [canvas .c] +} -body { + .c create rectangle 50 50 75 75 + .c rotate all 100 100 90 + list [lmap c [.c coords all] {format %.2f $c}] \ + [lmap o {} {.c itemcget all $o}] \ + [.c bbox all] +} -cleanup { + destroy .c +} -result {{50.00 125.00 75.00 150.00} {} {49 124 76 151}} +test canvas-22.8 {canvas rotate: text item rotation behaviour} -setup { + pack [canvas .c] +} -body { + .c create text 50 50 -text foo -angle 45 + .c rotate all 100 100 90 + list [lmap c [.c coords all] {format %.2f $c}] \ + [lmap o {-text -angle} {.c itemcget all $o}] + # [.c bbox all] + # No testing of text bounding box; fonts too variable! +} -cleanup { + destroy .c +} -result {{50.00 150.00} {foo 45.0}} +test canvas-22.9 {canvas rotate: window item rotation behaviour} -setup { + pack [canvas .c] +} -body { + .c create window 50 50 -window [frame .c.f -width 25 -height 25] \ + -anchor se + .c rotate all 100 100 90 + list [lmap c [.c coords all] {format %.2f $c}] \ + [lmap o {} {.c itemcget all $o}] \ + [.c bbox all] +} -cleanup { + destroy .c +} -result {{50.00 150.00} {} {25 125 50 150}} + # cleanup imageCleanup cleanupTests -- cgit v0.12 From 013e787609043566d56a742e5fd5c12a95128e6d Mon Sep 17 00:00:00 2001 From: culler Date: Fri, 29 Mar 2019 21:38:08 +0000 Subject: Fix bug [1001070]: Aqua labels do not display highlight background. --- macosx/tkMacOSXButton.c | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/macosx/tkMacOSXButton.c b/macosx/tkMacOSXButton.c index 484dcf2..705b214 100644 --- a/macosx/tkMacOSXButton.c +++ b/macosx/tkMacOSXButton.c @@ -67,9 +67,28 @@ typedef struct { } MacButton; /* - * Forward declarations for procedures defined later in this file: + * When drawing highlight borders for Buttons or Labels, the function + * Tk_Draw3DRectangle is called with SOLID relief. This in turn calls the + * stubs Tk_3DVerticalBevel and Tk_3DHorizontalBevel. The Mac port does not + * define these stubs itself, but instead uses the ones defined in tkUnix3d.c, + * which gets compiled and linked into the Mac Tk library. One of the + * arguments to these stubs is a pointer to a UnixBorder struct, which is an + * extension of TkBorder containing one additional field which is a graphics + * context to be used when drawing the bevels. The UnixBorder is declared in + * the file tkUnix3d.c and not in any header file. We include the declaration + * here, so that we can draw highlight borders. But this declaration must be + * kept in sync with the one in tkUnix3d.c. */ +#include "tk3d.h" +typedef struct { + TkBorder info; + GC solidGC; /* Used to draw solid relief. */ +} UnixBorder; + +/* + * Forward declarations for procedures defined later in this file: + */ static void ButtonBackgroundDrawCB (const HIRect *btnbounds, MacButton *ptr, SInt16 depth, Boolean isColorDev); @@ -227,8 +246,17 @@ TkpDisplayButton( /* Draw highlight border, if needed. */ if (needhighlight) { - if ((butPtr->flags & GOT_FOCUS)) { - Tk_Draw3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0, + if ((butPtr->flags & GOT_FOCUS || butPtr->type == TYPE_LABEL)) { + GC gc; + UnixBorder border; + if (butPtr->highlightColorPtr) { + gc = Tk_GCForColor(butPtr->highlightColorPtr, pixmap); + } else { + gc = Tk_GCForColor(Tk_3DBorderColor(butPtr->highlightBorder), + pixmap); + } + border.solidGC = gc; + Tk_Draw3DRectangle(tkwin, pixmap, &border, 0, 0, Tk_Width(tkwin), Tk_Height(tkwin), butPtr->highlightWidth, TK_RELIEF_SOLID); } -- cgit v0.12 From f3cda13076d3cb843499495810340da272036737 Mon Sep 17 00:00:00 2001 From: fvogel Date: Fri, 29 Mar 2019 22:05:26 +0000 Subject: Cross-reference UnixBorder structs in different files. --- unix/tkUnix3d.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/unix/tkUnix3d.c b/unix/tkUnix3d.c index 2969de1..3dbd45e 100644 --- a/unix/tkUnix3d.c +++ b/unix/tkUnix3d.c @@ -19,7 +19,8 @@ /* * This structure is used to keep track of the extra colors used by Unix 3D - * borders. + * borders. Warning: The structure of the same name in tkMacOSXButton.c must + * be kept in sync with this one. */ typedef struct { -- cgit v0.12 From ab7aa7d7f951b4cc5821e902bb952901b5b9bf9c Mon Sep 17 00:00:00 2001 From: culler Date: Sat, 30 Mar 2019 14:26:46 +0000 Subject: Keep It Safe and Simple. Just draw the border. Do not use tkUnix3d.c. Also update the manual to document this behavior. --- doc/label.n | 5 +++++ macosx/tkMacOSXButton.c | 41 ++++++++-------------------------------- macosx/tkMacOSXDraw.c | 49 ++++++++++++++++++++++++++++++++++++++++++++++++ macosx/tkMacOSXPrivate.h | 2 ++ unix/tkUnix3d.c | 3 +-- 5 files changed, 65 insertions(+), 35 deletions(-) diff --git a/doc/label.n b/doc/label.n index f2ba88c..e4b4749 100644 --- a/doc/label.n +++ b/doc/label.n @@ -68,6 +68,11 @@ one of the characters may optionally be underlined using the \fB\-underline\fR option. The label can be manipulated in a few simple ways, such as changing its relief or text, using the commands described below. +.PP +With respect to the \fB-highlightbackground\fR option, a label is +considered to always have focus, meaning that the highlight border +will always be drawn, provided that \fB-highllightthickness\fR is +positive. .SH "WIDGET COMMAND" .PP The \fBlabel\fR command creates a new Tcl command whose diff --git a/macosx/tkMacOSXButton.c b/macosx/tkMacOSXButton.c index 705b214..23596d4 100644 --- a/macosx/tkMacOSXButton.c +++ b/macosx/tkMacOSXButton.c @@ -67,26 +67,6 @@ typedef struct { } MacButton; /* - * When drawing highlight borders for Buttons or Labels, the function - * Tk_Draw3DRectangle is called with SOLID relief. This in turn calls the - * stubs Tk_3DVerticalBevel and Tk_3DHorizontalBevel. The Mac port does not - * define these stubs itself, but instead uses the ones defined in tkUnix3d.c, - * which gets compiled and linked into the Mac Tk library. One of the - * arguments to these stubs is a pointer to a UnixBorder struct, which is an - * extension of TkBorder containing one additional field which is a graphics - * context to be used when drawing the bevels. The UnixBorder is declared in - * the file tkUnix3d.c and not in any header file. We include the declaration - * here, so that we can draw highlight borders. But this declaration must be - * kept in sync with the one in tkUnix3d.c. - */ - -#include "tk3d.h" -typedef struct { - TkBorder info; - GC solidGC; /* Used to draw solid relief. */ -} UnixBorder; - -/* * Forward declarations for procedures defined later in this file: */ @@ -208,6 +188,12 @@ TkpDisplayButton( return; } pixmap = (Pixmap) Tk_WindowId(tkwin); + + /* + * Set up clipping region. Make sure the we are using the port + * for this button, or we will set the wrong window's clip. + */ + TkMacOSXSetUpClippingRgn(Tk_WindowId(tkwin)); if (TkMacOSXComputeButtonDrawParams(butPtr, dpPtr) ) { @@ -215,13 +201,6 @@ TkpDisplayButton( } else { macButtonPtr->useTkText = 1; } - - - /* - * Set up clipping region. Make sure the we are using the port - * for this button, or we will set the wrong window's clip. - */ - if (macButtonPtr->useTkText) { if (butPtr->type == TYPE_BUTTON) { Tk_Fill3DRectangle(tkwin, pixmap, butPtr->highlightBorder, 0, 0, @@ -248,17 +227,13 @@ TkpDisplayButton( if (needhighlight) { if ((butPtr->flags & GOT_FOCUS || butPtr->type == TYPE_LABEL)) { GC gc; - UnixBorder border; if (butPtr->highlightColorPtr) { - gc = Tk_GCForColor(butPtr->highlightColorPtr, pixmap); + gc = Tk_GCForColor(butPtr->highlightColorPtr, pixmap); } else { gc = Tk_GCForColor(Tk_3DBorderColor(butPtr->highlightBorder), pixmap); } - border.solidGC = gc; - Tk_Draw3DRectangle(tkwin, pixmap, &border, 0, 0, - Tk_Width(tkwin), Tk_Height(tkwin), - butPtr->highlightWidth, TK_RELIEF_SOLID); + TkMacOSXDrawSolidBorder(tkwin, gc, 0, butPtr->highlightWidth); } } } diff --git a/macosx/tkMacOSXDraw.c b/macosx/tkMacOSXDraw.c index faad137..598b581 100644 --- a/macosx/tkMacOSXDraw.c +++ b/macosx/tkMacOSXDraw.c @@ -1027,6 +1027,55 @@ XFillRectangles( /* *---------------------------------------------------------------------- * + * TkMacOSXDrawSolidBorder -- + * + * Draws a border rectangle of specified thickness inside the bounding + * rectangle of a Tk Window. The border rectangle can be inset within the + * bounding rectangle. For a highlight border the inset should be 0, but + * for a solid border around the actual window the inset should equal the + * thickness of the highlight border. The color of the border rectangle + * is the foreground color of the graphics context passed to the function. + * + * Results: + * None. + * + * Side effects: + * Draws a rectangular border inside the bounding rectangle of a window. + * + *---------------------------------------------------------------------- + */ + +MODULE_SCOPE void +TkMacOSXDrawSolidBorder( + Tk_Window tkwin, + GC gc, + int inset, + int thickness) +{ + Drawable d = Tk_WindowId(tkwin); + MacDrawable *macWin = (MacDrawable *) d; + TkMacOSXDrawingContext dc; + CGRect outerRect, innerRect; + + if (!TkMacOSXSetupDrawingContext(d, gc, 1, &dc)) { + return; + } + if (dc.context) { + outerRect = CGRectMake(Tk_X(tkwin), Tk_Y(tkwin), + Tk_Width(tkwin), Tk_Height(tkwin)); + outerRect = CGRectInset(outerRect, inset, inset); + innerRect = CGRectInset(outerRect, thickness, thickness); + CGContextBeginPath(dc.context); + CGContextAddRect(dc.context, outerRect); + CGContextAddRect(dc.context, innerRect); + CGContextEOFillPath(dc.context); + } + TkMacOSXRestoreDrawingContext(&dc); +} + +/* + *---------------------------------------------------------------------- + * * XDrawArc -- * * Draw an arc. diff --git a/macosx/tkMacOSXPrivate.h b/macosx/tkMacOSXPrivate.h index 105317d..668562a 100644 --- a/macosx/tkMacOSXPrivate.h +++ b/macosx/tkMacOSXPrivate.h @@ -233,6 +233,8 @@ MODULE_SCOPE int TkMacOSXStandardAboutPanelObjCmd(ClientData clientData, MODULE_SCOPE int TkMacOSXIconBitmapObjCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]); +MODULE_SCOPE void TkMacOSXDrawSolidBorder(Tk_Window tkwin, GC gc, + int inset, int thickness); #pragma mark Private Objective-C Classes diff --git a/unix/tkUnix3d.c b/unix/tkUnix3d.c index 3dbd45e..2969de1 100644 --- a/unix/tkUnix3d.c +++ b/unix/tkUnix3d.c @@ -19,8 +19,7 @@ /* * This structure is used to keep track of the extra colors used by Unix 3D - * borders. Warning: The structure of the same name in tkMacOSXButton.c must - * be kept in sync with this one. + * borders. */ typedef struct { -- cgit v0.12 From 761cdb86562088f0dd44c45d314dce97acd38a79 Mon Sep 17 00:00:00 2001 From: culler Date: Sat, 30 Mar 2019 17:29:31 +0000 Subject: Correctly distinguish between -highlightcolor and -highlightbackground and revert unnecessary changes to the label manual. --- doc/label.n | 5 ----- macosx/tkMacOSXButton.c | 15 +++++++-------- 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/doc/label.n b/doc/label.n index e4b4749..f2ba88c 100644 --- a/doc/label.n +++ b/doc/label.n @@ -68,11 +68,6 @@ one of the characters may optionally be underlined using the \fB\-underline\fR option. The label can be manipulated in a few simple ways, such as changing its relief or text, using the commands described below. -.PP -With respect to the \fB-highlightbackground\fR option, a label is -considered to always have focus, meaning that the highlight border -will always be drawn, provided that \fB-highllightthickness\fR is -positive. .SH "WIDGET COMMAND" .PP The \fBlabel\fR command creates a new Tcl command whose diff --git a/macosx/tkMacOSXButton.c b/macosx/tkMacOSXButton.c index 23596d4..8ccfdb3 100644 --- a/macosx/tkMacOSXButton.c +++ b/macosx/tkMacOSXButton.c @@ -225,14 +225,13 @@ TkpDisplayButton( /* Draw highlight border, if needed. */ if (needhighlight) { - if ((butPtr->flags & GOT_FOCUS || butPtr->type == TYPE_LABEL)) { - GC gc; - if (butPtr->highlightColorPtr) { - gc = Tk_GCForColor(butPtr->highlightColorPtr, pixmap); - } else { - gc = Tk_GCForColor(Tk_3DBorderColor(butPtr->highlightBorder), - pixmap); - } + GC gc = NULL; + if ((butPtr->flags & GOT_FOCUS) && butPtr->highlightColorPtr) { + gc = Tk_GCForColor(butPtr->highlightColorPtr, pixmap); + } else if (butPtr->type == TYPE_LABEL) { + gc = Tk_GCForColor(Tk_3DBorderColor(butPtr->highlightBorder), pixmap); + } + if (gc) { TkMacOSXDrawSolidBorder(tkwin, gc, 0, butPtr->highlightWidth); } } -- cgit v0.12 From 8139b018a833b0ef8c1263ff3e6b90a45fcbaf99 Mon Sep 17 00:00:00 2001 From: fvogel Date: Sun, 31 Mar 2019 11:01:32 +0000 Subject: Remove an unused variable, squelching a compiler warning. --- macosx/tkMacOSXDraw.c | 1 - 1 file changed, 1 deletion(-) diff --git a/macosx/tkMacOSXDraw.c b/macosx/tkMacOSXDraw.c index 598b581..013f654 100644 --- a/macosx/tkMacOSXDraw.c +++ b/macosx/tkMacOSXDraw.c @@ -1053,7 +1053,6 @@ TkMacOSXDrawSolidBorder( int thickness) { Drawable d = Tk_WindowId(tkwin); - MacDrawable *macWin = (MacDrawable *) d; TkMacOSXDrawingContext dc; CGRect outerRect, innerRect; -- cgit v0.12 From d84fefbe9128b55dfa168232174559c52e11011e Mon Sep 17 00:00:00 2001 From: fvogel Date: Sun, 31 Mar 2019 12:52:10 +0000 Subject: Make labels, checkbuttons and radiobuttons honor -highlightbackground and -highlightcolor options on Windows. --- win/tkWinButton.c | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/win/tkWinButton.c b/win/tkWinButton.c index ee0ce82..f101f89 100644 --- a/win/tkWinButton.c +++ b/win/tkWinButton.c @@ -410,7 +410,7 @@ TkpDisplayButton( ? butPtr->highlightWidth : 0); offset = 1; } else { - defaultWidth = 0; + defaultWidth = butPtr->highlightWidth;; if ((butPtr->type >= TYPE_CHECK_BUTTON) && !butPtr->indicatorOn) { offset = 1; } else { @@ -759,17 +759,23 @@ TkpDisplayButton( butPtr->borderWidth, relief); } if (defaultWidth != 0) { + int highlightColor = + (int) Tk_3DBorderColor(butPtr->highlightBorder)->pixel; + dc = TkWinGetDrawableDC(butPtr->display, pixmap, &state); + if (butPtr->flags & GOT_FOCUS) { + highlightColor = (int) butPtr->highlightColorPtr->pixel; + } TkWinFillRect(dc, 0, 0, Tk_Width(tkwin), defaultWidth, - (int) butPtr->highlightColorPtr->pixel); + highlightColor); TkWinFillRect(dc, 0, 0, defaultWidth, Tk_Height(tkwin), - (int) butPtr->highlightColorPtr->pixel); + highlightColor); TkWinFillRect(dc, 0, Tk_Height(tkwin) - defaultWidth, Tk_Width(tkwin), defaultWidth, - (int) butPtr->highlightColorPtr->pixel); + highlightColor); TkWinFillRect(dc, Tk_Width(tkwin) - defaultWidth, 0, defaultWidth, Tk_Height(tkwin), - (int) butPtr->highlightColorPtr->pixel); + highlightColor); TkWinReleaseDrawableDC(pixmap, dc, &state); } -- cgit v0.12 From 8cf4a9bdbf03c6a9b09e09554c470e7f2e13abdf Mon Sep 17 00:00:00 2001 From: fvogel Date: Sun, 31 Mar 2019 14:34:16 +0000 Subject: Restore behavior of checkbuttons and radiobuttons on Windows. They again do not take -highlightbackground into account, in an attempt to follow platform specific conventions. The code now only changes this for labels. --- win/tkWinButton.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/win/tkWinButton.c b/win/tkWinButton.c index f101f89..6024b02 100644 --- a/win/tkWinButton.c +++ b/win/tkWinButton.c @@ -405,12 +405,15 @@ TkpDisplayButton( * Compute width of default ring and offset for pushed buttons. */ - if (butPtr->type == TYPE_BUTTON) { + if (butPtr->type == TYPE_LABEL) { + defaultWidth = butPtr->highlightWidth; + offset = 0; + } else if (butPtr->type == TYPE_BUTTON) { defaultWidth = ((butPtr->defaultState == DEFAULT_ACTIVE) ? butPtr->highlightWidth : 0); offset = 1; } else { - defaultWidth = butPtr->highlightWidth;; + defaultWidth = 0; if ((butPtr->type >= TYPE_CHECK_BUTTON) && !butPtr->indicatorOn) { offset = 1; } else { -- cgit v0.12 From a46a024f97912319754e4dae155b18f796b56b0d Mon Sep 17 00:00:00 2001 From: fvogel Date: Sun, 31 Mar 2019 14:43:09 +0000 Subject: *Really* don't change the behavior for *buttons, even with they have -default active --- win/tkWinButton.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/win/tkWinButton.c b/win/tkWinButton.c index 6024b02..d03a391 100644 --- a/win/tkWinButton.c +++ b/win/tkWinButton.c @@ -762,11 +762,12 @@ TkpDisplayButton( butPtr->borderWidth, relief); } if (defaultWidth != 0) { - int highlightColor = - (int) Tk_3DBorderColor(butPtr->highlightBorder)->pixel; + int highlightColor; dc = TkWinGetDrawableDC(butPtr->display, pixmap, &state); - if (butPtr->flags & GOT_FOCUS) { + if (butPtr->type == TYPE_LABEL) { + highlightColor = (int) Tk_3DBorderColor(butPtr->highlightBorder)->pixel; + } else { highlightColor = (int) butPtr->highlightColorPtr->pixel; } TkWinFillRect(dc, 0, 0, Tk_Width(tkwin), defaultWidth, -- cgit v0.12 From 1203c84117410cd64aba7bee09446665f14792f9 Mon Sep 17 00:00:00 2001 From: culler Date: Sun, 31 Mar 2019 16:33:50 +0000 Subject: Make menubuttons honor the -highlightcolor option on macOS. --- macosx/tkMacOSXMenubutton.c | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/macosx/tkMacOSXMenubutton.c b/macosx/tkMacOSXMenubutton.c index b2b4b76..5b39e19 100644 --- a/macosx/tkMacOSXMenubutton.c +++ b/macosx/tkMacOSXMenubutton.c @@ -190,11 +190,10 @@ TkpDisplayMenuButton( /* Draw highlight border, if needed. */ if (butPtr->highlightWidth < 3) { - if ((butPtr->flags & GOT_FOCUS)) { - Tk_Draw3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0, - Tk_Width(tkwin), Tk_Height(tkwin), - butPtr->highlightWidth, TK_RELIEF_SOLID); - } + if (butPtr->flags & GOT_FOCUS) { + GC gc = Tk_GCForColor(butPtr->highlightColorPtr, pixmap); + TkMacOSXDrawSolidBorder(tkwin, gc, 0, butPtr->highlightWidth); + } } } -- cgit v0.12 From 992e83396570dcf0c161abd79226964eb535ad57 Mon Sep 17 00:00:00 2001 From: culler Date: Sun, 31 Mar 2019 16:34:59 +0000 Subject: Fix indentation. --- macosx/tkMacOSXMenubutton.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/macosx/tkMacOSXMenubutton.c b/macosx/tkMacOSXMenubutton.c index 5b39e19..f52b98e 100644 --- a/macosx/tkMacOSXMenubutton.c +++ b/macosx/tkMacOSXMenubutton.c @@ -191,8 +191,8 @@ TkpDisplayMenuButton( /* Draw highlight border, if needed. */ if (butPtr->highlightWidth < 3) { if (butPtr->flags & GOT_FOCUS) { - GC gc = Tk_GCForColor(butPtr->highlightColorPtr, pixmap); - TkMacOSXDrawSolidBorder(tkwin, gc, 0, butPtr->highlightWidth); + GC gc = Tk_GCForColor(butPtr->highlightColorPtr, pixmap); + TkMacOSXDrawSolidBorder(tkwin, gc, 0, butPtr->highlightWidth); } } } -- cgit v0.12 From bf851b7accfe65e18edffaa7eceaa0a7bf409e79 Mon Sep 17 00:00:00 2001 From: fvogel Date: Wed, 3 Apr 2019 20:49:28 +0000 Subject: Remove the error that was triggering with very small arcs while still preventing NaN and Inf values to leak in the computations. Add a new test canvas-21.1 checking results for zero-length arcs. --- generic/tkCanvArc.c | 33 ++++++++++++++++++--------------- tests/canvas.test | 18 ++++++++++++++++++ 2 files changed, 36 insertions(+), 15 deletions(-) diff --git a/generic/tkCanvArc.c b/generic/tkCanvArc.c index ead03bf..608caf7 100644 --- a/generic/tkCanvArc.c +++ b/generic/tkCanvArc.c @@ -185,7 +185,7 @@ static void ComputeArcBbox(Tk_Canvas canvas, ArcItem *arcPtr); static int ConfigureArc(Tcl_Interp *interp, Tk_Canvas canvas, Tk_Item *itemPtr, int objc, Tcl_Obj *const objv[], int flags); -static int ComputeArcFromHeight(ArcItem *arcPtr); +static void ComputeArcFromHeight(ArcItem *arcPtr); static int CreateArc(Tcl_Interp *interp, Tk_Canvas canvas, struct Tk_Item *itemPtr, int objc, Tcl_Obj *const objv[]); @@ -475,14 +475,7 @@ ConfigureArc( * overridden. */ if (arcPtr->height != 0) { - int ret = ComputeArcFromHeight(arcPtr); - if (ret != TCL_OK) { - Tcl_SetObjResult(interp, Tcl_ObjPrintf( - "coordinates too close to define a chord")); - Tcl_SetErrorCode(interp, "TK", "CANVAS", "COORDS", "ARC", - NULL); - return ret; - } + ComputeArcFromHeight(arcPtr); ComputeArcBbox(canvas, arcPtr); } @@ -604,7 +597,7 @@ ConfigureArc( * end-point and height (!= 0). * * Results: - * TCL_ERROR if the chord length is zero, TCL_OK otherwise. + * None. * * Side effects: * The height parameter is set to 0 on exit. @@ -612,7 +605,7 @@ ConfigureArc( *-------------------------------------------------------------- */ -static int +static void ComputeArcFromHeight( ArcItem* arcPtr) { @@ -625,8 +618,20 @@ ComputeArcFromHeight( chordLen = hypot(arcPtr->endPoint[1] - arcPtr->startPoint[1], arcPtr->startPoint[0] - arcPtr->endPoint[0]); - if (chordLen < DBL_EPSILON) - return TCL_ERROR; + if (chordLen < DBL_EPSILON) { + + /* + * Specialize computations for zero-length arc to avoid NaN or Inf. + */ + + arcPtr->start = arcPtr->extent = 0; + arcPtr->bbox[0] = arcPtr->bbox[2] = + (arcPtr->startPoint[0] + arcPtr->endPoint[0]) / 2; + arcPtr->bbox[1] = arcPtr->bbox[3] = + (arcPtr->startPoint[1] + arcPtr->endPoint[1]) / 2; + arcPtr->height = 0; + return; + } chordDir[0] = (arcPtr->endPoint[0] - arcPtr->startPoint[0]) / chordLen; chordDir[1] = (arcPtr->endPoint[1] - arcPtr->startPoint[1]) / chordLen; @@ -681,8 +686,6 @@ ComputeArcFromHeight( */ arcPtr->height = 0; - - return TCL_OK; } /* diff --git a/tests/canvas.test b/tests/canvas.test index e8dc332..dafce90 100644 --- a/tests/canvas.test +++ b/tests/canvas.test @@ -1040,6 +1040,24 @@ test canvas-20.3 {canvas image with subsample and zoom} -setup { image delete testimage } -result 1 +test canvas-21.1 {canvas very small arc} -setup { + catch {destroy .c} + canvas .c +} -body { + # no Inf or NaN must be generated even for very small arcs + .c create arc 0 100 0 100 -height 100 -style arc -outline "" -tags arc1 + set arcBox [.c bbox arc1] + .c create arc 0 100 0 100 -height 100 -style arc -outline blue -tags arc2 + set outlinedArcBox [.c bbox arc2] + set coords [.c coords arc1] + set start [.c itemcget arc1 -start] + set extent [.c itemcget arc1 -extent] + set width [.c itemcget arc1 -width] + set height [.c itemcget arc1 -height] + list $arcBox $outlinedArcBox $coords $start $extent $width $height +} -result {{-1 99 1 101} {-2 98 2 102} {0.0 100.0 0.0 100.0} 0.0 0.0 1.0 0.0} + + # cleanup imageCleanup cleanupTests -- cgit v0.12 From 6d78bbb85627dd66947ea2af0bc8d2a796cc0c58 Mon Sep 17 00:00:00 2001 From: fvogel Date: Sun, 7 Apr 2019 09:39:29 +0000 Subject: Improved patch to deal with zero length arcs specified by their height. --- generic/tkCanvArc.c | 38 +++++++++++++++++--------------------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/generic/tkCanvArc.c b/generic/tkCanvArc.c index 608caf7..c04de84 100644 --- a/generic/tkCanvArc.c +++ b/generic/tkCanvArc.c @@ -185,7 +185,7 @@ static void ComputeArcBbox(Tk_Canvas canvas, ArcItem *arcPtr); static int ConfigureArc(Tcl_Interp *interp, Tk_Canvas canvas, Tk_Item *itemPtr, int objc, Tcl_Obj *const objv[], int flags); -static void ComputeArcFromHeight(ArcItem *arcPtr); +static void ComputeArcParametersFromHeight(ArcItem *arcPtr); static int CreateArc(Tcl_Interp *interp, Tk_Canvas canvas, struct Tk_Item *itemPtr, int objc, Tcl_Obj *const objv[]); @@ -471,13 +471,12 @@ ConfigureArc( } /* - * If either the height is provided then the start and extent will be - * overridden. + * Override the start and extent if the height is given. */ - if (arcPtr->height != 0) { - ComputeArcFromHeight(arcPtr); - ComputeArcBbox(canvas, arcPtr); - } + + ComputeArcParametersFromHeight(arcPtr); + + ComputeArcBbox(canvas, arcPtr); i = (int) (arcPtr->start/360.0); arcPtr->start -= i*360.0; @@ -591,7 +590,7 @@ ConfigureArc( /* *-------------------------------------------------------------- * - * ComputeArcFromHeight -- + * ComputeArcParametersFromHeight -- * * This function calculates the arc parameters given start-point, * end-point and height (!= 0). @@ -606,30 +605,27 @@ ConfigureArc( */ static void -ComputeArcFromHeight( +ComputeArcParametersFromHeight( ArcItem* arcPtr) { double chordLen, chordDir[2], chordCen[2], arcCen[2], d, radToDeg, radius; /* - * The chord. + * Do nothing if no height has been specified. + */ + + if (arcPtr->height == 0) + return; + + /* + * Calculate the chord length, return early if it is too small. */ chordLen = hypot(arcPtr->endPoint[1] - arcPtr->startPoint[1], arcPtr->startPoint[0] - arcPtr->endPoint[0]); if (chordLen < DBL_EPSILON) { - - /* - * Specialize computations for zero-length arc to avoid NaN or Inf. - */ - - arcPtr->start = arcPtr->extent = 0; - arcPtr->bbox[0] = arcPtr->bbox[2] = - (arcPtr->startPoint[0] + arcPtr->endPoint[0]) / 2; - arcPtr->bbox[1] = arcPtr->bbox[3] = - (arcPtr->startPoint[1] + arcPtr->endPoint[1]) / 2; - arcPtr->height = 0; + arcPtr->start = arcPtr->extent = arcPtr->height = 0; return; } -- cgit v0.12 From d95284c405fba9c6f6222e1af119f5ba73b4443a Mon Sep 17 00:00:00 2001 From: fvogel Date: Wed, 10 Apr 2019 19:50:53 +0000 Subject: Fix [368fa4561e]: ttk::treeview open/closed indicators can be toggled while hidden --- library/ttk/treeview.tcl | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/library/ttk/treeview.tcl b/library/ttk/treeview.tcl index 1ed87db..6a6f5d4 100644 --- a/library/ttk/treeview.tcl +++ b/library/ttk/treeview.tcl @@ -336,6 +336,12 @@ proc ttk::treeview::CloseItem {w item} { ## Toggle -- toggle opened/closed state of item # proc ttk::treeview::Toggle {w item} { + # don't allow toggling on indicators that + # are not present in front of leaf items + if {[$w children $item] == {}} { + return + } + # not a leaf, toggle! if {[$w item $item -open]} { CloseItem $w $item } else { -- cgit v0.12 From 1c8361c420075b482b5eee473b2958e7b8e6b934 Mon Sep 17 00:00:00 2001 From: culler Date: Fri, 12 Apr 2019 21:10:03 +0000 Subject: Adjust for the new ttk widgets. --- library/ttk/menubutton.tcl | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/library/ttk/menubutton.tcl b/library/ttk/menubutton.tcl index 9d12b05..43b3cd8 100644 --- a/library/ttk/menubutton.tcl +++ b/library/ttk/menubutton.tcl @@ -74,35 +74,41 @@ if {[tk windowingsystem] eq "x11"} { if {[tk windowingsystem] eq "aqua"} { proc ::ttk::menubutton::PostPosition {mb menu} { - set mh [expr {[winfo reqheight $menu] - 6}] - set bh [expr {[winfo height $mb] + 1}] - set mw [expr {[winfo reqwidth $menu] - 2}] - set bw [expr {[winfo width $mb] -1}] - set dF [expr {[winfo width $mb] - [winfo reqwidth $menu] -9}] + set menuPad 5 + set buttonPad 1 + set bevelPad 4 + set mh [winfo reqheight $menu] + set bh [expr {[winfo height $mb]} + $buttonPad] + set bbh [expr {[winfo height $mb]} + $bevelPad] + set mw [winfo reqwidth $menu] + set bw [winfo width $mb] + set dF [expr {[winfo width $mb] - [winfo reqwidth $menu] - $menuPad}] set entry "" set entry [::tk::MenuFindName $menu [$mb cget -text]] if {$entry eq ""} { set entry 0 } set x [winfo rootx $mb] - set y [expr {2 + [winfo rooty $mb]}] + set y [winfo rooty $mb] switch [$mb cget -direction] { above { set entry "" - incr y -$mh + incr y [expr {-$mh + 2 * $menuPad}] } below { set entry "" incr y $bh } left { + incr y $menuPad incr x -$mw } right { + incr y $menuPad incr x $bw } default { - incr x $dF + incr y $bbh } } return [list $x $y $entry] -- cgit v0.12 From bfc9e1b9f79100fa104697353b670f9ba95d012d Mon Sep 17 00:00:00 2001 From: fvogel Date: Fri, 12 Apr 2019 21:42:51 +0000 Subject: Repair the test suite (the svgnano format was renamed svg, and -x/-y options were removed from the implementation. --- tests/imgSVGnano.test | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/tests/imgSVGnano.test b/tests/imgSVGnano.test index ec93f0a..74c3318 100644 --- a/tests/imgSVGnano.test +++ b/tests/imgSVGnano.test @@ -39,7 +39,7 @@ test imgSVGnano-1.1 {reading simple image} -setup { test imgSVGnano-1.2 {simple image with options} -setup { catch {rename foo ""} } -body { - image create photo foo -data $data(plus) -format {svgnano -dpi 100 -scale 3} + image create photo foo -data $data(plus) -format {svg -dpi 100 -scale 3} list [image width foo] [image height foo] } -cleanup { rename foo "" @@ -50,7 +50,7 @@ test imgSVGnano-1.3 {reformat image options} -setup { catch {rename foo ""} } -body { image create photo foo -data $data(plus) - catch {foo configure -format {svgnano -scale}} + catch {foo configure -format {svg -scale}} list {} } -cleanup { rename foo "" @@ -60,14 +60,13 @@ test imgSVGnano-1.4 {image options} -setup { catch {rename foo ""} } -body { image create photo foo -data $data(plus) - foo configure -format {svgnano -scale 2} - foo configure -format {svgnano -x 20 -y -10} - foo configure -format {svgnano -unit pt} - foo configure -format {svgnano -unit mm} - foo configure -format {svgnano -unit cm} - foo configure -format {svgnano -unit in} - foo configure -format {svgnano -unit px} - foo configure -format {svgnano -dpi 600} + foo configure -format {svg -scale 2} + foo configure -format {svg -unit pt} + foo configure -format {svg -unit mm} + foo configure -format {svg -unit cm} + foo configure -format {svg -unit in} + foo configure -format {svg -unit px} + foo configure -format {svg -dpi 600} list [image width foo] [image height foo] } -cleanup { rename foo "" @@ -75,10 +74,10 @@ test imgSVGnano-1.4 {image options} -setup { test imgSVGnano-2.1 {reading a bad image} -body { - image create photo foo -format svgnano -data $data(bad) + image create photo foo -format svg -data $data(bad) } -returnCodes error -result {couldn't recognize image data} test imgSVGnano-2.2 {using bad option} -body { - image create photo -data $data(plus) -format {svgnano -scale 0} + image create photo -data $data(plus) -format {svg -scale 0} } -returnCodes error -result {couldn't recognize image data} };# end of namespace svgnano -- cgit v0.12 From 3a81c1fb68b1e2b976651df7359209916ea5be63 Mon Sep 17 00:00:00 2001 From: fvogel Date: Sat, 13 Apr 2019 16:44:20 +0000 Subject: Add test treeview-368fa4561e checking for non-regression regarding [368fa4561e] --- tests/ttk/treeview.test | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tests/ttk/treeview.test b/tests/ttk/treeview.test index aa7e64a..be82f68 100644 --- a/tests/ttk/treeview.test +++ b/tests/ttk/treeview.test @@ -636,4 +636,21 @@ test treeview-3085489-2 "tag remove, no -tags" -setup { destroy .tv } -result [list] +test treeview-368fa4561e "indicators cannot be clicked on leafs" -setup { + pack [ttk::treeview .tv] + .tv insert {} end -id foo -text "<-- (1) Click the blank space to my left" + update +} -body { + foreach {x y w h} [.tv bbox foo #0] {} + set res [.tv item foo -open] + # using $h even for x computation is intentional here in order to simulate + # a mouse click on the (invisible since we're on a leaf) indicator + event generate .tv \ + -x [expr ($x + $h / 2)] \ + -y [expr ($y + $h / 2)] + lappend res [.tv item foo -open] + .tv insert foo end -text "sub" + lappend res [.tv item foo -open] +} -result {0 0 0} + tcltest::cleanupTests -- cgit v0.12 From a231332e57a1d87c18d3e76889cc32749851f591 Mon Sep 17 00:00:00 2001 From: culler Date: Sun, 14 Apr 2019 17:29:55 +0000 Subject: For Aqua, rename systemTtkBackground to systemWindowBackgroundColor to match the NSColor name. Document the new colors. --- doc/colors.n | 39 ++++++++++++++++++++++++++++++++++++--- library/ttk/aquaTheme.tcl | 4 ++-- macosx/README | 9 +++++---- macosx/tkMacOSXColor.c | 26 ++++++++++++++++---------- 4 files changed, 59 insertions(+), 19 deletions(-) diff --git a/doc/colors.n b/doc/colors.n index dc7007b..18f73b7 100644 --- a/doc/colors.n +++ b/doc/colors.n @@ -784,9 +784,10 @@ YellowGreen 154 205 50 .TP \fBMac OS X\fR . -On Mac OS X, the following additional system colors are available -(note that the actual color values depend on the currently active OS theme, -and typically many of these will in fact be patterns rather than pure colors): +On macOS, the following additional system colors are available. +This first group contains all colors available in the HIToolbox library. +(Note that in some cases the actual color values may depend on the +current Appearance.) .RS .DS systemActiveAreaFill @@ -925,7 +926,39 @@ systemWindowHeaderBackground systemWindowHeaderInactiveText .DE .RE +. +The second group of MacOS colors below are based on Apple's "semantic" +NScolors. On OSX 10.14 (Mojave) and later these colors change value +when Dark Mode is enabled. However, the change is only observable +when the Apple window manager is drawing to the screen. So the +\fBwinfo rgb\fR command will return the color coordinates used in the +standard Aqua mode, even if Dark Mode has been selected in the system +preferences. The numbered systemWindowBackgroundColors are used in +the \fBttk::notebook\fR and \fBttk::labelframe\fR widgets to provide a +contrasting background. Each numbered color constrasts with its +predecessor. +.RS +.DS +systemControlTextColor +systemDisabledControlTextColor +systemLabelColor +systemSelectedTextBackgroundColor +systemSelectedTextColor +systemTextBackgroundColor +systemTextColor +systemWindowBackgroundColor +systemWindowBackgroundColor1 +systemWindowBackgroundColor2 +systemWindowBackgroundColor3 +systemWindowBackgroundColor4 +systemWindowBackgroundColor5 +systemWindowBackgroundColor6 +systemWindowBackgroundColor7 +.DE +.RE .TP + + \fBWindows\fR . On Windows, the following additional system colors are available diff --git a/library/ttk/aquaTheme.tcl b/library/ttk/aquaTheme.tcl index 77ece22..4b0740f 100644 --- a/library/ttk/aquaTheme.tcl +++ b/library/ttk/aquaTheme.tcl @@ -7,7 +7,7 @@ namespace eval ttk::theme::aqua { ttk::style configure . \ -font TkDefaultFont \ - -background systemTtkBackground \ + -background systemWindowBackgroundColor \ -foreground systemLabelColor \ -selectbackground systemHighlight \ -selectforeground systemLabelColor \ @@ -112,7 +112,7 @@ namespace eval ttk::theme::aqua { ttk::style configure Heading \ -font TkHeadingFont \ -foreground systemTextColor \ - -background systemTtkBackground + -background systemWindowBackgroundColor ttk::style configure Treeview -rowheight 18 \ -background systemTextBackgroundColor \ -foreground systemTextColor \ diff --git a/macosx/README b/macosx/README index cca90c5..12a7117 100644 --- a/macosx/README +++ b/macosx/README @@ -315,10 +315,11 @@ contrasts with the background of the containing object. This means that the background color of a Ttk widget depends on how deeply it is nested inside of other widgets that use contrasting backgrounds. To support this, there are 8 contrasting system colors named -systemTtkBackground, systemTtkBackground1, ... , systemTtkBackground7. -The systemTtkBackground color is the standard background for a dialog -window and the others match the contrasting background colors for -backgrounds which are nested to the corresponding depth. +systemWindowBackgroundColor, and systemWindowBackgroundColor1 - 7. +The systemWindowBackgroundColor is the standard background for a +dialog window and the others match the contrasting background colors +used in ttk::notebooks and ttk::labelframes which are nested to the +corresponding depth. 5. Building Tcl/Tk on macOS ------------------------------ diff --git a/macosx/tkMacOSXColor.c b/macosx/tkMacOSXColor.c index 0a25490..a368e8c 100644 --- a/macosx/tkMacOSXColor.c +++ b/macosx/tkMacOSXColor.c @@ -189,14 +189,14 @@ static const struct SystemColorMapEntry systemColorMap[] = { { "ListViewWindowHeaderBackground", HIBackground, kThemeBackgroundListViewWindowHeader }, /* 163 */ { "SecondaryGroupBoxBackground", HIBackground, kThemeBackgroundSecondaryGroupBox }, /* 164 */ { "MetalBackground", HIBackground, kThemeBackgroundMetal }, /* 165 */ - { "TtkBackground", ttkBackground, 0 }, /* 166 */ - { "TtkBackground1", ttkBackground, 1 }, /* 167 */ - { "TtkBackground2", ttkBackground, 2 }, /* 168 */ - { "TtkBackground3", ttkBackground, 3 }, /* 169 */ - { "TtkBackground4", ttkBackground, 4 }, /* 170 */ - { "TtkBackground5", ttkBackground, 5 }, /* 171 */ - { "TtkBackground6", ttkBackground, 6 }, /* 172 */ - { "TtkBackground7", ttkBackground, 7 }, /* 173 */ + { "WindowBackgroundColor", ttkBackground, 0 }, /* 166 */ + { "WindowBackgroundColor1", ttkBackground, 1 }, /* 167 */ + { "WindowBackgroundColor2", ttkBackground, 2 }, /* 168 */ + { "WindowBackgroundColor3", ttkBackground, 3 }, /* 169 */ + { "WindowBackgroundColor4", ttkBackground, 4 }, /* 170 */ + { "WindowBackgroundColor5", ttkBackground, 5 }, /* 171 */ + { "WindowBackgroundColor6", ttkBackground, 6 }, /* 172 */ + { "WindowBackgroundColor7", ttkBackground, 7 }, /* 173 */ { "TextColor", semantic, 0 }, /* 174 */ { "SelectedTextColor", semantic, 1 }, /* 175 */ { "LabelColor", semantic, 2 }, /* 176 */ @@ -292,8 +292,14 @@ SetCGColorComponents( bgColor = [[NSColor windowBackgroundColor] colorUsingColorSpace: deviceRGB]; [bgColor getComponents: rgba]; - for (int i=0; i<3; i++) { - rgba[i] -= entry.value*(8.0/255.0); + if (rgba[0] + rgba[1] + rgba[2] < 1.5) { + for (int i=0; i<3; i++) { + rgba[i] += entry.value*8.0/255.0; + } + } else { + for (int i=0; i<3; i++) { + rgba[i] -= entry.value*8.0/255.0; + } } break; case semantic: -- cgit v0.12 From 8eec3e9e63a26229b33ad826f232a3a0cceb9851 Mon Sep 17 00:00:00 2001 From: culler Date: Sun, 14 Apr 2019 20:01:55 +0000 Subject: For Aqua, add systemControlAccentColor; simulate the color for older systems. --- doc/colors.n | 1 + macosx/README | 29 ++++++++++++++++------------- macosx/tkMacOSXColor.c | 33 +++++++++++++++++++++++++++++++-- 3 files changed, 48 insertions(+), 15 deletions(-) diff --git a/doc/colors.n b/doc/colors.n index 18f73b7..41d6ed0 100644 --- a/doc/colors.n +++ b/doc/colors.n @@ -939,6 +939,7 @@ contrasting background. Each numbered color constrasts with its predecessor. .RS .DS +systemControlAccentColor systemControlTextColor systemDisabledControlTextColor systemLabelColor diff --git a/macosx/README b/macosx/README index 12a7117..fd54c2d 100644 --- a/macosx/README +++ b/macosx/README @@ -289,19 +289,22 @@ window. --------------------------------------- With the release of OSX 10.14 (Mojave), Apple introduced the DarkAqua -appearance. Part of the implementation of the Dark Mode was to make some of -the named NSColors have dynamic values. Apple calls these "semantic colors" -because the name does not specify a specific color, but rather refers to the -context in which the color should be used. Tk now provides the following -semantic colors as system colors: systemTextColor, systemTextBackgroundColor, -systemSelectedTextColor, systemSelectedTextBackgroundColor, -systemControlTextColor, systemDisabledControlTextColor, and systemLabelColor. -All of these except systemLabelColor, which was introduced in 10.10, were -present in OSX 10.0. The change in 10.14 was that the RGB color value of these -colors became dynamic, meaning that the color value can change when the -application appearance changes. In particular, when a user selects Dark Mode -in the system preferences these colors change appearance. For example -systemTextColor is dark in Aqua and light in DarkAqua. +appearance. Part of the implementation of the Dark Mode was to make +some of the named NSColors have dynamic values. Apple calls these +"semantic colors" because the name does not specify a specific color, +but rather refers to the context in which the color should be used. +Tk now provides the following semantic colors as system colors: +systemTextColor, systemTextBackgroundColor, systemSelectedTextColor, +systemSelectedTextBackgroundColor, systemControlTextColor, +systemDisabledControlTextColor, systemLabelColor and +systemControlAccentColor. All of these except the last two were +present in OSX 10.0 (and those two are simulated in systems where they +do not exist). The change in 10.14 was that the RGB color value of +these colors became dynamic, meaning that the color value can change +when the application appearance changes. In particular, when a user +selects Dark Mode in the system preferences these colors change +appearance. For example systemTextColor is dark in Aqua and light in +DarkAqua. The default background and foreground colors of most of the Tk widgets have been set to semantic colors, which means that the widgets will change diff --git a/macosx/tkMacOSXColor.c b/macosx/tkMacOSXColor.c index a368e8c..3885a77 100644 --- a/macosx/tkMacOSXColor.c +++ b/macosx/tkMacOSXColor.c @@ -189,6 +189,11 @@ static const struct SystemColorMapEntry systemColorMap[] = { { "ListViewWindowHeaderBackground", HIBackground, kThemeBackgroundListViewWindowHeader }, /* 163 */ { "SecondaryGroupBoxBackground", HIBackground, kThemeBackgroundSecondaryGroupBox }, /* 164 */ { "MetalBackground", HIBackground, kThemeBackgroundMetal }, /* 165 */ + + /* + * Colors based on "semantic" NSColors. + */ + { "WindowBackgroundColor", ttkBackground, 0 }, /* 166 */ { "WindowBackgroundColor1", ttkBackground, 1 }, /* 167 */ { "WindowBackgroundColor2", ttkBackground, 2 }, /* 168 */ @@ -204,10 +209,11 @@ static const struct SystemColorMapEntry systemColorMap[] = { { "DisabledControlTextColor", semantic, 4 }, /* 178 */ { "TextBackgroundColor", semantic, 5 }, /* 179 */ { "SelectedTextBackgroundColor", semantic, 6 }, /* 180 */ + { "ControlAccentColor", semantic, 7 }, /* 181 */ { NULL, 0, 0 } }; #define FIRST_SEMANTIC_COLOR 166 -#define MAX_PIXELCODE 180 +#define MAX_PIXELCODE 181 /* *---------------------------------------------------------------------- @@ -258,6 +264,8 @@ GetEntryFromPixelCode( */ static NSColorSpace* deviceRGB = NULL; +static CGFloat blueAccentRGBA[4] = {0, 122.0/255, 1.0, 1.0}; +static CGFloat graphiteAccentRGBA[4] = {152.0/255, 152.0/255, 152.0/255, 1.0}; static OSStatus SetCGColorComponents( @@ -268,6 +276,7 @@ SetCGColorComponents( OSStatus err = noErr; NSColor *bgColor, *color; CGFloat rgba[4] = {0, 0, 0, 1}; + NSInteger colorVariant = 1; if (!deviceRGB) { deviceRGB = [NSColorSpace deviceRGBColorSpace]; } @@ -337,12 +346,32 @@ SetCGColorComponents( color = [[NSColor selectedTextBackgroundColor] colorUsingColorSpace: deviceRGB]; break; + case 7: + if ([NSApp macMinorVersion] < 14) { + colorVariant = [[NSUserDefaults standardUserDefaults] + integerForKey:@"AppleAquaColorVariant"]; + if (colorVariant == 6) { + color = [NSColor colorWithColorSpace: deviceRGB + components: graphiteAccentRGBA + count: 4]; + } else { + color = [NSColor colorWithColorSpace: deviceRGB + components: blueAccentRGBA + count: 4]; + } + } else { +#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 + color = [[NSColor controlAccentColor] colorUsingColorSpace: + deviceRGB]; +#endif + } + break; default: if ([NSApp macMinorVersion] < 10) { color = [[NSColor textColor] colorUsingColorSpace: deviceRGB]; } else { -#if MAC_OS_X_VERSION_MIN_REQUIRED >= 101000 +#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101000 color = [[NSColor labelColor] colorUsingColorSpace: deviceRGB]; #endif -- cgit v0.12 From 40003fd7645e50415674cde270bb51ef18011c5e Mon Sep 17 00:00:00 2001 From: fvogel Date: Sun, 14 Apr 2019 20:59:16 +0000 Subject: Update makefile.vc in an attempt to repair the build for Windows. Not enough, alas. --- win/makefile.vc | 1 + 1 file changed, 1 insertion(+) diff --git a/win/makefile.vc b/win/makefile.vc index 88b1203..87fe366 100644 --- a/win/makefile.vc +++ b/win/makefile.vc @@ -236,6 +236,7 @@ TKOBJS = \ $(TMP_DIR)\tkOldConfig.obj \ $(TMP_DIR)\tkOption.obj \ $(TMP_DIR)\tkPack.obj \ + $(TMP_DIR)\tkPkgConfig.obj \ $(TMP_DIR)\tkPlace.obj \ $(TMP_DIR)\tkPointer.obj \ $(TMP_DIR)\tkRectOval.obj \ -- cgit v0.12 From 129eaeff4027eccba2a3c092d3609655911cce8d Mon Sep 17 00:00:00 2001 From: dkf Date: Sun, 14 Apr 2019 21:01:36 +0000 Subject: Don't record unknown information --- generic/tkPkgConfig.c | 24 ++++++++++++++++++++++++ win/Makefile.in | 1 + 2 files changed, 25 insertions(+) diff --git a/generic/tkPkgConfig.c b/generic/tkPkgConfig.c index 8019ac9..19f27b8 100644 --- a/generic/tkPkgConfig.c +++ b/generic/tkPkgConfig.c @@ -105,21 +105,45 @@ static Tcl_Config const cfg[] = { /* Runtime paths to various stuff */ +#ifdef CFG_RUNTIME_LIBDIR {"libdir,runtime", CFG_RUNTIME_LIBDIR}, +#endif +#ifdef CFG_RUNTIME_BINDIR {"bindir,runtime", CFG_RUNTIME_BINDIR}, +#endif +#ifdef CFG_RUNTIME_SCRDIR {"scriptdir,runtime", CFG_RUNTIME_SCRDIR}, +#endif +#ifdef CFG_RUNTIME_INCDIR {"includedir,runtime", CFG_RUNTIME_INCDIR}, +#endif +#ifdef CFG_RUNTIME_DOCDIR {"docdir,runtime", CFG_RUNTIME_DOCDIR}, +#endif +#ifdef CFG_RUNTIME_DEMODIR {"demodir,runtime", CFG_RUNTIME_DEMODIR}, +#endif /* Installation paths to various stuff */ +#ifdef CFG_INSTALL_LIBDIR {"libdir,install", CFG_INSTALL_LIBDIR}, +#endif +#ifdef CFG_INSTALL_BINDIR {"bindir,install", CFG_INSTALL_BINDIR}, +#endif +#ifdef CFG_INSTALL_SCRDIR {"scriptdir,install", CFG_INSTALL_SCRDIR}, +#endif +#ifdef CFG_INSTALL_INCDIR {"includedir,install", CFG_INSTALL_INCDIR}, +#endif +#ifdef CFG_INSTALL_DOCDIR {"docdir,install", CFG_INSTALL_DOCDIR}, +#endif +#ifdef CFG_INSTALL_DEMODIR {"demodir,install", CFG_INSTALL_DEMODIR}, +#endif /* Last entry, closes the array */ {NULL, NULL} diff --git a/win/Makefile.in b/win/Makefile.in index 91173da..f857b7c 100644 --- a/win/Makefile.in +++ b/win/Makefile.in @@ -339,6 +339,7 @@ TK_OBJS = \ tkOldConfig.$(OBJEXT) \ tkOption.$(OBJEXT) \ tkPack.$(OBJEXT) \ + tkPkgConfig.$(OBJEXT) \ tkPlace.$(OBJEXT) \ tkPointer.$(OBJEXT) \ tkRectOval.$(OBJEXT) \ -- cgit v0.12 From 1b1e4cc61c4f9772610d0e1c4c539d2562203ac6 Mon Sep 17 00:00:00 2001 From: culler Date: Sun, 14 Apr 2019 22:21:17 +0000 Subject: Implement "tk::unsupported::MacWindowStyle isdark" to determine whether an Aqua toplevel is currently being displayed in Dark Mode. --- macosx/README | 17 ++++++++++++----- macosx/tkMacOSXWindowEvent.c | 13 ++++--------- macosx/tkMacOSXWm.c | 12 +++++++++--- 3 files changed, 25 insertions(+), 17 deletions(-) diff --git a/macosx/README b/macosx/README index fd54c2d..37225c8 100644 --- a/macosx/README +++ b/macosx/README @@ -184,12 +184,13 @@ Note that not all attributes are valid for all window classes. Support for the support for some legacy Carbon-specific classes and attributes was removed (they are still accepted by the command but no longer have any effect). -- Another command available in the tk::unsupported::MacWindowStyle namespace is -tk::unsupported::MacWindowStyle tabbingid window ?newId? which can be used to -get or set the tabbingIdentifier for the NSWindow associated with a Tk Window. -See section 3 for details. +- Another command available in the tk::unsupported::MacWindowStyle namespace is: + tk::unsupported::MacWindowStyle tabbingid window ?newId? +which can be used to get or set the tabbingIdentifier for the NSWindow +associated with a Tk Window. See section 3 for details. -- A command tk::unsupported::MacWindowStyle appearance window ?newAappearance? +- The command: + tk::unsupported::MacWindowStyle appearance window ?newAappearance? is available when Tk is built and run on macOS 10.14 (Mojave) or later. In that case the Ttk widgets all support the "Dark Mode" appearance which was introduced in 10.14. The command accepts the following values for the optional @@ -199,6 +200,12 @@ appearance independent of any preferences settings. If it is set to "auto" the appearance will be determined by the preferences. This command can be used to opt out of Dark Mode on a per-window basis. +- To determine the current appearance of a window in macOS 10.14 (Mojave) and +higher, one can use the command: + tk::unsupported::MacWindowStyle isdark +The boolean return value is true if the window is currently displayed with the +dark appearance. + - If you want to use Remote Debugging with Xcode, you need to set the environment variable XCNOSTDIN to 1 in the Executable editor for Wish. That will cause us to force closing stdin & stdout. Otherwise, given how Xcode launches diff --git a/macosx/tkMacOSXWindowEvent.c b/macosx/tkMacOSXWindowEvent.c index 212381e..54e1272 100644 --- a/macosx/tkMacOSXWindowEvent.c +++ b/macosx/tkMacOSXWindowEvent.c @@ -1070,7 +1070,6 @@ ConfigureRestrictProc( { XVirtualEvent event; int x, y; - NSString *osxMode = [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"]; NSWindow *w = [self window]; TkWindow *winPtr = TkMacOSXGetTkWindow(w); Tk_Window tkwin = (Tk_Window) winPtr; @@ -1091,16 +1090,12 @@ ConfigureRestrictProc( &event.x_root, &event.y_root, &x, &y, &event.state); Tk_TopCoordsToWindow(tkwin, x, y, &event.x, &event.y); event.same_screen = true; - if (osxMode == nil) { - event.name = Tk_GetUid("LightAqua"); - Tk_QueueWindowEvent((XEvent *) &event, TCL_QUEUE_TAIL); - return; - } - if ([osxMode isEqual:@"Dark"]) { + if (TkMacOSXInDarkMode(tkwin)) { event.name = Tk_GetUid("DarkAqua"); - Tk_QueueWindowEvent((XEvent *) &event, TCL_QUEUE_TAIL); - return; + } else { + event.name = Tk_GetUid("LightAqua"); } + Tk_QueueWindowEvent((XEvent *) &event, TCL_QUEUE_TAIL); } /* diff --git a/macosx/tkMacOSXWm.c b/macosx/tkMacOSXWm.c index fa2acf7..504c73f 100644 --- a/macosx/tkMacOSXWm.c +++ b/macosx/tkMacOSXWm.c @@ -1021,7 +1021,6 @@ TkWmDeadWindow( while (Tk_DoOneEvent(TK_WINDOW_EVENTS|TK_DONT_WAIT)) {} } [NSApp _resetAutoreleasePool]; - #if DEBUG_ZOMBIES > 0 fprintf(stderr, "================= Pool dump ===================\n"); [NSAutoreleasePool showPools]; @@ -5518,10 +5517,10 @@ TkUnsupported1ObjCmd( Tcl_Obj *const objv[]) /* Argument objects. */ { static const char *const subcmds[] = { - "style", "tabbingid", "appearance", NULL + "style", "tabbingid", "appearance", "isdark", NULL }; enum SubCmds { - TKMWS_STYLE, TKMWS_TABID, TKMWS_APPEARANCE + TKMWS_STYLE, TKMWS_TABID, TKMWS_APPEARANCE, TKMWS_ISDARK }; Tk_Window tkwin = clientData; TkWindow *winPtr; @@ -5587,6 +5586,13 @@ TkUnsupported1ObjCmd( return TCL_ERROR; } return WmWinAppearance(interp, winPtr, objc, objv); + case TKMWS_ISDARK: + if ((objc != 3)) { + Tcl_WrongNumArgs(interp, 2, objv, "isdark window"); + return TCL_ERROR; + } + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(TkMacOSXInDarkMode(tkwin))); + return TCL_OK; default: return TCL_ERROR; } -- cgit v0.12 From 969a623434fafc0d7393a379934cc7472e0819db Mon Sep 17 00:00:00 2001 From: dkf Date: Mon, 15 Apr 2019 04:59:34 +0000 Subject: Reorder code to avoid uninit-variable warning --- macosx/tkMacOSXColor.c | 73 +++++++++++++++++++++++++------------------------- 1 file changed, 37 insertions(+), 36 deletions(-) diff --git a/macosx/tkMacOSXColor.c b/macosx/tkMacOSXColor.c index 3885a77..a3efca1 100644 --- a/macosx/tkMacOSXColor.c +++ b/macosx/tkMacOSXColor.c @@ -277,13 +277,14 @@ SetCGColorComponents( NSColor *bgColor, *color; CGFloat rgba[4] = {0, 0, 0, 1}; NSInteger colorVariant = 1; + if (!deviceRGB) { deviceRGB = [NSColorSpace deviceRGBColorSpace]; } /* - * This function is called before our autorelease pool is set up, - * so it needs its own pool. + * This function is called before our autorelease pool is set up, + * so it needs its own pool. */ NSAutoreleasePool *pool = [NSAutoreleasePool new]; @@ -314,20 +315,16 @@ SetCGColorComponents( case semantic: switch (entry.value) { case 0: - color = [[NSColor textColor] colorUsingColorSpace: - deviceRGB]; + color = [[NSColor textColor] colorUsingColorSpace: deviceRGB]; break; case 1: - color = [[NSColor selectedTextColor] colorUsingColorSpace: - deviceRGB]; + color = [[NSColor selectedTextColor] colorUsingColorSpace: deviceRGB]; break; case 2: #if MAC_OS_X_VERSION_MIN_REQUIRED > 101000 - color = [[NSColor labelColor] colorUsingColorSpace: - deviceRGB]; + color = [[NSColor labelColor] colorUsingColorSpace: deviceRGB]; #else - color = [[NSColor textColor] colorUsingColorSpace: - deviceRGB]; + color = [[NSColor textColor] colorUsingColorSpace: deviceRGB]; #endif break; case 3: @@ -347,36 +344,35 @@ SetCGColorComponents( deviceRGB]; break; case 7: - if ([NSApp macMinorVersion] < 14) { - colorVariant = [[NSUserDefaults standardUserDefaults] - integerForKey:@"AppleAquaColorVariant"]; - if (colorVariant == 6) { - color = [NSColor colorWithColorSpace: deviceRGB - components: graphiteAccentRGBA - count: 4]; - } else { - color = [NSColor colorWithColorSpace: deviceRGB - components: blueAccentRGBA - count: 4]; - } - } else { #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 + if ([NSApp macMinorVersion] >= 14) { color = [[NSColor controlAccentColor] colorUsingColorSpace: deviceRGB]; + break; + } #endif + colorVariant = [[NSUserDefaults standardUserDefaults] + integerForKey:@"AppleAquaColorVariant"]; + if (colorVariant == 6) { + color = [NSColor colorWithColorSpace: deviceRGB + components: graphiteAccentRGBA + count: 4]; + } else { + color = [NSColor colorWithColorSpace: deviceRGB + components: blueAccentRGBA + count: 4]; } break; default: - if ([NSApp macMinorVersion] < 10) { - color = [[NSColor textColor] colorUsingColorSpace: - deviceRGB]; - } else { #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101000 + if ([NSApp macMinorVersion] >= 10) { color = [[NSColor labelColor] colorUsingColorSpace: deviceRGB]; -#endif break; } +#endif + color = [[NSColor textColor] colorUsingColorSpace: deviceRGB]; + break; } [color getComponents: rgba]; break; @@ -395,7 +391,7 @@ SetCGColorComponents( default: break; } - *c = CGColorCreate(deviceRGB.CGColorSpace, rgba ); + *c = CGColorCreate(deviceRGB.CGColorSpace, rgba); [pool drain]; return err; } @@ -422,8 +418,9 @@ TkMacOSXInDarkMode(Tk_Window tkwin) { return false; #else static NSAppearanceName darkAqua = @"NSAppearanceNameDarkAqua"; - TkWindow *winPtr = (TkWindow*)tkwin; + TkWindow *winPtr = (TkWindow*) tkwin; NSView *view = TkMacOSXDrawableView(winPtr->privatePtr); + if (view && [view.effectiveAppearance.name isEqualToString:darkAqua]) { return True; } else { @@ -431,7 +428,6 @@ TkMacOSXInDarkMode(Tk_Window tkwin) { } #endif } - /* *---------------------------------------------------------------------- @@ -462,6 +458,7 @@ TkSetMacColor( CGColorRef *color = (CGColorRef*)macColor; OSStatus err = -1; struct SystemColorMapEntry entry; + if (GetEntryFromPixelCode((pixel >> 24) & 0xff, &entry)) { err = ChkErr(SetCGColorComponents, entry, pixel, color); } @@ -607,6 +604,7 @@ TkMacOSXGetNSColor( if (cgColor) { NSColorSpace *colorSpace = [[NSColorSpace alloc] initWithCGColorSpace:CGColorGetColorSpace(cgColor)]; + nsColor = [NSColor colorWithColorSpace:colorSpace components:CGColorGetComponents(cgColor) count:CGColorGetNumberOfComponents(cgColor)]; @@ -648,6 +646,7 @@ TkMacOSXSetColorInContext( int code = (pixel >> 24) & 0xff; HIThemeBackgroundDrawInfo info = { 0, kThemeStateActive, entry.value }; static CGColorSpaceRef deviceRGBSpace = NULL; + if (!deviceRGBSpace) { deviceRGBSpace = CGColorSpaceCreateDeviceRGB(); } @@ -728,14 +727,16 @@ TkpGetColor( if (strncasecmp(name, "system", 6) == 0) { Tcl_Obj *strPtr = Tcl_NewStringObj(name+6, -1); int idx, result; + result = Tcl_GetIndexFromObjStruct(NULL, strPtr, systemColorMap, - sizeof(struct SystemColorMapEntry), NULL, TCL_EXACT, &idx); + sizeof(struct SystemColorMapEntry), NULL, TCL_EXACT, &idx); Tcl_DecrRefCount(strPtr); if (result == TCL_OK) { OSStatus err; CGColorRef c; unsigned char pixelCode = idx + MIN_PIXELCODE; struct SystemColorMapEntry entry = systemColorMap[idx]; + err = ChkErr(SetCGColorComponents, entry, 0, &c); if (err == noErr) { const size_t n = CGColorGetNumberOfComponents(c); @@ -751,12 +752,12 @@ TkpGetColor( color.red = color.green = color.blue = rgba[0] * 65535.0; break; default: - Tcl_Panic("CGColor with %d components", (int) n); + Tcl_Panic("CGColor with %d components", (int) n); } color.pixel = ((((((pixelCode << 8) - | ((color.red >> 8) & 0xff)) << 8) - | ((color.green >> 8) & 0xff)) << 8) - | ((color.blue >> 8) & 0xff)); + | ((color.red >> 8) & 0xff)) << 8) + | ((color.green >> 8) & 0xff)) << 8) + | ((color.blue >> 8) & 0xff)); CGColorRelease(c); goto validXColor; } -- cgit v0.12 From c0ea768836e679bf83ef10912b3ee13fa6da1de9 Mon Sep 17 00:00:00 2001 From: fvogel Date: Mon, 15 Apr 2019 17:55:49 +0000 Subject: Fix [aa846938ef]: pkgconfig tests fail on Windows --- tests/pkgconfig.test | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/pkgconfig.test b/tests/pkgconfig.test index 1694eea..e080b91 100644 --- a/tests/pkgconfig.test +++ b/tests/pkgconfig.test @@ -18,7 +18,7 @@ namespace import ::tcltest::* eval tcltest::configure $argv tcltest::loadTestedCommands -test pkgconfig-1.1 {query keys} { +test pkgconfig-1.1 {query keys} nonwin { lsort [::tk::pkgconfig list] } [list \ 64bit bindir,install bindir,runtime debug demodir,install demodir,runtime \ @@ -31,8 +31,8 @@ test pkgconfig-1.2 {query keys multiple times} { } 0 test pkgconfig-1.3 {query value multiple times} { string compare \ - [::tk::pkgconfig get bindir,install] \ - [::tk::pkgconfig get bindir,install] + [::tk::pkgconfig get 64bit] \ + [::tk::pkgconfig get 64bit] } 0 -- cgit v0.12 From aabd71aac31bdb206f316717019b6db250bc91d8 Mon Sep 17 00:00:00 2001 From: culler Date: Mon, 15 Apr 2019 18:00:29 +0000 Subject: For Aqua, simulate systemWindowBackgroundColor in older OS versions. Adjust conditional code and formatting. --- macosx/tkMacOSXColor.c | 111 ++++++++++++++++++++++++++--------------------- macosx/ttkMacOSXTheme.c | 112 ++++++++++++++++++++++++------------------------ 2 files changed, 119 insertions(+), 104 deletions(-) diff --git a/macosx/tkMacOSXColor.c b/macosx/tkMacOSXColor.c index 3885a77..ae9e9df 100644 --- a/macosx/tkMacOSXColor.c +++ b/macosx/tkMacOSXColor.c @@ -266,6 +266,7 @@ GetEntryFromPixelCode( static NSColorSpace* deviceRGB = NULL; static CGFloat blueAccentRGBA[4] = {0, 122.0/255, 1.0, 1.0}; static CGFloat graphiteAccentRGBA[4] = {152.0/255, 152.0/255, 152.0/255, 1.0}; +static CGFloat windowBackground[4] = {236.0/255, 236.0/255, 236.0/255, 1.0}; static OSStatus SetCGColorComponents( @@ -277,13 +278,14 @@ SetCGColorComponents( NSColor *bgColor, *color; CGFloat rgba[4] = {0, 0, 0, 1}; NSInteger colorVariant = 1; + if (!deviceRGB) { deviceRGB = [NSColorSpace deviceRGBColorSpace]; } /* - * This function is called before our autorelease pool is set up, - * so it needs its own pool. + * This function is called before our autorelease pool is set up, + * so it needs its own pool. */ NSAutoreleasePool *pool = [NSAutoreleasePool new]; @@ -298,9 +300,21 @@ SetCGColorComponents( rgba[2] = ((pixel ) & 0xff) / 255.0; break; case ttkBackground: - bgColor = [[NSColor windowBackgroundColor] colorUsingColorSpace: - deviceRGB]; - [bgColor getComponents: rgba]; + + /* + * Prior to OSX 10.14, getComponents returns black when applied to + * windowBackGroundColor. + */ + + if ([NSApp macMinorVersion] < 14) { + for (int i=0; i<3; i++) { + rgba[i] = windowBackground[i]; + } + } else { + bgColor = [[NSColor windowBackgroundColor] colorUsingColorSpace: + deviceRGB]; + [bgColor getComponents: rgba]; + } if (rgba[0] + rgba[1] + rgba[2] < 1.5) { for (int i=0; i<3; i++) { rgba[i] += entry.value*8.0/255.0; @@ -314,20 +328,16 @@ SetCGColorComponents( case semantic: switch (entry.value) { case 0: - color = [[NSColor textColor] colorUsingColorSpace: - deviceRGB]; + color = [[NSColor textColor] colorUsingColorSpace: deviceRGB]; break; case 1: - color = [[NSColor selectedTextColor] colorUsingColorSpace: - deviceRGB]; + color = [[NSColor selectedTextColor] colorUsingColorSpace: deviceRGB]; break; case 2: #if MAC_OS_X_VERSION_MIN_REQUIRED > 101000 - color = [[NSColor labelColor] colorUsingColorSpace: - deviceRGB]; + color = [[NSColor labelColor] colorUsingColorSpace: deviceRGB]; #else - color = [[NSColor textColor] colorUsingColorSpace: - deviceRGB]; + color = [[NSColor textColor] colorUsingColorSpace: deviceRGB]; #endif break; case 3: @@ -347,36 +357,35 @@ SetCGColorComponents( deviceRGB]; break; case 7: - if ([NSApp macMinorVersion] < 14) { - colorVariant = [[NSUserDefaults standardUserDefaults] - integerForKey:@"AppleAquaColorVariant"]; - if (colorVariant == 6) { - color = [NSColor colorWithColorSpace: deviceRGB - components: graphiteAccentRGBA - count: 4]; - } else { - color = [NSColor colorWithColorSpace: deviceRGB - components: blueAccentRGBA - count: 4]; - } - } else { #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 + if ([NSApp macMinorVersion] >= 14) { color = [[NSColor controlAccentColor] colorUsingColorSpace: deviceRGB]; + break; + } #endif + colorVariant = [[NSUserDefaults standardUserDefaults] + integerForKey:@"AppleAquaColorVariant"]; + if (colorVariant == 6) { + color = [NSColor colorWithColorSpace: deviceRGB + components: graphiteAccentRGBA + count: 4]; + } else { + color = [NSColor colorWithColorSpace: deviceRGB + components: blueAccentRGBA + count: 4]; } break; default: - if ([NSApp macMinorVersion] < 10) { - color = [[NSColor textColor] colorUsingColorSpace: - deviceRGB]; - } else { #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101000 + if ([NSApp macMinorVersion] >= 10) { color = [[NSColor labelColor] colorUsingColorSpace: deviceRGB]; -#endif break; } +#endif + color = [[NSColor textColor] colorUsingColorSpace: deviceRGB]; + break; } [color getComponents: rgba]; break; @@ -395,7 +404,7 @@ SetCGColorComponents( default: break; } - *c = CGColorCreate(deviceRGB.CGColorSpace, rgba ); + *c = CGColorCreate(deviceRGB.CGColorSpace, rgba); [pool drain]; return err; } @@ -417,21 +426,20 @@ SetCGColorComponents( */ MODULE_SCOPE Bool -TkMacOSXInDarkMode(Tk_Window tkwin) { -#if MAC_OS_X_VERSION_MIN_REQUIRED < 101300 - return false; -#else - static NSAppearanceName darkAqua = @"NSAppearanceNameDarkAqua"; - TkWindow *winPtr = (TkWindow*)tkwin; - NSView *view = TkMacOSXDrawableView(winPtr->privatePtr); - if (view && [view.effectiveAppearance.name isEqualToString:darkAqua]) { - return True; - } else { - return false; +TkMacOSXInDarkMode(Tk_Window tkwin) +{ + int result = false; +#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 + if ([NSApp macMinorVersion] >= 14) { + static NSAppearanceName darkAqua = @"NSAppearanceNameDarkAqua"; + TkWindow *winPtr = (TkWindow*) tkwin; + NSView *view = TkMacOSXDrawableView(winPtr->privatePtr); + result = (view && + [view.effectiveAppearance.name isEqualToString:darkAqua]); } #endif + return result; } - /* *---------------------------------------------------------------------- @@ -462,6 +470,7 @@ TkSetMacColor( CGColorRef *color = (CGColorRef*)macColor; OSStatus err = -1; struct SystemColorMapEntry entry; + if (GetEntryFromPixelCode((pixel >> 24) & 0xff, &entry)) { err = ChkErr(SetCGColorComponents, entry, pixel, color); } @@ -607,6 +616,7 @@ TkMacOSXGetNSColor( if (cgColor) { NSColorSpace *colorSpace = [[NSColorSpace alloc] initWithCGColorSpace:CGColorGetColorSpace(cgColor)]; + nsColor = [NSColor colorWithColorSpace:colorSpace components:CGColorGetComponents(cgColor) count:CGColorGetNumberOfComponents(cgColor)]; @@ -648,6 +658,7 @@ TkMacOSXSetColorInContext( int code = (pixel >> 24) & 0xff; HIThemeBackgroundDrawInfo info = { 0, kThemeStateActive, entry.value }; static CGColorSpaceRef deviceRGBSpace = NULL; + if (!deviceRGBSpace) { deviceRGBSpace = CGColorSpaceCreateDeviceRGB(); } @@ -728,14 +739,16 @@ TkpGetColor( if (strncasecmp(name, "system", 6) == 0) { Tcl_Obj *strPtr = Tcl_NewStringObj(name+6, -1); int idx, result; + result = Tcl_GetIndexFromObjStruct(NULL, strPtr, systemColorMap, - sizeof(struct SystemColorMapEntry), NULL, TCL_EXACT, &idx); + sizeof(struct SystemColorMapEntry), NULL, TCL_EXACT, &idx); Tcl_DecrRefCount(strPtr); if (result == TCL_OK) { OSStatus err; CGColorRef c; unsigned char pixelCode = idx + MIN_PIXELCODE; struct SystemColorMapEntry entry = systemColorMap[idx]; + err = ChkErr(SetCGColorComponents, entry, 0, &c); if (err == noErr) { const size_t n = CGColorGetNumberOfComponents(c); @@ -751,12 +764,12 @@ TkpGetColor( color.red = color.green = color.blue = rgba[0] * 65535.0; break; default: - Tcl_Panic("CGColor with %d components", (int) n); + Tcl_Panic("CGColor with %d components", (int) n); } color.pixel = ((((((pixelCode << 8) - | ((color.red >> 8) & 0xff)) << 8) - | ((color.green >> 8) & 0xff)) << 8) - | ((color.blue >> 8) & 0xff)); + | ((color.red >> 8) & 0xff)) << 8) + | ((color.green >> 8) & 0xff)) << 8) + | ((color.blue >> 8) & 0xff)); CGColorRelease(c); goto validXColor; } diff --git a/macosx/ttkMacOSXTheme.c b/macosx/ttkMacOSXTheme.c index 84e5b5f..12667e1 100644 --- a/macosx/ttkMacOSXTheme.c +++ b/macosx/ttkMacOSXTheme.c @@ -124,7 +124,7 @@ static CGRect NormalizeButtonBounds( return bounds; } -#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 +#if MAC_OS_X_VERSION_MAX_ALLOWED > 1080 /*---------------------------------------------------------------------- * +++ Support for contrasting background colors when GroupBoxes or Tabbed * panes are nested inside each other. Early versions of macOS used ridged @@ -139,8 +139,7 @@ static CGRect NormalizeButtonBounds( * support Dark Mode anyway. */ -static CGFloat windowBackground[4] = {235.0/255, 235.0/255, 235.0/255, 1.0}; -static CGFloat whiteRGBA[4] = {1.0, 1.0, 1.0, 1.0}; +static CGFloat windowBackground[4] = {236.0/255, 236.0/255, 236.0/255, 1.0}; static CGFloat blackRGBA[4] = {0.0, 0.0, 0.0, 1.0}; /*---------------------------------------------------------------------- @@ -264,56 +263,6 @@ static void SolidFillRoundedRectangle( CFRelease(path); } -/*---------------------------------------------------------------------- - * GradientFillRoundedRectangle -- - * - * Fill a rounded rectangle with a specified gradient. - */ - -static void GradientFillRoundedRectangle( - CGContextRef context, - CGRect bounds, - CGFloat radius, - CGFloat* colors, - int numColors) -{ - NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; - CGPathRef path; - CGPoint end = { - bounds.origin.x, - bounds.origin.y + bounds.size.height - }; - CGGradientRef gradient = CGGradientCreateWithColorComponents( - deviceRGB.CGColorSpace, colors, NULL, numColors); - path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL); - CGContextBeginPath(context); - CGContextAddPath(context, path); - CGContextClip(context); - CGContextDrawLinearGradient(context, gradient, bounds.origin, end, 0); - CFRelease(path); - CFRelease(gradient); -} - -static void DrawUpDownArrows( - CGContextRef context, - CGRect bounds, - CGFloat inset, - CGFloat size, - CGFloat *rgba) -{ - CGFloat x, y; - CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); - CGContextSetLineWidth(context, 1.5); - x = bounds.origin.x + inset; - y = bounds.origin.y + trunc(bounds.size.height/2); - CGContextBeginPath(context); - CGPoint bottomArrow[3] = {{x, y+2}, {x+size/2, y+2+size/2}, {x+size, y+2}}; - CGContextAddLines(context, bottomArrow, 3); - CGPoint topArrow[3] = {{x, y-2}, {x+size/2, y-2-size/2}, {x+size, y-2}}; - CGContextAddLines(context, topArrow, 3); - CGContextStrokePath(context); -} - static void DrawDownArrow( CGContextRef context, CGRect bounds, @@ -429,9 +378,9 @@ static void DrawListHeader( } } -#endif /* MAC_OS_X_VERSION_MIN_REQUIRED > 1080 */ +#endif /* MAC_OS_X_VERSION_MAX_ALLOWED > 1080 */ -#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 +#if MAC_OS_X_VERSION_MAX_ALLOWED > 101300 /*---------------------------------------------------------------------- * +++ Drawing procedures for widgets in Apple's "Dark Mode" (10.14 and up). * @@ -464,6 +413,57 @@ static CGFloat darkInactiveGradient[8] = {89.0/255, 90.0/255, 93.0/255, 1.0, static CGFloat darkSelectedGradient[8] = {23.0/255, 111.0/255, 232.0/255, 1.0, 20.0/255, 94.0/255, 206.0/255, 1.0}; + +/*---------------------------------------------------------------------- + * GradientFillRoundedRectangle -- + * + * Fill a rounded rectangle with a specified gradient. + */ + +static void GradientFillRoundedRectangle( + CGContextRef context, + CGRect bounds, + CGFloat radius, + CGFloat* colors, + int numColors) +{ + NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; + CGPathRef path; + CGPoint end = { + bounds.origin.x, + bounds.origin.y + bounds.size.height + }; + CGGradientRef gradient = CGGradientCreateWithColorComponents( + deviceRGB.CGColorSpace, colors, NULL, numColors); + path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL); + CGContextBeginPath(context); + CGContextAddPath(context, path); + CGContextClip(context); + CGContextDrawLinearGradient(context, gradient, bounds.origin, end, 0); + CFRelease(path); + CFRelease(gradient); +} + +static void DrawUpDownArrows( + CGContextRef context, + CGRect bounds, + CGFloat inset, + CGFloat size, + CGFloat *rgba) +{ + CGFloat x, y; + CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); + CGContextSetLineWidth(context, 1.5); + x = bounds.origin.x + inset; + y = bounds.origin.y + trunc(bounds.size.height/2); + CGContextBeginPath(context); + CGPoint bottomArrow[3] = {{x, y+2}, {x+size/2, y+2+size/2}, {x+size, y+2}}; + CGContextAddLines(context, bottomArrow, 3); + CGPoint topArrow[3] = {{x, y-2}, {x+size/2, y-2-size/2}, {x+size, y-2}}; + CGContextAddLines(context, topArrow, 3); + CGContextStrokePath(context); +} + /*---------------------------------------------------------------------- * FillButtonBackground -- * @@ -528,6 +528,8 @@ static void HighlightButtonBorder( * PopupButtons in the Dark Mode style. */ +static CGFloat whiteRGBA[4] = {1.0, 1.0, 1.0, 1.0}; + static void DrawDarkButton( CGRect bounds, ThemeButtonKind kind, -- cgit v0.12 From 3c20b73064392e201bf678e471789379e5b27c53 Mon Sep 17 00:00:00 2001 From: culler Date: Mon, 15 Apr 2019 18:05:53 +0000 Subject: Add missing blank line. --- macosx/tkMacOSXColor.c | 1 + 1 file changed, 1 insertion(+) diff --git a/macosx/tkMacOSXColor.c b/macosx/tkMacOSXColor.c index ae9e9df..e89d42d 100644 --- a/macosx/tkMacOSXColor.c +++ b/macosx/tkMacOSXColor.c @@ -429,6 +429,7 @@ MODULE_SCOPE Bool TkMacOSXInDarkMode(Tk_Window tkwin) { int result = false; + #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 if ([NSApp macMinorVersion] >= 14) { static NSAppearanceName darkAqua = @"NSAppearanceNameDarkAqua"; -- cgit v0.12 From c7e4427914c39b33a76da2dc61a174c6481dd4fe Mon Sep 17 00:00:00 2001 From: culler Date: Mon, 15 Apr 2019 19:31:55 +0000 Subject: Less intrusive fix for test frame-3.9. --- tests/frame.test | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/frame.test b/tests/frame.test index b601137..45a91b3 100644 --- a/tests/frame.test +++ b/tests/frame.test @@ -662,10 +662,9 @@ test frame-3.9 {TkCreateFrame procedure, -use option} -constraints { } -body { toplevel .t -container 1 -width 300 -height 120 wm geometry .t +0+0 - update toplevel .x -width 140 -height 300 -use [winfo id .t] -bg green tkwait visibility .x - update + update idletasks list [expr {[winfo rootx .x] - [winfo rootx .t]}] \ [expr {[winfo rooty .x] - [winfo rooty .t]}] \ [winfo width .t] [winfo height .t] -- cgit v0.12 From 9b521b370e0520f6a489be15b65269a33761501a Mon Sep 17 00:00:00 2001 From: culler Date: Mon, 15 Apr 2019 20:48:29 +0000 Subject: Adjust conditional code to fix compiler warnings on macOS 10.9. --- macosx/ttkMacOSXTheme.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/macosx/ttkMacOSXTheme.c b/macosx/ttkMacOSXTheme.c index 12667e1..a890b63 100644 --- a/macosx/ttkMacOSXTheme.c +++ b/macosx/ttkMacOSXTheme.c @@ -1378,9 +1378,11 @@ static void PaneElementDraw( bounds.origin.y -= kThemeMetricTabFrameOverlap; bounds.size.height += kThemeMetricTabFrameOverlap; BEGIN_DRAWING(d) -#if MAC_OS_X_VERSION_MIN_REQUIRED > 10800 + if ([NSApp macMinorVersion] > 9) { +#if MAC_OS_X_VERSION_MAX_ALLOWED > 1080 DrawGroupBox(bounds, dc.context, tkwin); -#else +#endif + } else { HIThemeTabPaneDrawInfo info = { .version = 1, .state = Ttk_StateTableLookup(ThemeStateTable, state), @@ -1392,7 +1394,7 @@ static void PaneElementDraw( bounds.origin.y -= kThemeMetricTabFrameOverlap; bounds.size.height += kThemeMetricTabFrameOverlap; ChkErr(HIThemeDrawTabPane, &bounds, &info, dc.context, HIOrientation); -#endif + } END_DRAWING } @@ -1429,16 +1431,18 @@ static void GroupElementDraw( CGRect bounds = BoxToRect(d, b); BEGIN_DRAWING(d) -#if MAC_OS_X_VERSION_MIN_REQUIRED > 10800 + if ([NSApp macMinorVersion] > 9) { +#if MAC_OS_X_VERSION_MAX_ALLOWED > 1080 DrawGroupBox(bounds, dc.context, tkwin); -#else +#endif + } else { const HIThemeGroupBoxDrawInfo info = { .version = 0, .state = Ttk_StateTableLookup(ThemeStateTable, state), .kind = kHIThemeGroupBoxKindPrimaryOpaque, }; ChkErr(HIThemeDrawGroupBox, &bounds, &info, dc.context, HIOrientation); -#endif + } END_DRAWING } -- cgit v0.12 From 2e318c7f021f7401f9503e5ece135d99f29176b3 Mon Sep 17 00:00:00 2001 From: dkf Date: Tue, 16 Apr 2019 12:59:45 +0000 Subject: Guard against interpreters being killed out from under our feet when calling Tcl. --- macosx/tkMacOSXHLEvents.c | 146 ++++++++++++++++++++++++++-------------------- 1 file changed, 82 insertions(+), 64 deletions(-) diff --git a/macosx/tkMacOSXHLEvents.c b/macosx/tkMacOSXHLEvents.c index 9b874a5..8f04e45 100644 --- a/macosx/tkMacOSXHLEvents.c +++ b/macosx/tkMacOSXHLEvents.c @@ -33,12 +33,13 @@ typedef struct KillEvent { * Static functions used only in this file. */ -static void tkMacOSXProcessFiles(NSAppleEventDescriptor* event, - NSAppleEventDescriptor* replyEvent, - Tcl_Interp *interp, - const char* procedure); -static int MissedAnyParameters(const AppleEvent *theEvent); -static int ReallyKillMe(Tcl_Event *eventPtr, int flags); +static void tkMacOSXProcessFiles(NSAppleEventDescriptor *event, + NSAppleEventDescriptor *replyEvent, + Tcl_Interp *interp, const char* procedure); +static int MissedAnyParameters(const AppleEvent *theEvent); +static int ReallyKillMe(Tcl_Event *eventPtr, int flags); +static void RunSimpleTclCommand(Tcl_Interp *interp, + const char *command); #pragma mark TKApplication(TKHLEvents) @@ -78,55 +79,34 @@ static int ReallyKillMe(Tcl_Event *eventPtr, int flags); - (void) handleOpenApplicationEvent: (NSAppleEventDescriptor *)event withReplyEvent: (NSAppleEventDescriptor *)replyEvent { - Tcl_Interp *interp = _eventInterp; - - if (interp && - Tcl_FindCommand(_eventInterp, "::tk::mac::OpenApplication", NULL, 0)){ - int code = Tcl_EvalEx(_eventInterp, "::tk::mac::OpenApplication", - -1, TCL_EVAL_GLOBAL); - if (code != TCL_OK) { - Tcl_BackgroundException(_eventInterp, code); - } - } + RunSimpleTclCommand(_eventInterp, "::tk::mac::OpenApplication"); } - (void) handleReopenApplicationEvent: (NSAppleEventDescriptor *)event withReplyEvent: (NSAppleEventDescriptor *)replyEvent { [NSApp activateIgnoringOtherApps: YES]; - if (_eventInterp && Tcl_FindCommand(_eventInterp, - "::tk::mac::ReopenApplication", NULL, 0)) { - int code = Tcl_EvalEx(_eventInterp, "::tk::mac::ReopenApplication", - -1, TCL_EVAL_GLOBAL); - if (code != TCL_OK){ - Tcl_BackgroundException(_eventInterp, code); - } - } + RunSimpleTclCommand(_eventInterp, "::tk::mac::ReopenApplication"); } - (void) handleShowPreferencesEvent: (NSAppleEventDescriptor *)event withReplyEvent: (NSAppleEventDescriptor *)replyEvent { - if (_eventInterp && - Tcl_FindCommand(_eventInterp, "::tk::mac::ShowPreferences", NULL, 0)){ - int code = Tcl_EvalEx(_eventInterp, "::tk::mac::ShowPreferences", - -1, TCL_EVAL_GLOBAL); - if (code != TCL_OK) { - Tcl_BackgroundException(_eventInterp, code); - } - } + RunSimpleTclCommand(_eventInterp, "::tk::mac::ShowPreferences"); } - (void) handleOpenDocumentsEvent: (NSAppleEventDescriptor *)event withReplyEvent: (NSAppleEventDescriptor *)replyEvent { - tkMacOSXProcessFiles(event, replyEvent, _eventInterp, "::tk::mac::OpenDocument"); + tkMacOSXProcessFiles(event, replyEvent, _eventInterp, + "::tk::mac::OpenDocument"); } - (void) handlePrintDocumentsEvent: (NSAppleEventDescriptor *)event withReplyEvent: (NSAppleEventDescriptor *)replyEvent { - tkMacOSXProcessFiles(event, replyEvent, _eventInterp, "::tk::mac::PrintDocument"); + tkMacOSXProcessFiles(event, replyEvent, _eventInterp, + "::tk::mac::PrintDocument"); } - (void) handleDoScriptEvent: (NSAppleEventDescriptor *)event @@ -152,64 +132,73 @@ static int ReallyKillMe(Tcl_Event *eventPtr, int flags); } err = AEGetParamPtr(theDesc, keyDirectObject, typeWildCard, &initialType, - NULL, 0, NULL); + NULL, 0, NULL); if (err != noErr) { sprintf(errString, "AEDoScriptHandler: GetParamDesc error %d", (int)err); - AEPutParamPtr((AppleEvent*)[replyEvent aeDesc], keyErrorString, typeChar, - errString, strlen(errString)); + AEPutParamPtr((AppleEvent *) [replyEvent aeDesc], keyErrorString, + typeChar, errString, strlen(errString)); return; } - if (MissedAnyParameters((AppleEvent*)theDesc)) { + if (MissedAnyParameters((AppleEvent *) theDesc)) { sprintf(errString, "AEDoScriptHandler: extra parameters"); - AEPutParamPtr((AppleEvent*)[replyEvent aeDesc], keyErrorString, typeChar, - errString, strlen(errString)); + AEPutParamPtr((AppleEvent *) [replyEvent aeDesc], keyErrorString, + typeChar, errString, strlen(errString)); return; } + Tcl_Preserve(_eventInterp); if (initialType == typeFileURL || initialType == typeAlias) { /* * The descriptor can be coerced to a file url. Source the file, or * pass the path as a string argument to ::tk::mac::DoScriptFile if * that procedure exists. */ + err = AEGetParamPtr(theDesc, keyDirectObject, typeFileURL, &type, - (Ptr) URLBuffer, URL_MAX_LENGTH, &actual); + (Ptr) URLBuffer, URL_MAX_LENGTH, &actual); if (err == noErr && actual > 0){ URLBuffer[actual] = '\0'; NSString *urlString = [NSString stringWithUTF8String:(char*)URLBuffer]; NSURL *fileURL = [NSURL URLWithString:urlString]; Tcl_DString command; + Tcl_DStringInit(&command); - if (Tcl_FindCommand(_eventInterp, "::tk::mac::DoScriptFile", NULL, 0)){ + if (Tcl_FindCommand(_eventInterp, "::tk::mac::DoScriptFile", NULL, 0)) { Tcl_DStringAppend(&command, "::tk::mac::DoScriptFile", -1); } else { Tcl_DStringAppend(&command, "source", -1); } Tcl_DStringAppendElement(&command, [[fileURL path] UTF8String]); tclErr = Tcl_EvalEx(_eventInterp, Tcl_DStringValue(&command), - Tcl_DStringLength(&command), TCL_EVAL_GLOBAL); + Tcl_DStringLength(&command), TCL_EVAL_GLOBAL); } - } else if (noErr == AEGetParamPtr(theDesc, keyDirectObject, typeUTF8Text, &type, - NULL, 0, &actual)) { + } else if (noErr == AEGetParamPtr(theDesc, keyDirectObject, typeUTF8Text, + &type, NULL, 0, &actual)) { if (actual > 0) { /* * The descriptor can be coerced to UTF8 text. Evaluate as Tcl, or * or pass the text as a string argument to ::tk::mac::DoScriptText * if that procedure exists. */ + char *data = ckalloc(actual + 1); - if (noErr == AEGetParamPtr(theDesc, keyDirectObject, typeUTF8Text, &type, - data, actual, NULL)) { - if (Tcl_FindCommand(_eventInterp, "::tk::mac::DoScriptText", NULL, 0)){ + + if (noErr == AEGetParamPtr(theDesc, keyDirectObject, typeUTF8Text, + &type, data, actual, NULL)) { + if (Tcl_FindCommand(_eventInterp, "::tk::mac::DoScriptText", + NULL, 0)) { Tcl_DString command; + Tcl_DStringInit(&command); Tcl_DStringAppend(&command, "::tk::mac::DoScriptText", -1); Tcl_DStringAppendElement(&command, data); - tclErr = Tcl_EvalEx(_eventInterp, Tcl_DStringValue(&command), - Tcl_DStringLength(&command), TCL_EVAL_GLOBAL); + tclErr = Tcl_EvalEx(_eventInterp, + Tcl_DStringValue(&command), + Tcl_DStringLength(&command), TCL_EVAL_GLOBAL); } else { - tclErr = Tcl_EvalEx(_eventInterp, data, actual, TCL_EVAL_GLOBAL); + tclErr = Tcl_EvalEx(_eventInterp, data, actual, + TCL_EVAL_GLOBAL); } } ckfree(data); @@ -224,32 +213,53 @@ static int ReallyKillMe(Tcl_Event *eventPtr, int flags); typeString[4] = '\0'; sprintf(errString, "AEDoScriptHandler: invalid script type '%s', " "must be coercable to 'furl' or 'utf8'", typeString); - AEPutParamPtr((AppleEvent*)[replyEvent aeDesc], keyErrorString, typeChar, errString, - strlen(errString)); + AEPutParamPtr((AppleEvent*)[replyEvent aeDesc], keyErrorString, + typeChar, errString, strlen(errString)); } + /* * If we ran some Tcl code, put the result in the reply. */ + if (tclErr >= 0) { int reslen; const char *result = - Tcl_GetStringFromObj(Tcl_GetObjResult(_eventInterp), &reslen); + Tcl_GetStringFromObj(Tcl_GetObjResult(_eventInterp), &reslen); + if (tclErr == TCL_OK) { - AEPutParamPtr((AppleEvent*)[replyEvent aeDesc], keyDirectObject, typeChar, - result, reslen); + AEPutParamPtr((AppleEvent *) [replyEvent aeDesc], keyDirectObject, + typeChar, result, reslen); } else { - AEPutParamPtr((AppleEvent*)[replyEvent aeDesc], keyErrorString, typeChar, - result, reslen); - AEPutParamPtr((AppleEvent*)[replyEvent aeDesc], keyErrorNumber, typeSInt32, - (Ptr) &tclErr,sizeof(int)); + AEPutParamPtr((AppleEvent *) [replyEvent aeDesc], keyErrorString, + typeChar, result, reslen); + AEPutParamPtr((AppleEvent *) [replyEvent aeDesc], keyErrorNumber, + typeSInt32, (Ptr) &tclErr, sizeof(int)); } } + Tcl_Release(_eventInterp); return; } @end #pragma mark - + +static void +RunSimpleTclCommand( + Tcl_Interp *interp, + const char *command) +{ + int code; + if (interp && Tcl_FindCommand(interp, command, NULL, 0)) { + Tcl_Preserve(interp); + code = Tcl_EvalEx(interp, command, -1, TCL_EVAL_GLOBAL); + if (code != TCL_OK) { + Tcl_BackgroundException(interp, code); + } + Tcl_Release(interp); + } +} + /* *---------------------------------------------------------------------- * @@ -287,7 +297,8 @@ tkMacOSXProcessFiles( int code; /* - * Do nothing if we don't have an interpreter or the procedure doesn't exist. + * Do nothing if we don't have an interpreter or the procedure doesn't + * exist. */ if (!interp || !Tcl_FindCommand(interp, procedure, NULL, 0)) { @@ -353,12 +364,14 @@ tkMacOSXProcessFiles( * Handle the event by evaluating the Tcl expression we constructed. */ + Tcl_Preserve(interp); code = Tcl_EvalEx(interp, Tcl_DStringValue(&command), Tcl_DStringLength(&command), TCL_EVAL_GLOBAL); if (code != TCL_OK) { Tcl_BackgroundException(interp, code); } Tcl_DStringFree(&command); + Tcl_Release(interp); } /* @@ -382,7 +395,8 @@ void TkMacOSXInitAppleEvents( Tcl_Interp *interp) /* not used */ { - NSAppleEventManager *aeManager = [NSAppleEventManager sharedAppleEventManager]; + NSAppleEventManager *aeManager = + [NSAppleEventManager sharedAppleEventManager]; static Boolean initialized = FALSE; if (!initialized) { @@ -488,8 +502,12 @@ ReallyKillMe( int flags) { Tcl_Interp *interp = ((KillEvent *) eventPtr)->interp; + + Tcl_Preserve(interp); + int quit = Tcl_FindCommand(interp, "::tk::mac::Quit", NULL, 0)!=NULL; - int code = Tcl_EvalEx(interp, quit ? "::tk::mac::Quit" : "exit", -1, TCL_EVAL_GLOBAL); + int code = Tcl_EvalEx(interp, quit ? "::tk::mac::Quit" : "exit", -1, + TCL_EVAL_GLOBAL); if (code != TCL_OK) { /* @@ -498,6 +516,7 @@ ReallyKillMe( Tcl_BackgroundException(interp, code); } + Tcl_Release(interp); return 1; } @@ -531,7 +550,6 @@ MissedAnyParameters( return (err != errAEDescNotFound); } - /* * Local Variables: * mode: objc -- cgit v0.12 From 1ec2e5d741bf09af3cd7cf157bbc586f01a3758e Mon Sep 17 00:00:00 2001 From: dkf Date: Tue, 16 Apr 2019 13:22:46 +0000 Subject: Source readability run: macosx/* --- macosx/tkMacOSXButton.c | 685 +++++++++++++++++++++---------------------- macosx/tkMacOSXClipboard.c | 8 +- macosx/tkMacOSXCursor.c | 18 +- macosx/tkMacOSXDialog.c | 408 +++++++++++++++++--------- macosx/tkMacOSXDraw.c | 465 ++++++++++++++++------------- macosx/tkMacOSXEmbed.c | 58 ++-- macosx/tkMacOSXFont.c | 193 ++++++------ macosx/tkMacOSXImage.c | 145 ++++----- macosx/tkMacOSXInit.c | 19 +- macosx/tkMacOSXKeyEvent.c | 567 ++++++++++++++++++----------------- macosx/tkMacOSXMenu.c | 150 +++++----- macosx/tkMacOSXMenubutton.c | 415 +++++++++++++------------- macosx/tkMacOSXMenus.c | 1 - macosx/tkMacOSXNotify.c | 103 ++++--- macosx/tkMacOSXRegion.c | 16 +- macosx/tkMacOSXScale.c | 108 ++++--- macosx/tkMacOSXScrlbr.c | 395 +++++++++++++------------ macosx/tkMacOSXSend.c | 4 +- macosx/tkMacOSXSubwindows.c | 115 ++++---- macosx/tkMacOSXWindowEvent.c | 64 ++-- macosx/tkMacOSXWm.c | 82 +++--- macosx/ttkMacOSXTheme.c | 450 ++++++++++++++++------------ 22 files changed, 2436 insertions(+), 2033 deletions(-) diff --git a/macosx/tkMacOSXButton.c b/macosx/tkMacOSXButton.c index ad963e1..1c4ad25 100644 --- a/macosx/tkMacOSXButton.c +++ b/macosx/tkMacOSXButton.c @@ -1,8 +1,8 @@ /* * tkMacOSXButton.c -- * - * This file implements the Macintosh specific portion of the - * button widgets. + * This file implements the Macintosh specific portion of the button + * widgets. * * Copyright (c) 1996-1997 by Sun Microsystems, Inc. * Copyright 2001, Apple Computer, Inc. @@ -70,20 +70,23 @@ typedef struct { * Forward declarations for procedures defined later in this file: */ - -static void ButtonBackgroundDrawCB (const HIRect *btnbounds, MacButton *ptr, - SInt16 depth, Boolean isColorDev); -static void ButtonContentDrawCB (const HIRect *bounds, ThemeButtonKind kind, - const HIThemeButtonDrawInfo *info, MacButton *ptr, SInt16 depth, - Boolean isColorDev); -static void ButtonEventProc(ClientData clientData, XEvent *eventPtr); -static void TkMacOSXComputeButtonParams (TkButton * butPtr, ThemeButtonKind* btnkind, - HIThemeButtonDrawInfo* drawinfo); -static int TkMacOSXComputeButtonDrawParams (TkButton * butPtr, DrawParams * dpPtr); -static void TkMacOSXDrawButton (MacButton *butPtr, GC gc, Pixmap pixmap); -static void DrawButtonImageAndText(TkButton* butPtr); -static void PulseDefaultButtonProc(ClientData clientData); - +static void ButtonBackgroundDrawCB(const HIRect *btnbounds, + MacButton *ptr, SInt16 depth, Boolean isColorDev); +static void ButtonContentDrawCB(const HIRect *bounds, + ThemeButtonKind kind, + const HIThemeButtonDrawInfo *info, MacButton *ptr, + SInt16 depth, Boolean isColorDev); +static void ButtonEventProc(ClientData clientData, + XEvent *eventPtr); +static void TkMacOSXComputeButtonParams(TkButton *butPtr, + ThemeButtonKind *btnkind, + HIThemeButtonDrawInfo *drawinfo); +static int TkMacOSXComputeButtonDrawParams(TkButton *butPtr, + DrawParams * dpPtr); +static void TkMacOSXDrawButton(MacButton *butPtr, GC gc, + Pixmap pixmap); +static void DrawButtonImageAndText(TkButton *butPtr); +static void PulseDefaultButtonProc(ClientData clientData); /* * The class procedure table for the button widgets. @@ -95,15 +98,15 @@ const Tk_ClassProcs tkpButtonProcs = { }; static int bCount; - + /* *---------------------------------------------------------------------- * * TkpButtonSetDefaults -- * - * This procedure is invoked before option tables are created for - * buttons. It modifies some of the default values to match the current - * values defined for this platform. + * This procedure is invoked before option tables are created for buttons. + * It modifies some of the default values to match the current values + * defined for this platform. * * Results: * Some of the default values in *specPtr are modified. @@ -117,9 +120,8 @@ static int bCount; void TkpButtonSetDefaults() { -/*No-op.*/ + /*No-op.*/ } - /* *---------------------------------------------------------------------- @@ -141,10 +143,10 @@ TkButton * TkpCreateButton( Tk_Window tkwin) { - MacButton *macButtonPtr = (MacButton *) ckalloc(sizeof(MacButton)); + MacButton *macButtonPtr = ckalloc(sizeof(MacButton)); Tk_CreateEventHandler(tkwin, ActivateMask, - ButtonEventProc, (ClientData) macButtonPtr); + ButtonEventProc, macButtonPtr); macButtonPtr->id = bCount++; macButtonPtr->flags = FIRST_DRAW; macButtonPtr->btnkind = kThemePushButton; @@ -152,7 +154,7 @@ TkpCreateButton( bzero(&macButtonPtr->drawinfo, sizeof(macButtonPtr->drawinfo)); bzero(&macButtonPtr->lastdrawinfo, sizeof(macButtonPtr->lastdrawinfo)); - return (TkButton *)macButtonPtr; + return (TkButton *) macButtonPtr; } /* @@ -160,15 +162,15 @@ TkpCreateButton( * * TkpDisplayButton -- * - * This procedure is invoked to display a button widget. It is - * normally invoked as an idle handler. + * This procedure is invoked to display a button widget. It is normally + * invoked as an idle handler. * * Results: * None. * * Side effects: - * Commands are output to X to display the button in its - * current mode. The REDRAW_PENDING flag is cleared. + * Commands are output to X to display the button in its current mode. The + * REDRAW_PENDING flag is cleared. * *---------------------------------------------------------------------- */ @@ -177,8 +179,8 @@ void TkpDisplayButton( ClientData clientData) /* Information about widget. */ { - MacButton *macButtonPtr = (MacButton *) clientData; - TkButton *butPtr = (TkButton *) clientData; + MacButton *macButtonPtr = clientData; + TkButton *butPtr = clientData; Tk_Window tkwin = butPtr->tkwin; Pixmap pixmap; DrawParams* dpPtr = &macButtonPtr->drawParams; @@ -191,16 +193,15 @@ TkpDisplayButton( pixmap = (Pixmap) Tk_WindowId(tkwin); TkMacOSXSetUpClippingRgn(Tk_WindowId(tkwin)); - if (TkMacOSXComputeButtonDrawParams(butPtr, dpPtr) ) { + if (TkMacOSXComputeButtonDrawParams(butPtr, dpPtr)) { macButtonPtr->useTkText = 0; } else { macButtonPtr->useTkText = 1; } - /* - * Set up clipping region. Make sure the we are using the port - * for this button, or we will set the wrong window's clip. + * Set up clipping region. Make sure the we are using the port for this + * button, or we will set the wrong window's clip. */ if (macButtonPtr->useTkText) { @@ -212,26 +213,36 @@ TkpDisplayButton( Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT); } - /* Display image or bitmap or text for labels or custom controls. */ + /* + * Display image or bitmap or text for labels or custom controls. + */ + DrawButtonImageAndText(butPtr); - needhighlight = 1; + needhighlight = 1; } else { - /* Draw the native portion of the buttons. */ + /* + * Draw the native portion of the buttons. + */ + TkMacOSXDrawButton(macButtonPtr, dpPtr->gc, pixmap); - /* Draw highlight border, if needed. */ + /* + * Ask for the highlight border, if needed. + */ + if (butPtr->highlightWidth < 3) { needhighlight = 1; } } - /* Draw highlight border, if needed. */ - if (needhighlight) { - if ((butPtr->flags & GOT_FOCUS)) { - Tk_Draw3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0, + /* + * Draw highlight border. + */ + + if (needhighlight && (butPtr->flags & GOT_FOCUS)) { + Tk_Draw3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0, Tk_Width(tkwin), Tk_Height(tkwin), butPtr->highlightWidth, TK_RELIEF_SOLID); - } } } @@ -240,9 +251,9 @@ TkpDisplayButton( * * TkpComputeButtonGeometry -- * - * After changes in a button's text or bitmap, this procedure - * recomputes the button's geometry and passes this information - * along to the geometry manager for the window. + * After changes in a button's text or bitmap, this procedure recomputes + * the button's geometry and passes this information along to the geometry + * manager for the window. * * Results: * None. @@ -259,7 +270,7 @@ TkpComputeButtonGeometry( { int width = 0, height = 0, charWidth = 1, haveImage = 0, haveText = 0; int txtWidth = 0, txtHeight = 0; - MacButton *mbPtr = (MacButton*)butPtr; + MacButton *mbPtr = (MacButton *) butPtr; Tk_FontMetrics fm; char *text = Tcl_GetString(butPtr->textPtr); @@ -270,21 +281,27 @@ TkpComputeButtonGeometry( */ if (butPtr->indicatorOn) { - switch (butPtr->type) { - case TYPE_RADIO_BUTTON: - GetThemeMetric(kThemeMetricRadioButtonWidth, (SInt32 *)&butPtr->indicatorDiameter); - break; - case TYPE_CHECK_BUTTON: - GetThemeMetric(kThemeMetricCheckBoxWidth, (SInt32 *)&butPtr->indicatorDiameter); - break; - default: - break; - } - /* Allow 2px extra space next to the indicator. */ - butPtr->indicatorSpace = butPtr->indicatorDiameter + 2; + switch (butPtr->type) { + case TYPE_RADIO_BUTTON: + GetThemeMetric(kThemeMetricRadioButtonWidth, + (SInt32 *) &butPtr->indicatorDiameter); + break; + case TYPE_CHECK_BUTTON: + GetThemeMetric(kThemeMetricCheckBoxWidth, + (SInt32 *) &butPtr->indicatorDiameter); + break; + default: + break; + } + + /* + * Allow 2px extra space next to the indicator. + */ + + butPtr->indicatorSpace = butPtr->indicatorDiameter + 2; } else { - butPtr->indicatorSpace = 0; - butPtr->indicatorDiameter = 0; + butPtr->indicatorSpace = 0; + butPtr->indicatorDiameter = 0; } if (butPtr->image != NULL) { @@ -308,44 +325,43 @@ TkpComputeButtonGeometry( if (haveImage && haveText) { /* Image and Text */ switch ((enum compound) butPtr->compound) { - case COMPOUND_TOP: - case COMPOUND_BOTTOM: - - /* - * Image is above or below text. - */ - - height += txtHeight + butPtr->padY; - width = (width > txtWidth ? width : txtWidth); - break; - case COMPOUND_LEFT: - case COMPOUND_RIGHT: - - /* - * Image is left or right of text. - */ - - width += txtWidth + 2*butPtr->padX; - height = (height > txtHeight ? height : txtHeight); - break; - case COMPOUND_CENTER: - - /* - * Image and text are superimposed. - */ - - width = (width > txtWidth ? width : txtWidth); - height = (height > txtHeight ? height : txtHeight); - break; - default: - break; + case COMPOUND_TOP: + case COMPOUND_BOTTOM: + /* + * Image is above or below text. + */ + + height += txtHeight + butPtr->padY; + width = (width > txtWidth ? width : txtWidth); + break; + case COMPOUND_LEFT: + case COMPOUND_RIGHT: + /* + * Image is left or right of text. + */ + + width += txtWidth + 2*butPtr->padX; + height = (height > txtHeight ? height : txtHeight); + break; + case COMPOUND_CENTER: + /* + * Image and text are superimposed. + */ + + width = (width > txtWidth ? width : txtWidth); + height = (height > txtHeight ? height : txtHeight); + break; + default: + break; } width += butPtr->indicatorSpace; } else if (haveImage) { /* Image only */ width = butPtr->width > 0 ? butPtr->width : width + butPtr->indicatorSpace; height = butPtr->height > 0 ? butPtr->height : height; if (butPtr->type == TYPE_BUTTON) { - /* Allow room to shift the image. */ + /* + * Allow room to shift the image. + */ width += 2; height += 2; } @@ -375,17 +391,17 @@ TkpComputeButtonGeometry( width += butPtr->inset*2; height += butPtr->inset*2; if ([NSApp macMinorVersion] == 6) { - width += 12; + width += 12; } if (mbPtr->btnkind == kThemePushButton) { HIRect tmpRect; HIRect contBounds; /* - * A PushButton has a minimum size. We make sure that we - * are not underestimating the size by requesting the content - * size of a Pushbutton whose overall size is our content size - * expanded by the standard padding. + * A PushButton has a minimum size. We make sure that we are not + * underestimating the size by requesting the content size of a + * Pushbutton whose overall size is our content size expanded by the + * standard padding. */ tmpRect = CGRectMake(0, 0, width + 2*HI_PADX, height + 2*HI_PADY); @@ -402,51 +418,43 @@ TkpComputeButtonGeometry( Tk_GeometryRequest(butPtr->tkwin, width, height); Tk_SetInternalBorder(butPtr->tkwin, butPtr->inset); } - + /* *---------------------------------------------------------------------- * * DrawButtonImageAndText -- * - * Draws the image and text associated with a button or label. + * Draws the image and text associated with a button or label. * * Results: - * None. + * None. * * Side effects: - * The image and text are drawn. + * The image and text are drawn. * *---------------------------------------------------------------------- */ static void DrawButtonImageAndText( - TkButton* butPtr) + TkButton *butPtr) { - MacButton *mbPtr = (MacButton*)butPtr; - Tk_Window tkwin = butPtr->tkwin; - Pixmap pixmap; - int haveImage = 0; - int haveText = 0; - int imageWidth = 0; - int imageHeight = 0; - int imageXOffset = 0; - int imageYOffset = 0; - int textXOffset = 0; - int textYOffset = 0; - int width = 0; - int height = 0; - int fullWidth = 0; - int fullHeight = 0; - int pressed = 0; - + MacButton *mbPtr = (MacButton *) butPtr; + Tk_Window tkwin = butPtr->tkwin; + Pixmap pixmap; + int haveImage = 0, haveText = 0, pressed = 0; + int imageWidth = 0, imageHeight = 0; + int imageXOffset = 0, imageYOffset = 0; + int textXOffset = 0, textYOffset = 0; + int width = 0, height = 0; + int fullWidth = 0, fullHeight = 0; if (tkwin == NULL || !Tk_IsMapped(tkwin)) { return; } - DrawParams* dpPtr = &mbPtr->drawParams; - pixmap = (Pixmap)Tk_WindowId(tkwin); + DrawParams *dpPtr = &mbPtr->drawParams; + pixmap = (Pixmap) Tk_WindowId(tkwin); if (butPtr->image != None) { Tk_SizeOfImage(butPtr->image, &width, &height); @@ -456,74 +464,68 @@ DrawButtonImageAndText( haveImage = 1; } - imageWidth = width; + imageWidth = width; imageHeight = height; if (mbPtr->drawinfo.state == kThemeStatePressed) { - /* Offset bitmaps by a bit when the button is pressed. */ + /* + * Offset bitmaps by a bit when the button is pressed. + */ + pressed = 1; } haveText = (butPtr->textWidth != 0 && butPtr->textHeight != 0); if (haveImage && haveText) { /* Image and Text */ - int x; - int y; - textXOffset = 0; - textYOffset = 0; - fullWidth = 0; - fullHeight = 0; + int x, y; switch ((enum compound) butPtr->compound) { case COMPOUND_TOP: - case COMPOUND_BOTTOM: { - /* Image is above or below text */ - if (butPtr->compound == COMPOUND_TOP) { - textYOffset = height + butPtr->padY; - } else { - imageYOffset = butPtr->textHeight + butPtr->padY; - } - fullHeight = height + butPtr->textHeight + butPtr->padY; - fullWidth = (width > butPtr->textWidth ? width : - butPtr->textWidth); - textXOffset = (fullWidth - butPtr->textWidth)/2; - imageXOffset = (fullWidth - width)/2; - break; - } + case COMPOUND_BOTTOM: + /* Image is above or below text */ + if (butPtr->compound == COMPOUND_TOP) { + textYOffset = height + butPtr->padY; + } else { + imageYOffset = butPtr->textHeight + butPtr->padY; + } + fullHeight = height + butPtr->textHeight + butPtr->padY; + fullWidth = (width > butPtr->textWidth ? width : butPtr->textWidth); + textXOffset = (fullWidth - butPtr->textWidth)/2; + imageXOffset = (fullWidth - width)/2; + break; case COMPOUND_LEFT: - case COMPOUND_RIGHT: { - /* - * Image is left or right of text - */ - - if (butPtr->compound == COMPOUND_LEFT) { - textXOffset = width + butPtr->padX; - } else { - imageXOffset = butPtr->textWidth + butPtr->padX; - } - fullWidth = butPtr->textWidth + butPtr->padX + width; - fullHeight = (height > butPtr->textHeight ? height : - butPtr->textHeight); - textYOffset = (fullHeight - butPtr->textHeight)/2; - imageYOffset = (fullHeight - height)/2; - break; - } - case COMPOUND_CENTER: { - /* - * Image and text are superimposed - */ - - fullWidth = (width > butPtr->textWidth ? width : - butPtr->textWidth); - fullHeight = (height > butPtr->textHeight ? height : - butPtr->textHeight); - textXOffset = (fullWidth - butPtr->textWidth)/2; - imageXOffset = (fullWidth - width)/2; - textYOffset = (fullHeight - butPtr->textHeight)/2; - imageYOffset = (fullHeight - height)/2; - break; - } + case COMPOUND_RIGHT: + /* + * Image is left or right of text + */ + + if (butPtr->compound == COMPOUND_LEFT) { + textXOffset = width + butPtr->padX; + } else { + imageXOffset = butPtr->textWidth + butPtr->padX; + } + fullWidth = butPtr->textWidth + butPtr->padX + width; + fullHeight = (height > butPtr->textHeight ? height : + butPtr->textHeight); + textYOffset = (fullHeight - butPtr->textHeight)/2; + imageYOffset = (fullHeight - height)/2; + break; + case COMPOUND_CENTER: + /* + * Image and text are superimposed + */ + + fullWidth = (width > butPtr->textWidth ? width : + butPtr->textWidth); + fullHeight = (height > butPtr->textHeight ? height : + butPtr->textHeight); + textXOffset = (fullWidth - butPtr->textWidth)/2; + imageXOffset = (fullWidth - width)/2; + textYOffset = (fullHeight - butPtr->textHeight)/2; + imageYOffset = (fullHeight - height)/2; + break; default: - break; + break; } TkComputeAnchor(butPtr->anchor, tkwin, @@ -547,25 +549,25 @@ DrawButtonImageAndText( imageYOffset += y; if (butPtr->image != NULL) { - if ((butPtr->selectImage != NULL) && - (butPtr->flags & SELECTED)) { - Tk_RedrawImage(butPtr->selectImage, 0, 0, - width, height, pixmap, imageXOffset, imageYOffset); - } else if ((butPtr->tristateImage != NULL) && - (butPtr->flags & TRISTATED)) { - Tk_RedrawImage(butPtr->tristateImage, 0, 0, - width, height, pixmap, imageXOffset, imageYOffset); - } else { - Tk_RedrawImage(butPtr->image, 0, 0, width, - height, pixmap, imageXOffset, imageYOffset); - } + if ((butPtr->selectImage != NULL) && + (butPtr->flags & SELECTED)) { + Tk_RedrawImage(butPtr->selectImage, 0, 0, + width, height, pixmap, imageXOffset, imageYOffset); + } else if ((butPtr->tristateImage != NULL) && + (butPtr->flags & TRISTATED)) { + Tk_RedrawImage(butPtr->tristateImage, 0, 0, + width, height, pixmap, imageXOffset, imageYOffset); + } else { + Tk_RedrawImage(butPtr->image, 0, 0, width, + height, pixmap, imageXOffset, imageYOffset); + } } else { - XSetClipOrigin(butPtr->display, dpPtr->gc, - imageXOffset, imageYOffset); - XCopyPlane(butPtr->display, butPtr->bitmap, pixmap, dpPtr->gc, - 0, 0, (unsigned int) width, (unsigned int) height, - imageXOffset, imageYOffset, 1); - XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0); + XSetClipOrigin(butPtr->display, dpPtr->gc, + imageXOffset, imageYOffset); + XCopyPlane(butPtr->display, butPtr->bitmap, pixmap, dpPtr->gc, + 0, 0, (unsigned int) width, (unsigned int) height, + imageXOffset, imageYOffset, 1); + XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0); } y += 1; /* Tweak to match native buttons. */ @@ -577,60 +579,57 @@ DrawButtonImageAndText( x + textXOffset, y + textYOffset, butPtr->underline); } else if (haveImage) { /* Image only */ - int x = 0; - int y; + int x = 0, y; + TkComputeAnchor(butPtr->anchor, tkwin, - butPtr->padX + butPtr->borderWidth, - butPtr->padY + butPtr->borderWidth, - width + butPtr->indicatorSpace, - height, &x, &y); + butPtr->padX + butPtr->borderWidth, + butPtr->padY + butPtr->borderWidth, + width + butPtr->indicatorSpace, height, &x, &y); x += butPtr->indicatorSpace; if (pressed) { - x += dpPtr->offset; - y += dpPtr->offset; + x += dpPtr->offset; + y += dpPtr->offset; } imageXOffset += x; imageYOffset += y; if (butPtr->image != NULL) { - - if ((butPtr->selectImage != NULL) && - (butPtr->flags & SELECTED)) { - Tk_RedrawImage(butPtr->selectImage, 0, 0, width, - height, pixmap, imageXOffset, imageYOffset); - } else if ((butPtr->tristateImage != NULL) && - (butPtr->flags & TRISTATED)) { - Tk_RedrawImage(butPtr->tristateImage, 0, 0, width, - height, pixmap, imageXOffset, imageYOffset); - } else { - Tk_RedrawImage(butPtr->image, 0, 0, width, height, - pixmap, imageXOffset, imageYOffset); - } + if ((butPtr->selectImage != NULL) && + (butPtr->flags & SELECTED)) { + Tk_RedrawImage(butPtr->selectImage, 0, 0, width, + height, pixmap, imageXOffset, imageYOffset); + } else if ((butPtr->tristateImage != NULL) && + (butPtr->flags & TRISTATED)) { + Tk_RedrawImage(butPtr->tristateImage, 0, 0, width, + height, pixmap, imageXOffset, imageYOffset); + } else { + Tk_RedrawImage(butPtr->image, 0, 0, width, height, + pixmap, imageXOffset, imageYOffset); + } } else { - XSetClipOrigin(butPtr->display, dpPtr->gc, x, y); - XCopyPlane(butPtr->display, butPtr->bitmap, - pixmap, dpPtr->gc, - 0, 0, (unsigned int) width, - (unsigned int) height, - imageXOffset, imageYOffset, 1); - XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0); + XSetClipOrigin(butPtr->display, dpPtr->gc, x, y); + XCopyPlane(butPtr->display, butPtr->bitmap, pixmap, dpPtr->gc, + 0, 0, (unsigned int) width, (unsigned int) height, + imageXOffset, imageYOffset, 1); + XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0); } } else { /* Text only */ int x, y; + TkComputeAnchor(butPtr->anchor, tkwin, butPtr->padX, butPtr->padY, - butPtr->textWidth + butPtr->indicatorSpace, - butPtr->textHeight, &x, &y); + butPtr->textWidth + butPtr->indicatorSpace, + butPtr->textHeight, &x, &y); x += butPtr->indicatorSpace; y += 1; /* Tweak to match native buttons */ - Tk_DrawTextLayout(butPtr->display, pixmap, dpPtr->gc, butPtr->textLayout, - x, y, 0, -1); + Tk_DrawTextLayout(butPtr->display, pixmap, dpPtr->gc, + butPtr->textLayout, x, y, 0, -1); } /* * If the button is disabled with a stipple rather than a special - * foreground color, generate the stippled effect. If the widget - * is selected and we use a different background color when selected, - * must temporarily modify the GC so the stippling is the right color. + * foreground color, generate the stippled effect. If the widget is + * selected and we use a different background color when selected, must + * temporarily modify the GC so the stippling is the right color. */ if (mbPtr->useTkText) { @@ -668,18 +667,15 @@ DrawButtonImageAndText( */ if (dpPtr->relief != TK_RELIEF_FLAT) { - int inset = butPtr->highlightWidth; - Tk_Draw3DRectangle(tkwin, pixmap, dpPtr->border, inset, inset, - Tk_Width(tkwin) - 2*inset, Tk_Height(tkwin) - 2*inset, - butPtr->borderWidth, dpPtr->relief); + int inset = butPtr->highlightWidth; + + Tk_Draw3DRectangle(tkwin, pixmap, dpPtr->border, inset, inset, + Tk_Width(tkwin) - 2*inset, Tk_Height(tkwin) - 2*inset, + butPtr->borderWidth, dpPtr->relief); } } - - } - - - - +} + /* *---------------------------------------------------------------------- * @@ -701,6 +697,7 @@ TkpDestroyButton( TkButton *butPtr) { MacButton *mbPtr = (MacButton *) butPtr; /* Mac button. */ + if (mbPtr->defaultPulseHandler) { Tcl_DeleteTimerHandler(mbPtr->defaultPulseHandler); } @@ -711,9 +708,8 @@ TkpDestroyButton( * * TkMacOSXDrawButton -- * - * This function draws the tk button using Mac controls - * In addition, this code may apply custom colors passed - * in the TkButton. + * This function draws the tk button using Mac controls. In addition, + * this code may apply custom colors passed in the TkButton. * * Results: * None. @@ -732,23 +728,19 @@ TkMacOSXDrawButton( Pixmap pixmap) /* The pixmap we are drawing into - needed * for the bevel button */ { - TkButton * butPtr = ( TkButton *)mbPtr; - TkWindow * winPtr; - HIRect cntrRect; + TkButton *butPtr = (TkButton *) mbPtr; + TkWindow *winPtr = (TkWindow *) butPtr->tkwin; + HIRect cntrRect; TkMacOSXDrawingContext dc; - DrawParams* dpPtr = &mbPtr->drawParams; + DrawParams *dpPtr = &mbPtr->drawParams; int useNewerHITools = 1; - winPtr = (TkWindow *)butPtr->tkwin; - TkMacOSXComputeButtonParams(butPtr, &mbPtr->btnkind, &mbPtr->drawinfo); - cntrRect = CGRectMake(winPtr->privatePtr->xOff, - winPtr->privatePtr->yOff, - Tk_Width(butPtr->tkwin), - Tk_Height(butPtr->tkwin)); + cntrRect = CGRectMake(winPtr->privatePtr->xOff, winPtr->privatePtr->yOff, + Tk_Width(butPtr->tkwin), Tk_Height(butPtr->tkwin)); - cntrRect = CGRectInset(cntrRect, butPtr->inset, butPtr->inset); + cntrRect = CGRectInset(cntrRect, butPtr->inset, butPtr->inset); if (useNewerHITools == 1) { HIRect contHIRec; @@ -762,7 +754,7 @@ TkMacOSXDrawButton( hiinfo.version = 0; hiinfo.state = mbPtr->drawinfo.state; - hiinfo.kind = mbPtr->btnkind; + hiinfo.kind = mbPtr->btnkind; hiinfo.value = mbPtr->drawinfo.value; hiinfo.adornment = mbPtr->drawinfo.adornment; hiinfo.animation.time.current = CFAbsoluteTimeGetCurrent(); @@ -772,21 +764,19 @@ TkMacOSXDrawButton( /* * To avoid buttons with white text on a white background, we always - * set the state to inactive in Dark Mode. It isn't perfect but - * it is usable. Using a ttk::button would be a better choice, - * however. + * set the state to inactive in Dark Mode. It isn't perfect but it is + * usable. Using a ttk::button would be a better choice, however. */ if (TkMacOSXInDarkMode(butPtr->tkwin)) { hiinfo.state = kThemeStateInactive; } - HIThemeDrawButton(&cntrRect, &hiinfo, dc.context, kHIThemeOrientationNormal, - &contHIRec); + HIThemeDrawButton(&cntrRect, &hiinfo, dc.context, + kHIThemeOrientationNormal, &contHIRec); TkMacOSXRestoreDrawingContext(&dc); ButtonContentDrawCB(&contHIRec, mbPtr->btnkind, &mbPtr->drawinfo, - (MacButton *)mbPtr, 32, true); - + (MacButton *) mbPtr, 32, true); } else { if (!TkMacOSXSetupDrawingContext(pixmap, dpPtr->gc, 1, &dc)) { return; @@ -802,8 +792,8 @@ TkMacOSXDrawButton( * * ButtonBackgroundDrawCB -- * - * This function draws the background that - * lies under checkboxes and radiobuttons. + * This function draws the background that lies under checkboxes and + * radiobuttons. * * Results: * None. @@ -813,32 +803,33 @@ TkMacOSXDrawButton( * *-------------------------------------------------------------- */ + static void -ButtonBackgroundDrawCB ( - const HIRect * btnbounds, +ButtonBackgroundDrawCB( + const HIRect *btnbounds, MacButton *ptr, SInt16 depth, Boolean isColorDev) { - MacButton* mbPtr = (MacButton*)ptr; - TkButton* butPtr = (TkButton*)mbPtr; - Tk_Window tkwin = butPtr->tkwin; + MacButton *mbPtr = (MacButton *) ptr; + TkButton *butPtr = (TkButton *) mbPtr; + Tk_Window tkwin = butPtr->tkwin; Pixmap pixmap; int usehlborder = 0; if (tkwin == NULL || !Tk_IsMapped(tkwin)) { return; } - pixmap = (Pixmap)Tk_WindowId(tkwin); + pixmap = (Pixmap) Tk_WindowId(tkwin); if (butPtr->type != TYPE_LABEL) { switch (mbPtr->btnkind) { - case kThemeSmallBevelButton: - case kThemeBevelButton: - case kThemeRoundedBevelButton: - case kThemePushButton: - usehlborder = 1; - break; + case kThemeSmallBevelButton: + case kThemeBevelButton: + case kThemeRoundedBevelButton: + case kThemePushButton: + usehlborder = 1; + break; } } if (usehlborder) { @@ -874,17 +865,18 @@ ButtonContentDrawCB ( SInt16 depth, Boolean isColorDev) { - TkButton *butPtr = (TkButton *)ptr; - Tk_Window tkwin = butPtr->tkwin; + TkButton *butPtr = (TkButton *) ptr; + Tk_Window tkwin = butPtr->tkwin; if (tkwin == NULL || !Tk_IsMapped(tkwin)) { return; } /* - * Overlay Tk elements over button native region: drawing elements - * within button boundaries/native region causes unpredictable metrics. + * Overlay Tk elements over button native region: drawing elements within + * button boundaries/native region causes unpredictable metrics. */ + DrawButtonImageAndText( butPtr); } @@ -893,8 +885,8 @@ ButtonContentDrawCB ( * * ButtonEventProc -- * - * This procedure is invoked by the Tk dispatcher for various - * events on buttons. + * This procedure is invoked by the Tk dispatcher for various events on + * buttons. * * Results: * None. @@ -910,8 +902,8 @@ ButtonEventProc( ClientData clientData, /* Information about window. */ XEvent *eventPtr) /* Information about event. */ { - TkButton *buttonPtr = (TkButton *) clientData; - MacButton *mbPtr = (MacButton *) clientData; + TkButton *buttonPtr = clientData; + MacButton *mbPtr = clientData; if (eventPtr->type == ActivateNotify || eventPtr->type == DeactivateNotify) { @@ -924,7 +916,7 @@ ButtonEventProc( mbPtr->flags &= ~ACTIVE; } if ((buttonPtr->flags & REDRAW_PENDING) == 0) { - Tcl_DoWhenIdle(TkpDisplayButton, (ClientData) buttonPtr); + Tcl_DoWhenIdle(TkpDisplayButton, buttonPtr); buttonPtr->flags |= REDRAW_PENDING; } } @@ -935,9 +927,9 @@ ButtonEventProc( * * TkMacOSXComputeButtonParams -- * - * This procedure computes the various parameters used - * when creating a Carbon Appearance control. - * These are determined by the various tk button parameters + * This procedure computes the various parameters used when creating a + * Carbon Appearance control. These are determined by the various tk + * button parameters * * Results: * None. @@ -950,11 +942,11 @@ ButtonEventProc( static void TkMacOSXComputeButtonParams( - TkButton * butPtr, - ThemeButtonKind* btnkind, - HIThemeButtonDrawInfo *drawinfo) + TkButton *butPtr, + ThemeButtonKind *btnkind, + HIThemeButtonDrawInfo *drawinfo) { - MacButton *mbPtr = (MacButton *)butPtr; + MacButton *mbPtr = (MacButton *) butPtr; if (butPtr->borderWidth <= 2) { *btnkind = kThemeSmallBevelButton; @@ -968,47 +960,46 @@ TkMacOSXComputeButtonParams( if ((butPtr->image == None) && (butPtr->bitmap == None)) { switch (butPtr->type) { - case TYPE_BUTTON: - *btnkind = kThemePushButton; - break; - case TYPE_RADIO_BUTTON: - if (butPtr->borderWidth <= 1) { - *btnkind = kThemeSmallRadioButton; - } else { - *btnkind = kThemeRadioButton; - } - break; - case TYPE_CHECK_BUTTON: - if (butPtr->borderWidth <= 1) { - *btnkind = kThemeSmallCheckBox; - } else { - *btnkind = kThemeCheckBox; - } - break; + case TYPE_BUTTON: + *btnkind = kThemePushButton; + break; + case TYPE_RADIO_BUTTON: + if (butPtr->borderWidth <= 1) { + *btnkind = kThemeSmallRadioButton; + } else { + *btnkind = kThemeRadioButton; + } + break; + case TYPE_CHECK_BUTTON: + if (butPtr->borderWidth <= 1) { + *btnkind = kThemeSmallCheckBox; + } else { + *btnkind = kThemeCheckBox; + } + break; } } if (butPtr->indicatorOn) { switch (butPtr->type) { - case TYPE_RADIO_BUTTON: - if (butPtr->borderWidth <= 1) { - *btnkind = kThemeSmallRadioButton; - } else { - *btnkind = kThemeRadioButton; - } - break; - case TYPE_CHECK_BUTTON: - if (butPtr->borderWidth <= 1) { - *btnkind = kThemeSmallCheckBox; - } else { - *btnkind = kThemeCheckBox; - } - break; + case TYPE_RADIO_BUTTON: + if (butPtr->borderWidth <= 1) { + *btnkind = kThemeSmallRadioButton; + } else { + *btnkind = kThemeRadioButton; + } + break; + case TYPE_CHECK_BUTTON: + if (butPtr->borderWidth <= 1) { + *btnkind = kThemeSmallCheckBox; + } else { + *btnkind = kThemeCheckBox; + } + break; } } else { if (butPtr->type == TYPE_RADIO_BUTTON || - butPtr->type == TYPE_CHECK_BUTTON - ) { + butPtr->type == TYPE_CHECK_BUTTON) { if (*btnkind == kThemePushButton) { *btnkind = kThemeBevelButton; } @@ -1050,8 +1041,7 @@ TkMacOSXComputeButtonParams( drawinfo->adornment |= kThemeAdornmentDefault; if (!mbPtr->defaultPulseHandler) { mbPtr->defaultPulseHandler = Tcl_CreateTimerHandler( - PULSE_TIMER_MSECS, PulseDefaultButtonProc, - (ClientData) butPtr); + PULSE_TIMER_MSECS, PulseDefaultButtonProc, butPtr); } } else if (mbPtr->defaultPulseHandler) { Tcl_DeleteTimerHandler(mbPtr->defaultPulseHandler); @@ -1068,9 +1058,8 @@ TkMacOSXComputeButtonParams( * * TkMacOSXComputeButtonDrawParams -- * - * This procedure computes the various parameters used - * when drawing a button - * These are determined by the various tk button parameters + * This procedure computes the various parameters used when drawing a + * button. These are determined by the various tk button parameters * * Results: * 1 if control will be used, 0 otherwise. @@ -1086,7 +1075,7 @@ TkMacOSXComputeButtonDrawParams( TkButton *butPtr, DrawParams *dpPtr) { - MacButton *mbPtr = (MacButton *)butPtr; + MacButton *mbPtr = (MacButton *) butPtr; dpPtr->hasImageOrBitmap = ((butPtr->image != NULL) || (butPtr->bitmap != None)); @@ -1095,12 +1084,12 @@ TkMacOSXComputeButtonDrawParams( dpPtr->offset = 0; if (dpPtr->hasImageOrBitmap) { switch (mbPtr->btnkind) { - case kThemeSmallBevelButton: - case kThemeBevelButton: - case kThemeRoundedBevelButton: - case kThemePushButton: - dpPtr->offset = 1; - break; + case kThemeSmallBevelButton: + case kThemeBevelButton: + case kThemeRoundedBevelButton: + case kThemePushButton: + dpPtr->offset = 1; + break; } } } @@ -1121,8 +1110,8 @@ TkMacOSXComputeButtonDrawParams( } /* - * Override the relief specified for the button if this is a - * checkbutton or radiobutton and there's no indicator. + * Override the relief specified for the button if this is a checkbutton or + * radiobutton and there's no indicator. */ dpPtr->relief = butPtr->relief; @@ -1134,18 +1123,14 @@ TkMacOSXComputeButtonDrawParams( } } - if (butPtr->type != TYPE_LABEL && - (butPtr->type == TYPE_BUTTON || - butPtr->indicatorOn || - dpPtr->hasImageOrBitmap)) { - + if (butPtr->type != TYPE_LABEL && (butPtr->type == TYPE_BUTTON || + butPtr->indicatorOn || dpPtr->hasImageOrBitmap)) { /* * Draw this widget as a native control. */ - + return 1; } else { - /* * Draw this widget from scratch. */ @@ -1170,15 +1155,17 @@ TkMacOSXComputeButtonDrawParams( * *-------------------------------------------------------------- */ + static void PulseDefaultButtonProc(ClientData clientData) { - MacButton *mbPtr = (MacButton *)clientData; + MacButton *mbPtr = clientData; + TkpDisplayButton(clientData); mbPtr->defaultPulseHandler = Tcl_CreateTimerHandler( PULSE_TIMER_MSECS, PulseDefaultButtonProc, clientData); } - + /* * Local Variables: * mode: objc diff --git a/macosx/tkMacOSXClipboard.c b/macosx/tkMacOSXClipboard.c index efd3c69..6cbcdf6 100644 --- a/macosx/tkMacOSXClipboard.c +++ b/macosx/tkMacOSXClipboard.c @@ -123,8 +123,9 @@ TkSelGetSelection( { int result = TCL_ERROR; TkDisplay *dispPtr = ((TkWindow *) tkwin)->dispPtr; + int haveExternalClip = + ([[NSPasteboard generalPasteboard] changeCount] != changeCount); - int haveExternalClip = ([[NSPasteboard generalPasteboard] changeCount] != changeCount); if (dispPtr && (haveExternalClip || dispPtr->clipboardActive) && selection == dispPtr->clipboardAtom && (target == XA_STRING || target == dispPtr->utf8Atom)) { @@ -177,6 +178,7 @@ XSetSelectionOwner( clipboardOwner = owner ? Tk_IdToWindow(display, owner) : NULL; if (!dispPtr->clipboardActive) { NSPasteboard *pb = [NSPasteboard generalPasteboard]; + changeCount = [pb declareTypes:[NSArray array] owner:NSApp]; } } @@ -188,8 +190,8 @@ XSetSelectionOwner( * * TkMacOSXSelDeadWindow -- * - * This function is invoked just before a TkWindow is deleted. It - * performs selection-related cleanup. + * This function is invoked just before a TkWindow is deleted. It performs + * selection-related cleanup. * * Results: * None. diff --git a/macosx/tkMacOSXCursor.c b/macosx/tkMacOSXCursor.c index b6394b7..03d13dd 100644 --- a/macosx/tkMacOSXCursor.c +++ b/macosx/tkMacOSXCursor.c @@ -185,7 +185,7 @@ static const struct CursorName cursorNames[] = { * Declarations of static variables used in this file. */ -static TkMacOSXCursor * gCurrentCursor = NULL; +static TkMacOSXCursor *gCurrentCursor = NULL; /* A pointer to the current cursor. */ static int gResizeOverride = false; /* A boolean indicating whether we should use @@ -194,7 +194,7 @@ static int gTkOwnsCursor = true;/* A boolean indicating whether Tk owns the * cursor. If not (for instance, in the case * where a Tk window is embedded in another * app's window, and the cursor is out of the - * tk window, we will not attempt to adjust + * Tk window, we will not attempt to adjust * the cursor. */ /* @@ -278,6 +278,7 @@ FindCursorByName( kCGColorSpaceGenericGray); CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, bitmap, pix*pix/8, NULL); + if (provider) { img = CGImageCreate(pix, pix, 1, 1, pix/8, colorspace, kCGBitmapByteOrderDefault, provider, decodeWB, 0, @@ -299,14 +300,21 @@ FindCursorByName( initWithCGImage:maskedImg]; CFRelease(maskedImg); } - if (mask) { CFRelease(mask); } - if (img) { CFRelease(img); } - if (colorspace) { CFRelease(colorspace); } + if (mask) { + CFRelease(mask); + } + if (img) { + CFRelease(img); + } + if (colorspace) { + CFRelease(colorspace); + } if (bitmapImageRep) { image = [[NSImage alloc] initWithSize:NSMakeSize(pix, pix)]; [image addRepresentation:bitmapImageRep]; [bitmapImageRep release]; } + uint16_t *hotSpotData = (uint16_t*)(bitmap + 2*pix*pix/8); hotSpot.y = CFSwapInt16BigToHost(*hotSpotData++); hotSpot.x = CFSwapInt16BigToHost(*hotSpotData); diff --git a/macosx/tkMacOSXDialog.c b/macosx/tkMacOSXDialog.c index a7e10b4..c96d294 100644 --- a/macosx/tkMacOSXDialog.c +++ b/macosx/tkMacOSXDialog.c @@ -22,31 +22,39 @@ #else #define modalOK NSModalResponseOK #define modalCancel NSModalResponseCancel -#endif +#endif // MAC_OS_X_VERSION_MIN_REQUIRED < 1090 #define modalOther -1 #define modalError -2 -/*Vars for filtering in "open file" and "save file" dialogs.*/ -typedef struct { - bool doFileTypes; // show the accessory view which displays the filter menu - bool preselectFilter; // a filter was selected by the typevariable - bool userHasSelectedFilter; // The user has changed the filter in the accessory view - - NSMutableArray *fileTypeNames; // array of names, e.g. "Text document" - NSMutableArray *fileTypeExtensions; // array of allowed extensions per name, e.g. "txt", "doc" - NSMutableArray *fileTypeLabels; // displayed string, e.g. "Text document (.txt, .doc)" - NSMutableArray *fileTypeAllowsAll; // boolean if the all pattern (*.*) is included - - NSMutableArray *allowedExtensions; // set of all allowed extensions - bool allowedExtensionsAllowAll; // set of all allowed extensions includes *.* +/* + * Vars for filtering in "open file" and "save file" dialogs. + */ - NSUInteger fileTypeIndex; // index of currently selected filter +typedef struct { + bool doFileTypes; /* Show the accessory view which + * displays the filter menu */ + bool preselectFilter; /* A filter was selected by the + * typevariable. */ + bool userHasSelectedFilter; /* The user has changed the filter in + * the accessory view. */ + NSMutableArray *fileTypeNames; /* Array of names, e.g. "Text + * document". */ + NSMutableArray *fileTypeExtensions; /* Array of allowed extensions per + * name, e.g. "txt", "doc". */ + NSMutableArray *fileTypeLabels; /* Displayed string, e.g. "Text + * document (.txt, .doc)". */ + NSMutableArray *fileTypeAllowsAll; /* Boolean if the all pattern (*.*) is + * included. */ + NSMutableArray *allowedExtensions; /* Set of all allowed extensions. */ + bool allowedExtensionsAllowAll; /* Set of all allowed extensions + * includes *.* */ + NSUInteger fileTypeIndex; /* Index of currently selected + * filter. */ } filepanelFilterInfo; -filepanelFilterInfo filterInfo; - -NSOpenPanel *openpanel; -NSSavePanel *savepanel; +static filepanelFilterInfo filterInfo; +static NSOpenPanel *openpanel; +static NSSavePanel *savepanel; static const char *const colorOptionStrings[] = { "-initialcolor", "-parent", "-title", NULL @@ -166,10 +174,15 @@ static const short alertNativeButtonIndexAndTypeToButtonIndex[][3] = { }; /* - * Construct a file URL from directory and filename. Either may - * be nil. If both are nil, returns nil. + * Construct a file URL from directory and filename. Either may be nil. If both + * are nil, returns nil. */ -static NSURL *getFileURL(NSString *directory, NSString *filename) { + +static NSURL * +getFileURL( + NSString *directory, + NSString *filename) +{ NSURL *url = nil; if (directory) { url = [NSURL fileURLWithPath:directory isDirectory:YES]; @@ -229,7 +242,6 @@ static NSURL *getFileURL(NSString *directory, NSString *filename) { } } - - (void) tkAlertDidEnd: (NSAlert *) alert returnCode: (NSInteger) returnCode contextInfo: (void *) contextInfo { @@ -272,12 +284,18 @@ static NSURL *getFileURL(NSString *directory, NSString *filename) { if ([[filterInfo.fileTypeAllowsAll objectAtIndex:filterInfo.fileTypeIndex] boolValue]) { [openpanel setAllowsOtherFileTypes:YES]; - /* setAllowsOtherFileTypes might have no effect; it's inherited from the - * NSSavePanel, where it has the effect that it does not append an extension - * Setting the allowed file types to nil allows selecting any file */ + + /* + * setAllowsOtherFileTypes might have no effect; it's inherited from + * the NSSavePanel, where it has the effect that it does not append an + * extension. Setting the allowed file types to nil allows selecting + * any file. + */ + [openpanel setAllowedFileTypes:nil]; } else { - NSMutableArray *allowedtypes = [filterInfo.fileTypeExtensions objectAtIndex:filterInfo.fileTypeIndex]; + NSMutableArray *allowedtypes = + [filterInfo.fileTypeExtensions objectAtIndex:filterInfo.fileTypeIndex]; [openpanel setAllowedFileTypes:allowedtypes]; [openpanel setAllowsOtherFileTypes:NO]; } @@ -293,7 +311,8 @@ static NSURL *getFileURL(NSString *directory, NSString *filename) { [savepanel setAllowsOtherFileTypes:YES]; [savepanel setAllowedFileTypes:nil]; } else { - NSMutableArray *allowedtypes = [filterInfo.fileTypeExtensions objectAtIndex:filterInfo.fileTypeIndex]; + NSMutableArray *allowedtypes = + [filterInfo.fileTypeExtensions objectAtIndex:filterInfo.fileTypeIndex]; [savepanel setAllowedFileTypes:allowedtypes]; [savepanel setAllowsOtherFileTypes:NO]; } @@ -384,6 +403,7 @@ Tk_ChooseColorObjCmd( [colorPanel _setUseModalAppearance:YES]; if (title) { NSString *s = [[NSString alloc] initWithUTF8String:title]; + [colorPanel setTitle:s]; [s release]; } @@ -415,9 +435,17 @@ end: return result; } -/* dissect the -filetype nested lists and store the information - * in the filterInfo structure */ -int parseFileFilters(Tcl_Interp *interp, Tcl_Obj *fileTypesPtr, Tcl_Obj *typeVariablePtr) { +/* + * Dissect the -filetype nested lists and store the information in the + * filterInfo structure. + */ + +static int +parseFileFilters( + Tcl_Interp *interp, + Tcl_Obj *fileTypesPtr, + Tcl_Obj *typeVariablePtr) +{ if (!fileTypesPtr) { filterInfo.doFileTypes = false; @@ -425,6 +453,7 @@ int parseFileFilters(Tcl_Interp *interp, Tcl_Obj *fileTypesPtr, Tcl_Obj *typeVar } FileFilterList fl; + TkInitFileFilters(&fl); if (TkGetFileFilters(interp, &fl, fileTypesPtr, 0) != TCL_OK) { TkFreeFileFilters(&fl); @@ -445,11 +474,12 @@ int parseFileFilters(Tcl_Interp *interp, Tcl_Obj *fileTypesPtr, Tcl_Obj *typeVar if (filterInfo.doFileTypes) { for (FileFilter *filterPtr = fl.filters; filterPtr; filterPtr = filterPtr->next) { - NSString * name = [[NSString alloc] initWithUTF8String: filterPtr -> name]; + NSString *name = [[NSString alloc] initWithUTF8String: filterPtr->name]; + [filterInfo.fileTypeNames addObject:name]; [name release]; - NSMutableArray * clauseextensions = [NSMutableArray array]; - NSMutableArray * displayextensions = [NSMutableArray array]; + NSMutableArray *clauseextensions = [NSMutableArray array]; + NSMutableArray *displayextensions = [NSMutableArray array]; bool allowsAll = NO; for (FileFilterClause *clausePtr = filterPtr->clauses; clausePtr; @@ -460,7 +490,7 @@ int parseFileFilters(Tcl_Interp *interp, Tcl_Obj *fileTypesPtr, Tcl_Obj *typeVar const char *str = globPtr->pattern; while (*str && (*str == '*' || *str == '.')) { str++; - } + } if (*str) { NSString *extension = [[NSString alloc] initWithUTF8String:str]; if (![filterInfo.allowedExtensions containsObject:extension]) { @@ -472,7 +502,10 @@ int parseFileFilters(Tcl_Interp *interp, Tcl_Obj *fileTypesPtr, Tcl_Obj *typeVar [extension release]; } else { - // it is the all pattern (*, .* or *.*) + /* + * It is the all pattern (*, .* or *.*) + */ + allowsAll = YES; filterInfo.allowedExtensionsAllowAll = YES; [displayextensions addObject:@"*"]; @@ -482,27 +515,39 @@ int parseFileFilters(Tcl_Interp *interp, Tcl_Obj *fileTypesPtr, Tcl_Obj *typeVar [filterInfo.fileTypeExtensions addObject:clauseextensions]; [filterInfo.fileTypeAllowsAll addObject:[NSNumber numberWithBool:allowsAll]]; - NSMutableString * label = [[NSMutableString alloc] initWithString:name]; + NSMutableString *label = [[NSMutableString alloc] initWithString:name]; [label appendString:@" ("]; [label appendString:[displayextensions componentsJoinedByString:@", "]]; [label appendString:@")"]; [filterInfo.fileTypeLabels addObject:label]; [label release]; - } - /* Check if the typevariable exists and matches one of the names */ + /* + * Check if the typevariable exists and matches one of the names. + */ + filterInfo.preselectFilter = false; filterInfo.userHasSelectedFilter = false; if (typeVariablePtr) { - /* extract the variable content as a NSString */ - Tcl_Obj *selectedFileTypeObj = Tcl_ObjGetVar2(interp, typeVariablePtr, NULL, TCL_GLOBAL_ONLY); + /* + * Extract the variable content as a NSString. + */ + + Tcl_Obj *selectedFileTypeObj = Tcl_ObjGetVar2(interp, + typeVariablePtr, NULL, TCL_GLOBAL_ONLY); + + /* + * Check that the typevariable exists. + */ - /* check that the typevariable exists */ if (selectedFileTypeObj != NULL) { - const char *selectedFileType = Tcl_GetString(selectedFileTypeObj); - NSString *selectedFileTypeStr = [[NSString alloc] initWithUTF8String:selectedFileType]; - NSUInteger index = [filterInfo.fileTypeNames indexOfObject:selectedFileTypeStr]; + const char *selectedFileType = + Tcl_GetString(selectedFileTypeObj); + NSString *selectedFileTypeStr = + [[NSString alloc] initWithUTF8String:selectedFileType]; + NSUInteger index = + [filterInfo.fileTypeNames indexOfObject:selectedFileTypeStr]; if (index != NSNotFound) { filterInfo.fileTypeIndex = index; @@ -517,17 +562,24 @@ int parseFileFilters(Tcl_Interp *interp, Tcl_Obj *fileTypesPtr, Tcl_Obj *typeVar return TCL_OK; } -bool filterCompatible(NSString *extension, int filterIndex) { - NSMutableArray *allowedExtensions = [filterInfo.fileTypeExtensions objectAtIndex: filterIndex]; +static bool +filterCompatible( + NSString *extension, + int filterIndex) +{ + NSMutableArray *allowedExtensions = + [filterInfo.fileTypeExtensions objectAtIndex: filterIndex]; + + /* + * If this contains the all pattern, accept any extension. + */ - /* If this contains the all pattern, accept any extension */ if ([[filterInfo.fileTypeAllowsAll objectAtIndex:filterIndex] boolValue]) { return true; } return [allowedExtensions containsObject: extension]; } - /* *---------------------------------------------------------------------- @@ -631,13 +683,16 @@ Tk_GetOpenFileObjCmd( if (title) { [openpanel setTitle:title]; - /* From OSX 10.11, the title string is silently ignored in the open panel. - * Prepend the title to the message in this case - * NOTE should be conditional on OSX version, but - * -mmacosx-version-min does not revert this behaviour*/ + /* + * From OSX 10.11, the title string is silently ignored in the open + * panel. Prepend the title to the message in this case. NOTE should + * be conditional on OSX version, but -mmacosx-version-min does not + * revert this behaviour + */ if (message) { - NSString *fullmessage = [[NSString alloc] initWithFormat:@"%@\n%@",title,message]; + NSString *fullmessage = + [[NSString alloc] initWithFormat:@"%@\n%@", title, message]; [message release]; [title release]; message = fullmessage; @@ -658,15 +713,20 @@ Tk_GetOpenFileObjCmd( } if (filterInfo.doFileTypes) { - NSView *accessoryView = [[NSView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 300, 32.0)]; - NSTextField *label = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 60, 22)]; + NSView *accessoryView = [[NSView alloc] + initWithFrame:NSMakeRect(0.0, 0.0, 300, 32.0)]; + NSTextField *label = [[NSTextField alloc] + initWithFrame:NSMakeRect(0, 0, 60, 22)]; + [label setEditable:NO]; [label setStringValue:@"Filter:"]; [label setBordered:NO]; [label setBezeled:NO]; [label setDrawsBackground:NO]; - NSPopUpButton *popupButton = [[NSPopUpButton alloc] initWithFrame:NSMakeRect(50.0, 2, 240, 22.0) pullsDown:NO]; + NSPopUpButton *popupButton = [[NSPopUpButton alloc] + initWithFrame:NSMakeRect(50.0, 2, 240, 22.0) pullsDown:NO]; + [popupButton addItemsWithTitles:filterInfo.fileTypeLabels]; [popupButton setAction:@selector(selectFormat:)]; @@ -674,10 +734,16 @@ Tk_GetOpenFileObjCmd( [accessoryView addSubview:popupButton]; if (filterInfo.preselectFilter) { - /* A specific filter was selected from the typevariable. Select it and - * open the accessory view */ + /* + * A specific filter was selected from the typevariable. Select it + * and open the accessory view. + */ + [popupButton selectItemAtIndex:filterInfo.fileTypeIndex]; - /* on OSX > 10.11, the optons are not visible by default. Ergo allow all file types + + /* + * On OSX > 10.11, the options are not visible by default. Ergo + * allow all file types [openpanel setAllowedFileTypes:filterInfo.fileTypeExtensions[filterInfo.fileTypeIndex]]; */ [openpanel setAllowedFileTypes:filterInfo.allowedExtensions]; @@ -693,7 +759,10 @@ Tk_GetOpenFileObjCmd( [openpanel setAccessoryView:accessoryView]; } else { - /* No filters are given. Allow picking all files */ + /* + * No filters are given. Allow picking all files. + */ + [openpanel setAllowsOtherFileTypes:YES]; } @@ -711,20 +780,24 @@ Tk_GetOpenFileObjCmd( parent = TkMacOSXDrawableWindow(((TkWindow *) tkwin)->window); if (haveParentOption && parent && ![parent attachedSheet]) { parentIsKey = [parent isKeyWindow]; - if (directory || filename ) { - NSURL * fileURL = getFileURL(directory, filename); + if (directory || filename) { + NSURL *fileURL = getFileURL(directory, filename); + [openpanel setDirectoryURL:fileURL]; } [openpanel beginSheetModalForWindow:parent - completionHandler:^(NSInteger returnCode) - { [NSApp tkFilePanelDidEnd:openpanel + completionHandler:^(NSInteger returnCode) { + [NSApp tkFilePanelDidEnd:openpanel returnCode:returnCode - contextInfo:callbackInfo ]; } ]; - modalReturnCode = cmdObj ? modalOther : [NSApp runModalForWindow:openpanel]; + contextInfo:callbackInfo ]; + }]; + modalReturnCode = cmdObj ? modalOther : + [NSApp runModalForWindow:openpanel]; } else { - if (directory || filename ) { - NSURL * fileURL = getFileURL(directory, filename); + if (directory || filename) { + NSURL *fileURL = getFileURL(directory, filename); + [openpanel setDirectoryURL:fileURL]; } @@ -737,38 +810,50 @@ Tk_GetOpenFileObjCmd( [parent makeKeyWindow]; } - if ((typeVariablePtr && (modalReturnCode == NSOKButton)) && - filterInfo.doFileTypes) { + if ((typeVariablePtr && (modalReturnCode == NSOKButton)) + && filterInfo.doFileTypes) { /* - * The -typevariable must be set to the selected file type, if the dialog was not cancelled + * The -typevariable must be set to the selected file type, if the + * dialog was not cancelled. */ + NSUInteger selectedFilterIndex = filterInfo.fileTypeIndex; NSString *selectedFilter = NULL; + if (filterInfo.userHasSelectedFilter) { selectedFilterIndex = filterInfo.fileTypeIndex; selectedFilter = [filterInfo.fileTypeNames objectAtIndex:selectedFilterIndex]; } else { - /* Difficult case: the user has not touched the filter settings, but we must - * return something in the typevariable. First check if the preselected type is compatible - * with the selected file, otherwise choose the first compatible type from the list, - * finally fall back to the empty string */ + /* + * Difficult case: the user has not touched the filter settings, + * but we must return something in the typevariable. First check if + * the preselected type is compatible with the selected file, + * otherwise choose the first compatible type from the list, + * finally fall back to the empty string. + */ + NSURL *selectedFile; + if (multiple) { - // Use the first file in the case of multiple selection - // Anyway it is not overly useful here + /* + * Use the first file in the case of multiple selection. + * Anyway it is not overly useful here. + */ selectedFile = [[openpanel URLs] objectAtIndex:0]; } else { selectedFile = [openpanel URL]; } NSString *extension = [selectedFile pathExtension]; + if (filterInfo.preselectFilter && - filterCompatible(extension, filterInfo.fileTypeIndex)) { + filterCompatible(extension, filterInfo.fileTypeIndex)) { selectedFilterIndex = filterInfo.fileTypeIndex; // The preselection from the typevariable selectedFilter = [filterInfo.fileTypeNames objectAtIndex:selectedFilterIndex]; } else { // scan the list NSUInteger i; + for (i = 0; i < [filterInfo.fileTypeNames count]; i++) { if (filterCompatible(extension, i)) { selectedFilterIndex = i; @@ -780,19 +865,17 @@ Tk_GetOpenFileObjCmd( } else { selectedFilter = @""; } - } } Tcl_ObjSetVar2(interp, typeVariablePtr, NULL, - Tcl_NewStringObj([selectedFilter UTF8String], -1), TCL_GLOBAL_ONLY); + Tcl_NewStringObj([selectedFilter UTF8String], -1), + TCL_GLOBAL_ONLY); } - end: return result; } - /* *---------------------------------------------------------------------- @@ -807,6 +890,7 @@ Tk_GetOpenFileObjCmd( * * Side effects: * See user documentation. + * *---------------------------------------------------------------------- */ @@ -828,7 +912,7 @@ Tk_GetSaveFileObjCmd( NSString *directory = nil, *filename = nil, *defaultType = nil; NSString *message = nil, *title = nil; NSWindow *parent; - savepanel = [NSSavePanel savePanel]; + savepanel = [NSSavePanel savePanel]; NSInteger modalReturnCode = modalError; BOOL parentIsKey = NO; @@ -906,13 +990,17 @@ Tk_GetSaveFileObjCmd( if (title) { [savepanel setTitle:title]; - /* From OSX 10.11, the title string is silently ignored, if the save panel is a sheet. - * Prepend the title to the message in this case - * NOTE should be conditional on OSX version, but - * -mmacosx-version-min does not revert this behaviour*/ + /* + * From OSX 10.11, the title string is silently ignored, if the save + * panel is a sheet. Prepend the title to the message in this case. + * NOTE: should be conditional on OSX version, but -mmacosx-version-min + * does not revert this behaviour. + */ + if (haveParentOption) { if (message) { - NSString *fullmessage = [[NSString alloc] initWithFormat:@"%@\n%@",title,message]; + NSString *fullmessage = + [[NSString alloc] initWithFormat:@"%@\n%@",title,message]; [message release]; [title release]; message = fullmessage; @@ -932,15 +1020,20 @@ Tk_GetSaveFileObjCmd( } if (filterInfo.doFileTypes) { - NSView *accessoryView = [[NSView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 300, 32.0)]; - NSTextField *label = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 60, 22)]; + NSView *accessoryView = [[NSView alloc] + initWithFrame:NSMakeRect(0.0, 0.0, 300, 32.0)]; + NSTextField *label = [[NSTextField alloc] + initWithFrame:NSMakeRect(0, 0, 60, 22)]; + [label setEditable:NO]; [label setStringValue:NSLocalizedString(@"Format:", nil)]; [label setBordered:NO]; [label setBezeled:NO]; [label setDrawsBackground:NO]; - NSPopUpButton *popupButton = [[NSPopUpButton alloc] initWithFrame:NSMakeRect(50.0, 2, 340, 22.0) pullsDown:NO]; + NSPopUpButton *popupButton = [[NSPopUpButton alloc] + initWithFrame:NSMakeRect(50.0, 2, 340, 22.0) pullsDown:NO]; + [popupButton addItemsWithTitles:filterInfo.fileTypeLabels]; [popupButton selectItemAtIndex:filterInfo.fileTypeIndex]; [popupButton setAction:@selector(saveFormat:)]; @@ -953,10 +1046,14 @@ Tk_GetSaveFileObjCmd( [savepanel setAllowedFileTypes:[filterInfo.fileTypeExtensions objectAtIndex:filterInfo.fileTypeIndex]]; [savepanel setAllowsOtherFileTypes:filterInfo.allowedExtensionsAllowAll]; } else if (defaultType) { - /* If no filetypes are given, defaultextension is an alternative way - * to specify the attached extension. Just propose this extension, - * but don't display an accessory view */ + /* + * If no filetypes are given, defaultextension is an alternative way to + * specify the attached extension. Just propose this extension, but + * don't display an accessory view. + */ + NSMutableArray *AllowedFileTypes = [NSMutableArray array]; + [AllowedFileTypes addObject:defaultType]; [savepanel setAllowedFileTypes:AllowedFileTypes]; [savepanel setAllowsOtherFileTypes:YES]; @@ -978,27 +1075,39 @@ Tk_GetSaveFileObjCmd( parent = TkMacOSXDrawableWindow(((TkWindow *) tkwin)->window); if (haveParentOption && parent && ![parent attachedSheet]) { - parentIsKey = [parent isKeyWindow]; - if (directory) { + parentIsKey = [parent isKeyWindow]; + if (directory) { [savepanel setDirectoryURL:[NSURL fileURLWithPath:directory isDirectory:YES]]; } - /*check for file name, otherwise set to empty string; crashes with uncaught exception if set to nil*/ + + /* + * Check for file name, otherwise set to empty string; crashes with + * uncaught exception if set to nil. + */ + if (filename) { [savepanel setNameFieldStringValue:filename]; } else { [savepanel setNameFieldStringValue:@""]; } [savepanel beginSheetModalForWindow:parent - completionHandler:^(NSInteger returnCode) - { [NSApp tkFilePanelDidEnd:savepanel + completionHandler:^(NSInteger returnCode) { + [NSApp tkFilePanelDidEnd:savepanel returnCode:returnCode - contextInfo:callbackInfo ]; } ]; - modalReturnCode = cmdObj ? modalOther : [NSApp runModalForWindow:savepanel]; + contextInfo:callbackInfo]; + }]; + modalReturnCode = cmdObj ? modalOther : + [NSApp runModalForWindow:savepanel]; } else { if (directory) { [savepanel setDirectoryURL:[NSURL fileURLWithPath:directory isDirectory:YES]]; } - /*check for file name, otherwise set to empty string; crashes with uncaught exception if set to nil*/ + + /* + * Check for file name, otherwise set to empty string; crashes with + * uncaught exception if set to nil. + */ + if (filename) { [savepanel setNameFieldStringValue:filename]; } else { @@ -1013,16 +1122,20 @@ Tk_GetSaveFileObjCmd( [parent makeKeyWindow]; } - if ((typeVariablePtr && (modalReturnCode == NSOKButton)) && filterInfo.doFileTypes) { + if (typeVariablePtr && (modalReturnCode == NSOKButton) + && filterInfo.doFileTypes) { /* - * The -typevariable must be set to the selected file type, if the dialog was not cancelled + * The -typevariable must be set to the selected file type, if the + * dialog was not cancelled. */ - NSString * selectedFilter = [filterInfo.fileTypeNames objectAtIndex:filterInfo.fileTypeIndex]; + + NSString *selectedFilter = + [filterInfo.fileTypeNames objectAtIndex:filterInfo.fileTypeIndex]; Tcl_ObjSetVar2(interp, typeVariablePtr, NULL, - Tcl_NewStringObj([selectedFilter UTF8String], -1), TCL_GLOBAL_ONLY); + Tcl_NewStringObj([selectedFilter UTF8String], -1), + TCL_GLOBAL_ONLY); } - end: return result; } @@ -1130,7 +1243,12 @@ Tk_ChooseDirectoryObjCmd( callbackInfo->cmdObj = cmdObj; callbackInfo->interp = interp; callbackInfo->multiple = 0; - /*check for directory value, set to root if not specified; otherwise crashes with exception because of nil string parameter*/ + + /* + * Check for directory value, set to root if not specified; otherwise + * crashes with exception because of nil string parameter. + */ + if (!directory) { directory = @"/"; } @@ -1139,10 +1257,11 @@ Tk_ChooseDirectoryObjCmd( parentIsKey = [parent isKeyWindow]; [panel setDirectoryURL:[NSURL fileURLWithPath:directory isDirectory:YES]]; [panel beginSheetModalForWindow:parent - completionHandler:^(NSInteger returnCode) - { [NSApp tkFilePanelDidEnd:panel - returnCode:returnCode - contextInfo:callbackInfo ]; } ]; + completionHandler:^(NSInteger returnCode) { + [NSApp tkFilePanelDidEnd:panel + returnCode:returnCode + contextInfo:callbackInfo]; + }]; modalReturnCode = cmdObj ? modalOther : [NSApp runModalForWindow:panel]; } else { [panel setDirectoryURL:[NSURL fileURLWithPath:directory isDirectory:YES]]; @@ -1201,11 +1320,12 @@ TkAboutDlg(void) */ NSString *version = @"Tcl " TCL_PATCH_LEVEL " & Tk " TCL_PATCH_LEVEL; - NSString *url = @"www.tcl-lang.org"; + NSString *url = @"www.tcl-lang.org"; NSTextView *credits = [[NSTextView alloc] initWithFrame:NSMakeRect(0,0,300,300)]; NSFont *font = [NSFont systemFontOfSize:[NSFont systemFontSize]]; NSDictionary *textAttributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName]; + [credits insertText: [[NSAttributedString alloc] initWithString:[NSString stringWithFormat: @"\n" "Tcl and Tk are distributed under a modified BSD license: " @@ -1219,11 +1339,13 @@ TkAboutDlg(void) "%1$C 1998-2000 Jim Ingham & Ray Johnson\n\n" "%1$C 1998-2000 Scriptics Inc.\n\n" "%1$C 1996-1997 Sun Microsystems Inc.", 0xA9, year] - attributes:textAttributes] - replacementRange:NSMakeRange(0,0)]; + attributes:textAttributes] + replacementRange:NSMakeRange(0,0)]; [credits setDrawsBackground:NO]; [credits setEditable:NO]; - NSAlert *about = [[NSAlert alloc] init]; + + NSAlert *about = [[NSAlert alloc] init]; + [[about window] setTitle:@"About Tcl & Tk"]; [about setMessageText: version]; [about setInformativeText:url]; @@ -1378,7 +1500,8 @@ Tk_MessageBoxObjCmd( */ if (Tcl_GetIndexFromObjStruct(interp, objv[indexDefaultOption + 1], - alertButtonStrings, sizeof(char *), "-default value", TCL_EXACT, &index) != TCL_OK) { + alertButtonStrings, sizeof(char *), "-default value", + TCL_EXACT, &index) != TCL_OK) { goto end; } @@ -1399,7 +1522,7 @@ Tk_MessageBoxObjCmd( [alert setAlertStyle:alertStyles[iconIndex]]; i = 0; while (i < 3 && alertButtonNames[typeIndex][i]) { - [alert addButtonWithTitle:(NSString*)alertButtonNames[typeIndex][i++]]; + [alert addButtonWithTitle:(NSString*) alertButtonNames[typeIndex][i++]]; } buttons = [alert buttons]; for (NSButton *b in buttons) { @@ -1428,10 +1551,11 @@ Tk_MessageBoxObjCmd( parentIsKey = [parent isKeyWindow]; #if MAC_OS_X_VERSION_MIN_REQUIRED > 1090 [alert beginSheetModalForWindow:parent - completionHandler:^(NSModalResponse returnCode) - { [NSApp tkAlertDidEnd:alert - returnCode:returnCode - contextInfo:callbackInfo ]; } ]; + completionHandler:^(NSModalResponse returnCode) { + [NSApp tkAlertDidEnd:alert + returnCode:returnCode + contextInfo:callbackInfo]; + }]; #else [alert beginSheetModalForWindow:parent modalDelegate:NSApp @@ -1471,7 +1595,10 @@ typedef struct FontchooserData { Tk_Window parent; } FontchooserData; -enum FontchooserEvent { FontchooserClosed, FontchooserSelection }; +enum FontchooserEvent { + FontchooserClosed, + FontchooserSelection +}; static void FontchooserEvent(int kind); static Tcl_Obj * FontchooserCget(FontchooserData *fcdPtr, @@ -1563,8 +1690,8 @@ enum FontchooserOption { * * FontchooserEvent -- * - * This processes events generated by user interaction with the - * font panel. + * This processes events generated by user interaction with the font + * panel. * * Results: * None. @@ -1623,9 +1750,8 @@ FontchooserEvent( * * FontchooserCget -- * - * Helper for the FontchooserConfigure command to return the - * current value of any of the options (which may be NULL in - * the structure) + * Helper for the FontchooserConfigure command to return the current value + * of any of the options (which may be NULL in the structure). * * Results: * Tcl object of option value. @@ -1688,8 +1814,8 @@ FontchooserCget( * * FontchooserConfigureCmd -- * - * Implementation of the 'tk fontchooser configure' ensemble command. - * See the user documentation for what it does. + * Implementation of the 'tk fontchooser configure' ensemble command. See + * the user documentation for what it does. * * Results: * See the user documentation. @@ -1822,7 +1948,8 @@ FontchooserConfigureCmd( [fm setSelectedAttributes:fontPanelFontAttributes isMultiple:NO]; if ([fp isVisible]) { - TkSendVirtualEvent(fcdPtr->parent, "TkFontchooserFontChanged", NULL); + TkSendVirtualEvent(fcdPtr->parent, + "TkFontchooserFontChanged", NULL); } break; case FontchooserCmd: @@ -1850,9 +1977,9 @@ FontchooserConfigureCmd( * * FontchooserShowCmd -- * - * Implements the 'tk fontchooser show' ensemble command. The - * per-interp configuration data for the dialog is held in an interp - * associated structure. + * Implements the 'tk fontchooser show' ensemble command. The per-interp + * configuration data for the dialog is held in an interp associated + * structure. * * Results: * See the user documentation. @@ -1878,8 +2005,10 @@ FontchooserShowCmd( Tk_CreateEventHandler(fcdPtr->parent, StructureNotifyMask, FontchooserParentEventHandler, fcdPtr); } + NSFontManager *fm = [NSFontManager sharedFontManager]; NSFontPanel *fp = [fm fontPanel:YES]; + if ([fp delegate] != NSApp) { [fp setDelegate:NSApp]; } @@ -1897,8 +2026,8 @@ FontchooserShowCmd( * * FontchooserHideCmd -- * - * Implementation of the 'tk fontchooser hide' ensemble. See the - * user documentation for details. + * Implementation of the 'tk fontchooser hide' ensemble. See the user + * documentation for details. * * Results: * See the user documentation. @@ -1917,6 +2046,7 @@ FontchooserHideCmd( Tcl_Obj *const objv[]) { NSFontPanel *fp = [[NSFontManager sharedFontManager] fontPanel:NO]; + if ([fp isVisible]) { [fp orderOut:NSApp]; } @@ -1997,8 +2127,8 @@ DeleteFontchooserData( * * TkInitFontchooser -- * - * Associate the font chooser configuration data with the Tcl - * interpreter. There is one font chooser per interp. + * Associate the font chooser configuration data with the Tcl interpreter. + * There is one font chooser per interp. * * Results: * None. diff --git a/macosx/tkMacOSXDraw.c b/macosx/tkMacOSXDraw.c index faad137..dceb3a6 100644 --- a/macosx/tkMacOSXDraw.c +++ b/macosx/tkMacOSXDraw.c @@ -1,9 +1,8 @@ /* * tkMacOSXDraw.c -- * - * This file contains functions that perform drawing to - * Xlib windows. Most of the functions simple emulate - * Xlib functions. + * This file contains functions that perform drawing to Xlib windows. Most + * of the functions simple emulate Xlib functions. * * Copyright (c) 1995-1997 Sun Microsystems, Inc. * Copyright 2001-2009, Apple Inc. @@ -31,7 +30,7 @@ #endif */ -#define radians(d) ((d) * (M_PI/180.0)) +#define radians(d) ((d) * (M_PI/180.0)) /* * Non-antialiased CG drawing looks better and more like X11 drawing when using @@ -40,7 +39,7 @@ #define NON_AA_CG_OFFSET .999 static int cgAntiAliasLimit = 0; -#define notAA(w) ((w) < cgAntiAliasLimit) +#define notAA(w) ((w) < cgAntiAliasLimit) static int useThemedToplevel = 0; static int useThemedFrame = 0; @@ -119,24 +118,24 @@ TkMacOSXInitCGDrawing( * replacement is [NSView cacheDisplayInRect: toBitmapImageRep:] and that * is what is being used here. However, that method only works when the * view has a valid CGContext, and a view is only guaranteed to have a - * valid context during a call to [NSView drawRect]. To further - * complicate matters, cacheDisplayInRect calls [NSView drawRect]. - * Essentially it is asking the view to draw a subrectangle of itself into - * a special graphics context which is linked to the BitmapImageRep. But - * our implementation of [NSView drawRect] does not allow recursive calls. - * If called recursively it returns immediately without doing any drawing. + * valid context during a call to [NSView drawRect]. To further complicate + * matters, cacheDisplayInRect calls [NSView drawRect]. Essentially it is + * asking the view to draw a subrectangle of itself into a special + * graphics context which is linked to the BitmapImageRep. But our + * implementation of [NSView drawRect] does not allow recursive calls. If + * called recursively it returns immediately without doing any drawing. * So the bottom line is that this function either returns a NULL pointer - * or a black image. To make it useful would require a significant amount - * of rewriting of the drawRect method. Perhaps the next release of OSX + * or a black image. To make it useful would require a significant amount + * of rewriting of the drawRect method. Perhaps the next release of OSX * will include some more helpful ways of doing this. * * Results: - * Returns an NSBitmapRep representing the image of the given - * rectangle of the given drawable. This object is retained. - * The caller is responsible for releasing it. + * Returns an NSBitmapRep representing the image of the given rectangle of + * the given drawable. This object is retained. The caller is responsible + * for releasing it. * - * NOTE: The x,y coordinates should be relative to a coordinate system with - * origin at the top left, as used by XImage and CGImage, not bottom + * NOTE: The x,y coordinates should be relative to a coordinate system + * with origin at the top left, as used by XImage and CGImage, not bottom * left as used by NSView. * * Side effects: @@ -144,46 +143,46 @@ TkMacOSXInitCGDrawing( * *---------------------------------------------------------------------- */ -NSBitmapImageRep* + +NSBitmapImageRep * TkMacOSXBitmapRepFromDrawableRect( - Drawable drawable, - int x, - int y, - unsigned int width, - unsigned int height) + Drawable drawable, + int x, + int y, + unsigned int width, + unsigned int height) { MacDrawable *mac_drawable = (MacDrawable *) drawable; CGContextRef cg_context = NULL; - CGImageRef cg_image=NULL, sub_cg_image = NULL; + CGImageRef cg_image = NULL, sub_cg_image = NULL; NSBitmapImageRep *bitmap_rep = NULL; - NSView *view=NULL; - if ( mac_drawable->flags & TK_IS_PIXMAP ) { - + NSView *view = NULL; + if (mac_drawable->flags & TK_IS_PIXMAP) { /* * This MacDrawable is a bitmap, so its view is NULL. */ - cg_context = TkMacOSXGetCGContextForDrawable(drawable); CGRect image_rect = CGRectMake(x, y, width, height); - cg_image = CGBitmapContextCreateImage( (CGContextRef) cg_context); + + cg_context = TkMacOSXGetCGContextForDrawable(drawable); + cg_image = CGBitmapContextCreateImage((CGContextRef) cg_context); sub_cg_image = CGImageCreateWithImageInRect(cg_image, image_rect); - if ( sub_cg_image ) { + if (sub_cg_image) { bitmap_rep = [NSBitmapImageRep alloc]; [bitmap_rep initWithCGImage:sub_cg_image]; } - if ( cg_image ) { + if (cg_image) { CGImageRelease(cg_image); } - } else if ( (view = TkMacOSXDrawableView(mac_drawable)) ) { - + } else if ((view = TkMacOSXDrawableView(mac_drawable)) != NULL) { /* * Convert Tk top-left to NSView bottom-left coordinates. */ int view_height = [view bounds].size.height; NSRect view_rect = NSMakeRect(x + mac_drawable->xOff, - view_height - height - y - mac_drawable->yOff, - width, height); + view_height - height - y - mac_drawable->yOff, + width, height); /* * Attempt to copy from the view to a bitmapImageRep. If the view does @@ -218,8 +217,7 @@ TkMacOSXBitmapRepFromDrawableRect( * None. * * Side effects: - * Data is moved from a window or bitmap to a second window or - * bitmap. + * Data is moved from a window or bitmap to a second window or bitmap. * *---------------------------------------------------------------------- */ @@ -229,10 +227,10 @@ XCopyArea( Display *display, /* Display. */ Drawable src, /* Source drawable. */ Drawable dst, /* Destination drawable. */ - GC gc, /* GC to use. */ + GC gc, /* GC to use. */ int src_x, /* X & Y, width & height */ int src_y, /* define the source rectangle */ - unsigned int width, /* that will be copied. */ + unsigned int width, /* that will be copied. */ unsigned int height, int dest_x, /* Dest X & Y on dest rect. */ int dest_y) @@ -249,37 +247,36 @@ XCopyArea( } if (!TkMacOSXSetupDrawingContext(dst, gc, 1, &dc)) { - return; TkMacOSXDbgMsg("Failed to setup drawing context."); + return; } - if ( dc.context ) { - if (srcDraw->flags & TK_IS_PIXMAP) { - img = TkMacOSXCreateCGImageWithDrawable(src); - }else if (TkMacOSXDrawableWindow(src)) { - bitmap_rep = TkMacOSXBitmapRepFromDrawableRect(src, - src_x, src_y, width, height); - if ( bitmap_rep ) { - img = [bitmap_rep CGImage]; - } - } else { - TkMacOSXDbgMsg("Invalid source drawable - neither window nor pixmap."); - } + if (!dc.context) { + TkMacOSXDbgMsg("Invalid destination drawable - no context."); + return; + } - if (img) { - bounds = CGRectMake(0, 0, srcDraw->size.width, srcDraw->size.height); - srcRect = CGRectMake(src_x, src_y, width, height); - dstRect = CGRectMake(dest_x, dest_y, width, height); - TkMacOSXDrawCGImage(dst, gc, dc.context, img, - gc->foreground, gc->background, bounds, srcRect, dstRect); - CFRelease(img); - } else { - TkMacOSXDbgMsg("Failed to construct CGImage."); + if (srcDraw->flags & TK_IS_PIXMAP) { + img = TkMacOSXCreateCGImageWithDrawable(src); + } else if (TkMacOSXDrawableWindow(src)) { + bitmap_rep = TkMacOSXBitmapRepFromDrawableRect(src, + src_x, src_y, width, height); + if (bitmap_rep) { + img = [bitmap_rep CGImage]; } + } else { + TkMacOSXDbgMsg("Invalid source drawable - neither window nor pixmap."); + } + if (img) { + bounds = CGRectMake(0, 0, srcDraw->size.width, srcDraw->size.height); + srcRect = CGRectMake(src_x, src_y, width, height); + dstRect = CGRectMake(dest_x, dest_y, width, height); + TkMacOSXDrawCGImage(dst, gc, dc.context, img, + gc->foreground, gc->background, bounds, srcRect, dstRect); + CFRelease(img); } else { - TkMacOSXDbgMsg("Invalid destination drawable - no context."); - return; + TkMacOSXDbgMsg("Failed to construct CGImage."); } TkMacOSXRestoreDrawingContext(&dc); @@ -290,10 +287,9 @@ XCopyArea( * * XCopyPlane -- * - * Copies a bitmap from a source drawable to a destination - * drawable. The plane argument specifies which bit plane of - * the source contains the bitmap. Note that this implementation - * ignores the gc->function. + * Copies a bitmap from a source drawable to a destination drawable. The + * plane argument specifies which bit plane of the source contains the + * bitmap. Note that this implementation ignores the gc->function. * * Results: * None. @@ -334,29 +330,50 @@ XCopyPlane( if (!TkMacOSXSetupDrawingContext(dst, gc, 1, &dc)) { return; } + CGContextRef context = dc.context; + if (context) { CGImageRef img = TkMacOSXCreateCGImageWithDrawable(src); + if (img) { TkpClipMask *clipPtr = (TkpClipMask *) gc->clip_mask; unsigned long imageBackground = gc->background; - if (clipPtr && clipPtr->type == TKP_CLIP_PIXMAP){ + + if (clipPtr && clipPtr->type == TKP_CLIP_PIXMAP) { srcRect = CGRectMake(src_x, src_y, width, height); - CGImageRef mask = TkMacOSXCreateCGImageWithDrawable(clipPtr->value.pixmap); - CGImageRef submask = CGImageCreateWithImageInRect(img, srcRect); + CGImageRef mask = TkMacOSXCreateCGImageWithDrawable( + clipPtr->value.pixmap); + CGImageRef submask = CGImageCreateWithImageInRect( + img, srcRect); CGRect rect = CGRectMake(dest_x, dest_y, width, height); + rect = CGRectOffset(rect, dstDraw->xOff, dstDraw->yOff); CGContextSaveGState(context); - /* Move the origin of the destination to top left. */ - CGContextTranslateCTM(context, 0, rect.origin.y + CGRectGetMaxY(rect)); + + /* + * Move the origin of the destination to top left. + */ + + CGContextTranslateCTM(context, + 0, rect.origin.y + CGRectGetMaxY(rect)); CGContextScaleCTM(context, 1, -1); - /* Fill with the background color, clipping to the mask. */ + + /* + * Fill with the background color, clipping to the mask. + */ + CGContextClipToMask(context, rect, submask); TkMacOSXSetColorInContext(gc, gc->background, dc.context); CGContextFillRect(context, rect); - /* Fill with the foreground color, clipping to the - intersection of img and mask. */ - CGImageRef subimage = CGImageCreateWithImageInRect(img, srcRect); + + /* + * Fill with the foreground color, clipping to the + * intersection of img and mask. + */ + + CGImageRef subimage = CGImageCreateWithImageInRect( + img, srcRect); CGContextClipToMask(context, rect, subimage); TkMacOSXSetColorInContext(gc, gc->foreground, context); CGContextFillRect(context, rect); @@ -366,22 +383,31 @@ XCopyPlane( CGImageRelease(submask); CGImageRelease(subimage); } else { - bounds = CGRectMake(0, 0, srcDraw->size.width, srcDraw->size.height); + bounds = CGRectMake(0, 0, + srcDraw->size.width, srcDraw->size.height); srcRect = CGRectMake(src_x, src_y, width, height); dstRect = CGRectMake(dest_x, dest_y, width, height); - TkMacOSXDrawCGImage(dst, gc, dc.context, img, gc->foreground, - imageBackground, bounds, srcRect, dstRect); + TkMacOSXDrawCGImage(dst, gc, dc.context, img, + gc->foreground, imageBackground, bounds, + srcRect, dstRect); CGImageRelease(img); } - } else { /* no image */ + } else { + /* no image */ TkMacOSXDbgMsg("Invalid source drawable"); } } else { - TkMacOSXDbgMsg("Invalid destination drawable - could not get a bitmap context."); + TkMacOSXDbgMsg("Invalid destination drawable - " + "could not get a bitmap context."); } TkMacOSXRestoreDrawingContext(&dc); - } else { /* source drawable is a window, not a Pixmap */ - XCopyArea(display, src, dst, gc, src_x, src_y, width, height, dest_x, dest_y); + } else { + /* + * Source drawable is a Window, not a Pixmap. + */ + + XCopyArea(display, src, dst, gc, src_x, src_y, width, height, + dest_x, dest_y); } } @@ -430,7 +456,7 @@ TkMacOSXCreateCGImageWithDrawable( *---------------------------------------------------------------------- */ -static NSImage* +static NSImage * CreateNSImageWithPixmap( Pixmap pixmap, int width, @@ -466,7 +492,7 @@ CreateNSImageWithPixmap( *---------------------------------------------------------------------- */ -NSImage* +NSImage * TkMacOSXGetNSImageWithTkImage( Display *display, Tk_Image image, @@ -499,7 +525,7 @@ TkMacOSXGetNSImageWithTkImage( *---------------------------------------------------------------------- */ -NSImage* +NSImage * TkMacOSXGetNSImageWithBitmap( Display *display, Pixmap bitmap, @@ -550,23 +576,24 @@ TkMacOSXGetCGContextForDrawable( CGColorSpaceRef colorspace = NULL; CGBitmapInfo bitmapInfo = #ifdef __LITTLE_ENDIAN__ - kCGBitmapByteOrder32Host; + kCGBitmapByteOrder32Host; #else - kCGBitmapByteOrderDefault; + kCGBitmapByteOrderDefault; #endif char *data; - CGRect bounds = CGRectMake(0, 0, macDraw->size.width, macDraw->size.height); + CGRect bounds = CGRectMake(0, 0, + macDraw->size.width, macDraw->size.height); if (macDraw->flags & TK_IS_BW_PIXMAP) { bitsPerPixel = 8; - bitmapInfo = (CGBitmapInfo)kCGImageAlphaOnly; + bitmapInfo = (CGBitmapInfo) kCGImageAlphaOnly; } else { colorspace = CGColorSpaceCreateDeviceRGB(); bitsPerPixel = 32; bitmapInfo |= kCGImageAlphaPremultipliedFirst; } - bytesPerRow = ((size_t) macDraw->size.width * bitsPerPixel + 127) >> 3 - & ~15; + bytesPerRow = ((size_t) + macDraw->size.width * bitsPerPixel + 127) >> 3 & ~15; len = macDraw->size.height * bytesPerRow; data = ckalloc(len); bzero(data, len); @@ -630,8 +657,8 @@ TkMacOSXDrawCGImage( dstBounds = CGRectOffset(dstBounds, macDraw->xOff, macDraw->yOff); if (CGImageIsMask(image)) { if (macDraw->flags & TK_IS_BW_PIXMAP) { - - /* Set fill color to black; background comes from the context, + /* + * Set fill color to black; background comes from the context, * or is transparent. */ @@ -655,11 +682,13 @@ TkMacOSXDrawCGImage( CGContextSetRGBFillColor(context, 0, 1, 0, 0.1); CGContextFillRect(context, dstBounds); CGContextStrokeRect(context, dstBounds); + CGPoint p[4] = {dstBounds.origin, CGPointMake(CGRectGetMaxX(dstBounds), CGRectGetMaxY(dstBounds)), CGPointMake(CGRectGetMinX(dstBounds), CGRectGetMaxY(dstBounds)), CGPointMake(CGRectGetMaxX(dstBounds), CGRectGetMinY(dstBounds)) }; + CGContextStrokeLineSegments(context, p, 4); CGContextRestoreGState(context); TkMacOSXDbgMsg("Drawing CGImage at (x=%f, y=%f), (w=%f, h=%f)", @@ -736,12 +765,13 @@ XDrawLines( CGContextAddLineToPoint(dc.context, prevx, prevy); } } + /* - * In the case of closed polylines, the first and last points - * are the same. We want miter or bevel join be rendered also - * at this point, this needs telling CoreGraphics that the - * path is closed. + * In the case of closed polylines, the first and last points are the + * same. We want miter or bevel join be rendered also at this point, + * this needs telling CoreGraphics that the path is closed. */ + if ((points[0].x == points[npoints-1].x) && (points[0].y == points[npoints-1].y)) { CGContextClosePath(dc.context); @@ -820,10 +850,10 @@ XDrawSegments( void XFillPolygon( - Display* display, /* Display. */ + Display *display, /* Display. */ Drawable d, /* Draw on this. */ GC gc, /* Use this GC. */ - XPoint* points, /* Array of points. */ + XPoint *points, /* Array of points. */ int npoints, /* Number of points. */ int shape, /* Shape to draw. */ int mode) /* Drawing mode. */ @@ -902,8 +932,7 @@ XDrawRectangle( double o = (lw % 2) ? .5 : 0; rect = CGRectMake( - macWin->xOff + x + o, - macWin->yOff + y + o, + macWin->xOff + x + o, macWin->yOff + y + o, width, height); CGContextStrokeRect(dc.context, rect); } @@ -916,17 +945,15 @@ XDrawRectangle( * * XDrawRectangles -- * - * Draws the outlines of the specified rectangles as if a - * five-point PolyLine protocol request were specified for each - * rectangle: + * Draws the outlines of the specified rectangles as if a five-point + * PolyLine protocol request were specified for each rectangle: * * [x,y] [x+width,y] [x+width,y+height] [x,y+height] [x,y] * - * For the specified rectangles, these functions do not draw a - * pixel more than once. XDrawRectangles draws the rectangles in - * the order listed in the array. If rectangles intersect, the - * intersecting pixels are drawn multiple times. Draws a - * rectangle. + * For the specified rectangles, these functions do not draw a pixel more + * than once. XDrawRectangles draws the rectangles in the order listed in + * the array. If rectangles intersect, the intersecting pixels are drawn + * multiple times. Draws a rectangle. * * Results: * None. @@ -991,7 +1018,7 @@ XDrawRectangles( int XFillRectangles( - Display* display, /* Display. */ + Display *display, /* Display. */ Drawable d, /* Draw on this. */ GC gc, /* Use this GC. */ XRectangle *rectangles, /* Rectangle array. */ @@ -1042,7 +1069,7 @@ XFillRectangles( void XDrawArc( - Display* display, /* Display. */ + Display *display, /* Display. */ Drawable d, /* Draw on this. */ GC gc, /* Use this GC. */ int x, int y, /* Upper left of bounding rect. */ @@ -1099,14 +1126,13 @@ XDrawArc( * * XDrawArcs -- * - * Draws multiple circular or elliptical arcs. Each arc is - * specified by a rectangle and two angles. The center of the - * circle or ellipse is the center of the rect- angle, and the - * major and minor axes are specified by the width and height. - * Positive angles indicate counterclock- wise motion, and - * negative angles indicate clockwise motion. If the magnitude - * of angle2 is greater than 360 degrees, XDrawArcs truncates it - * to 360 degrees. + * Draws multiple circular or elliptical arcs. Each arc is specified by a + * rectangle and two angles. The center of the circle or ellipse is the + * center of the rect- angle, and the major and minor axes are specified + * by the width and height. Positive angles indicate counterclock- wise + * motion, and negative angles indicate clockwise motion. If the magnitude + * of angle2 is greater than 360 degrees, XDrawArcs truncates it to 360 + * degrees. * * Results: * None. @@ -1125,7 +1151,6 @@ XDrawArcs( XArc *arcArr, int nArcs) { - MacDrawable *macWin = (MacDrawable *) d; TkMacOSXDrawingContext dc; XArc *arcPtr; @@ -1195,7 +1220,7 @@ XDrawArcs( void XFillArc( - Display* display, /* Display. */ + Display *display, /* Display. */ Drawable d, /* Draw on this. */ GC gc, /* Use this GC. */ int x, int y, /* Upper left of bounding rect. */ @@ -1360,13 +1385,12 @@ XMaxRequestSize( * * TkScrollWindow -- * - * Scroll a rectangle of the specified window and accumulate - * a damage region. + * Scroll a rectangle of the specified window and accumulate a damage + * region. * * Results: - * Returns 0 if the scroll generated no additional damage. - * Otherwise, sets the region that needs to be repainted after - * scrolling and returns 1. + * Returns 0 if the scroll generated no additional damage. Otherwise, sets + * the region that needs to be repainted after scrolling and returns 1. * * Side effects: * Scrolls the bits in the window. @@ -1385,47 +1409,63 @@ TkScrollWindow( { Drawable drawable = Tk_WindowId(tkwin); MacDrawable *macDraw = (MacDrawable *) drawable; - TKContentView *view = (TKContentView *)TkMacOSXDrawableView(macDraw); + TKContentView *view = (TKContentView *) TkMacOSXDrawableView(macDraw); CGRect srcRect, dstRect; HIShapeRef dmgRgn = NULL, extraRgn = NULL; NSRect bounds, visRect, scrollSrc, scrollDst; int result = 0; - if ( view ) { - /* Get the scroll area in NSView coordinates (origin at bottom left). */ + if (view) { + /* + * Get the scroll area in NSView coordinates (origin at bottom left). + */ + bounds = [view bounds]; scrollSrc = NSMakeRect(macDraw->xOff + x, - bounds.size.height - height - (macDraw->yOff + y), - width, height); + bounds.size.height - height - (macDraw->yOff + y), + width, height); scrollDst = NSOffsetRect(scrollSrc, dx, -dy); - /* Limit scrolling to the window content area. */ + /* + * Limit scrolling to the window content area. + */ + visRect = [view visibleRect]; scrollSrc = NSIntersectionRect(scrollSrc, visRect); scrollDst = NSIntersectionRect(scrollDst, visRect); - if ( !NSIsEmptyRect(scrollSrc) && !NSIsEmptyRect(scrollDst) ) { + if (!NSIsEmptyRect(scrollSrc) && !NSIsEmptyRect(scrollDst)) { /* * Mark the difference between source and destination as damaged. - * This region is described in NSView coordinates (y=0 at the bottom) - * and converted to Tk coordinates later. + * This region is described in NSView coordinates (y=0 at the + * bottom) and converted to Tk coordinates later. */ srcRect = CGRectMake(x, y, width, height); dstRect = CGRectOffset(srcRect, dx, dy); - /* Compute the damage. */ + /* + * Compute the damage. + */ + dmgRgn = HIShapeCreateMutableWithRect(&srcRect); extraRgn = HIShapeCreateWithRect(&dstRect); - ChkErr(HIShapeDifference, dmgRgn, extraRgn, (HIMutableShapeRef) dmgRgn); + ChkErr(HIShapeDifference, dmgRgn, extraRgn, + (HIMutableShapeRef) dmgRgn); result = HIShapeIsEmpty(dmgRgn) ? 0 : 1; - /* Convert to Tk coordinates, offset by the window origin. */ + /* + * Convert to Tk coordinates, offset by the window origin. + */ + TkMacOSXSetWithNativeRegion(damageRgn, dmgRgn); if (extraRgn) { CFRelease(extraRgn); } - /* Scroll the rectangle. */ + /* + * Scroll the rectangle. + */ + [view scrollRect:scrollSrc by:NSMakeSize(dx, -dy)]; } } else { @@ -1472,8 +1512,8 @@ TkMacOSXSetUpGraphicsPort( * Set up a drawing context for the given drawable and GC. * * Results: - * Boolean indicating whether it is ok to draw; if false, drawing - * context was not setup, so do not attempt to draw and do not call + * Boolean indicating whether it is ok to draw; if false, drawing context + * was not setup, so do not attempt to draw and do not call * TkMacOSXRestoreDrawingContext(). * * Side effects: @@ -1486,18 +1526,18 @@ Bool TkMacOSXSetupDrawingContext( Drawable d, GC gc, - int useCG, /* advisory only ! */ + int useCG, /* advisory only ! */ TkMacOSXDrawingContext *dcPtr) { - MacDrawable *macDraw = ((MacDrawable*)d); + MacDrawable *macDraw = (MacDrawable *) d; Bool canDraw = true; NSWindow *win = NULL; TkMacOSXDrawingContext dc = {}; CGRect clipBounds; /* - * If the drawable is not a pixmap and it has an associated - * NSWindow then we know we are drawing to a window. + * If the drawable is not a pixmap and it has an associated NSWindow then + * we know we are drawing to a window. */ if (!(macDraw->flags & TK_IS_PIXMAP)) { @@ -1516,9 +1556,8 @@ TkMacOSXSetupDrawingContext( } /* - * If we already have a CGContext, use it. Otherwise, if we - * are drawing to a window then we can get one from the - * window. + * If we already have a CGContext, use it. Otherwise, if we are drawing to + * a window then we can get one from the window. */ dc.context = TkMacOSXGetCGContextForDrawable(d); @@ -1526,35 +1565,34 @@ TkMacOSXSetupDrawingContext( dc.portBounds = clipBounds = CGContextGetClipBoundingBox(dc.context); } else if (win) { NSView *view = TkMacOSXDrawableView(macDraw); - if (view) { - - /* - * We can only draw into the view when the current CGContext is - * valid and belongs to the view. Validity can only be guaranteed - * inside of a view's drawRect or setFrame methods. The isDrawing - * attribute tells us whether we are being called from one of those - * methods. - * - * If the CGContext is not valid, or belongs to a different View, - * then we mark our view as needing display and return failure. - * It should get drawn in a later call to drawRect. - */ - if (view != [NSView focusView]) { - [view setNeedsDisplay:YES]; - canDraw = false; - goto end; - } - dc.view = view; - dc.context = GET_CGCONTEXT; - dc.portBounds = NSRectToCGRect([view bounds]); - if (dc.clipRgn) { - clipBounds = CGContextGetClipBoundingBox(dc.context); - } - } else { + if (!view) { Tcl_Panic("TkMacOSXSetupDrawingContext(): " "no NSView to draw into !"); } + + /* + * We can only draw into the view when the current CGContext is valid + * and belongs to the view. Validity can only be guaranteed inside of + * a view's drawRect or setFrame methods. The isDrawing attribute + * tells us whether we are being called from one of those methods. + * + * If the CGContext is not valid, or belongs to a different View, then + * we mark our view as needing display and return failure. It should + * get drawn in a later call to drawRect. + */ + + if (view != [NSView focusView]) { + [view setNeedsDisplay:YES]; + canDraw = false; + goto end; + } + dc.view = view; + dc.context = GET_CGCONTEXT; + dc.portBounds = NSRectToCGRect([view bounds]); + if (dc.clipRgn) { + clipBounds = CGContextGetClipBoundingBox(dc.context); + } } else { Tcl_Panic("TkMacOSXSetupDrawingContext(): " "no context to draw into !"); @@ -1565,8 +1603,13 @@ TkMacOSXSetupDrawingContext( */ if (dc.context) { - CGAffineTransform t = { .a = 1, .b = 0, .c = 0, .d = -1, .tx = 0, - .ty = dc.portBounds.size.height}; + CGAffineTransform t = { + .a = 1, .b = 0, + .c = 0, .d = -1, + .tx = 0, + .ty = dc.portBounds.size.height + }; + dc.portBounds.origin.x += macDraw->xOff; dc.portBounds.origin.y += macDraw->yOff; CGContextSaveGState(dc.context); @@ -1581,6 +1624,7 @@ TkMacOSXSetupDrawingContext( CGContextRestoreGState(dc.context); #endif /* TK_MAC_DEBUG_DRAWING */ CGRect r; + if (!HIShapeIsRectangular(dc.clipRgn) || !CGRectContainsRect( *HIShapeGetBounds(dc.clipRgn, &r), CGRectApplyAffineTransform(clipBounds, t))) { @@ -1608,21 +1652,28 @@ TkMacOSXSetupDrawingContext( CGContextSetPatternPhase(dc.context, CGSizeMake( dc.portBounds.size.width, dc.portBounds.size.height)); } - if(gc->function != GXcopy) { + if (gc->function != GXcopy) { TkMacOSXDbgMsg("Logical functions other than GXcopy are " "not supported for CG drawing!"); } - /* When should we antialias? */ + + /* + * When should we antialias? + */ + shouldAntialias = !notAA(gc->line_width); if (!shouldAntialias) { - /* Make non-antialiased CG drawing look more like X11 */ + /* + * Make non-antialiased CG drawing look more like X11. + */ + w -= (gc->line_width ? NON_AA_CG_OFFSET : 0); } CGContextSetShouldAntialias(dc.context, shouldAntialias); CGContextSetLineWidth(dc.context, w); if (gc->line_style != LineSolid) { int num = 0; - char *p = &(gc->dashes); + char *p = &gc->dashes; CGFloat dashOffset = gc->dash_offset; CGFloat lengths[10]; @@ -1632,13 +1683,13 @@ TkMacOSXSetupDrawingContext( } CGContextSetLineDash(dc.context, dashOffset, lengths, num); } - if ((unsigned)gc->cap_style < sizeof(cgCap)/sizeof(CGLineCap)) { + if ((unsigned) gc->cap_style < sizeof(cgCap)/sizeof(CGLineCap)) { CGContextSetLineCap(dc.context, - cgCap[(unsigned)gc->cap_style]); + cgCap[(unsigned) gc->cap_style]); } if ((unsigned)gc->join_style < sizeof(cgJoin)/sizeof(CGLineJoin)) { CGContextSetLineJoin(dc.context, - cgJoin[(unsigned)gc->join_style]); + cgJoin[(unsigned) gc->join_style]); } } } @@ -1647,8 +1698,11 @@ end: #ifdef TK_MAC_DEBUG_DRAWING if (!canDraw && win != NULL) { TkWindow *winPtr = TkMacOSXGetTkWindow(win); - if (winPtr) fprintf(stderr, "Cannot draw in %s - postponing.\n", - Tk_PathName(winPtr)); + + if (winPtr) { + fprintf(stderr, "Cannot draw in %s - postponing.\n", + Tk_PathName(winPtr)); + } } #endif if (!canDraw && dc.clipRgn) { @@ -1719,7 +1773,9 @@ TkMacOSXGetClipRgn( TkMacOSXUpdateClipRgn(macDraw->winPtr); #ifdef TK_MAC_DEBUG_DRAWING TkMacOSXDbgMsg("%s", macDraw->winPtr->pathName); + NSView *view = TkMacOSXDrawableView(macDraw); + CGContextSaveGState(context); CGContextConcatCTM(context, CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, [view bounds].size.height)); @@ -1743,8 +1799,8 @@ TkMacOSXGetClipRgn( * * TkMacOSXSetUpClippingRgn -- * - * Set up the clipping region so that drawing only occurs on the - * specified X subwindow. + * Set up the clipping region so that drawing only occurs on the specified + * X subwindow. * * Results: * None. @@ -1766,8 +1822,8 @@ TkMacOSXSetUpClippingRgn( * * TkpClipDrawableToRect -- * - * Clip all drawing into the drawable d to the given rectangle. - * If width or height are negative, reset to no clipping. + * Clip all drawing into the drawable d to the given rectangle. If width + * or height are negative, reset to no clipping. * * Results: * None. @@ -1832,8 +1888,8 @@ ClipToGC( HIShapeRef *clipRgnPtr) /* must point to initialized variable */ { if (gc && gc->clip_mask && - ((TkpClipMask*)gc->clip_mask)->type == TKP_CLIP_REGION) { - TkRegion gcClip = ((TkpClipMask*)gc->clip_mask)->value.region; + ((TkpClipMask *) gc->clip_mask)->type == TKP_CLIP_REGION) { + TkRegion gcClip = ((TkpClipMask *) gc->clip_mask)->value.region; int xOffset = ((MacDrawable *) d)->xOff + gc->clip_x_origin; int yOffset = ((MacDrawable *) d)->yOff + gc->clip_y_origin; HIShapeRef clipRgn = *clipRgnPtr, gcClipRgn; @@ -1856,10 +1912,9 @@ ClipToGC( * * TkMacOSXMakeStippleMap -- * - * Given a drawable and a stipple pattern this function draws the - * pattern repeatedly over the drawable. The drawable can then - * be used as a mask for bit-bliting a stipple pattern over an - * object. + * Given a drawable and a stipple pattern this function draws the pattern + * repeatedly over the drawable. The drawable can then be used as a mask + * for bit-bliting a stipple pattern over an object. * * Results: * A BitMap data structure. @@ -1883,12 +1938,12 @@ TkMacOSXMakeStippleMap( * * TkpDrawHighlightBorder -- * - * This procedure draws a rectangular ring around the outside of - * a widget to indicate that it has received the input focus. + * This procedure draws a rectangular ring around the outside of a widget + * to indicate that it has received the input focus. * - * On the Macintosh, this puts a 1 pixel border in the bgGC color - * between the widget and the focus ring, except in the case where - * highlightWidth is 1, in which case the border is left out. + * On the Macintosh, this puts a 1 pixel border in the bgGC color between + * the widget and the focus ring, except in the case where highlightWidth + * is 1, in which case the border is left out. * * For proper Mac L&F, use highlightWidth of 3. * @@ -1896,8 +1951,8 @@ TkMacOSXMakeStippleMap( * None. * * Side effects: - * A rectangle "width" pixels wide is drawn in "drawable", - * corresponding to the outer area of "tkwin". + * A rectangle "width" pixels wide is drawn in "drawable", corresponding + * to the outer area of "tkwin". * *---------------------------------------------------------------------- */ @@ -1926,8 +1981,8 @@ TkpDrawHighlightBorder ( * * TkpDrawFrame -- * - * This procedure draws the rectangular frame area. If the user - * has requested themeing, it draws with the background theme. + * This procedure draws the rectangular frame area. If the user has + * requested themeing, it draws with the background theme. * * Results: * None. diff --git a/macosx/tkMacOSXEmbed.c b/macosx/tkMacOSXEmbed.c index b23f33b..4f67f13 100644 --- a/macosx/tkMacOSXEmbed.c +++ b/macosx/tkMacOSXEmbed.c @@ -334,15 +334,15 @@ TkpUseWindow( macWin->flags |= TK_EMBEDDED; macWin->xOff = parent->winPtr->privatePtr->xOff + - parent->winPtr->changes.border_width + - winPtr->changes.x; + parent->winPtr->changes.border_width + + winPtr->changes.x; macWin->yOff = parent->winPtr->privatePtr->yOff + - parent->winPtr->changes.border_width + - winPtr->changes.y; + parent->winPtr->changes.border_width + + winPtr->changes.y; /* - * Finish filling up the container structure with the embedded - * window's information. + * Finish filling up the container structure with the embedded window's + * information. */ containerPtr->embedded = (Window) macWin; @@ -353,8 +353,8 @@ TkpUseWindow( * tkwin is eventually deleted. */ - Tk_CreateEventHandler(tkwin, StructureNotifyMask, EmbeddedEventProc, - winPtr); + Tk_CreateEventHandler(tkwin, StructureNotifyMask, + EmbeddedEventProc, winPtr); return TCL_OK; } @@ -588,16 +588,25 @@ TkpTestembedCmd( continue; } Tcl_DStringStartSublist(&dString); - /* Parent id */ + + /* + * Parent id + */ + if (containerPtr->parent == None) { Tcl_DStringAppendElement(&dString, ""); } else if (all) { - sprintf(buffer, "0x%" TCL_Z_MODIFIER "x", (size_t) containerPtr->parent); + sprintf(buffer, "0x%" TCL_Z_MODIFIER "x", + (size_t) containerPtr->parent); Tcl_DStringAppendElement(&dString, buffer); } else { Tcl_DStringAppendElement(&dString, "XXX"); } - /* Parent pathName */ + + /* + * Parent pathName + */ + if (containerPtr->parentPtr == NULL || parentInterp != interp) { Tcl_DStringAppendElement(&dString, ""); @@ -605,11 +614,17 @@ TkpTestembedCmd( Tcl_DStringAppendElement(&dString, containerPtr->parentPtr->pathName); } + /* * On X11 embedded is a wrapper, which does not exist on macOS. */ + Tcl_DStringAppendElement(&dString, ""); - /* Embedded window pathName */ + + /* + * Embedded window pathName + */ + if (containerPtr->embeddedPtr == NULL || embeddedInterp != interp) { Tcl_DStringAppendElement(&dString, ""); @@ -768,6 +783,7 @@ ContainerEventProc( /* * When the interpreter is being dismantled this can be nil. */ + return; } @@ -920,6 +936,7 @@ EmbedActivateProc( XEvent *eventPtr) /* ResizeRequest event. */ { Container *containerPtr = clientData; + if (containerPtr->embeddedPtr != NULL) { if (eventPtr->type == ActivateNotify) { TkGenerateActivateEvents(containerPtr->embeddedPtr,1); @@ -1024,11 +1041,10 @@ EmbedGeometryRequest( /* * Forward the requested size into our geometry management hierarchy via * the container window. We need to send a Configure event back to the - * embedded application if we decide not to honor its request; to make - * this happen, process all idle event handlers synchronously here (so - * that the geometry managers have had a chance to do whatever they want - * to do), and if the window's size didn't change then generate a - * configure event. + * embedded application if we decide not to honor its request; to make this + * happen, process all idle event handlers synchronously here (so that the + * geometry managers have had a chance to do whatever they want to do), and + * if the window's size didn't change then generate a configure event. */ Tk_GeometryRequest((Tk_Window) winPtr, width, height); @@ -1050,8 +1066,8 @@ EmbedGeometryRequest( * application of its current size and location. This procedure is called * when the embedded application made a geometry request that we did not * grant, so that the embedded application knows that its geometry didn't - * change after all. It is a response to ConfigureRequest events, which - * we do not currently synthesize on the Mac + * change after all. It is a response to ConfigureRequest events, which we + * do not currently synthesize on the Mac * * Results: * None. @@ -1111,8 +1127,8 @@ EmbedWindowDeleted( containerPtr->parentPtr->flags & TK_BOTH_HALVES) { XEvent event; - event.xany.serial = - LastKnownRequestProcessed(Tk_Display(containerPtr->parentPtr)); + event.xany.serial = LastKnownRequestProcessed( + Tk_Display(containerPtr->parentPtr)); event.xany.send_event = False; event.xany.display = Tk_Display(containerPtr->parentPtr); diff --git a/macosx/tkMacOSXFont.c b/macosx/tkMacOSXFont.c index deaab20..7f1cc72 100644 --- a/macosx/tkMacOSXFont.c +++ b/macosx/tkMacOSXFont.c @@ -1,8 +1,8 @@ /* * tkMacOSXFont.c -- * - * Contains the Macintosh implementation of the platform-independant - * font package interface. + * Contains the Macintosh implementation of the platform-independant font + * package interface. * * Copyright 2002-2004 Benjamin Riefenstahl, Benjamin.Riefenstahl@epost.de * Copyright (c) 2006-2009 Daniel A. Steffen @@ -32,9 +32,8 @@ */ typedef struct { - TkFont font; /* Stuff used by generic font package. Must - * be first in structure. */ - + TkFont font; /* Stuff used by generic font package. Must be + * first in structure. */ NSFont *nsFont; NSDictionary *nsAttributes; } MacFont; @@ -83,17 +82,21 @@ static int antialiasedTextEnabled = -1; static NSCharacterSet *whitespaceCharacterSet = nil; static NSCharacterSet *lineendingCharacterSet = nil; -static void GetTkFontAttributesForNSFont(NSFont *nsFont, - TkFontAttributes *faPtr); -static NSFont *FindNSFont(const char *familyName, NSFontTraitMask traits, - NSInteger weight, CGFloat size, int fallbackToDefault); -static void InitFont(NSFont *nsFont, const TkFontAttributes *reqFaPtr, - MacFont * fontPtr); -static int CreateNamedSystemFont(Tcl_Interp *interp, Tk_Window tkwin, - const char* name, TkFontAttributes *faPtr); -static void DrawCharsInContext(Display *display, Drawable drawable, GC gc, - Tk_Font tkfont, const char *source, int numBytes, int rangeStart, - int rangeLength, int x, int y, double angle); +static void GetTkFontAttributesForNSFont(NSFont *nsFont, + TkFontAttributes *faPtr); +static NSFont * FindNSFont(const char *familyName, + NSFontTraitMask traits, NSInteger weight, + CGFloat size, int fallbackToDefault); +static void InitFont(NSFont *nsFont, + const TkFontAttributes *reqFaPtr, + MacFont *fontPtr); +static int CreateNamedSystemFont(Tcl_Interp *interp, + Tk_Window tkwin, const char *name, + TkFontAttributes *faPtr); +static void DrawCharsInContext(Display *display, Drawable drawable, + GC gc, Tk_Font tkfont, const char *source, + int numBytes, int rangeStart, int rangeLength, + int x, int y, double angle); #pragma mark - #pragma mark Font Helpers: @@ -232,7 +235,7 @@ InitFont( int ascent, descent/*, dontAA*/; static const UniChar ch[] = {'.', 'W', ' ', 0xc4, 0xc1, 0xc2, 0xc3, 0xc7}; /* ., W, Space, Auml, Aacute, Acirc, Atilde, Ccedilla */ - #define nCh (sizeof(ch) / sizeof(UniChar)) +#define nCh (sizeof(ch) / sizeof(UniChar)) CGGlyph glyphs[nCh]; CGRect boundingRects[nCh]; @@ -244,7 +247,11 @@ InitFont( TkInitFontAttributes(faPtr); } fontPtr->nsFont = nsFont; - // some don't like antialiasing on fixed-width even if bigger than limit + + /* + * Some don't like antialiasing on fixed-width even if bigger than limit + */ + // dontAA = [nsFont isFixedPitch] && fontPtr->font.fa.size <= 10; if (antialiasedTextEnabled >= 0/* || dontAA*/) { renderingMode = (antialiasedTextEnabled == 0/* || dontAA*/) ? @@ -294,7 +301,7 @@ InitFont( NSLigatureAttributeName, [NSNumber numberWithDouble:kern], NSKernAttributeName, nil]; fontPtr->nsAttributes = [nsAttributes retain]; - #undef nCh +#undef nCh } /* @@ -358,10 +365,14 @@ TkpFontPkgInit( NSFont *nsFont; TkFontAttributes fa; NSMutableCharacterSet *cs; - /* Since we called before TkpInit, we need our own autorelease pool. */ + /* + * Since we called before TkpInit, we need our own autorelease pool. + */ NSAutoreleasePool *pool = [NSAutoreleasePool new]; - /* force this for now */ + /* + * Force this for now. + */ if (!mainPtr->winPtr->mainPtr) { mainPtr->winPtr->mainPtr = mainPtr; } @@ -413,17 +424,17 @@ TkpFontPkgInit( * Map a platform-specific native font name to a TkFont. * * Results: - * The return value is a pointer to a TkFont that represents the - * native font. If a native font by the given name could not be - * found, the return value is NULL. + * The return value is a pointer to a TkFont that represents the native + * font. If a native font by the given name could not be found, the return + * value is NULL. * - * Every call to this procedure returns a new TkFont structure, even - * if the name has already been seen before. The caller should call + * Every call to this procedure returns a new TkFont structure, even if + * the name has already been seen before. The caller should call * TkpDeleteFont() when the font is no longer needed. * - * The caller is responsible for initializing the memory associated - * with the generic TkFont when this function returns and releasing - * the contents of the generics TkFont before calling TkpDeleteFont(). + * The caller is responsible for initializing the memory associated with + * the generic TkFont when this function returns and releasing the + * contents of the generics TkFont before calling TkpDeleteFont(). * * Side effects: * None. @@ -449,8 +460,8 @@ TkpGetNativeFont( } else { return NULL; } - ctFont = CTFontCreateUIFontForLanguage(HIThemeGetUIFontType( - themeFontId), 0, NULL); + ctFont = CTFontCreateUIFontForLanguage( + HIThemeGetUIFontType(themeFontId), 0, NULL); if (ctFont) { fontPtr = ckalloc(sizeof(MacFont)); InitFont((NSFont*) ctFont, NULL, fontPtr); @@ -468,19 +479,18 @@ TkpGetNativeFont( * closest matching attributes. * * Results: - * The return value is a pointer to a TkFont that represents the font - * with the desired attributes. If a font with the desired attributes - * could not be constructed, some other font will be substituted - * automatically. + * The return value is a pointer to a TkFont that represents the font with + * the desired attributes. If a font with the desired attributes could not + * be constructed, some other font will be substituted automatically. * - * Every call to this procedure returns a new TkFont structure, even - * if the specified attributes have already been seen before. The - * caller should call TkpDeleteFont() to free the platform- specific - * data when the font is no longer needed. + * Every call to this procedure returns a new TkFont structure, even if + * the specified attributes have already been seen before. The caller + * should call TkpDeleteFont() to free the platform- specific data when + * the font is no longer needed. * - * The caller is responsible for initializing the memory associated - * with the generic TkFont when this function returns and releasing - * the contents of the generic TkFont before calling TkpDeleteFont(). + * The caller is responsible for initializing the memory associated with + * the generic TkFont when this function returns and releasing the + * contents of the generic TkFont before calling TkpDeleteFont(). * * Side effects: * None. @@ -492,16 +502,16 @@ TkFont * TkpGetFontFromAttributes( TkFont *tkFontPtr, /* If non-NULL, store the information in this * existing TkFont structure, rather than - * allocating a new structure to hold the - * font; the existing contents of the font - * will be released. If NULL, a new TkFont - * structure is allocated. */ + * allocating a new structure to hold the font; + * the existing contents of the font will be + * released. If NULL, a new TkFont structure is + * allocated. */ Tk_Window tkwin, /* For display where font will be used. */ const TkFontAttributes *faPtr) /* Set of attributes to match. */ { MacFont *fontPtr; - int points = (int)(TkFontGetPoints(tkwin, faPtr->size) + 0.5); + int points = (int) (TkFontGetPoints(tkwin, faPtr->size) + 0.5); NSFontTraitMask traits = GetNSFontTraitsFromTkFontAttributes(faPtr); NSInteger weight = (faPtr->weight == TK_FW_BOLD ? 9 : 5); NSFont *nsFont; @@ -538,9 +548,9 @@ TkpGetFontFromAttributes( * TkpDeleteFont -- * * Called to release a font allocated by TkpGetNativeFont() or - * TkpGetFontFromAttributes(). The caller should have already - * released the fields of the TkFont that are used exclusively by the - * generic TkFont code. + * TkpGetFontFromAttributes(). The caller should have already released the + * fields of the TkFont that are used exclusively by the generic TkFont + * code. * * Results: * TkFont is deallocated. @@ -567,8 +577,8 @@ TkpDeleteFont( * * TkpGetFontFamilies -- * - * Return information about the font families that are available on - * the display of the given window. + * Return information about the font families that are available on the + * display of the given window. * * Results: * Modifies interp's result object to hold a list of all the available @@ -600,12 +610,12 @@ TkpGetFontFamilies( * * TkpGetSubFonts -- * - * A function used by the testing package for querying the actual - * screen fonts that make up a font object. + * A function used by the testing package for querying the actual screen + * fonts that make up a font object. * * Results: - * Modifies interp's result object to hold a list containing the names - * of the screen fonts that make up the given font object. + * Modifies interp's result object to hold a list containing the names of + * the screen fonts that make up the given font object. * * Side effects: * None. @@ -642,8 +652,8 @@ TkpGetSubFonts( * * TkpGetFontAttrsForChar -- * - * Retrieve the font attributes of the actual font used to render a - * given character. + * Retrieve the font attributes of the actual font used to render a given + * character. * * Results: * None. @@ -745,10 +755,9 @@ Tk_MeasureChars( * all the characters on the line for context. * * Results: - * The return value is the number of bytes from source that - * fit into the span that extends from 0 to maxLength. *lengthPtr is - * filled with the x-coordinate of the right edge of the last - * character that did fit. + * The return value is the number of bytes from source that fit into the + * span that extends from 0 to maxLength. *lengthPtr is filled with the + * x-coordinate of the right edge of the last character that did fit. * * Side effects: * None. @@ -774,11 +783,11 @@ TkpMeasureCharsInContext( * TK_PARTIAL_OK means include the last char * which only partially fits on this line. * TK_WHOLE_WORDS means stop on a word - * boundary, if possible. TK_AT_LEAST_ONE - * means return at least one character even - * if no characters fit. If TK_WHOLE_WORDS - * and TK_AT_LEAST_ONE are set and the first - * word doesn't fit, we return at least one + * boundary, if possible. TK_AT_LEAST_ONE means + * return at least one character even if no + * characters fit. If TK_WHOLE_WORDS and + * TK_AT_LEAST_ONE are set and the first word + * doesn't fit, we return at least one * character or whatever characters fit into * maxLength. TK_ISOLATE_END means that the * last character should not be considered in @@ -864,14 +873,13 @@ TkpMeasureCharsInContext( } /* - * If there is no line breakpoint in the source string between - * its start and the index position that fits in maxWidth, then + * If there is no line breakpoint in the source string between its + * start and the index position that fits in maxWidth, then * CTTypesetterSuggestLineBreak() returns that very last index. - * However if the TK_WHOLE_WORDS flag is set, we want to break - * at a word boundary. In this situation, unless TK_AT_LEAST_ONE - * is set, we must report that zero chars actually fit (in other - * words the smallest word of the source string is still larger - * than maxWidth). + * However if the TK_WHOLE_WORDS flag is set, we want to break at a + * word boundary. In this situation, unless TK_AT_LEAST_ONE is set, we + * must report that zero chars actually fit (in other words the + * smallest word of the source string is still larger than maxWidth). */ if ((index >= start) && (index < len) && @@ -903,9 +911,12 @@ TkpMeasureCharsInContext( CFRelease(line); } - /* The call to CTTypesetterSuggestClusterBreak above will always - return at least one character regardless of whether it exceeded - it or not. Clean that up now. */ + /* + * The call to CTTypesetterSuggestClusterBreak above will always return + * at least one character regardless of whether it exceeded it or not. + * Clean that up now. + */ + while (width > maxWidth && !(flags & TK_PARTIAL_OK) && index > start+(flags & TK_AT_LEAST_ONE)) { range.length = --index; @@ -946,7 +957,7 @@ done: * actual implementation in TkpDrawCharsInContext(). * * Results: - * None. + * None. * * Side effects: * Information gets drawn on the screen. @@ -964,8 +975,8 @@ Tk_DrawChars( const char *source, /* UTF-8 string to be displayed. Need not be * '\0' terminated. All Tk meta-characters * (tabs, control characters, and newlines) - * should be stripped out of the string that - * is passed to this function. If they are not + * should be stripped out of the string that is + * passed to this function. If they are not * stripped out, they will be displayed as * regular printing characters. */ int numBytes, /* Number of bytes in string. */ @@ -986,8 +997,8 @@ TkDrawAngledChars( const char *source, /* UTF-8 string to be displayed. Need not be * '\0' terminated. All Tk meta-characters * (tabs, control characters, and newlines) - * should be stripped out of the string that - * is passed to this function. If they are not + * should be stripped out of the string that is + * passed to this function. If they are not * stripped out, they will be displayed as * regular printing characters. */ int numBytes, /* Number of bytes in string. */ @@ -1029,8 +1040,8 @@ TkpDrawCharsInContext( const char * source, /* UTF-8 string to be displayed. Need not be * '\0' terminated. All Tk meta-characters * (tabs, control characters, and newlines) - * should be stripped out of the string that - * is passed to this function. If they are not + * should be stripped out of the string that is + * passed to this function. If they are not * stripped out, they will be displayed as * regular printing characters. */ int numBytes, /* Number of bytes in string. */ @@ -1054,8 +1065,8 @@ DrawCharsInContext( const char * source, /* UTF-8 string to be displayed. Need not be * '\0' terminated. All Tk meta-characters * (tabs, control characters, and newlines) - * should be stripped out of the string that - * is passed to this function. If they are not + * should be stripped out of the string that is + * passed to this function. If they are not * stripped out, they will be displayed as * regular printing characters. */ int numBytes, /* Number of bytes in string. */ @@ -1091,6 +1102,7 @@ DrawCharsInContext( if (!string) { return; } + context = drawingContext.context; fg = TkMacOSXCreateCGColor(gc, gc->foreground); attributes = [fontPtr->nsAttributes mutableCopy]; @@ -1119,6 +1131,7 @@ DrawCharsInContext( len = Tcl_NumUtfChars(source, rangeStart + rangeLength); if (start > 0) { CGRect clipRect = CGRectInfinite, startBounds; + line = CTTypesetterCreateLine(typesetter, CFRangeMake(0, start)); startBounds = CTLineGetImageBounds(line, context); CFRelease(line); @@ -1241,9 +1254,10 @@ TkMacOSXFontDescriptionForNSFontAndNSFontAttributes( NSUnderlineStyleAttributeName]; id strikethrough = [nsAttributes objectForKey: NSStrikethroughStyleAttributeName]; + objv[i++] = Tcl_NewStringObj(familyName, -1); objv[i++] = Tcl_NewWideIntObj([nsFont pointSize]); -#define S(s) Tcl_NewStringObj(STRINGIFY(s),(int)(sizeof(STRINGIFY(s))-1)) +#define S(s) Tcl_NewStringObj(STRINGIFY(s), (int)(sizeof(STRINGIFY(s))-1)) objv[i++] = (traits & NSBoldFontMask) ? S(bold) : S(normal); objv[i++] = (traits & NSItalicFontMask) ? S(italic) : S(roman); if ([underline respondsToSelector:@selector(intValue)] && @@ -1267,8 +1281,9 @@ TkMacOSXFontDescriptionForNSFontAndNSFontAttributes( * TkMacOSXUseAntialiasedText -- * * Enables or disables application-wide use of antialiased text (where - * available). Sets up a linked Tcl global variable to allow - * disabling of antialiased text from tcl. + * available). Sets up a linked Tcl global variable to allow disabling of + * antialiased text from Tcl. + * * The possible values for this variable are: * * -1 - Use system default as configurable in "System Prefs" -> "General". diff --git a/macosx/tkMacOSXImage.c b/macosx/tkMacOSXImage.c index 38f4a70..36f1fc6 100644 --- a/macosx/tkMacOSXImage.c +++ b/macosx/tkMacOSXImage.c @@ -23,7 +23,7 @@ _XInitImageFuncPtrs( { return 0; } - + /* *---------------------------------------------------------------------- * @@ -81,14 +81,15 @@ TkMacOSXCreateCGImageWithXImage( data = memcpy(ckalloc(len), image->data + image->xoffset, len); } if (data) { - provider = CGDataProviderCreateWithData(data, data, len, releaseData); + provider = CGDataProviderCreateWithData(data, data, len, + releaseData); } if (provider) { - img = CGImageMaskCreate(image->width, image->height, bitsPerComponent, - bitsPerPixel, image->bytes_per_line, provider, decode, 0); + img = CGImageMaskCreate(image->width, image->height, + bitsPerComponent, bitsPerPixel, image->bytes_per_line, + provider, decode, 0); } - } else if (image->format == ZPixmap && image->bits_per_pixel == 32) { - + } else if ((image->format == ZPixmap) && (image->bits_per_pixel == 32)) { /* * Color image */ @@ -96,7 +97,6 @@ TkMacOSXCreateCGImageWithXImage( CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB(); if (image->width == 0 && image->height == 0) { - /* * CGCreateImage complains on early macOS releases. */ @@ -106,11 +106,12 @@ TkMacOSXCreateCGImageWithXImage( bitsPerComponent = 8; bitsPerPixel = 32; bitmapInfo = (image->byte_order == MSBFirst ? - kCGBitmapByteOrder32Little : kCGBitmapByteOrder32Big); + kCGBitmapByteOrder32Little : kCGBitmapByteOrder32Big); bitmapInfo |= kCGImageAlphaLast; data = memcpy(ckalloc(len), image->data + image->xoffset, len); if (data) { - provider = CGDataProviderCreateWithData(data, data, len, releaseData); + provider = CGDataProviderCreateWithData(data, data, len, + releaseData); } if (provider) { img = CGImageCreate(image->width, image->height, bitsPerComponent, @@ -127,7 +128,6 @@ TkMacOSXCreateCGImageWithXImage( return img; } - /* *---------------------------------------------------------------------- * @@ -179,15 +179,14 @@ XGetImage( if (win && has_retina == unknown) { #ifdef __clang__ - has_retina = [win respondsToSelector:@selector(backingScaleFactor)]? - yes : no; + has_retina = [win respondsToSelector:@selector(backingScaleFactor)] ? + yes : no; #else has_retina = no; #endif } if (has_retina == yes) { - /* * We only allow scale factors 1 or 2, as Apple currently does. */ @@ -205,7 +204,7 @@ XGetImage( } bitmap_rep = TkMacOSXBitmapRepFromDrawableRect(drawable, - x, y, width, height); + x, y, width, height); if (!bitmap_rep) { TkMacOSXDbgMsg("XGetImage: Failed to construct NSBitmapRep"); return NULL; @@ -214,12 +213,12 @@ XGetImage( size = [bitmap_rep bytesPerPlane]; bytes_per_row = [bitmap_rep bytesPerRow]; bitmap = ckalloc(size); - if (!bitmap || - (bitmap_fmt != 0 && bitmap_fmt != 1) || - [bitmap_rep samplesPerPixel] != 4 || - [bitmap_rep isPlanar] != 0 || - bytes_per_row < 4 * scaled_width || - size != bytes_per_row*scaled_height ) { + if (!bitmap + || (bitmap_fmt != 0 && bitmap_fmt != 1) + || [bitmap_rep samplesPerPixel] != 4 + || [bitmap_rep isPlanar] != 0 + || bytes_per_row < 4 * scaled_width + || size != bytes_per_row * scaled_height) { TkMacOSXDbgMsg("XGetImage: Unrecognized bitmap format"); CFRelease(bitmap_rep); return NULL; @@ -228,8 +227,8 @@ XGetImage( CFRelease(bitmap_rep); /* - * When Apple extracts a bitmap from an NSView, it may be in - * either BGRA or ABGR format. For an XImage we need RGBA. + * When Apple extracts a bitmap from an NSView, it may be in either + * BGRA or ABGR format. For an XImage we need RGBA. */ struct pixel_fmt pixel = bitmap_fmt == 0 ? bgra : abgr; @@ -248,16 +247,16 @@ XGetImage( } } imagePtr = XCreateImage(display, NULL, depth, format, offset, - (char*)bitmap, scaled_width, scaled_height, - bitmap_pad, bytes_per_row); + (char*) bitmap, scaled_width, scaled_height, + bitmap_pad, bytes_per_row); if (scalefactor == 2) { imagePtr->pixelpower = 1; } } else { /* - * There are some calls to XGetImage in the generic Tk - * code which pass an XYPixmap rather than a ZPixmap. - * XYPixmaps should be handled here. + * There are some calls to XGetImage in the generic Tk code which pass + * an XYPixmap rather than a ZPixmap. XYPixmaps should be handled + * here. */ TkMacOSXDbgMsg("XGetImage does not handle XYPixmaps at the moment."); } @@ -323,40 +322,40 @@ ImageGetPixel( + (((image->xoffset + x) * image->bits_per_pixel) / NBBY); switch (image->bits_per_pixel) { - case 32: { - r = (*((unsigned int*) srcPtr) >> 16) & 0xff; - g = (*((unsigned int*) srcPtr) >> 8) & 0xff; - b = (*((unsigned int*) srcPtr) ) & 0xff; - /*if (image->byte_order == LSBFirst) { - r = srcPtr[2]; g = srcPtr[1]; b = srcPtr[0]; - } else { - r = srcPtr[1]; g = srcPtr[2]; b = srcPtr[3]; - }*/ - break; - } - case 16: - r = (*((unsigned short*) srcPtr) >> 7) & 0xf8; - g = (*((unsigned short*) srcPtr) >> 2) & 0xf8; - b = (*((unsigned short*) srcPtr) << 3) & 0xf8; - break; - case 8: - r = (*srcPtr << 2) & 0xc0; - g = (*srcPtr << 4) & 0xc0; - b = (*srcPtr << 6) & 0xc0; - r |= r >> 2 | r >> 4 | r >> 6; - g |= g >> 2 | g >> 4 | g >> 6; - b |= b >> 2 | b >> 4 | b >> 6; - break; - case 4: { - unsigned char c = (x % 2) ? *srcPtr : (*srcPtr >> 4); - r = (c & 0x04) ? 0xff : 0; - g = (c & 0x02) ? 0xff : 0; - b = (c & 0x01) ? 0xff : 0; - break; - } - case 1: - r = g = b = ((*srcPtr) & (0x80 >> (x % 8))) ? 0xff : 0; - break; + case 32: + r = (*((unsigned int*) srcPtr) >> 16) & 0xff; + g = (*((unsigned int*) srcPtr) >> 8) & 0xff; + b = (*((unsigned int*) srcPtr) ) & 0xff; + /*if (image->byte_order == LSBFirst) { + r = srcPtr[2]; g = srcPtr[1]; b = srcPtr[0]; + } else { + r = srcPtr[1]; g = srcPtr[2]; b = srcPtr[3]; + }*/ + break; + case 16: + r = (*((unsigned short*) srcPtr) >> 7) & 0xf8; + g = (*((unsigned short*) srcPtr) >> 2) & 0xf8; + b = (*((unsigned short*) srcPtr) << 3) & 0xf8; + break; + case 8: + r = (*srcPtr << 2) & 0xc0; + g = (*srcPtr << 4) & 0xc0; + b = (*srcPtr << 6) & 0xc0; + r |= r >> 2 | r >> 4 | r >> 6; + g |= g >> 2 | g >> 4 | g >> 6; + b |= b >> 2 | b >> 4 | b >> 6; + break; + case 4: { + unsigned char c = (x % 2) ? *srcPtr : (*srcPtr >> 4); + + r = (c & 0x04) ? 0xff : 0; + g = (c & 0x02) ? 0xff : 0; + b = (c & 0x01) ? 0xff : 0; + break; + } + case 1: + r = g = b = ((*srcPtr) & (0x80 >> (x % 8))) ? 0xff : 0; + break; } } return (PIXEL_MAGIC << 24) | (r << 16) | (g << 8) | b; @@ -389,6 +388,7 @@ ImagePutPixel( unsigned char *dstPtr = ((unsigned char*) image->data) + (y * image->bytes_per_line) + (((image->xoffset + x) * image->bits_per_pixel) / NBBY); + if (image->bits_per_pixel == 32) { *((unsigned int*) dstPtr) = pixel; } else { @@ -420,7 +420,7 @@ ImagePutPixel( } return 0; } - + /* *---------------------------------------------------------------------- * @@ -451,6 +451,7 @@ XCreateImage( int bytes_per_line) { XImage *ximage; + display->request++; ximage = ckalloc(sizeof(XImage)); @@ -461,9 +462,12 @@ XCreateImage( ximage->format = format; ximage->data = data; ximage->obdata = NULL; - /* The default pixelpower is 0. This must be explicitly set to 1 in the + + /* + * The default pixelpower is 0. This must be explicitly set to 1 in the * case of an XImage extracted from a Retina display. */ + ximage->pixelpower = 0; if (format == ZPixmap) { @@ -476,7 +480,10 @@ XCreateImage( if (bitmap_pad) { ximage->bitmap_pad = bitmap_pad; } else { - /* Use 16 byte alignment for best Quartz perfomance */ + /* + * Use 16 byte alignment for best Quartz perfomance. + */ + ximage->bitmap_pad = 128; } if (bytes_per_line) { @@ -511,9 +518,9 @@ XCreateImage( * * TkPutImage -- * - * Copies a rectangular subimage of an XImage into a drawable. - * Currently this is only called by TkImgPhotoDisplay, using - * a Window as the drawable. + * Copies a rectangular subimage of an XImage into a drawable. Currently + * this is only called by TkImgPhotoDisplay, using a Window as the + * drawable. * * Results: * None. @@ -559,13 +566,15 @@ TkPutImage( } if (img) { - /* If the XImage has big pixels, the source is rescaled to reflect + /* + * If the XImage has big pixels, the source is rescaled to reflect * the actual pixel dimensions. This is not currently used, but * could arise if the image were copied from a retina monitor and * redrawn on an ordinary monitor. */ int pp = image->pixelpower; + bounds = CGRectMake(0, 0, image->width, image->height); srcRect = CGRectMake(src_x<dispPtr->grabWinPtr; - if (grabWinPtr && - grabWinPtr != winPtr && - !winPtr->dispPtr->grabFlags && /* this means the grab is local. */ - grabWinPtr->mainPtr == winPtr->mainPtr) { + + if (grabWinPtr + && grabWinPtr != winPtr + && !winPtr->dispPtr->grabFlags /* this means the grab is local. */ + && grabWinPtr->mainPtr == winPtr->mainPtr) { return theEvent; } } else { tkwin = (Tk_Window) winPtr->dispPtr->focusPtr; } if (!tkwin) { - TkMacOSXDbgMsg("tkwin == NULL"); - return theEvent; /* Give up. No window for this event. */ + TkMacOSXDbgMsg("tkwin == NULL"); + return theEvent; /* Give up. No window for this event. */ } /* - * If it's a function key, or we have modifiers other than Shift or Alt, - * pass it straight to Tk. Otherwise we'll send for input processing. + * If it's a function key, or we have modifiers other than Shift or + * Alt, pass it straight to Tk. Otherwise we'll send for input + * processing. */ - int code = (len == 0) ? - 0 : [charactersIgnoringModifiers characterAtIndex: 0]; + int code = (len == 0) ? 0 : + [charactersIgnoringModifiers characterAtIndex: 0]; if (type != NSKeyDown || isFunctionKey(code) - || (len > 0 && state & (ControlMask | Mod1Mask | Mod3Mask | Mod4Mask))) { - + || (len > 0 && state & (ControlMask | Mod1Mask | Mod3Mask | Mod4Mask))) { XEvent xEvent; - setupXEvent(&xEvent, w, state); + setupXEvent(&xEvent, w, state); if (type == NSFlagsChanged) { - if (savedModifiers > modifiers) { - xEvent.xany.type = KeyRelease; - } else { - xEvent.xany.type = KeyPress; - } + if (savedModifiers > modifiers) { + xEvent.xany.type = KeyRelease; + } else { + xEvent.xany.type = KeyPress; + } - /* - * Use special '-1' to signify a special keycode to our platform - * specific code in tkMacOSXKeyboard.c. This is rather like what - * happens on Windows. - */ + /* + * Use special '-1' to signify a special keycode to our + * platform specific code in tkMacOSXKeyboard.c. This is rather + * like what happens on Windows. + */ - xEvent.xany.send_event = -1; + xEvent.xany.send_event = -1; - /* - * Set keycode (which was zero) to the changed modifier - */ + /* + * Set keycode (which was zero) to the changed modifier + */ - xEvent.xkey.keycode = (modifiers ^ savedModifiers); + xEvent.xkey.keycode = (modifiers ^ savedModifiers); } else { - if (type == NSKeyUp || repeat) { - xEvent.xany.type = KeyRelease; - } else { - xEvent.xany.type = KeyPress; - } - - /* For command key, take input manager's word so things - like dvorak / qwerty layout work. */ - if ((modifiers & NSCommandKeyMask) == NSCommandKeyMask - && (modifiers & NSAlternateKeyMask) != NSAlternateKeyMask - && len > 0 && !isFunctionKey(code)) { - // head off keycode-based translation in tkMacOSXKeyboard.c - xEvent.xkey.nbytes = [characters length]; //len - } - - if ([characters length] > 0) { - xEvent.xkey.keycode = - (keyCode << 16) | (UInt16) [characters characterAtIndex:0]; - if (![characters getCString:xEvent.xkey.trans_chars - maxLength:XMaxTransChars encoding:NSUTF8StringEncoding]) { - /* prevent SF bug 2907388 (crash on some composite chars) */ - //PENDING: we might not need this anymore - TkMacOSXDbgMsg("characters too long"); - return theEvent; - } - } - - if (repeat) { - Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL); - xEvent.xany.type = KeyPress; - xEvent.xany.serial = LastKnownRequestProcessed(Tk_Display(tkwin)); - } + if (type == NSKeyUp || repeat) { + xEvent.xany.type = KeyRelease; + } else { + xEvent.xany.type = KeyPress; + } + + /* + * For command key, take input manager's word so things like + * dvorak / qwerty layout work. + */ + + if ((modifiers & NSCommandKeyMask) == NSCommandKeyMask + && (modifiers & NSAlternateKeyMask) != NSAlternateKeyMask + && len > 0 && !isFunctionKey(code)) { + // head off keycode-based translation in tkMacOSXKeyboard.c + xEvent.xkey.nbytes = [characters length]; //len + } + + if ([characters length] > 0) { + xEvent.xkey.keycode = (keyCode << 16) | + (UInt16) [characters characterAtIndex:0]; + if (![characters getCString:xEvent.xkey.trans_chars + maxLength:XMaxTransChars encoding:NSUTF8StringEncoding]) { + /* prevent SF bug 2907388 (crash on some composite chars) */ + //PENDING: we might not need this anymore + TkMacOSXDbgMsg("characters too long"); + return theEvent; + } + } + + if (repeat) { + Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL); + xEvent.xany.type = KeyPress; + xEvent.xany.serial = LastKnownRequestProcessed(Tk_Display(tkwin)); + } } Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL); savedModifiers = modifiers; return theEvent; - } /* if send straight to TK */ - - } /* if not processing compose */ + } /* if send straight to TK */ + } /* if not processing compose */ if (type == NSKeyDown) { - if (NS_KEYLOG) - fprintf (stderr, "keyDown: %s compose sequence.\n", - processingCompose == YES ? "Continue" : "Begin"); + if (NS_KEYLOG) { + TKLog(@"keyDown: %s compose sequence.\n", + processingCompose == YES ? "Continue" : "Begin"); + } processingCompose = YES; [nsEvArray addObject: theEvent]; [[w contentView] interpretKeyEvents: nsEvArray]; [nsEvArray removeObject: theEvent]; - } + } savedModifiers = modifiers; - return theEvent; } @end - @implementation TKContentView @@ -261,163 +264,189 @@ unsigned short releaseCode; by doCommandBySelector: deleteBackward: */ - (void)insertText: (id)aString { - int i, len = [(NSString *)aString length]; - XEvent xEvent; + int i, len = [(NSString *) aString length]; + XEvent xEvent; - if (NS_KEYLOG) - TKLog (@"insertText '%@'\tlen = %d", aString, len); - processingCompose = NO; - finishedCompose = YES; + if (NS_KEYLOG) { + TKLog(@"insertText '%@'\tlen = %d", aString, len); + } + processingCompose = NO; + finishedCompose = YES; - /* first, clear any working text */ - if (privateWorkingText != nil) - [self deleteWorkingText]; + /* + * First, clear any working text. + */ + + if (privateWorkingText != nil) { + [self deleteWorkingText]; + } - /* now insert the string as keystrokes */ - setupXEvent(&xEvent, [self window], 0); - xEvent.xany.type = KeyPress; + /* + * Now insert the string as keystrokes. + */ - for (i =0; i: inserts display of composing characters */ - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange { - NSString *str = [aString respondsToSelector: @selector (string)] ? - [aString string] : aString; - if (NS_KEYLOG) - TKLog (@"setMarkedText '%@' len =%lu range %lu from %lu", str, - (unsigned long) [str length], (unsigned long) selRange.length, - (unsigned long) selRange.location); - - if (privateWorkingText != nil) - [self deleteWorkingText]; - if ([str length] == 0) - return; + NSString *str = [aString respondsToSelector: @selector (string)] ? + [aString string] : aString; + if (NS_KEYLOG) { + TKLog(@"setMarkedText '%@' len =%lu range %lu from %lu", str, + (unsigned long) [str length], (unsigned long) selRange.length, + (unsigned long) selRange.location); + } + + if (privateWorkingText != nil) { + [self deleteWorkingText]; + } + if ([str length] == 0) { + return; + } - processingCompose = YES; - privateWorkingText = [str copy]; + processingCompose = YES; + privateWorkingText = [str copy]; - //PENDING: insert workingText underlined + //PENDING: insert workingText underlined } - (BOOL)hasMarkedText { - return privateWorkingText != nil; + return privateWorkingText != nil; } - (NSRange)markedRange { - NSRange rng = privateWorkingText != nil - ? NSMakeRange (0, [privateWorkingText length]) : NSMakeRange (NSNotFound, 0); - if (NS_KEYLOG) - TKLog (@"markedRange request"); - return rng; + NSRange rng = privateWorkingText != nil + ? NSMakeRange(0, [privateWorkingText length]) + : NSMakeRange(NSNotFound, 0); + + if (NS_KEYLOG) { + TKLog(@"markedRange request"); + } + return rng; } - (void)unmarkText { - if (NS_KEYLOG) - TKLog (@"unmark (accept) text"); - [self deleteWorkingText]; - processingCompose = NO; + if (NS_KEYLOG) { + TKLog(@"unmark (accept) text"); + } + [self deleteWorkingText]; + processingCompose = NO; } /* used to position char selection windows, etc. */ - (NSRect)firstRectForCharacterRange: (NSRange)theRange { - NSRect rect; - NSPoint pt; + NSRect rect; + NSPoint pt; - pt.x = caret_x; - pt.y = caret_y; + pt.x = caret_x; + pt.y = caret_y; - pt = [self convertPoint: pt toView: nil]; - pt = [[self window] tkConvertPointToScreen: pt]; - pt.y -= caret_height; + pt = [self convertPoint: pt toView: nil]; + pt = [[self window] tkConvertPointToScreen: pt]; + pt.y -= caret_height; - rect.origin = pt; - rect.size.width = caret_height; - rect.size.height = caret_height; - return rect; + rect.origin = pt; + rect.size.width = caret_height; + rect.size.height = caret_height; + return rect; } - (NSInteger)conversationIdentifier { - return (NSInteger)self; + return (NSInteger) self; } - (void)doCommandBySelector: (SEL)aSelector { - if (NS_KEYLOG) - TKLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector)); - processingCompose = NO; - if (aSelector == @selector (deleteBackward:)) - { - /* happens when user backspaces over an ongoing composition: - throw a 'delete' into the event queue */ - XEvent xEvent; - setupXEvent(&xEvent, [self window], 0); - xEvent.xany.type = KeyPress; - xEvent.xkey.nbytes = 1; - xEvent.xkey.keycode = (0x33 << 16) | 0x7F; - xEvent.xkey.trans_chars[0] = 0x7F; - xEvent.xkey.trans_chars[1] = 0x0; - Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL); + if (NS_KEYLOG) { + TKLog(@"doCommandBySelector: %@", NSStringFromSelector(aSelector)); + } + processingCompose = NO; + if (aSelector == @selector (deleteBackward:)) { + /* + * Happens when user backspaces over an ongoing composition: + * throw a 'delete' into the event queue. + */ + + XEvent xEvent; + + setupXEvent(&xEvent, [self window], 0); + xEvent.xany.type = KeyPress; + xEvent.xkey.nbytes = 1; + xEvent.xkey.keycode = (0x33 << 16) | 0x7F; + xEvent.xkey.trans_chars[0] = 0x7F; + xEvent.xkey.trans_chars[1] = 0x0; + Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL); } } - (NSArray *)validAttributesForMarkedText { - static NSArray *arr = nil; - if (arr == nil) arr = [NSArray new]; - /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */ - return arr; + static NSArray *arr = nil; + + if (arr == nil) { + arr = [NSArray new]; + } + /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */ + return arr; } - (NSRange)selectedRange { - if (NS_KEYLOG) - TKLog (@"selectedRange request"); - return NSMakeRange (NSNotFound, 0); + if (NS_KEYLOG) { + TKLog(@"selectedRange request"); + } + return NSMakeRange(NSNotFound, 0); } - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint { - if (NS_KEYLOG) - TKLog (@"characterIndexForPoint request"); - return 0; + if (NS_KEYLOG) { + TKLog(@"characterIndexForPoint request"); + } + return 0; } - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange { - static NSAttributedString *str = nil; - if (str == nil) str = [NSAttributedString new]; - if (NS_KEYLOG) - TKLog (@"attributedSubstringFromRange request"); - return str; + static NSAttributedString *str = nil; + if (str == nil) { + str = [NSAttributedString new]; + } + if (NS_KEYLOG) { + TKLog(@"attributedSubstringFromRange request"); + } + return str; } /* End impl. */ @end @@ -427,29 +456,30 @@ unsigned short releaseCode; /* delete display of composing characters [not in ] */ - (void)deleteWorkingText { - if (privateWorkingText == nil) - return; - if (NS_KEYLOG) - TKLog(@"deleteWorkingText len = %lu\n", - (unsigned long)[privateWorkingText length]); - [privateWorkingText release]; - privateWorkingText = nil; - processingCompose = NO; - - //PENDING: delete working text + if (privateWorkingText == nil) { + return; + } + if (NS_KEYLOG) { + TKLog(@"deleteWorkingText len = %lu\n", + (unsigned long)[privateWorkingText length]); + } + [privateWorkingText release]; + privateWorkingText = nil; + processingCompose = NO; + + //PENDING: delete working text } @end - - /* - * Set up basic fields in xevent for keyboard input. + * Set up basic fields in xevent for keyboard input. */ static void setupXEvent(XEvent *xEvent, NSWindow *w, unsigned int state) { TkWindow *winPtr = TkMacOSXGetTkWindow(w); Tk_Window tkwin = (Tk_Window) winPtr; + if (!winPtr) { return; } @@ -497,12 +527,13 @@ XGrabKeyboard( Time time) { keyboardGrabWinPtr = Tk_IdToWindow(display, grab_window); - TkWindow *captureWinPtr = (TkWindow *)TkMacOSXGetCapture(); + TkWindow *captureWinPtr = (TkWindow *) TkMacOSXGetCapture(); + if (keyboardGrabWinPtr && captureWinPtr) { NSWindow *w = TkMacOSXDrawableWindow(grab_window); MacDrawable *macWin = (MacDrawable *) grab_window; - if (w && macWin->toplevel->winPtr == (TkWindow*) captureWinPtr) { + if (w && macWin->toplevel->winPtr == (TkWindow *) captureWinPtr) { if (modalSession) { Tcl_Panic("XGrabKeyboard: already grabbed"); } @@ -621,7 +652,10 @@ Tk_SetCaretPos( } } - /* But adjust for fact that NS uses flipped view. */ + /* + * But adjust for fact that NS uses flipped view. + */ + y = Tk_Height(tkwin) - y; caret_x = x; @@ -632,75 +666,80 @@ Tk_SetCaretPos( static unsigned convert_ns_to_X_keysym[] = { - NSHomeFunctionKey, 0x50, - NSLeftArrowFunctionKey, 0x51, - NSUpArrowFunctionKey, 0x52, - NSRightArrowFunctionKey, 0x53, - NSDownArrowFunctionKey, 0x54, - NSPageUpFunctionKey, 0x55, - NSPageDownFunctionKey, 0x56, - NSEndFunctionKey, 0x57, - NSBeginFunctionKey, 0x58, - NSSelectFunctionKey, 0x60, - NSPrintFunctionKey, 0x61, - NSExecuteFunctionKey, 0x62, - NSInsertFunctionKey, 0x63, - NSUndoFunctionKey, 0x65, - NSRedoFunctionKey, 0x66, - NSMenuFunctionKey, 0x67, - NSFindFunctionKey, 0x68, - NSHelpFunctionKey, 0x6A, - NSBreakFunctionKey, 0x6B, - - NSF1FunctionKey, 0xBE, - NSF2FunctionKey, 0xBF, - NSF3FunctionKey, 0xC0, - NSF4FunctionKey, 0xC1, - NSF5FunctionKey, 0xC2, - NSF6FunctionKey, 0xC3, - NSF7FunctionKey, 0xC4, - NSF8FunctionKey, 0xC5, - NSF9FunctionKey, 0xC6, - NSF10FunctionKey, 0xC7, - NSF11FunctionKey, 0xC8, - NSF12FunctionKey, 0xC9, - NSF13FunctionKey, 0xCA, - NSF14FunctionKey, 0xCB, - NSF15FunctionKey, 0xCC, - NSF16FunctionKey, 0xCD, - NSF17FunctionKey, 0xCE, - NSF18FunctionKey, 0xCF, - NSF19FunctionKey, 0xD0, - NSF20FunctionKey, 0xD1, - NSF21FunctionKey, 0xD2, - NSF22FunctionKey, 0xD3, - NSF23FunctionKey, 0xD4, - NSF24FunctionKey, 0xD5, - - NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */ - NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */ - NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */ - - NSTabCharacter, 0x09, - 0x19, 0x09, /* left tab->regular since pass shift */ - NSCarriageReturnCharacter, 0x0D, - NSNewlineCharacter, 0x0D, - NSEnterCharacter, 0x8D, - - 0x1B, 0x1B /* escape */ + NSHomeFunctionKey, 0x50, + NSLeftArrowFunctionKey, 0x51, + NSUpArrowFunctionKey, 0x52, + NSRightArrowFunctionKey, 0x53, + NSDownArrowFunctionKey, 0x54, + NSPageUpFunctionKey, 0x55, + NSPageDownFunctionKey, 0x56, + NSEndFunctionKey, 0x57, + NSBeginFunctionKey, 0x58, + NSSelectFunctionKey, 0x60, + NSPrintFunctionKey, 0x61, + NSExecuteFunctionKey, 0x62, + NSInsertFunctionKey, 0x63, + NSUndoFunctionKey, 0x65, + NSRedoFunctionKey, 0x66, + NSMenuFunctionKey, 0x67, + NSFindFunctionKey, 0x68, + NSHelpFunctionKey, 0x6A, + NSBreakFunctionKey, 0x6B, + + NSF1FunctionKey, 0xBE, + NSF2FunctionKey, 0xBF, + NSF3FunctionKey, 0xC0, + NSF4FunctionKey, 0xC1, + NSF5FunctionKey, 0xC2, + NSF6FunctionKey, 0xC3, + NSF7FunctionKey, 0xC4, + NSF8FunctionKey, 0xC5, + NSF9FunctionKey, 0xC6, + NSF10FunctionKey, 0xC7, + NSF11FunctionKey, 0xC8, + NSF12FunctionKey, 0xC9, + NSF13FunctionKey, 0xCA, + NSF14FunctionKey, 0xCB, + NSF15FunctionKey, 0xCC, + NSF16FunctionKey, 0xCD, + NSF17FunctionKey, 0xCE, + NSF18FunctionKey, 0xCF, + NSF19FunctionKey, 0xD0, + NSF20FunctionKey, 0xD1, + NSF21FunctionKey, 0xD2, + NSF22FunctionKey, 0xD3, + NSF23FunctionKey, 0xD4, + NSF24FunctionKey, 0xD5, + + NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */ + NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */ + NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */ + + NSTabCharacter, 0x09, + 0x19, 0x09, /* left tab->regular since pass shift */ + NSCarriageReturnCharacter, 0x0D, + NSNewlineCharacter, 0x0D, + NSEnterCharacter, 0x8D, + + 0x1B, 0x1B /* escape */ }; -static unsigned isFunctionKey(unsigned code) +static unsigned +isFunctionKey( + unsigned code) { - const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym) - / sizeof (convert_ns_to_X_keysym[0])); - unsigned keysym; - for (keysym = 0; keysym < last_keysym; keysym += 2) - if (code == convert_ns_to_X_keysym[keysym]) - return 0xFF00 | convert_ns_to_X_keysym[keysym+1]; - return 0; - } + const unsigned last_keysym = (sizeof(convert_ns_to_X_keysym) + / sizeof(convert_ns_to_X_keysym[0])); + unsigned keysym; + + for (keysym = 0; keysym < last_keysym; keysym += 2) { + if (code == convert_ns_to_X_keysym[keysym]) { + return 0xFF00 | convert_ns_to_X_keysym[keysym + 1]; + } + } + return 0; +} /* * Local Variables: diff --git a/macosx/tkMacOSXMenu.c b/macosx/tkMacOSXMenu.c index 3d7cdaf..2292ede 100644 --- a/macosx/tkMacOSXMenu.c +++ b/macosx/tkMacOSXMenu.c @@ -193,10 +193,10 @@ static int ModifierCharWidth(Tk_Font tkfont); - (void) insertItem: (NSMenuItem *) newItem atIndex: (NSInteger) index { if (_tkMenu && index >= 0) { - if ((NSUInteger)index <= _tkOffset) { + if ((NSUInteger) index <= _tkOffset) { _tkOffset++; } else { - NSAssert((NSUInteger)index >= _tkItemCount + _tkOffset, + NSAssert((NSUInteger) index >= _tkItemCount + _tkOffset, @"Cannot insert in the middle of Tk menu"); } } @@ -206,9 +206,9 @@ static int ModifierCharWidth(Tk_Font tkfont); - (void) removeItemAtIndex: (NSInteger) index { if (_tkMenu && index >= 0) { - if ((NSUInteger)index < _tkOffset) { + if ((NSUInteger) index < _tkOffset) { _tkOffset--; - } else if ((NSUInteger)index < _tkItemCount + _tkOffset) { + } else if ((NSUInteger) index < _tkItemCount + _tkOffset) { _tkItemCount--; } } @@ -221,7 +221,7 @@ static int ModifierCharWidth(Tk_Font tkfont); action:@selector(tkMenuItemInvoke:) keyEquivalent:@""]; [menuItem setTarget:self]; - [menuItem setTag:(NSInteger)mePtr]; + [menuItem setTag:(NSInteger) mePtr]; return menuItem; } @end @@ -252,15 +252,16 @@ static int ModifierCharWidth(Tk_Font tkfont); */ if ([sender isKindOfClass:[NSMenuItem class]]) { - NSMenuItem *menuItem = (NSMenuItem *)sender; - TkMenu *menuPtr = (TkMenu *)_tkMenu; - TkMenuEntry *mePtr = (TkMenuEntry *)[menuItem tag]; + NSMenuItem *menuItem = (NSMenuItem *) sender; + TkMenu *menuPtr = (TkMenu *) _tkMenu; + TkMenuEntry *mePtr = (TkMenuEntry *) [menuItem tag]; if (menuPtr && mePtr) { Tcl_Interp *interp = menuPtr->interp; - /*Add time for errors to fire if necessary. This is sub-optimal - *but avoids issues with Tcl/Cocoa event loop integration. + /* + * Add time for errors to fire if necessary. This is sub-optimal + * but avoids issues with Tcl/Cocoa event loop integration. */ //Tcl_Sleep(100); @@ -305,8 +306,8 @@ static int ModifierCharWidth(Tk_Font tkfont); return NO; } else if (modifiers == (NSControlKeyMask | NSShiftKeyMask) && [event keyCode] == 48) { - - /* Starting with OSX 10.12 Control-Tab and Control-Shift-Tab are used + /* + * Starting with OSX 10.12 Control-Tab and Control-Shift-Tab are used * to select window tabs. But for some even more mysterious reason the * Control-Shift-Tab event has character 0x19 = NSBackTabCharacter * rather than 0x09 = NSTabCharacter. At the same time, the @@ -317,7 +318,6 @@ static int ModifierCharWidth(Tk_Font tkfont); key = @"\t"; } else if (([event modifierFlags] & NSCommandKeyMask) == NSCommandKeyMask) { - /* * If the command modifier is set, use the full character string so * things like the dvorak / qwerty layout will work. @@ -650,7 +650,7 @@ TkpConfigureMenuEntry( gc->foreground!=defaultFg? gc->foreground:gc->background); attributes = [[attributes mutableCopy] autorelease]; - [(NSMutableDictionary *)attributes setObject:color + [(NSMutableDictionary *) attributes setObject:color forKey:NSForegroundColorAttributeName]; } if (attributes) { @@ -690,21 +690,30 @@ TkpConfigureMenuEntry( [submenu setTitle:title]; if ([menuItem isEnabled]) { - /* This menuItem might have been previously disabled (XXX: - track this), which would have disabled entries; we must - re-enable the entries here. */ - int i = 0; - NSArray *itemArray = [submenu itemArray]; - for (NSMenuItem *item in itemArray) { - TkMenuEntry *submePtr = menuRefPtr->menuPtr->entries[i]; - /* Work around an apparent bug where itemArray can have - more items than the menu's entries[] array. */ - if (i >= (int)menuRefPtr->menuPtr->numEntries) break; - [item setEnabled: !(submePtr->state == ENTRY_DISABLED)]; - i++; - } + /* + * This menuItem might have been previously disabled (XXX: + * track this), which would have disabled entries; we must + * re-enable the entries here. + */ + + int i = 0; + NSArray *itemArray = [submenu itemArray]; + + for (NSMenuItem *item in itemArray) { + TkMenuEntry *submePtr = menuRefPtr->menuPtr->entries[i]; + + /* + * Work around an apparent bug where itemArray can have + * more items than the menu's entries[] array. + */ + + if (i >= (int) menuRefPtr->menuPtr->numEntries) { + break; + } + [item setEnabled: !(submePtr->state == ENTRY_DISABLED)]; + i++; + } } - } } } @@ -755,10 +764,10 @@ TkpDestroyMenuEntry( * * TkpPostMenu -- * - * Posts a menu on the screen. If entry is < 0 then the menu is - * drawn so its top left corner is located at the point with - * screen coordinates (x, y). Otherwise the top left corner of - * the specified entry is located at that point. + * Posts a menu on the screen. If entry is < 0 then the menu is drawn so + * its top left corner is located at the point with screen coordinates + * (x,y). Otherwise the top left corner of the specified entry is located + * at that point. * * Results: * Returns a standard Tcl result. @@ -828,13 +837,13 @@ TkpPostMenu( * * TkpPostTearoffMenu -- * - * Tearoff menus are not supported on the Mac. This placeholder - * function, which is simply a copy of the unix function, posts a - * completely useless window with a black background on the screen. If - * entry is < 0 then the window is positioned so that its top left corner - * is located at the point with screen coordinates (x, y). Otherwise the - * window position is offset so that top left corner of the specified - * entry would be located at that point, if there actually were a menu. + * Tearoff menus are not supported on the Mac. This placeholder function, + * which is simply a copy of the unix function, posts a completely useless + * window with a black background on the screen. If entry is < 0 then the + * window is positioned so that its top left corner is located at the + * point with screen coordinates (x, y). Otherwise the window position is + * offset so that top left corner of the specified entry would be located + * at that point, if there actually were a menu. * * Mac menus steal all mouse or keyboard input from the application until * the menu is dismissed, with or without a selection, by a mouse or key @@ -862,7 +871,7 @@ TkpPostTearoffMenu( int vRootX, vRootY, vRootWidth, vRootHeight; int result; - if (index >= (int)menuPtr->numEntries) { + if (index >= (int) menuPtr->numEntries) { index = menuPtr->numEntries - 1; } if (index >= 0) { @@ -960,12 +969,12 @@ TkpSetWindowMenuBar( * * TkpSetMainMenubar -- * - * Puts the menu associated with a window into the menubar. Should only - * be called when the window is in front. + * Puts the menu associated with a window into the menubar. Should only be + * called when the window is in front. * * This is a no-op on all other platforms. On OS X it is a no-op when - * passed a NULL menuName or a nonexistent menuName, with an exception - * for the first call in a new interpreter. In that special case, passing a + * passed a NULL menuName or a nonexistent menuName, with an exception for + * the first call in a new interpreter. In that special case, passing a * NULL menuName installs the default menu. * * Results: @@ -993,19 +1002,21 @@ TkpSetMainMenubar( */ if (Tk_IsEmbedded(winPtr)) { - return; - } + return; + } if (menuName) { Tk_Window menubar = NULL; + if (winPtr->wmInfoPtr && - winPtr->wmInfoPtr->menuPtr && - winPtr->wmInfoPtr->menuPtr->masterMenuPtr) { + winPtr->wmInfoPtr->menuPtr && + winPtr->wmInfoPtr->menuPtr->masterMenuPtr) { menubar = winPtr->wmInfoPtr->menuPtr->masterMenuPtr->tkwin; } /* - * Attempt to find the NSMenu directly. If that fails, ask Tk to find it. + * Attempt to find the NSMenu directly. If that fails, ask Tk to find + * it. */ if (menubar != NULL && strcmp(menuName, Tk_PathName(menubar)) == 0) { @@ -1013,6 +1024,7 @@ TkpSetMainMenubar( } else { TkMenuReferences *menuRefPtr = TkFindMenuReferences(interp, menuName); + if (menuRefPtr && menuRefPtr->menuPtr && menuRefPtr->menuPtr->platformData) { menu = (TKMenu *) menuRefPtr->menuPtr->platformData; @@ -1021,9 +1033,8 @@ TkpSetMainMenubar( } /* - * If we couldn't find a menu, do nothing unless the window belongs - * to a different application. In that case, install the default - * menubar. + * If we couldn't find a menu, do nothing unless the window belongs to a + * different application. In that case, install the default menubar. */ if (menu || interp != currentInterp) { @@ -1038,8 +1049,8 @@ TkpSetMainMenubar( * CheckForSpecialMenu -- * * Given a menu, check to see whether or not it is a cascade in a menubar - * with one of the special names ".apple", ".help" or ".window". If it - * is, the entry that points to this menu will be marked. + * with one of the special names ".apple", ".help" or ".window". If it is, + * the entry that points to this menu will be marked. * * Results: * None. @@ -1230,11 +1241,12 @@ TkpComputeStandardMenuGeometry( /* * Do nothing if this menu is a clone. */ + if (menuPtr->tkwin == NULL || menuPtr->masterMenuPtr != menuPtr) { return; } - menuSize = [(NSMenu *)menuPtr->platformData size]; + menuSize = [(NSMenu *) menuPtr->platformData size]; Tk_GetPixelsFromObj(NULL, menuPtr->tkwin, menuPtr->borderWidthPtr, &borderWidth); Tk_GetPixelsFromObj(NULL, menuPtr->tkwin, menuPtr->activeBorderWidthPtr, @@ -1248,16 +1260,16 @@ TkpComputeStandardMenuGeometry( * want to do it intelligently. We are going to precalculate them and pass * them down to all of the measuring and drawing routines. We will measure * the font metrics of the menu once. If an entry does not have its own - * font set, then we give the geometry/drawing routines the menu's font - * and metrics. If an entry has its own font, we will measure that font - * and give all of the geometry/drawing the entry's font and metrics. + * font set, then we give the geometry/drawing routines the menu's font and + * metrics. If an entry has its own font, we will measure that font and + * give all of the geometry/drawing the entry's font and metrics. */ menuFont = Tk_GetFontFromObj(menuPtr->tkwin, menuPtr->fontPtr); Tk_GetFontMetrics(menuFont, &menuMetrics); menuModifierCharWidth = ModifierCharWidth(menuFont); - for (i = 0; i < (int)menuPtr->numEntries; i++) { + for (i = 0; i < (int) menuPtr->numEntries; i++) { mePtr = menuPtr->entries[i]; if (mePtr->type == CASCADE_ENTRY || mePtr->accelLength > 0) { haveAccel = 1; @@ -1265,7 +1277,7 @@ TkpComputeStandardMenuGeometry( } } - for (i = 0; i < (int)menuPtr->numEntries; i++) { + for (i = 0; i < (int) menuPtr->numEntries; i++) { mePtr = menuPtr->entries[i]; if (mePtr->type == TEAROFF_ENTRY) { continue; @@ -1295,6 +1307,7 @@ TkpComputeStandardMenuGeometry( NSMenuItem *menuItem = (NSMenuItem *) mePtr->platformEntryData; int haveImage = 0, width = 0, height = 0; + if (mePtr->image) { Tk_SizeOfImage(mePtr->image, &width, &height); haveImage = 1; @@ -1302,6 +1315,7 @@ TkpComputeStandardMenuGeometry( } else if (mePtr->bitmapPtr) { Pixmap bitmap = Tk_GetBitmapFromObj(menuPtr->tkwin, mePtr->bitmapPtr); + Tk_SizeOfBitmap(menuPtr->display, bitmap, &width, &height); haveImage = 1; height += 2; /* tweak */ @@ -1413,7 +1427,7 @@ GenerateMenuSelectEvent( if (menuPtr) { int index = [menu tkIndexOfItem:menuItem]; - if (index < 0 || index >= (int)menuPtr->numEntries || + if (index < 0 || index >= (int) menuPtr->numEntries || (menuPtr->entries[index])->state == ENTRY_DISABLED) { TkActivateMenuEntry(menuPtr, -1); } else { @@ -1492,7 +1506,7 @@ RecursivelyClearActiveMenu( int i; TkActivateMenuEntry(menuPtr, -1); - for (i = 0; i < (int)menuPtr->numEntries; i++) { + for (i = 0; i < (int) menuPtr->numEntries; i++) { TkMenuEntry *mePtr = menuPtr->entries[i]; if (mePtr->type == CASCADE_ENTRY @@ -1781,7 +1795,7 @@ TkMacOSXPreprocessMenu(void) * TkMacOSXUseID -- * * Take the ID out of the available list for new menus. Used by the - * default menu bar's menus so that they do not get created at the tk + * default menu bar's menus so that they do not get created at the Tk * level. See TkMacOSXGetNewMenuID for more information. * * Results: @@ -1806,8 +1820,7 @@ TkMacOSXUseMenuID( * * TkMacOSXDispatchMenuEvent -- * - * Given a menu id and an item, dispatches the command associated with - * it. + * Given a menu id and an item, dispatches the command associated with it. * * Results: * None. @@ -1857,9 +1870,10 @@ TkMacOSXHandleTearoffMenu(void) * * TkMacOSXSetHelpMenuItemCount -- * - * Has to be called after the first call to InsertMenu. Sets up the - * global variable for the number of items in the unmodified help menu. - * NB. Nobody uses this any more, since you can get the number of system + * Has to be called after the first call to InsertMenu. Sets up the global + * variable for the number of items in the unmodified help menu. + * + * NB: Nobody uses this any more, since you can get the number of system * help items from HMGetHelpMenu trivially. But it is in the stubs * table... * diff --git a/macosx/tkMacOSXMenubutton.c b/macosx/tkMacOSXMenubutton.c index b2b4b76..33ae213 100644 --- a/macosx/tkMacOSXMenubutton.c +++ b/macosx/tkMacOSXMenubutton.c @@ -1,8 +1,8 @@ /* * tkMacOSXMenubutton.c -- * - * This file implements the Macintosh specific portion of the - * menubutton widget. + * This file implements the Macintosh specific portion of the menubutton + * widget. * * Copyright (c) 1996 by Sun Microsystems, Inc. * Copyright 2001, Apple Computer, Inc. @@ -32,7 +32,6 @@ typedef struct { int hasImageOrBitmap; } DrawParams; - /* * Declaration of Mac specific button structure. */ @@ -50,21 +49,24 @@ typedef struct MacMenuButton { * Forward declarations for static functions defined later in this file: */ -static void MenuButtonEventProc(ClientData clientData, XEvent *eventPtr); -static void MenuButtonBackgroundDrawCB (MacMenuButton *ptr, SInt16 depth, - Boolean isColorDev); -static void MenuButtonContentDrawCB (ThemeButtonKind kind, - const HIThemeButtonDrawInfo * info, - MacMenuButton *ptr, SInt16 depth, - Boolean isColorDev); -static void MenuButtonEventProc ( ClientData clientData, XEvent *eventPtr); -static void TkMacOSXComputeMenuButtonParams (TkMenuButton * butPtr, - ThemeButtonKind* btnkind, - HIThemeButtonDrawInfo* drawinfo); -static void TkMacOSXComputeMenuButtonDrawParams (TkMenuButton * butPtr, - DrawParams * dpPtr); -static void TkMacOSXDrawMenuButton (MacMenuButton *butPtr, GC gc, Pixmap pixmap); -static void DrawMenuButtonImageAndText(TkMenuButton* butPtr); +static void MenuButtonEventProc(ClientData clientData, + XEvent *eventPtr); +static void MenuButtonBackgroundDrawCB(MacMenuButton *ptr, + SInt16 depth, Boolean isColorDev); +static void MenuButtonContentDrawCB(ThemeButtonKind kind, + const HIThemeButtonDrawInfo *info, + MacMenuButton *ptr, SInt16 depth, + Boolean isColorDev); +static void MenuButtonEventProc(ClientData clientData, + XEvent *eventPtr); +static void TkMacOSXComputeMenuButtonParams(TkMenuButton *butPtr, + ThemeButtonKind *btnkind, + HIThemeButtonDrawInfo *drawinfo); +static void TkMacOSXComputeMenuButtonDrawParams( + TkMenuButton *butPtr, DrawParams *dpPtr); +static void TkMacOSXDrawMenuButton(MacMenuButton *butPtr, GC gc, + Pixmap pixmap); +static void DrawMenuButtonImageAndText(TkMenuButton *butPtr); /* * The structure below defines menubutton class behavior by means of @@ -133,8 +135,7 @@ TkpCreateMenuButton( { MacMenuButton *mbPtr = (MacMenuButton *) ckalloc(sizeof(MacMenuButton)); - Tk_CreateEventHandler(tkwin, ActivateMask, MenuButtonEventProc, - (ClientData) mbPtr); + Tk_CreateEventHandler(tkwin, ActivateMask, MenuButtonEventProc, mbPtr); mbPtr->flags = FIRST_DRAW; mbPtr->btnkind = kThemePopupButton; bzero(&mbPtr->drawinfo, sizeof(mbPtr->drawinfo)); @@ -153,8 +154,7 @@ TkpCreateMenuButton( * None. * * Side effects: - * Commands are output to X to display the menubutton in its - * current mode. + * Commands are output to X to display the menubutton in its current mode. * *---------------------------------------------------------------------- */ @@ -163,11 +163,11 @@ void TkpDisplayMenuButton( ClientData clientData) /* Information about widget. */ { - MacMenuButton *mbPtr = (MacMenuButton *)clientData; - TkMenuButton *butPtr = (TkMenuButton *) clientData; - Tk_Window tkwin = butPtr->tkwin; + MacMenuButton *mbPtr = clientData; + TkMenuButton *butPtr = clientData; + Tk_Window tkwin = butPtr->tkwin; Pixmap pixmap; - DrawParams* dpPtr = &mbPtr->drawParams; + DrawParams *dpPtr = &mbPtr->drawParams; butPtr->flags &= ~REDRAW_PENDING; if ((butPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) { @@ -179,22 +179,26 @@ TkpDisplayMenuButton( TkMacOSXComputeMenuButtonDrawParams(butPtr, dpPtr); /* - * set up clipping region. Make sure the we are using the port - * for this button, or we will set the wrong window's clip. + * Set up clipping region. Make sure the we are using the port for this + * button, or we will set the wrong window's clip. */ TkMacOSXSetUpClippingRgn(pixmap); - /* Draw the native portion of the buttons. */ + /* + * Draw the native portion of the buttons. + */ + TkMacOSXDrawMenuButton(mbPtr, dpPtr->gc, pixmap); - /* Draw highlight border, if needed. */ - if (butPtr->highlightWidth < 3) { - if ((butPtr->flags & GOT_FOCUS)) { - Tk_Draw3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0, + /* + * Draw highlight border, if needed. + */ + + if ((butPtr->highlightWidth < 3) && (butPtr->flags & GOT_FOCUS)) { + Tk_Draw3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0, Tk_Width(tkwin), Tk_Height(tkwin), butPtr->highlightWidth, TK_RELIEF_SOLID); - } } } @@ -203,8 +207,8 @@ TkpDisplayMenuButton( * * TkpDestroyMenuButton -- * - * Free data structures associated with the menubutton control. - * This is a no-op on the Mac. + * Free data structures associated with the menubutton control. This is a + * no-op on the Mac. * * Results: * None. @@ -279,44 +283,42 @@ TkpComputeMenuButtonGeometry(butPtr) } /* - * If the button is compound (ie, it shows both an image and text), - * the new geometry is a combination of the image and text geometry. - * We only honor the compound bit if the button has both text and an - * image, because otherwise it is not really a compound button. + * If the button is compound (ie, it shows both an image and text), the new + * geometry is a combination of the image and text geometry. We only honor + * the compound bit if the button has both text and an image, because + * otherwise it is not really a compound button. */ if (haveImage && haveText) { switch ((enum compound) butPtr->compound) { - case COMPOUND_TOP: - case COMPOUND_BOTTOM: { - /* - * Image is above or below text - */ - - height += txtHeight + butPtr->padY; - width = (width > txtWidth ? width : txtWidth); - break; - } - case COMPOUND_LEFT: - case COMPOUND_RIGHT: { - /* - * Image is left or right of text - */ - - width += txtWidth + butPtr->padX; - height = (height > txtHeight ? height : txtHeight); - break; - } - case COMPOUND_CENTER: { - /* - * Image and text are superimposed - */ - - width = (width > txtWidth ? width : txtWidth); - height = (height > txtHeight ? height : txtHeight); - break; - } - case COMPOUND_NONE: {break;} + case COMPOUND_TOP: + case COMPOUND_BOTTOM: + /* + * Image is above or below text + */ + + height += txtHeight + butPtr->padY; + width = (width > txtWidth ? width : txtWidth); + break; + case COMPOUND_LEFT: + case COMPOUND_RIGHT: + /* + * Image is left or right of text + */ + + width += txtWidth + butPtr->padX; + height = (height > txtHeight ? height : txtHeight); + break; + case COMPOUND_CENTER: + /* + * Image and text are superimposed + */ + + width = (width > txtWidth ? width : txtWidth); + height = (height > txtHeight ? height : txtHeight); + break; + case COMPOUND_NONE: + break; } if (butPtr->width > 0) { @@ -371,32 +373,24 @@ TkpComputeMenuButtonGeometry(butPtr) */ void DrawMenuButtonImageAndText( - TkMenuButton* butPtr) + TkMenuButton *butPtr) { - MacMenuButton *mbPtr = (MacMenuButton*)butPtr; - Tk_Window tkwin = butPtr->tkwin; - Pixmap pixmap; - int haveImage = 0; - int haveText = 0; - int imageWidth = 0; - int imageHeight = 0; - int imageXOffset = 0; - int imageYOffset = 0; - int textXOffset = 0; - int textYOffset = 0; - int width = 0; - int height = 0; - int fullWidth = 0; - int fullHeight = 0; - int pressed; + MacMenuButton *mbPtr = (MacMenuButton *) butPtr; + Tk_Window tkwin = butPtr->tkwin; + Pixmap pixmap; + int haveImage = 0, haveText = 0; + int imageWidth = 0, imageHeight = 0; + int imageXOffset = 0, imageYOffset = 0; + int textXOffset = 0, textYOffset = 0; + int width = 0, height = 0; + int fullWidth = 0, fullHeight = 0; if (tkwin == NULL || !Tk_IsMapped(tkwin)) { return; } - DrawParams* dpPtr = &mbPtr->drawParams; - pixmap = (Pixmap)Tk_WindowId(tkwin); - + DrawParams *dpPtr = &mbPtr->drawParams; + pixmap = (Pixmap) Tk_WindowId(tkwin); if (butPtr->image != None) { Tk_SizeOfImage(butPtr->image, &width, &height); @@ -406,86 +400,80 @@ DrawMenuButtonImageAndText( haveImage = 1; } - imageWidth = width; + imageWidth = width; imageHeight = height; - if (mbPtr->drawinfo.state == kThemeStatePressed) { - /* Offset bitmaps by a bit when the button is pressed. */ - pressed = 1; - } - haveText = (butPtr->textWidth != 0 && butPtr->textHeight != 0); if (butPtr->compound != COMPOUND_NONE && haveImage && haveText) { - int x = 0; - int y = 0; + int x = 0, y = 0; + textXOffset = 0; textYOffset = 0; fullWidth = 0; fullHeight = 0; switch ((enum compound) butPtr->compound) { - case COMPOUND_TOP: - case COMPOUND_BOTTOM: { - /* Image is above or below text */ - if (butPtr->compound == COMPOUND_TOP) { - textYOffset = height + butPtr->padY; - } else { - imageYOffset = butPtr->textHeight + butPtr->padY; - } - fullHeight = height + butPtr->textHeight + butPtr->padY; - fullWidth = (width > butPtr->textWidth ? - width : butPtr->textWidth); - textXOffset = (fullWidth - butPtr->textWidth)/2; - imageXOffset = (fullWidth - width)/2; - break; - } - case COMPOUND_LEFT: - case COMPOUND_RIGHT: { - /* - * Image is left or right of text - */ - - if (butPtr->compound == COMPOUND_LEFT) { - textXOffset = width + butPtr->padX - 2; - } else { - imageXOffset = butPtr->textWidth + butPtr->padX; - } - fullWidth = butPtr->textWidth + butPtr->padX + width; - fullHeight = (height > butPtr->textHeight ? height : - butPtr->textHeight); - textYOffset = (fullHeight - butPtr->textHeight)/2; - imageYOffset = (fullHeight - height)/2; - break; - } - case COMPOUND_CENTER: { - /* - * Image and text are superimposed - */ - - fullWidth = (width > butPtr->textWidth ? width : - butPtr->textWidth); - fullHeight = (height > butPtr->textHeight ? height : - butPtr->textHeight); - textXOffset = (fullWidth - butPtr->textWidth)/2; - imageXOffset = (fullWidth - width)/2; - textYOffset = (fullHeight - butPtr->textHeight)/2; - imageYOffset = (fullHeight - height)/2; - break; - } - case COMPOUND_NONE: {break;} + case COMPOUND_TOP: + case COMPOUND_BOTTOM: + /* + * Image is above or below text. + */ + + if (butPtr->compound == COMPOUND_TOP) { + textYOffset = height + butPtr->padY; + } else { + imageYOffset = butPtr->textHeight + butPtr->padY; + } + fullHeight = height + butPtr->textHeight + butPtr->padY; + fullWidth = (width > butPtr->textWidth ? + width : butPtr->textWidth); + textXOffset = (fullWidth - butPtr->textWidth)/2; + imageXOffset = (fullWidth - width)/2; + break; + case COMPOUND_LEFT: + case COMPOUND_RIGHT: + /* + * Image is left or right of text + */ + + if (butPtr->compound == COMPOUND_LEFT) { + textXOffset = width + butPtr->padX - 2; + } else { + imageXOffset = butPtr->textWidth + butPtr->padX; + } + fullWidth = butPtr->textWidth + butPtr->padX + width; + fullHeight = (height > butPtr->textHeight ? height : + butPtr->textHeight); + textYOffset = (fullHeight - butPtr->textHeight)/2; + imageYOffset = (fullHeight - height)/2; + break; + case COMPOUND_CENTER: + /* + * Image and text are superimposed + */ + + fullWidth = (width > butPtr->textWidth ? width : butPtr->textWidth); + fullHeight = (height > butPtr->textHeight ? height : + butPtr->textHeight); + textXOffset = (fullWidth - butPtr->textWidth) / 2; + imageXOffset = (fullWidth - width) / 2; + textYOffset = (fullHeight - butPtr->textHeight) / 2; + imageYOffset = (fullHeight - height) / 2; + break; + case COMPOUND_NONE: + break; } TkComputeAnchor(butPtr->anchor, tkwin, - butPtr->padX + butPtr->inset, - butPtr->padY + butPtr->inset, + butPtr->padX + butPtr->inset, butPtr->padY + butPtr->inset, fullWidth, fullHeight, &x, &y); imageXOffset = LEFT_INSET; imageYOffset += y; textYOffset -= 1; if (butPtr->image != NULL) { - Tk_RedrawImage(butPtr->image, 0, 0, width, - height, pixmap, imageXOffset, imageYOffset); + Tk_RedrawImage(butPtr->image, 0, 0, width, + height, pixmap, imageXOffset, imageYOffset); } else { XSetClipOrigin(butPtr->display, dpPtr->gc, imageXOffset, imageYOffset); @@ -499,12 +487,12 @@ DrawMenuButtonImageAndText( dpPtr->gc, butPtr->textLayout, x + textXOffset, y + textYOffset, 0, -1); Tk_UnderlineTextLayout(butPtr->display, pixmap, dpPtr->gc, - butPtr->textLayout, - x + textXOffset, y + textYOffset, + butPtr->textLayout, x + textXOffset, y + textYOffset, butPtr->underline); } else { + int x, y; + if (haveImage) { - int x, y; TkComputeAnchor(butPtr->anchor, tkwin, butPtr->padX + butPtr->borderWidth, butPtr->padY + butPtr->borderWidth, @@ -524,27 +512,24 @@ DrawMenuButtonImageAndText( XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0); } } else { - int x, y; textXOffset = LEFT_INSET; TkComputeAnchor(butPtr->anchor, tkwin, butPtr->padX, butPtr->padY, - butPtr->textWidth, butPtr->textHeight, &x, &y); + butPtr->textWidth, butPtr->textHeight, &x, &y); Tk_DrawTextLayout(butPtr->display, pixmap, dpPtr->gc, - butPtr->textLayout, textXOffset, y, 0, -1); + butPtr->textLayout, textXOffset, y, 0, -1); y += butPtr->textHeight/2; - } + } } } - - - + /* *-------------------------------------------------------------- * * TkMacOSXDrawMenuButton -- * - * This function draws the tk menubutton using Mac controls - * In addition, this code may apply custom colors passed - * in the TkMenubutton. + * This function draws the tk menubutton using Mac controls. In + * addition, this code may apply custom colors passed in the + * TkMenubutton. * * Results: * None. @@ -554,43 +539,39 @@ DrawMenuButtonImageAndText( * *-------------------------------------------------------------- */ + static void TkMacOSXDrawMenuButton( MacMenuButton *mbPtr, /* Mac menubutton. */ - GC gc, /* The GC we are drawing into - needed for - * the bevel button */ - Pixmap pixmap) /* The pixmap we are drawing into - needed - * for the bevel button */ + GC gc, /* The GC we are drawing into - needed for the bevel + * button */ + Pixmap pixmap) /* The pixmap we are drawing into - needed for the + * bevel button */ { - TkMenuButton * butPtr = ( TkMenuButton *)mbPtr; - TkWindow * winPtr; - HIRect cntrRect; + TkMenuButton *butPtr = (TkMenuButton *) mbPtr; + TkWindow *winPtr = (TkWindow *) butPtr->tkwin; + HIRect cntrRect; TkMacOSXDrawingContext dc; - DrawParams* dpPtr = &mbPtr->drawParams; + DrawParams *dpPtr = &mbPtr->drawParams; int useNewerHITools = 1; - winPtr = (TkWindow *)butPtr->tkwin; - TkMacOSXComputeMenuButtonParams(butPtr, &mbPtr->btnkind, &mbPtr->drawinfo); cntrRect = CGRectMake(winPtr->privatePtr->xOff, winPtr->privatePtr->yOff, - Tk_Width(butPtr->tkwin), - Tk_Height(butPtr->tkwin)); + Tk_Width(butPtr->tkwin), Tk_Height(butPtr->tkwin)); if (useNewerHITools == 1) { HIRect contHIRec; static HIThemeButtonDrawInfo hiinfo; - MenuButtonBackgroundDrawCB((MacMenuButton*) mbPtr, 32, true); - + MenuButtonBackgroundDrawCB(mbPtr, 32, true); if (!TkMacOSXSetupDrawingContext(pixmap, dpPtr->gc, 1, &dc)) { return; } - hiinfo.version = 0; hiinfo.state = mbPtr->drawinfo.state; - hiinfo.kind = mbPtr->btnkind; + hiinfo.kind = mbPtr->btnkind; hiinfo.value = mbPtr->drawinfo.value; hiinfo.adornment = mbPtr->drawinfo.adornment; hiinfo.animation.time.current = CFAbsoluteTimeGetCurrent(); @@ -599,10 +580,10 @@ TkMacOSXDrawMenuButton( } HIThemeDrawButton(&cntrRect, &hiinfo, dc.context, - kHIThemeOrientationNormal, &contHIRec); + kHIThemeOrientationNormal, &contHIRec); TkMacOSXRestoreDrawingContext(&dc); - MenuButtonContentDrawCB( mbPtr->btnkind, &mbPtr->drawinfo, - (MacMenuButton *)mbPtr, 32, true); + MenuButtonContentDrawCB(mbPtr->btnkind, &mbPtr->drawinfo, + mbPtr, 32, true); } else { if (!TkMacOSXSetupDrawingContext(pixmap, dpPtr->gc, 1, &dc)) { return; @@ -617,33 +598,34 @@ TkMacOSXDrawMenuButton( * * MenuButtonBackgroundDrawCB -- * - * This function draws the background that - * lies under checkboxes and radiobuttons. + * This function draws the background that lies under checkboxes and + * radiobuttons. * * Results: - * None. + * None. * * Side effects: - * The background gets updated to the current color. + * The background gets updated to the current color. * *-------------------------------------------------------------- */ + static void MenuButtonBackgroundDrawCB ( MacMenuButton *ptr, SInt16 depth, Boolean isColorDev) { - TkMenuButton* butPtr = (TkMenuButton*)ptr; - Tk_Window tkwin = butPtr->tkwin; + TkMenuButton* butPtr = (TkMenuButton *) ptr; + Tk_Window tkwin = butPtr->tkwin; Pixmap pixmap; + if (tkwin == NULL || !Tk_IsMapped(tkwin)) { return; } - pixmap = (Pixmap)Tk_WindowId(tkwin); - + pixmap = (Pixmap) Tk_WindowId(tkwin); Tk_Fill3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0, - Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT); + Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT); } /* @@ -651,16 +633,17 @@ MenuButtonBackgroundDrawCB ( * * MenuButtonContentDrawCB -- * - * This function draws the label and image for the button. + * This function draws the label and image for the button. * * Results: - * None. + * None. * * Side effects: - * The content of the button gets updated. + * The content of the button gets updated. * *-------------------------------------------------------------- */ + static void MenuButtonContentDrawCB ( ThemeButtonKind kind, @@ -669,8 +652,8 @@ MenuButtonContentDrawCB ( SInt16 depth, Boolean isColorDev) { - TkMenuButton *butPtr = (TkMenuButton *)ptr; - Tk_Window tkwin = butPtr->tkwin; + TkMenuButton *butPtr = (TkMenuButton *) ptr; + Tk_Window tkwin = butPtr->tkwin; if (tkwin == NULL || !Tk_IsMapped(tkwin)) { return; @@ -683,8 +666,8 @@ MenuButtonContentDrawCB ( * * MenuButtonEventProc -- * - * This procedure is invoked by the Tk dispatcher for various - * events on buttons. + * This procedure is invoked by the Tk dispatcher for various events on + * buttons. * * Results: * None. @@ -700,8 +683,8 @@ MenuButtonEventProc( ClientData clientData, /* Information about window. */ XEvent *eventPtr) /* Information about event. */ { - TkMenuButton *buttonPtr = (TkMenuButton *) clientData; - MacMenuButton *mbPtr = (MacMenuButton *) clientData; + TkMenuButton *buttonPtr = clientData; + MacMenuButton *mbPtr = clientData; if (eventPtr->type == ActivateNotify || eventPtr->type == DeactivateNotify) { @@ -725,9 +708,9 @@ MenuButtonEventProc( * * TkMacOSXComputeMenuButtonParams -- * - * This procedure computes the various parameters used - * when creating a Carbon Appearance control. - * These are determined by the various tk button parameters + * This procedure computes the various parameters used when creating a + * Carbon Appearance control. These are determined by the various Tk + * button parameters * * Results: * None. @@ -740,11 +723,11 @@ MenuButtonEventProc( static void TkMacOSXComputeMenuButtonParams( - TkMenuButton * butPtr, - ThemeButtonKind* btnkind, + TkMenuButton *butPtr, + ThemeButtonKind *btnkind, HIThemeButtonDrawInfo *drawinfo) { - MacMenuButton *mbPtr = (MacMenuButton *)butPtr; + MacMenuButton *mbPtr = (MacMenuButton *) butPtr; if (butPtr->image || butPtr->bitmap || butPtr->text) { /* TODO: allow for Small and Mini menubuttons. */ @@ -789,25 +772,25 @@ TkMacOSXComputeMenuButtonParams( * * TkMacOSXComputeMenuButtonDrawParams -- * - * This procedure selects an appropriate drawing context for - * drawing a menubutton. + * This procedure selects an appropriate drawing context for drawing a + * menubutton. * * Results: - * None. + * None. * * Side effects: - * Sets the button draw parameters. + * Sets the button draw parameters. * *---------------------------------------------------------------------- */ static void TkMacOSXComputeMenuButtonDrawParams( - TkMenuButton * butPtr, - DrawParams * dpPtr) + TkMenuButton *butPtr, + DrawParams *dpPtr) { - dpPtr->hasImageOrBitmap = ((butPtr->image != NULL) || - (butPtr->bitmap != None)); + dpPtr->hasImageOrBitmap = + ((butPtr->image != NULL) || (butPtr->bitmap != None)); dpPtr->border = butPtr->normalBorder; if ((butPtr->state == STATE_DISABLED) && (butPtr->disabledFg != NULL)) { dpPtr->gc = butPtr->disabledGC; @@ -818,7 +801,7 @@ TkMacOSXComputeMenuButtonDrawParams( dpPtr->gc = butPtr->normalTextGC; } } - + /* * Local Variables: * mode: objc diff --git a/macosx/tkMacOSXMenus.c b/macosx/tkMacOSXMenus.c index 32d807e..bc66a10 100644 --- a/macosx/tkMacOSXMenus.c +++ b/macosx/tkMacOSXMenus.c @@ -177,7 +177,6 @@ static Tcl_Obj * GetWidgetDemoPath(Tcl_Interp *interp); SEL action = [anItem action]; if (sel_isEqual(action, @selector(preferences:))) { - return (_eventInterp && Tcl_FindCommand(_eventInterp, "::tk::mac::ShowPreferences", NULL, 0)); } else if (sel_isEqual(action, @selector(tkDemo:))) { diff --git a/macosx/tkMacOSXNotify.c b/macosx/tkMacOSXNotify.c index 3a32527..7267b00 100644 --- a/macosx/tkMacOSXNotify.c +++ b/macosx/tkMacOSXNotify.c @@ -33,7 +33,7 @@ static void TkMacOSXEventsSetupProc(ClientData clientData, int flags); static void TkMacOSXEventsCheckProc(ClientData clientData, int flags); #ifdef TK_MAC_DEBUG_EVENTS -static char* Tk_EventName[39] = { +static const char *Tk_EventName[39] = { "", "", "KeyPress", /*2*/ @@ -136,8 +136,8 @@ void DebugPrintQueue(void) /* * Since the contentView is the first responder for a Tk Window, it is - * responsible for sending events up the responder chain. We also check - * the pasteboard here. + * responsible for sending events up the responder chain. We also check the + * pasteboard here. */ - (void) sendEvent: (NSEvent *) theEvent { @@ -190,8 +190,8 @@ GetRunLoopMode(NSModalSession modalSession) * * Tk_MacOSXSetupTkNotifier -- * - * This procedure is called during Tk initialization to create - * the event source for TkAqua events. + * This procedure is called during Tk initialization to create the event + * source for TkAqua events. * * Results: * None. @@ -224,8 +224,7 @@ Tk_MacOSXSetupTkNotifier(void) "first [load] of TkAqua has to occur in the main thread!"); } Tcl_CreateEventSource(TkMacOSXEventsSetupProc, - TkMacOSXEventsCheckProc, - NULL); + TkMacOSXEventsCheckProc, NULL); TkCreateExitHandler(TkMacOSXNotifyExitHandler, NULL); Tcl_SetServiceMode(TCL_SERVICE_ALL); TclMacOSXNotifierAddRunLoopMode(NSEventTrackingRunLoopMode); @@ -258,8 +257,7 @@ TkMacOSXNotifyExitHandler( TSD_INIT(); Tcl_DeleteEventSource(TkMacOSXEventsSetupProc, - TkMacOSXEventsCheckProc, - NULL); + TkMacOSXEventsCheckProc, NULL); tsdPtr->initialized = 0; } @@ -268,19 +266,19 @@ TkMacOSXNotifyExitHandler( * * TkMacOSXEventsSetupProc -- * - * This procedure implements the setup part of the MacOSX event - * source. It is invoked by Tcl_DoOneEvent before calling - * TkMacOSXEventsProc to process all queued NSEvents. In our - * case, all we need to do is to set the Tcl MaxBlockTime to - * 0 before starting the loop to process all queued NSEvents. + * This procedure implements the setup part of the MacOSX event source. It + * is invoked by Tcl_DoOneEvent before calling TkMacOSXEventsProc to + * process all queued NSEvents. In our case, all we need to do is to set + * the Tcl MaxBlockTime to 0 before starting the loop to process all + * queued NSEvents. * * Results: * None. * * Side effects: * - * If NSEvents are queued, then the maximum block time will be set - * to 0 to ensure that control returns immediately to Tcl. + * If NSEvents are queued, then the maximum block time will be set to 0 to + * ensure that control returns immediately to Tcl. * *---------------------------------------------------------------------- */ @@ -291,15 +289,24 @@ TkMacOSXEventsSetupProc( int flags) { NSString *runloopMode = [[NSRunLoop currentRunLoop] currentMode]; - /* runloopMode will be nil if we are in a Tcl event loop. */ + + /* + * runloopMode will be nil if we are in a Tcl event loop. + */ + if (flags & TCL_WINDOW_EVENTS && !runloopMode) { static const Tcl_Time zeroBlockTime = { 0, 0 }; [NSApp _resetAutoreleasePool]; - /* Call this with dequeue=NO -- just checking if the queue is empty. */ - NSEvent *currentEvent = [NSApp nextEventMatchingMask:NSAnyEventMask - untilDate:[NSDate distantPast] - inMode:GetRunLoopMode(TkMacOSXGetModalSession()) - dequeue:NO]; + + /* + * Call this with dequeue=NO -- just checking if the queue is empty. + */ + + NSEvent *currentEvent = + [NSApp nextEventMatchingMask:NSAnyEventMask + untilDate:[NSDate distantPast] + inMode:GetRunLoopMode(TkMacOSXGetModalSession()) + dequeue:NO]; if (currentEvent) { if (currentEvent.type > 0) { Tcl_SetMaxBlockTime(&zeroBlockTime); @@ -313,15 +320,15 @@ TkMacOSXEventsSetupProc( * * TkMacOSXEventsCheckProc -- * - * This procedure loops through all NSEvents waiting in the - * TKApplication event queue, generating X events from them. + * This procedure loops through all NSEvents waiting in the TKApplication + * event queue, generating X events from them. * * Results: * None. * * Side effects: - * NSevents are used to generate X events, which are added to the - * Tcl event queue. + * NSevents are used to generate X events, which are added to the Tcl + * event queue. * *---------------------------------------------------------------------- */ @@ -331,34 +338,48 @@ TkMacOSXEventsCheckProc( int flags) { NSString *runloopMode = [[NSRunLoop currentRunLoop] currentMode]; - /* runloopMode will be nil if we are in a Tcl event loop. */ + + /* + * runloopMode will be nil if we are in a Tcl event loop. + */ + if (flags & TCL_WINDOW_EVENTS && !runloopMode) { NSEvent *currentEvent = nil; NSEvent *testEvent = nil; NSModalSession modalSession; - /* It is possible for the SetupProc to be called before this function + + /* + * It is possible for the SetupProc to be called before this function * returns. This happens, for example, when we process an event which * opens a modal window. To prevent premature release of our * application-wide autorelease pool by a nested call to the SetupProc, * we must lock it here. */ + [NSApp _lockAutoreleasePool]; do { modalSession = TkMacOSXGetModalSession(); - testEvent = [NSApp nextEventMatchingMask:NSAnyEventMask - untilDate:[NSDate distantPast] - inMode:GetRunLoopMode(modalSession) - dequeue:NO]; - /* We must not steal any events during LiveResize. */ + testEvent = [NSApp nextEventMatchingMask:NSAnyEventMask + untilDate:[NSDate distantPast] + inMode:GetRunLoopMode(modalSession) + dequeue:NO]; + + /* + * We must not steal any events during LiveResize. + */ + if (testEvent && [[testEvent window] inLiveResize]) { break; } currentEvent = [NSApp nextEventMatchingMask:NSAnyEventMask - untilDate:[NSDate distantPast] - inMode:GetRunLoopMode(modalSession) - dequeue:YES]; + untilDate:[NSDate distantPast] + inMode:GetRunLoopMode(modalSession) + dequeue:YES]; if (currentEvent) { - /* Generate Xevents. */ + /* + * Generate Xevents. + */ + int oldServiceMode = Tcl_SetServiceMode(TCL_SERVICE_ALL); NSEvent *processedEvent = [NSApp tkProcessEvent:currentEvent]; Tcl_SetServiceMode(oldServiceMode); @@ -372,16 +393,18 @@ TkMacOSXEventsCheckProc( [NSApp sendEvent:currentEvent]; } } - } else { break; } } while (1); - /* Now we can unlock the pool. */ + + /* + * Now we can unlock the pool. + */ + [NSApp _unlockAutoreleasePool]; } } - /* * Local Variables: diff --git a/macosx/tkMacOSXRegion.c b/macosx/tkMacOSXRegion.c index 0f2a74a..323318c 100644 --- a/macosx/tkMacOSXRegion.c +++ b/macosx/tkMacOSXRegion.c @@ -187,8 +187,8 @@ TkMacOSXIsEmptyRegion( * Xwindow documentation for more details. * * Results: - * Returns RectanglePart or RectangleOut. Note that this is not a - * complete implementation since it doesn't test for RectangleIn. + * Returns RectanglePart or RectangleOut. Note that this is not a complete + * implementation since it doesn't test for RectangleIn. * * Side effects: * None. @@ -204,13 +204,13 @@ TkRectInRegion( unsigned int width, unsigned int height) { - if ( TkMacOSXIsEmptyRegion(region) ) { - return RectangleOut; - } - else { + if (TkMacOSXIsEmptyRegion(region)) { + return RectangleOut; + } else { const CGRect r = CGRectMake(x, y, width, height); + return HIShapeIntersectsRect((HIShapeRef) region, &r) ? - RectanglePart : RectangleOut; + RectanglePart : RectangleOut; } } @@ -234,7 +234,7 @@ TkRectInRegion( void TkClipBox( TkRegion r, - XRectangle* rect_return) + XRectangle *rect_return) { CGRect rect; diff --git a/macosx/tkMacOSXScale.c b/macosx/tkMacOSXScale.c index 8a6a96b..0195ffb 100644 --- a/macosx/tkMacOSXScale.c +++ b/macosx/tkMacOSXScale.c @@ -51,10 +51,10 @@ static ControlActionUPP scaleActionProc = NULL; /* Pointer to func. */ * Forward declarations for procedures defined later in this file: */ -static void MacScaleEventProc(ClientData clientData, XEvent *eventPtr); -static pascal void ScaleActionProc(ControlRef theControl, - ControlPartCode partCode); - +static void MacScaleEventProc(ClientData clientData, + XEvent *eventPtr); +static pascal void ScaleActionProc(ControlRef theControl, + ControlPartCode partCode); /* *---------------------------------------------------------------------- @@ -84,7 +84,7 @@ TkpCreateScale( } Tk_CreateEventHandler(tkwin, ButtonPressMask, - MacScaleEventProc, (ClientData) macScalePtr); + MacScaleEventProc, macScalePtr); return (TkScale *) macScalePtr; } @@ -125,8 +125,8 @@ TkpDestroyScale( * * TkpDisplayScale -- * - * This procedure is invoked as an idle handler to redisplay - * the contents of a scale widget. + * This procedure is invoked as an idle handler to redisplay the contents + * of a scale widget. * * Results: * None. @@ -141,12 +141,12 @@ void TkpDisplayScale( ClientData clientData) /* Widget record for scale. */ { - TkScale *scalePtr = (TkScale *) clientData; + TkScale *scalePtr = clientData; Tk_Window tkwin = scalePtr->tkwin; Tcl_Interp *interp = scalePtr->interp; int result; char string[TCL_DOUBLE_SPACE]; - MacScale *macScalePtr = (MacScale *) clientData; + MacScale *macScalePtr = clientData; Rect r; WindowRef windowRef; CGrafPtr destPort, savePort; @@ -168,9 +168,9 @@ TkpDisplayScale( * Invoke the scale's command if needed. */ - Tcl_Preserve((ClientData) scalePtr); + Tcl_Preserve(scalePtr); if ((scalePtr->flags & INVOKE_COMMAND) && (scalePtr->command != NULL)) { - Tcl_Preserve((ClientData) interp); + Tcl_Preserve(interp); if (snprintf(string, TCL_DOUBLE_SPACE, scalePtr->format, scalePtr->value) < 0) { string[TCL_DOUBLE_SPACE - 1] = '\0'; @@ -185,19 +185,18 @@ TkpDisplayScale( Tcl_AddErrorInfo(interp, "\n (command executed by scale)"); Tcl_BackgroundException(interp, result); } - Tcl_Release((ClientData) interp); + Tcl_Release(interp); } scalePtr->flags &= ~INVOKE_COMMAND; if (scalePtr->flags & SCALE_DELETED) { - Tcl_Release((ClientData) scalePtr); + Tcl_Release(scalePtr); return; } - Tcl_Release((ClientData) scalePtr); + Tcl_Release(scalePtr); /* - * Now handle the part of redisplay that is the same for - * horizontal and vertical scales: border and traversal - * highlight. + * Now handle the part of redisplay that is the same for horizontal and + * vertical scales: border and traversal highlight. */ if (scalePtr->highlightWidth != 0) { @@ -229,7 +228,7 @@ TkpDisplayScale( #define MAC_OSX_SCROLL_WIDTH 10 if (scalePtr->orient == ORIENT_HORIZONTAL) { - int offset = (Tk_Height(tkwin) - MAC_OSX_SCROLL_WIDTH)/2; + int offset = (Tk_Height(tkwin) - MAC_OSX_SCROLL_WIDTH) / 2; if (offset < 0) { offset = 0; @@ -240,7 +239,7 @@ TkpDisplayScale( r.right = macDraw->xOff+Tk_Width(tkwin) - scalePtr->inset; r.bottom = macDraw->yOff + offset + MAC_OSX_SCROLL_WIDTH/2; } else { - int offset = (Tk_Width(tkwin) - MAC_OSX_SCROLL_WIDTH)/2; + int offset = (Tk_Width(tkwin) - MAC_OSX_SCROLL_WIDTH) / 2; if (offset < 0) { offset = 0; @@ -249,7 +248,7 @@ TkpDisplayScale( r.left = macDraw->xOff + offset; r.top = macDraw->yOff + scalePtr->inset; r.right = macDraw->xOff + offset + MAC_OSX_SCROLL_WIDTH/2; - r.bottom = macDraw->yOff+Tk_Height(tkwin) - scalePtr->inset; + r.bottom = macDraw->yOff + Tk_Height(tkwin) - scalePtr->inset; } if (macScalePtr->scaleHandle == NULL) { @@ -273,7 +272,7 @@ TkpDisplayScale( CreateSliderControl(windowRef, &r, initialValue, minValue, maxValue, kControlSliderPointsDownOrRight, numTicks, 1, scaleActionProc, - &(macScalePtr->scaleHandle)); + &macScalePtr->scaleHandle); SetControlReference(macScalePtr->scaleHandle, (UInt32) scalePtr); if (IsWindowActive(windowRef)) { @@ -290,8 +289,8 @@ TkpDisplayScale( * Finally draw the control. */ - SetControlVisibility(macScalePtr->scaleHandle,true,true); - HiliteControl(macScalePtr->scaleHandle,0); + SetControlVisibility(macScalePtr->scaleHandle, true, true); + HiliteControl(macScalePtr->scaleHandle, 0); Draw1Control(macScalePtr->scaleHandle); if (portChanged) { @@ -306,13 +305,12 @@ done: * * TkpScaleElement -- * - * Determine which part of a scale widget lies under a given - * point. + * Determine which part of a scale widget lies under a given point. * * Results: - * The return value is either TROUGH1, SLIDER, TROUGH2, or - * OTHER, depending on which of the scale's active elements - * (if any) is under the point at (x,y). + * The return value is either TROUGH1, SLIDER, TROUGH2, or OTHER, + * depending on which of the scale's active elements (if any) is under the + * point at (x,y). * * Side effects: * None. @@ -357,22 +355,22 @@ TkpScaleElement( #endif switch (part) { - case inSlider: - return SLIDER; - case inInc: - if (scalePtr->orient == ORIENT_VERTICAL) { - return TROUGH1; - } else { - return TROUGH2; - } - case inDecr: - if (scalePtr->orient == ORIENT_VERTICAL) { - return TROUGH2; - } else { - return TROUGH1; - } - default: - return OTHER; + case inSlider: + return SLIDER; + case inInc: + if (scalePtr->orient == ORIENT_VERTICAL) { + return TROUGH1; + } else { + return TROUGH2; + } + case inDecr: + if (scalePtr->orient == ORIENT_VERTICAL) { + return TROUGH2; + } else { + return TROUGH1; + } + default: + return OTHER; } } @@ -381,15 +379,15 @@ TkpScaleElement( * * MacScaleEventProc -- * - * This procedure is invoked by the Tk dispatcher for - * ButtonPress events on scales. + * This procedure is invoked by the Tk dispatcher for ButtonPress events + * on scales. * * Results: * None. * * Side effects: - * When the window gets deleted, internal structures get - * cleaned up. When it gets exposed, it is redisplayed. + * When the window gets deleted, internal structures get cleaned up. When + * it gets exposed, it is redisplayed. * *-------------------------------------------------------------- */ @@ -411,9 +409,9 @@ MacScaleEventProc( #endif /* - * To call Macintosh control routines we must have the port - * set to the window containing the control. We will then test - * which part of the control was hit and act accordingly. + * To call Macintosh control routines we must have the port set to the + * window containing the control. We will then test which part of the + * control was hit and act accordingly. */ destPort = TkMacOSXGetDrawablePort(Tk_WindowId(macScalePtr->info.tkwin)); @@ -461,8 +459,8 @@ MacScaleEventProc( * ScaleActionProc -- * * Callback procedure used by the Macintosh toolbox call - * HandleControlClick. This call will update the display - * while the scrollbar is being manipulated by the user. + * HandleControlClick. This call will update the display while the + * scrollbar is being manipulated by the user. * * Results: * None. @@ -486,9 +484,9 @@ ScaleActionProc( #endif value = GetControlValue(theControl); TkScaleSetValue(scalePtr, value, 1, 1); - Tcl_Preserve((ClientData) scalePtr); + Tcl_Preserve(scalePtr); TkMacOSXRunTclEventLoop(); - Tcl_Release((ClientData) scalePtr); + Tcl_Release(scalePtr); } #endif diff --git a/macosx/tkMacOSXScrlbr.c b/macosx/tkMacOSXScrlbr.c index 4a108db..06e0a64 100644 --- a/macosx/tkMacOSXScrlbr.c +++ b/macosx/tkMacOSXScrlbr.c @@ -9,6 +9,7 @@ * Copyright (c) 2006-2009 Daniel A. Steffen * Copyright (c) 2015 Kevin Walzer/WordTech Commununications LLC. * Copyright (c) 2018 Marc Culler + * * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. */ @@ -17,7 +18,6 @@ #include "tkScrollbar.h" #include "tkMacOSXPrivate.h" - #define MIN_SCROLLBAR_VALUE 0 /* @@ -27,18 +27,21 @@ #define MIN_SLIDER_LENGTH 5 -/*Borrowed from ttkMacOSXTheme.c to provide appropriate scaling.*/ +/* + * Borrowed from ttkMacOSXTheme.c to provide appropriate scaling. + */ + #ifdef __LP64__ -#define RangeToFactor(maximum) (((double) (INT_MAX >> 1)) / (maximum)) +#define RangeToFactor(maximum) (((double) (INT_MAX >> 1)) / (maximum)) #else -#define RangeToFactor(maximum) (((double) (LONG_MAX >> 1)) / (maximum)) +#define RangeToFactor(maximum) (((double) (LONG_MAX >> 1)) / (maximum)) #endif /* __LP64__ */ /* * Apple reversed the scroll direction with the release of OSX 10.7 Lion. */ -#define SNOW_LEOPARD_STYLE (NSAppKitVersionNumber < 1138) +#define SNOW_LEOPARD_STYLE (NSAppKitVersionNumber < 1138) /* * Declaration of an extended scrollbar structure with Mac specific additions. @@ -50,7 +53,7 @@ typedef struct MacScrollbar { GC copyGC; /* Used for copying from pixmap onto screen. */ Bool buttonDown; /* Is the mouse button down? */ Bool mouseOver; /* Is the pointer over the scrollbar. */ - HIThemeTrackDrawInfo info; /* Controls how the scrollbar is drawn. */ + HIThemeTrackDrawInfo info; /* Controls how the scrollbar is drawn. */ } MacScrollbar; /* Used to initialize a MacScrollbar's info field. */ @@ -69,33 +72,35 @@ HIThemeTrackDrawInfo defaultInfo = { const Tk_ClassProcs tkpScrollbarProcs = { sizeof(Tk_ClassProcs), /* size */ - NULL, /* worldChangedProc */ - NULL, /* createProc */ - NULL /* modalProc */ + NULL, /* worldChangedProc */ + NULL, /* createProc */ + NULL /* modalProc */ }; +/* + * Information on scrollbar layout, metrics, and draw info. + */ -/* Information on scrollbar layout, metrics, and draw info.*/ typedef struct ScrollbarMetrics { SInt32 width, minThumbHeight; int minHeight, topArrowHeight, bottomArrowHeight; NSControlSize controlSize; } ScrollbarMetrics; - static ScrollbarMetrics metrics = { - 15, 54, 26, 14, 14, kControlSizeNormal /* kThemeScrollBarMedium */ + 15, 54, 26, 14, 14, kControlSizeNormal /* kThemeScrollBarMedium */ }; - /* * Declarations of static functions defined later in this file: */ -static void ScrollbarEventProc(ClientData clientData, XEvent *eventPtr); -static int ScrollbarEvent(TkScrollbar *scrollPtr, XEvent *eventPtr); -static void UpdateControlValues(TkScrollbar *scrollPtr); - +static void ScrollbarEventProc(ClientData clientData, + XEvent *eventPtr); +static int ScrollbarEvent(TkScrollbar *scrollPtr, + XEvent *eventPtr); +static void UpdateControlValues(TkScrollbar *scrollPtr); + /* *---------------------------------------------------------------------- * @@ -114,10 +119,9 @@ static void UpdateControlValues(TkScrollbar *scrollPtr); TkScrollbar * TkpCreateScrollbar( - Tk_Window tkwin) + Tk_Window tkwin) { - - MacScrollbar *scrollPtr = (MacScrollbar *)ckalloc(sizeof(MacScrollbar)); + MacScrollbar *scrollPtr = ckalloc(sizeof(MacScrollbar)); scrollPtr->troughGC = NULL; scrollPtr->copyGC = NULL; @@ -125,15 +129,15 @@ TkpCreateScrollbar( scrollPtr->buttonDown = false; Tk_CreateEventHandler(tkwin, - ExposureMask | - StructureNotifyMask | - FocusChangeMask | - ButtonPressMask | - ButtonReleaseMask | - EnterWindowMask | - LeaveWindowMask | - VisibilityChangeMask, - ScrollbarEventProc, scrollPtr); + ExposureMask | + StructureNotifyMask | + FocusChangeMask | + ButtonPressMask | + ButtonReleaseMask | + EnterWindowMask | + LeaveWindowMask | + VisibilityChangeMask, + ScrollbarEventProc, scrollPtr); return (TkScrollbar *) scrollPtr; } @@ -144,8 +148,8 @@ TkpCreateScrollbar( * TkpDisplayScrollbar -- * * This procedure redraws the contents of a scrollbar window. It is - * invoked as a do-when-idle handler, so it only runs when there's - * nothing else for the application to do. + * invoked as a do-when-idle handler, so it only runs when there's nothing + * else for the application to do. * * Results: * None. @@ -158,9 +162,9 @@ TkpCreateScrollbar( void TkpDisplayScrollbar( - ClientData clientData) /* Information about window. */ + ClientData clientData) /* Information about window. */ { - register TkScrollbar *scrollPtr = (TkScrollbar *) clientData; + register TkScrollbar *scrollPtr = clientData; MacScrollbar *msPtr = (MacScrollbar *) scrollPtr; register Tk_Window tkwin = scrollPtr->tkwin; TkWindow *winPtr = (TkWindow *) tkwin; @@ -169,23 +173,31 @@ TkpDisplayScrollbar( scrollPtr->flags &= ~REDRAW_PENDING; if (tkwin == NULL || !Tk_IsMapped(tkwin)) { - return; + return; } - MacDrawable *macWin = (MacDrawable *) winPtr->window; + MacDrawable *macWin = (MacDrawable *) winPtr->window; NSView *view = TkMacOSXDrawableView(macWin); - if (!view || - macWin->flags & TK_DO_NOT_DRAW || - !TkMacOSXSetupDrawingContext((Drawable) macWin, NULL, 1, &dc)) { - return; + + if ((view == NULL) + || (macWin->flags & TK_DO_NOT_DRAW) + || !TkMacOSXSetupDrawingContext((Drawable) macWin, NULL, 1, &dc)) { + return; } CGFloat viewHeight = [view bounds].size.height; - CGAffineTransform t = { .a = 1, .b = 0, .c = 0, .d = -1, .tx = 0, - .ty = viewHeight}; + CGAffineTransform t = { + .a = 1, .b = 0, + .c = 0, .d = -1, + .tx = 0, .ty = viewHeight + }; + CGContextConcatCTM(dc.context, t); - /*Draw a 3D rectangle to provide a base for the native scrollbar.*/ + /* + * Draw a 3D rectangle to provide a base for the native scrollbar. + */ + if (scrollPtr->highlightWidth != 0) { GC fgGC, bgGC; @@ -196,32 +208,37 @@ TkpDisplayScrollbar( fgGC = bgGC; } TkpDrawHighlightBorder(tkwin, fgGC, bgGC, scrollPtr->highlightWidth, - (Pixmap) macWin); + (Pixmap) macWin); } Tk_Draw3DRectangle(tkwin, (Pixmap) macWin, scrollPtr->bgBorder, - scrollPtr->highlightWidth, scrollPtr->highlightWidth, - Tk_Width(tkwin) - 2*scrollPtr->highlightWidth, - Tk_Height(tkwin) - 2*scrollPtr->highlightWidth, - scrollPtr->borderWidth, scrollPtr->relief); + scrollPtr->highlightWidth, scrollPtr->highlightWidth, + Tk_Width(tkwin) - 2*scrollPtr->highlightWidth, + Tk_Height(tkwin) - 2*scrollPtr->highlightWidth, + scrollPtr->borderWidth, scrollPtr->relief); Tk_Fill3DRectangle(tkwin, (Pixmap) macWin, scrollPtr->bgBorder, - scrollPtr->inset, scrollPtr->inset, - Tk_Width(tkwin) - 2*scrollPtr->inset, - Tk_Height(tkwin) - 2*scrollPtr->inset, 0, TK_RELIEF_FLAT); + scrollPtr->inset, scrollPtr->inset, + Tk_Width(tkwin) - 2*scrollPtr->inset, + Tk_Height(tkwin) - 2*scrollPtr->inset, 0, TK_RELIEF_FLAT); + + /* + * Update values and then draw the native scrollbar over the rectangle. + */ - /* Update values and then draw the native scrollbar over the rectangle.*/ UpdateControlValues(scrollPtr); if (SNOW_LEOPARD_STYLE) { - HIThemeDrawTrack (&(msPtr->info), 0, dc.context, kHIThemeOrientationInverted); + HIThemeDrawTrack(&msPtr->info, 0, dc.context, + kHIThemeOrientationInverted); } else { - HIThemeDrawTrack (&(msPtr->info), 0, dc.context, kHIThemeOrientationNormal); + HIThemeDrawTrack(&msPtr->info, 0, dc.context, + kHIThemeOrientationNormal); } TkMacOSXRestoreDrawingContext(&dc); scrollPtr->flags &= ~REDRAW_PENDING; } - + /* *---------------------------------------------------------------------- * @@ -240,44 +257,41 @@ TkpDisplayScrollbar( *---------------------------------------------------------------------- */ - - extern void TkpComputeScrollbarGeometry( register TkScrollbar *scrollPtr) - /* Scrollbar whose geometry may have - * changed. */ + /* Scrollbar whose geometry may have + * changed. */ { - - /* - * The code below is borrowed from tkUnixScrlbr.c but has been adjusted to - * account for some differences between macOS and X11. The Unix scrollbar - * has an arrow button on each end. On macOS 10.6 (Snow Leopard) the - * scrollbars by default have both arrow buttons at the bottom or right. - * (There is a preferences setting to use the Unix layout, but we are not - * supporting that!) On more recent versions of macOS there are no arrow - * buttons at all. The case of no arrow buttons can be handled as a special - * case of having both buttons at the end, but where scrollPtr->arrowLength - * happens to be zero. To adjust for having both arrows at the same end we - * shift the scrollbar up by the arrowLength. - */ + /* + * The code below is borrowed from tkUnixScrlbr.c but has been adjusted to + * account for some differences between macOS and X11. The Unix scrollbar + * has an arrow button on each end. On macOS 10.6 (Snow Leopard) the + * scrollbars by default have both arrow buttons at the bottom or right. + * (There is a preferences setting to use the Unix layout, but we are not + * supporting that!) On more recent versions of macOS there are no arrow + * buttons at all. The case of no arrow buttons can be handled as a special + * case of having both buttons at the end, but where scrollPtr->arrowLength + * happens to be zero. To adjust for having both arrows at the same end we + * shift the scrollbar up by the arrowLength. + */ int fieldLength; if (scrollPtr->highlightWidth < 0) { - scrollPtr->highlightWidth = 0; + scrollPtr->highlightWidth = 0; } scrollPtr->inset = scrollPtr->highlightWidth + scrollPtr->borderWidth; if ([NSApp macMinorVersion] == 6) { - scrollPtr->arrowLength = scrollPtr->width; + scrollPtr->arrowLength = scrollPtr->width; } else { - scrollPtr->arrowLength = 0; + scrollPtr->arrowLength = 0; } fieldLength = (scrollPtr->vertical ? Tk_Height(scrollPtr->tkwin) - : Tk_Width(scrollPtr->tkwin)) - - 2*(scrollPtr->arrowLength + scrollPtr->inset); + : Tk_Width(scrollPtr->tkwin)) + - 2*(scrollPtr->arrowLength + scrollPtr->inset); if (fieldLength < 0) { - fieldLength = 0; + fieldLength = 0; } scrollPtr->sliderFirst = fieldLength*scrollPtr->firstFraction; scrollPtr->sliderLast = fieldLength*scrollPtr->lastFraction; @@ -289,16 +303,16 @@ TkpComputeScrollbarGeometry( */ if (scrollPtr->sliderFirst > fieldLength - MIN_SLIDER_LENGTH) { - scrollPtr->sliderFirst = fieldLength - MIN_SLIDER_LENGTH; + scrollPtr->sliderFirst = fieldLength - MIN_SLIDER_LENGTH; } if (scrollPtr->sliderFirst < 0) { - scrollPtr->sliderFirst = 0; + scrollPtr->sliderFirst = 0; } if (scrollPtr->sliderLast < scrollPtr->sliderFirst + MIN_SLIDER_LENGTH) { - scrollPtr->sliderLast = scrollPtr->sliderFirst + MIN_SLIDER_LENGTH; + scrollPtr->sliderLast = scrollPtr->sliderFirst + MIN_SLIDER_LENGTH; } if (scrollPtr->sliderLast > fieldLength) { - scrollPtr->sliderLast = fieldLength; + scrollPtr->sliderLast = fieldLength; } scrollPtr->sliderFirst += -scrollPtr->arrowLength + scrollPtr->inset; scrollPtr->sliderLast += scrollPtr->inset; @@ -310,20 +324,20 @@ TkpComputeScrollbarGeometry( * be redisplayed. */ - if (scrollPtr->vertical) { - Tk_GeometryRequest(scrollPtr->tkwin, - scrollPtr->width + 2*scrollPtr->inset, - 2*(scrollPtr->arrowLength + scrollPtr->borderWidth - + scrollPtr->inset) + metrics.minThumbHeight); + if (scrollPtr->vertical) { + Tk_GeometryRequest(scrollPtr->tkwin, + scrollPtr->width + 2*scrollPtr->inset, + 2*(scrollPtr->arrowLength + scrollPtr->borderWidth + + scrollPtr->inset) + metrics.minThumbHeight); } else { - Tk_GeometryRequest(scrollPtr->tkwin, - 2*(scrollPtr->arrowLength + scrollPtr->borderWidth - + scrollPtr->inset) + metrics.minThumbHeight, - scrollPtr->width + 2*scrollPtr->inset); + Tk_GeometryRequest(scrollPtr->tkwin, + 2*(scrollPtr->arrowLength + scrollPtr->borderWidth + + scrollPtr->inset) + metrics.minThumbHeight, + scrollPtr->width + 2*scrollPtr->inset); } Tk_SetInternalBorder(scrollPtr->tkwin, scrollPtr->inset); } - + /* *---------------------------------------------------------------------- * @@ -342,9 +356,9 @@ TkpComputeScrollbarGeometry( void TkpDestroyScrollbar( - TkScrollbar *scrollPtr) + TkScrollbar *scrollPtr) { - MacScrollbar *macScrollPtr = (MacScrollbar *)scrollPtr; + MacScrollbar *macScrollPtr = (MacScrollbar *) scrollPtr; if (macScrollPtr->troughGC != None) { Tk_FreeGC(scrollPtr->display, macScrollPtr->troughGC); @@ -353,15 +367,15 @@ TkpDestroyScrollbar( Tk_FreeGC(scrollPtr->display, macScrollPtr->copyGC); } } - + /* *---------------------------------------------------------------------- * * TkpConfigureScrollbar -- * - * This procedure is called after the generic code has finished - * processing configuration options, in order to configure platform - * specific options. There are no such option on the Mac, however. + * This procedure is called after the generic code has finished processing + * configuration options, in order to configure platform specific options. + * There are no such option on the Mac, however. * * Results: * None. @@ -374,11 +388,11 @@ TkpDestroyScrollbar( void TkpConfigureScrollbar( - register TkScrollbar *scrollPtr) + register TkScrollbar *scrollPtr) { - + /* empty */ } - + /* *-------------------------------------------------------------- * @@ -403,29 +417,28 @@ TkpScrollbarPosition( /* Scrollbar widget record. */ int x, int y) /* Coordinates within scrollPtr's window. */ { - - /* - * The code below is borrowed from tkUnixScrlbr.c and needs no adjustment - * since it does not involve the arrow buttons. - */ + /* + * The code below is borrowed from tkUnixScrlbr.c and needs no adjustment + * since it does not involve the arrow buttons. + */ int length, width, tmp; register const int inset = scrollPtr->inset; if (scrollPtr->vertical) { - length = Tk_Height(scrollPtr->tkwin); - width = Tk_Width(scrollPtr->tkwin); + length = Tk_Height(scrollPtr->tkwin); + width = Tk_Width(scrollPtr->tkwin); } else { - tmp = x; - x = y; - y = tmp; - length = Tk_Width(scrollPtr->tkwin); - width = Tk_Height(scrollPtr->tkwin); + tmp = x; + x = y; + y = tmp; + length = Tk_Width(scrollPtr->tkwin); + width = Tk_Height(scrollPtr->tkwin); } if (x < inset || x >= width - inset || - y < inset || y >= length - inset) { - return OUTSIDE; + y < inset || y >= length - inset) { + return OUTSIDE; } /* @@ -436,31 +449,34 @@ TkpScrollbarPosition( */ if (y < scrollPtr->sliderFirst + scrollPtr->arrowLength) { - return TOP_GAP; - } - if (y < scrollPtr->sliderLast) { - return SLIDER; - } - if (y < length - (2*scrollPtr->arrowLength + inset)) { - return BOTTOM_GAP; - } - /* On systems newer than 10.6 we have already returned. */ - if (y < length - (scrollPtr->arrowLength + inset)) { - return TOP_ARROW; - } - return BOTTOM_ARROW; -} + return TOP_GAP; + } + if (y < scrollPtr->sliderLast) { + return SLIDER; + } + if (y < length - (2*scrollPtr->arrowLength + inset)) { + return BOTTOM_GAP; + } + /* + * On systems newer than 10.6 we have already returned. + */ + + if (y < length - (scrollPtr->arrowLength + inset)) { + return TOP_ARROW; + } + return BOTTOM_ARROW; +} + /* *-------------------------------------------------------------- * * UpdateControlValues -- * - * This procedure updates the Macintosh scrollbar control to - * display the values defined by the Tk scrollbar. This is the - * key interface to the Mac-native scrollbar; the Unix bindings - * drive scrolling in the Tk window and all the Mac scrollbar has - * to do is redraw itself. + * This procedure updates the Macintosh scrollbar control to display the + * values defined by the Tk scrollbar. This is the key interface to the + * Mac-native scrollbar; the Unix bindings drive scrolling in the Tk + * window and all the Mac scrollbar has to do is redraw itself. * * Results: * None. @@ -473,20 +489,21 @@ TkpScrollbarPosition( static void UpdateControlValues( - TkScrollbar *scrollPtr) /* Scrollbar data struct. */ + TkScrollbar *scrollPtr) /* Scrollbar data struct. */ { - MacScrollbar *msPtr = (MacScrollbar *)scrollPtr; + MacScrollbar *msPtr = (MacScrollbar *) scrollPtr; Tk_Window tkwin = scrollPtr->tkwin; MacDrawable *macWin = (MacDrawable *) Tk_WindowId(scrollPtr->tkwin); double dViewSize; - HIRect contrlRect; + HIRect contrlRect; short width, height; NSView *view = TkMacOSXDrawableView(macWin); CGFloat viewHeight = [view bounds].size.height; NSRect frame; + frame = NSMakeRect(macWin->xOff, macWin->yOff, Tk_Width(tkwin), - Tk_Height(tkwin)); + Tk_Height(tkwin)); frame = NSInsetRect(frame, scrollPtr->inset, scrollPtr->inset); frame.origin.y = viewHeight - (frame.origin.y + frame.size.height); @@ -503,9 +520,9 @@ UpdateControlValues( msPtr->info.bounds = contrlRect; if (scrollPtr->vertical) { - msPtr->info.attributes &= ~kThemeTrackHorizontal; + msPtr->info.attributes &= ~kThemeTrackHorizontal; } else { - msPtr->info.attributes |= kThemeTrackHorizontal; + msPtr->info.attributes |= kThemeTrackHorizontal; } /* @@ -518,69 +535,73 @@ UpdateControlValues( * the view area. */ - double maximum = 100, factor; - factor = RangeToFactor(maximum); - dViewSize = (scrollPtr->lastFraction - scrollPtr->firstFraction) - * factor; - msPtr->info.max = MIN_SCROLLBAR_VALUE + - factor - dViewSize; + double maximum = 100, factor = RangeToFactor(maximum); + + dViewSize = (scrollPtr->lastFraction - scrollPtr->firstFraction) * factor; + msPtr->info.max = MIN_SCROLLBAR_VALUE + factor - dViewSize; msPtr->info.trackInfo.scrollbar.viewsize = dViewSize; if (scrollPtr->vertical) { - if (SNOW_LEOPARD_STYLE) { - msPtr->info.value = factor * scrollPtr->firstFraction; - } else { - msPtr->info.value = msPtr->info.max - factor * scrollPtr->firstFraction; - } + if (SNOW_LEOPARD_STYLE) { + msPtr->info.value = factor * scrollPtr->firstFraction; + } else { + msPtr->info.value = msPtr->info.max - + factor * scrollPtr->firstFraction; + } } else { - msPtr->info.value = MIN_SCROLLBAR_VALUE + factor * scrollPtr->firstFraction; + msPtr->info.value = MIN_SCROLLBAR_VALUE + + factor * scrollPtr->firstFraction; } - if((scrollPtr->firstFraction <= 0.0 && scrollPtr->lastFraction >= 1.0) - || height <= metrics.minHeight) { + if ((scrollPtr->firstFraction <= 0.0 && scrollPtr->lastFraction >= 1.0) + || height <= metrics.minHeight) { msPtr->info.enableState = kThemeTrackHideTrack; } else { msPtr->info.enableState = kThemeTrackActive; - msPtr->info.attributes = kThemeTrackShowThumb | kThemeTrackThumbRgnIsNotGhost; + msPtr->info.attributes = + kThemeTrackShowThumb | kThemeTrackThumbRgnIsNotGhost; } - } - + /* *-------------------------------------------------------------- * * ScrollbarEvent -- * - * This procedure is invoked in response to , , - * , and events. The Scrollbar appearance is - * modified for each event. + * This procedure is invoked in response to , + * , , and events. The + * Scrollbar appearance is modified for each event. * *-------------------------------------------------------------- */ static int -ScrollbarEvent(TkScrollbar *scrollPtr, XEvent *eventPtr) +ScrollbarEvent( + TkScrollbar *scrollPtr, + XEvent *eventPtr) { - MacScrollbar *msPtr = (MacScrollbar *)scrollPtr; - - /* The pressState does not indicate whether the moused button was - * pressed at some location in the Scrollbar. Rather, it indicates - * that the scrollbar should appear as if it were pressed in that - * location. The standard Mac behavior is that once the button is - * pressed inside the Scrollbar the appearance should not change until - * the button is released, even if the mouse moves outside of the - * scrollbar. However, if the mouse lies over the scrollbar but the - * button is not pressed then the appearance should be the same as if - * the button had been pressed on the slider, i.e. kThemeThumbPressed. - * See the file Appearance.r, or HIToolbox.bridgesupport on 10.14. + MacScrollbar *msPtr = (MacScrollbar *) scrollPtr; + + /* + * The pressState does not indicate whether the moused button was pressed + * at some location in the Scrollbar. Rather, it indicates that the + * scrollbar should appear as if it were pressed in that location. The + * standard Mac behavior is that once the button is pressed inside the + * Scrollbar the appearance should not change until the button is released, + * even if the mouse moves outside of the scrollbar. However, if the mouse + * lies over the scrollbar but the button is not pressed then the + * appearance should be the same as if the button had been pressed on the + * slider, i.e. kThemeThumbPressed. See the file Appearance.r, or + * HIToolbox.bridgesupport on 10.14. */ if (eventPtr->type == ButtonPress) { msPtr->buttonDown = true; UpdateControlValues(scrollPtr); + int where = TkpScrollbarPosition(scrollPtr, - eventPtr->xbutton.x, - eventPtr->xbutton.y); - switch(where) { + eventPtr->xbutton.x, eventPtr->xbutton.y); + + switch (where) { case OUTSIDE: msPtr->info.trackInfo.scrollbar.pressState = 0; break; @@ -591,14 +612,20 @@ ScrollbarEvent(TkScrollbar *scrollPtr, XEvent *eventPtr) msPtr->info.trackInfo.scrollbar.pressState = kThemeThumbPressed; break; case BOTTOM_GAP: - msPtr->info.trackInfo.scrollbar.pressState = kThemeBottomTrackPressed; + msPtr->info.trackInfo.scrollbar.pressState = + kThemeBottomTrackPressed; break; case TOP_ARROW: - /* This looks wrong and the docs say it is wrong but it works. */ - msPtr->info.trackInfo.scrollbar.pressState = kThemeTopInsideArrowPressed; + /* + * This looks wrong and the docs say it is wrong but it works. + */ + + msPtr->info.trackInfo.scrollbar.pressState = + kThemeTopInsideArrowPressed; break; case BOTTOM_ARROW: - msPtr->info.trackInfo.scrollbar.pressState = kThemeBottomOutsideArrowPressed; + msPtr->info.trackInfo.scrollbar.pressState = + kThemeBottomOutsideArrowPressed; break; } } @@ -622,9 +649,7 @@ ScrollbarEvent(TkScrollbar *scrollPtr, XEvent *eventPtr) } return TCL_OK; } - - - + /* *-------------------------------------------------------------- * @@ -645,8 +670,8 @@ ScrollbarEvent(TkScrollbar *scrollPtr, XEvent *eventPtr) static void ScrollbarEventProc( - ClientData clientData, /* Information about window. */ - XEvent *eventPtr) /* Information about event. */ + ClientData clientData, /* Information about window. */ + XEvent *eventPtr) /* Information about event. */ { TkScrollbar *scrollPtr = clientData; @@ -668,7 +693,7 @@ ScrollbarEventProc( TkScrollbarEventProc(clientData, eventPtr); } } - + /* * Local Variables: * mode: objc diff --git a/macosx/tkMacOSXSend.c b/macosx/tkMacOSXSend.c index 1fdf048..8b65532 100644 --- a/macosx/tkMacOSXSend.c +++ b/macosx/tkMacOSXSend.c @@ -51,7 +51,7 @@ typedef struct RegisteredInterp { * A registry of all interpreters for a display is kept in a property * "InterpRegistry" on the root window of the display. It is organized as a * series of zero or more concatenated strings (in no particular order), each - * of the form + * of the form: * window space name '\0' * where "window" is the hex id of the comm. window to use to talk to an * interpreter named "name". @@ -78,7 +78,7 @@ typedef struct NameRegistry { * XFree; zero means use ckfree. */ } NameRegistry; -static int initialized = 0; /* A flag to denote if we have initialized +static int initialized = 0; /* A flag to denote if we have initialized * yet. */ static RegisteredInterp *interpListPtr = NULL; diff --git a/macosx/tkMacOSXSubwindows.c b/macosx/tkMacOSXSubwindows.c index 805d58f..06aaa9d 100644 --- a/macosx/tkMacOSXSubwindows.c +++ b/macosx/tkMacOSXSubwindows.c @@ -65,7 +65,7 @@ XDestroyWindow( TkMacOSXSelDeadWindow(macWin->winPtr); macWin->toplevel->referenceCount--; - if (!Tk_IsTopLevel(macWin->winPtr) ) { + if (!Tk_IsTopLevel(macWin->winPtr)) { TkMacOSXInvalidateWindow(macWin, TK_PARENT_WINDOW); if (macWin->winPtr->parentPtr != NULL) { TkMacOSXInvalClipRgns((Tk_Window) macWin->winPtr->parentPtr); @@ -151,19 +151,18 @@ XMapWindow( NSWindow *win = TkMacOSXDrawableWindow(window); /* - * We want to activate Tk when a toplevel is mapped - * but we must not supply YES here. This is because - * during Tk initialization the root window is mapped - * before applicationDidFinishLaunching returns. Forcing - * the app to activate too early can make the menu bar - * unresponsive. + * We want to activate Tk when a toplevel is mapped but we must not + * supply YES here. This is because during Tk initialization the + * root window is mapped before applicationDidFinishLaunching + * returns. Forcing the app to activate too early can make the menu + * bar unresponsive. */ TkMacOSXApplyWindowAttributes(macWin->winPtr, win); [win setExcludedFromWindowsMenu:NO]; [NSApp activateIgnoringOtherApps:NO]; [[win contentView] setNeedsDisplay:YES]; - if ( [win canBecomeKeyWindow] ) { + if ([win canBecomeKeyWindow]) { [win makeKeyAndOrderFront:NSApp]; } else { [win orderFrontRegardless]; @@ -185,7 +184,8 @@ XMapWindow( */ TkWindow *contWinPtr = TkpGetOtherWindow(macWin->winPtr); - TkMacOSXInvalClipRgns((Tk_Window)contWinPtr); + + TkMacOSXInvalClipRgns((Tk_Window) contWinPtr); TkMacOSXInvalidateWindow(macWin, TK_PARENT_WINDOW); } TkMacOSXInvalClipRgns((Tk_Window) macWin->winPtr); @@ -203,12 +203,9 @@ XMapWindow( event.xmap.event = window; event.xmap.override_redirect = macWin->winPtr->atts.override_redirect; Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); - } else { - /* * Rebuild the parent's clipping region and display the window. - * */ TkMacOSXInvalClipRgns((Tk_Window) macWin->winPtr->parentPtr); @@ -298,6 +295,7 @@ XUnmapWindow( if (!Tk_IsEmbedded(winPtr) && winPtr->wmInfoPtr->hints.initial_state!=IconicState) { NSWindow *win = TkMacOSXDrawableWindow(window); + [win orderOut:nil]; } TkMacOSXInvalClipRgns((Tk_Window) winPtr); @@ -316,15 +314,15 @@ XUnmapWindow( event.xunmap.from_configure = false; Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); } else { - /* * Rebuild the visRgn clip region for the parent so it will be allowed * to draw in the space from which this subwindow was removed. */ if (parentPtr && parentPtr->privatePtr->visRgn) { - TkMacOSXInvalidateViewRegion(TkMacOSXDrawableView(parentPtr->privatePtr), - parentPtr->privatePtr->visRgn); + TkMacOSXInvalidateViewRegion( + TkMacOSXDrawableView(parentPtr->privatePtr), + parentPtr->privatePtr->visRgn); } TkMacOSXInvalClipRgns((Tk_Window) parentPtr); TkMacOSXUpdateClipRgn(parentPtr); @@ -357,11 +355,14 @@ XResizeWindow( unsigned int height) { MacDrawable *macWin = (MacDrawable *) window; + display->request++; if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) { NSWindow *w = macWin->winPtr->wmInfoPtr->window; + if (w) { NSRect r = [w contentRectForFrameRect:[w frame]]; + r.origin.y += r.size.height - height; r.size.width = width; r.size.height = height; @@ -377,8 +378,8 @@ XResizeWindow( * * XMoveResizeWindow -- * - * Move or resize a given X window. See X windows documentation - * for further details. + * Move or resize a given X window. See X windows documentation for + * further details. * * Results: * None. @@ -402,22 +403,24 @@ XMoveResizeWindow( display->request++; if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) { NSWindow *w = macWin->winPtr->wmInfoPtr->window; - if (w) { - /* We explicitly convert everything to doubles so we don't get + if (w) { + /* + * We explicitly convert everything to doubles so we don't get * surprised (again) by what happens when you do arithmetic with * unsigned ints. */ - CGFloat X = (CGFloat)x; - CGFloat Y = (CGFloat)y; - CGFloat Width = (CGFloat)width; - CGFloat Height = (CGFloat)height; - CGFloat XOff = (CGFloat)macWin->winPtr->wmInfoPtr->xInParent; - CGFloat YOff = (CGFloat)macWin->winPtr->wmInfoPtr->yInParent; - NSRect r = NSMakeRect(X + XOff, - tkMacOSXZeroScreenHeight - Y - YOff - Height, - Width, Height); + CGFloat X = (CGFloat) x; + CGFloat Y = (CGFloat) y; + CGFloat Width = (CGFloat) width; + CGFloat Height = (CGFloat) height; + CGFloat XOff = (CGFloat) macWin->winPtr->wmInfoPtr->xInParent; + CGFloat YOff = (CGFloat) macWin->winPtr->wmInfoPtr->yInParent; + NSRect r = NSMakeRect( + X + XOff, tkMacOSXZeroScreenHeight - Y - YOff - Height, + Width, Height); + [w setFrame:[w frameRectForContentRect:r] display:YES]; } } else { @@ -430,8 +433,7 @@ XMoveResizeWindow( * * XMoveWindow -- * - * Move a given X window. See X windows documentation for further - * details. + * Move a given X window. See X windows documentation for further details. * * Results: * None. @@ -453,8 +455,10 @@ XMoveWindow( display->request++; if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) { NSWindow *w = macWin->winPtr->wmInfoPtr->window; + if (w) { - [w setFrameTopLeftPoint:NSMakePoint(x, tkMacOSXZeroScreenHeight - y)]; + [w setFrameTopLeftPoint: NSMakePoint( + x, tkMacOSXZeroScreenHeight - y)]; } } else { MoveResizeWindow(macWin); @@ -495,7 +499,6 @@ MoveResizeWindow( if (contWinPtr) { macParent = contWinPtr->privatePtr; } else { - /* * Here we should handle out of process embedding. At this point, * we are assuming that the changes.x,y is not maintained, if you @@ -504,7 +507,6 @@ MoveResizeWindow( */ } } else { - /* * TODO: update all xOff & yOffs */ @@ -596,7 +598,6 @@ XRaiseWindow( if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) { TkWmRestackToplevel(macWin->winPtr, Above, NULL); } else { - /* * TODO: this should generate damage */ @@ -631,7 +632,6 @@ XLowerWindow( if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) { TkWmRestackToplevel(macWin->winPtr, Below, NULL); } else { - /* * TODO: this should generate damage */ @@ -694,14 +694,16 @@ XConfigureWindow( TkMacOSXInvalClipRgns((Tk_Window) winPtr->parentPtr); TkMacOSXWinBounds(winPtr, &bounds); r = NSMakeRect(bounds.left, - [view bounds].size.height - bounds.bottom, - bounds.right - bounds.left, bounds.bottom - bounds.top); + [view bounds].size.height - bounds.bottom, + bounds.right - bounds.left, bounds.bottom - bounds.top); [view setNeedsDisplayInRect:r]; } } - /* TkGenWMMoveRequestEvent(macWin->winPtr, - macWin->winPtr->changes.x, macWin->winPtr->changes.y); */ +#if 0 + TkGenWMMoveRequestEvent(macWin->winPtr, + macWin->winPtr->changes.x, macWin->winPtr->changes.y); +#endif } /* @@ -723,14 +725,14 @@ XConfigureWindow( void TkMacOSXSetDrawingEnabled( - TkWindow *winPtr, - int flag) + TkWindow *winPtr, + int flag) { TkWindow *childPtr; MacDrawable *macWin = winPtr->privatePtr; if (macWin) { - if (flag ) { + if (flag) { macWin->flags &= ~TK_DO_NOT_DRAW; } else { macWin->flags |= TK_DO_NOT_DRAW; @@ -738,8 +740,8 @@ TkMacOSXSetDrawingEnabled( } /* - * Set the flag for all children & their descendants, excluding - * Toplevels. (??? Do we need to exclude Toplevels?) + * Set the flag for all children & their descendants, excluding Toplevels. + * (??? Do we need to exclude Toplevels?) */ childPtr = winPtr->childList; @@ -903,7 +905,6 @@ TkMacOSXUpdateClipRgn( } CFRelease(rgn); } else { - /* * An unmapped window has empty clip regions to prevent any * (erroneous) drawing into it or its children from becoming @@ -933,8 +934,8 @@ TkMacOSXUpdateClipRgn( * TkMacOSXVisableClipRgn -- * * This function returns the Macintosh clipping region for the given - * window. The caller is responsible for disposing of the returned - * region via TkDestroyRegion(). + * window. The caller is responsible for disposing of the returned region + * via TkDestroyRegion(). * * Results: * The region. @@ -952,7 +953,7 @@ TkMacOSXVisableClipRgn( if (winPtr->privatePtr->flags & TK_CLIP_INVALID) { TkMacOSXUpdateClipRgn(winPtr); } - return (TkRegion)HIShapeCreateMutableCopy(winPtr->privatePtr->visRgn); + return (TkRegion) HIShapeCreateMutableCopy(winPtr->privatePtr->visRgn); } /* @@ -972,7 +973,12 @@ TkMacOSXVisableClipRgn( */ static OSStatus -InvalViewRect(int msg, HIShapeRef rgn, const CGRect *rect, void *ref) { +InvalViewRect( + int msg, + HIShapeRef rgn, + const CGRect *rect, + void *ref) +{ static CGAffineTransform t; NSView *view = ref; @@ -1052,7 +1058,7 @@ TkMacOSXInvalidateWindow( *---------------------------------------------------------------------- */ -NSWindow* +NSWindow * TkMacOSXDrawableWindow( Drawable drawable) { @@ -1070,6 +1076,7 @@ TkMacOSXDrawableWindow( result = macWin->winPtr->wmInfoPtr->window; } else if (macWin->toplevel && (macWin->toplevel->flags & TK_EMBEDDED)) { TkWindow *contWinPtr = TkpGetOtherWindow(macWin->toplevel->winPtr); + if (contWinPtr) { result = TkMacOSXDrawableWindow((Drawable) contWinPtr->privatePtr); } @@ -1123,7 +1130,7 @@ TkMacOSXGetDrawablePort( *---------------------------------------------------------------------- */ -NSView* +NSView * TkMacOSXDrawableView( MacDrawable *macWin) { @@ -1137,6 +1144,7 @@ TkMacOSXDrawableView( result = macWin->toplevel->view; } else { TkWindow *contWinPtr = TkpGetOtherWindow(macWin->toplevel->winPtr); + if (contWinPtr) { result = TkMacOSXDrawableView(contWinPtr->privatePtr); } @@ -1164,7 +1172,6 @@ void * TkMacOSXGetRootControl( Drawable drawable) { - /* * will probably need to fix this up for embedding */ @@ -1281,7 +1288,8 @@ TkMacOSXWinBounds( TkWindow *winPtr, void *bounds) { - Rect *b = (Rect *)bounds; + Rect *b = (Rect *) bounds; + b->left = winPtr->privatePtr->xOff; b->top = winPtr->privatePtr->yOff; b->right = b->left + winPtr->changes.width; @@ -1345,7 +1353,6 @@ UpdateOffsets( TkWindow *childPtr; if (winPtr->privatePtr == NULL) { - /* * We haven't called Tk_MakeWindowExist for this window yet. The offset * information will be postponed and calulated at that time. (This will diff --git a/macosx/tkMacOSXWindowEvent.c b/macosx/tkMacOSXWindowEvent.c index 54e1272..6b80761 100644 --- a/macosx/tkMacOSXWindowEvent.c +++ b/macosx/tkMacOSXWindowEvent.c @@ -68,7 +68,7 @@ extern NSString *NSWindowDidOrderOffScreenNotification; TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd, notification); #endif BOOL movedOnly = [[notification name] - isEqualToString:NSWindowDidMoveNotification]; + isEqualToString:NSWindowDidMoveNotification]; NSWindow *w = [notification object]; TkWindow *winPtr = TkMacOSXGetTkWindow(w); @@ -91,7 +91,6 @@ extern NSString *NSWindowDidOrderOffScreenNotification; flags |= TK_SIZE_CHANGED; } if (Tcl_GetServiceMode() != TCL_SERVICE_NONE) { - /* * Propagate geometry changes immediately. */ @@ -140,11 +139,10 @@ extern NSString *NSWindowDidOrderOffScreenNotification; - (NSRect)windowWillUseStandardFrame:(NSWindow *)window defaultFrame:(NSRect)newFrame { - /* - * This method needs to be implemented in order for [NSWindow isZoomed] - * to give the correct answer. But it suffices to always validate - * every request. + * This method needs to be implemented in order for [NSWindow isZoomed] to + * give the correct answer. But it suffices to always validate every + * request. */ return newFrame; @@ -153,13 +151,12 @@ extern NSString *NSWindowDidOrderOffScreenNotification; - (NSSize)window:(NSWindow *)window willUseFullScreenContentSize:(NSSize)proposedSize { - /* - * We don't need to change the proposed size, but we do need to - * implement this method. Otherwise the full screen window will - * be sized to the screen's visibleFrame, leaving black bands at - * the top and bottom. + * We don't need to change the proposed size, but we do need to implement + * this method. Otherwise the full screen window will be sized to the + * screen's visibleFrame, leaving black bands at the top and bottom. */ + return proposedSize; } @@ -208,14 +205,13 @@ extern NSString *NSWindowDidOrderOffScreenNotification; } /* - * If necessary, TkGenWMDestroyEvent() handles [close]ing the window, - * so can always return NO from -windowShouldClose: for a Tk window. + * If necessary, TkGenWMDestroyEvent() handles [close]ing the window, so + * can always return NO from -windowShouldClose: for a Tk window. */ return (winPtr ? NO : YES); } - #ifdef TK_MAC_DEBUG_NOTIFICATIONS - (void) windowDragStart: (NSNotification *) notification @@ -256,7 +252,6 @@ extern NSString *NSWindowDidOrderOffScreenNotification; } } - #endif /* TK_MAC_DEBUG_NOTIFICATIONS */ - (void) _setupWindowNotifications @@ -363,11 +358,11 @@ extern NSString *NSWindowDidOrderOffScreenNotification; * * TkpAppIsDrawing -- * - * A widget display procedure can call this to determine whether it - * is being run inside of the drawRect method. This is needed for - * some tests, especially of the Text widget, which record data in - * a global Tcl variable and assume that display procedures will be - * run in a predictable sequence as Tcl idle tasks. + * A widget display procedure can call this to determine whether it is + * being run inside of the drawRect method. This is needed for some tests, + * especially of the Text widget, which record data in a global Tcl + * variable and assume that display procedures will be run in a + * predictable sequence as Tcl idle tasks. * * Results: * True only while running the drawRect method of a TKContentView; @@ -377,11 +372,11 @@ extern NSString *NSWindowDidOrderOffScreenNotification; * *---------------------------------------------------------------------- */ + MODULE_SCOPE Bool TkpAppIsDrawing(void) { return [NSApp isDrawing]; } - /* *---------------------------------------------------------------------- @@ -670,12 +665,10 @@ TkGenWMConfigureEvent( if ((flags & TK_SIZE_CHANGED) && !(wmPtr->flags & WM_SYNC_PENDING) && ((width != Tk_Width(tkwin)) || (height != Tk_Height(tkwin)))) { if ((wmPtr->width == -1) && (width == winPtr->reqWidth)) { - /* * Don't set external width, since the user didn't change it * from what the widgets asked for. */ - } else if (wmPtr->gridWin != NULL) { wmPtr->width = wmPtr->reqGridWidth + (width - winPtr->reqWidth)/wmPtr->widthInc; @@ -687,12 +680,10 @@ TkGenWMConfigureEvent( } if ((wmPtr->height == -1) && (height == winPtr->reqHeight)) { - /* * Don't set external height, since the user didn't change it * from what the widgets asked for. */ - } else if (wmPtr->gridWin != NULL) { wmPtr->height = wmPtr->reqGridHeight + (height - winPtr->reqHeight)/wmPtr->heightInc; @@ -708,7 +699,6 @@ TkGenWMConfigureEvent( } } - /* * Now set up the changes structure. Under X we wait for the * ConfigureNotify to set these values. On the Mac we know imediatly that @@ -899,8 +889,8 @@ ConfigureRestrictProc( #endif /* - * We do not allow recursive calls to drawRect, but we only log - * them on OSX > 10.13, where they should never happen. + * We do not allow recursive calls to drawRect, but we only log them on OSX + * > 10.13, where they should never happen. */ if ([NSApp isDrawing]) { @@ -955,9 +945,9 @@ ConfigureRestrictProc( Tk_RestrictProc *oldProc; /* - * This can be called from outside the Tk event loop. - * Since it calls Tcl_DoOneEvent, we need to make sure we - * don't clobber the AutoreleasePool set up by the caller. + * This can be called from outside the Tk event loop. Since it calls + * Tcl_DoOneEvent, we need to make sure we don't clobber the + * AutoreleasePool set up by the caller. */ [NSApp _lockAutoreleasePool]; @@ -973,7 +963,7 @@ ConfigureRestrictProc( */ TkGenWMConfigureEvent(tkwin, Tk_X(tkwin), Tk_Y(tkwin), width, height, - TK_SIZE_CHANGED | TK_MACOSX_HANDLE_EVENT_IMMEDIATELY); + TK_SIZE_CHANGED | TK_MACOSX_HANDLE_EVENT_IMMEDIATELY); oldProc = Tk_RestrictEvents(ConfigureRestrictProc, NULL, &oldArg); Tk_RestrictEvents(oldProc, oldArg, &oldArg); @@ -1061,9 +1051,9 @@ ConfigureRestrictProc( } /* - * This method is called when a user changes between light and dark mode. - * The implementation here generates a Tk virtual event which can be bound - * to a function that redraws the window in an appropriate style. + * This method is called when a user changes between light and dark mode. The + * implementation here generates a Tk virtual event which can be bound to a + * function that redraws the window in an appropriate style. */ - (void) viewDidChangeEffectiveAppearance @@ -1099,8 +1089,8 @@ ConfigureRestrictProc( } /* - * This is no-op on 10.7 and up because Apple has removed this widget, - * but we are leaving it here for backwards compatibility. + * This is no-op on 10.7 and up because Apple has removed this widget, but we + * are leaving it here for backwards compatibility. */ - (void) tkToolbarButton: (id) sender diff --git a/macosx/tkMacOSXWm.c b/macosx/tkMacOSXWm.c index 60277d1..648cf66 100644 --- a/macosx/tkMacOSXWm.c +++ b/macosx/tkMacOSXWm.c @@ -3,8 +3,7 @@ * * This module takes care of the interactions between a Tk-based * application and the window manager. Among other things, it implements - * the "wm" command and passes geometry information to the window - * manager. + * the "wm" command and passes geometry information to the window manager. * * Copyright (c) 1994-1997 Sun Microsystems, Inc. * Copyright 2001-2009, Apple Inc. @@ -392,7 +391,7 @@ static void RemoveTransient(TkWindow *winPtr); if ([self styleMask] & NSFullScreenWindowMask) { frameRect = [NSWindow frameRectForContentRect:NSZeroRect - styleMask:[self styleMask]]; + styleMask:[self styleMask]]; } else { frameRect = [self frameRectForContentRect:NSZeroRect]; } @@ -454,7 +453,7 @@ static void RemoveTransient(TkWindow *winPtr); if (title == nil) { title = "unnamed window"; } - if (DEBUG_ZOMBIES > 1){ + if (DEBUG_ZOMBIES > 1) { fprintf(stderr, "Retained <%s>. Count is: %lu\n", title, [self retainCount]); } @@ -468,7 +467,7 @@ static void RemoveTransient(TkWindow *winPtr); if (title == nil) { title = "unnamed window"; } - if (DEBUG_ZOMBIES > 1){ + if (DEBUG_ZOMBIES > 1) { fprintf(stderr, "Autoreleased <%s>. Count is %lu\n", title, [self retainCount]); } @@ -480,7 +479,7 @@ static void RemoveTransient(TkWindow *winPtr); if (title == nil) { title = "unnamed window"; } - if (DEBUG_ZOMBIES > 1){ + if (DEBUG_ZOMBIES > 1) { fprintf(stderr, "Releasing <%s>. Count is %lu\n", title, [self retainCount]); } @@ -492,7 +491,7 @@ static void RemoveTransient(TkWindow *winPtr); if (title == nil) { title = "unnamed window"; } - if (DEBUG_ZOMBIES > 0){ + if (DEBUG_ZOMBIES > 0) { fprintf(stderr, ">>>> Freeing <%s>. Count is %lu\n", title, [self retainCount]); } @@ -998,25 +997,29 @@ TkWmDeadWindow( if (winPtr2 && nswindow != window) { WmInfo *wmPtr = winPtr2->wmInfoPtr; - BOOL minimized = (wmPtr->hints.initial_state == IconicState || - wmPtr->hints.initial_state == WithdrawnState); + BOOL minimized = (wmPtr->hints.initial_state == IconicState + || wmPtr->hints.initial_state == WithdrawnState); + /* * If no windows are left on the screen and the next window is * iconified or withdrawn, we don't want to make it be the * KeyWindow because that would cause it to be displayed on the * screen. */ + if ([nswindow canBecomeKeyWindow] && !minimized) { [nswindow makeKeyAndOrderFront:NSApp]; break; } } } + /* * Process all window events immediately to force the closed window to * be deallocated. But don't do this for the root window as that is * unnecessary and can lead to segfaults. */ + if (winPtr->parentPtr) { while (Tk_DoOneEvent(TK_WINDOW_EVENTS|TK_DONT_WAIT)) {} } @@ -2624,7 +2627,7 @@ WmIconpositionCmd( wmPtr->hints.flags &= ~IconPositionHint; } else { if ((Tcl_GetIntFromObj(interp, objv[3], &x) != TCL_OK) - || (Tcl_GetIntFromObj(interp, objv[4], &y) != TCL_OK)){ + || (Tcl_GetIntFromObj(interp, objv[4], &y) != TCL_OK)) { return TCL_ERROR; } wmPtr->hints.icon_x = x; @@ -3455,14 +3458,17 @@ WmStateCmd( return TCL_ERROR; } - if (index == OPT_NORMAL) { + switch (index) { + case OPT_NORMAL: TkpWmSetState(winPtr, NormalState); /* * This varies from 'wm deiconify' because it does not force the * window to be raised and receive focus */ - } else if (index == OPT_ICONIC) { + + break; + case OPT_ICONIC: if (Tk_Attributes((Tk_Window) winPtr)->override_redirect) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "can't iconify \"%s\": override-redirect flag is set", @@ -3480,10 +3486,13 @@ WmStateCmd( return TCL_ERROR; } TkpWmSetState(winPtr, IconicState); - } else if (index == OPT_WITHDRAWN) { + break; + case OPT_WITHDRAWN: TkpWmSetState(winPtr, WithdrawnState); - } else { /* OPT_ZOOMED */ + break; + default: /* OPT_ZOOMED */ TkpWmSetState(winPtr, ZoomState); + break; } } else if (wmPtr->iconFor != NULL) { Tcl_SetObjResult(interp, Tcl_NewStringObj("icon", -1)); @@ -3603,14 +3612,12 @@ WmTransientCmd( } if (Tcl_GetString(objv[3])[0] == '\0') { RemoveTransient(winPtr); - } else { if (TkGetWindowFromObj(interp, tkwin, objv[3], &master) != TCL_OK) { return TCL_ERROR; } masterPtr = (TkWindow*) master; while (!Tk_TopWinHierarchy(masterPtr)) { - /* * Ensure that the master window is actually a Tk toplevel. */ @@ -3628,7 +3635,11 @@ WmTransientCmd( } wmPtr2 = masterPtr->wmInfoPtr; - /* Under some circumstances, wmPtr2 is NULL here. */ + + /* + * Under some circumstances, wmPtr2 is NULL here. + */ + if (wmPtr2 != NULL && wmPtr2->iconFor != NULL) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "can't make \"%s\" a master: it is an icon for %s", @@ -3679,7 +3690,7 @@ WmTransientCmd( ApplyMasterOverrideChanges(winPtr, NULL); return TCL_OK; } - + /* *---------------------------------------------------------------------- * @@ -3786,6 +3797,7 @@ WmWithdrawCmd( /* * If this window has a transient, the transient must also be withdrawn. */ + for (Transient *transientPtr = wmPtr->transientPtr; transientPtr != NULL; transientPtr = transientPtr->nextPtr) { TkWindow *winPtr2 = transientPtr->winPtr; @@ -3800,10 +3812,10 @@ WmWithdrawCmd( return TCL_OK; } - + /* - * Invoked by those wm subcommands that affect geometry. - * Schedules a geometry update. + * Invoked by those wm subcommands that affect geometry. Schedules a geometry + * update. */ static void @@ -4417,9 +4429,10 @@ ParseGeometry( if (flags & WM_NEGATIVE_X) { int borderwidth = wmPtr->parentWidth - winPtr->changes.width; int newWidth = width == -1 ? winPtr->changes.width : width; + x = (x == -1) ? - wmPtr->x + winPtr->changes.width - newWidth : - wmPtr->vRootWidth - x - newWidth - borderwidth; + wmPtr->x + winPtr->changes.width - newWidth : + wmPtr->vRootWidth - x - newWidth - borderwidth; } if (x == -1) { x = wmPtr->x; @@ -4427,9 +4440,10 @@ ParseGeometry( if (flags & WM_NEGATIVE_Y) { int borderheight = wmPtr->parentHeight - winPtr->changes.height; int newHeight = height == -1 ? winPtr->changes.height : height; + y = (y == -1) ? - wmPtr->y + winPtr->changes.height - newHeight : - wmPtr->vRootHeight - y - newHeight - borderheight; + wmPtr->y + winPtr->changes.height - newHeight : + wmPtr->vRootHeight - y - newHeight - borderheight; } if (y == -1) { y = wmPtr->y; @@ -4556,8 +4570,7 @@ Tk_GetRootCoords( * * Results: * The return result is either a token for the window corresponding to - * rootX and rootY, or else NULL to indicate that there is no such - * window. + * rootX and rootY, or else NULL to indicate that there is no such window. * * Side effects: * None. @@ -6146,9 +6159,9 @@ TkMacOSXMakeRealWindowExist( * * TkpDisplayWindow -- * - * Mark the contentView of this window as needing display so the - * window will be drawn by the window manager. If this is called - * within the drawRect method, do nothing. + * Mark the contentView of this window as needing display so the window + * will be drawn by the window manager. If this is called within the + * drawRect method, do nothing. * * Results: * None. @@ -6162,7 +6175,7 @@ TkMacOSXMakeRealWindowExist( MODULE_SCOPE void TkpDisplayWindow(Tk_Window tkwin) { if (![NSApp isDrawing]) { - TkWindow *winPtr = (TkWindow*)tkwin; + TkWindow *winPtr = (TkWindow *) tkwin; NSWindow *w = TkMacOSXDrawableWindow(winPtr->window); [[w contentView] setNeedsDisplay: YES]; @@ -6174,8 +6187,8 @@ TkpDisplayWindow(Tk_Window tkwin) { * * TkMacOSXRegisterOffScreenWindow -- * - * This function adds the passed in Off Screen Port to the hash table - * that maps Mac windows to root X windows. + * This function adds the passed in Off Screen Port to the hash table that + * maps Mac windows to root X windows. * * Results: * None. @@ -6983,7 +6996,7 @@ ApplyMasterOverrideChanges( } if (macWindow) { structureRect = [NSWindow frameRectForContentRect:NSZeroRect - styleMask:styleMask]; + styleMask:styleMask]; /* * Synchronize the wmInfoPtr to match the new window configuration @@ -7238,6 +7251,7 @@ RemapWindows( MacDrawable *parentWin) { TkWindow *childPtr; + /* * Remove the OS specific window. It will get rebuilt when the window gets * Mapped. diff --git a/macosx/ttkMacOSXTheme.c b/macosx/ttkMacOSXTheme.c index a890b63..0c474f0 100644 --- a/macosx/ttkMacOSXTheme.c +++ b/macosx/ttkMacOSXTheme.c @@ -60,10 +60,14 @@ /* * BoxToRect -- - * Convert a Ttk_Box in Tk coordinates relative to the given Drawable - * to a native Rect relative to the containing port. + * Convert a Ttk_Box in Tk coordinates relative to the given Drawable to a + * native Rect relative to the containing port. */ -static inline CGRect BoxToRect(Drawable d, Ttk_Box b) + +static inline CGRect +BoxToRect( + Drawable d, + Ttk_Box b) { MacDrawable *md = (MacDrawable*)d; CGRect rect; @@ -102,10 +106,10 @@ static Ttk_StateTable ThemeStateTable[] = { * * Apple's Human Interface Guidelines only allow three specific heights for * most buttons: Regular, small and mini. We always use the regular size. - * However, Ttk may provide an arbitrary bounding rectangle. We always draw - * the button centered vertically on the rectangle, and having the same width - * as the rectangle. This function returns the actual bounding rectangle that - * will be used in drawing the button. + * However, Ttk may provide an arbitrary bounding rectangle. We always draw the + * button centered vertically on the rectangle, and having the same width as + * the rectangle. This function returns the actual bounding rectangle that will + * be used in drawing the button. * * The BevelButton is allowed to have arbitrary size, and also has external * padding. This is handled separately here. @@ -115,8 +119,9 @@ static CGRect NormalizeButtonBounds( SInt32 heightMetric, CGRect bounds) { - SInt32 height; - if (heightMetric != NoThemeMetric) { + if (heightMetric != (SInt32) NoThemeMetric) { + SInt32 height; + ChkErr(GetThemeMetric, heightMetric, &height); bounds.origin.y += (bounds.size.height - height)/2; bounds.size.height = height; @@ -149,8 +154,8 @@ static CGFloat blackRGBA[4] = {0.0, 0.0, 0.0, 1.0}; * Start with the background color of a window's geometry master, or the * standard ttk window background if not. If the contrast parameter is * nonzero modify this color to be darker, for the aqua appearance, or - * lighter for the DarkAqua appearance. This is primarily used by the - * Fill and Background elements. + * lighter for the DarkAqua appearance. This is primarily used by the Fill + * and Background elements. */ static void GetBackgroundColor( @@ -161,11 +166,12 @@ static void GetBackgroundColor( { TkWindow *winPtr = (TkWindow *) tkwin; TkWindow *masterPtr = (TkWindow *) TkGetGeomMaster(tkwin); + while (masterPtr != NULL) { if (masterPtr->privatePtr->flags & TTK_HAS_CONTRASTING_BG) { break; } - masterPtr = (TkWindow *)TkGetGeomMaster(masterPtr); + masterPtr = (TkWindow *) TkGetGeomMaster(masterPtr); } if (masterPtr) { for (int i = 0; i < 4; i++) { @@ -176,6 +182,7 @@ static void GetBackgroundColor( NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *windowColor = [[NSColor windowBackgroundColor] colorUsingColorSpace: deviceRGB]; + [windowColor getComponents: rgba]; } else { for (int i = 0; i < 4; i++) { @@ -219,6 +226,7 @@ static void DrawGroupBox( NSColor *borderColor, *bgColor; static CGFloat border[4] = {1.0, 1.0, 1.0, 0.25}; CGFloat fill[4]; + GetBackgroundColor(context, tkwin, 1, fill); bgColor = [NSColor colorWithColorSpace: deviceRGB components: fill count: 4]; @@ -255,6 +263,7 @@ static void SolidFillRoundedRectangle( NSColor *color) { CGPathRef path; + CGContextSetFillColorWithColor(context, color.CGColor); path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL); CGContextBeginPath(context); @@ -271,14 +280,17 @@ static void DrawDownArrow( CGFloat *rgba) { CGFloat x, y; + CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); CGContextSetLineWidth(context, 1.5); x = bounds.origin.x + inset; y = bounds.origin.y + trunc(bounds.size.height/2); - CGContextBeginPath(context); + CGPoint arrow[3] = { {x, y-size/4}, {x+size/2, y+size/4}, {x+size, y-size/4} }; + + CGContextBeginPath(context); CGContextAddLines(context, arrow, 3); CGContextStrokePath(context); } @@ -291,14 +303,17 @@ static void DrawUpArrow( CGFloat *rgba) { CGFloat x, y; + CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); CGContextSetLineWidth(context, 1.5); x = bounds.origin.x + inset; y = bounds.origin.y + trunc(bounds.size.height/2); - CGContextBeginPath(context); + CGPoint arrow[3] = { {x, y+size/4}, {x+size/2, y-size/4}, {x+size, y+size/4} }; + + CGContextBeginPath(context); CGContextAddLines(context, arrow, 3); CGContextStrokePath(context); } @@ -368,6 +383,7 @@ static void DrawListHeader( if (state & TTK_TREEVIEW_STATE_SORTARROW) { CGRect arrowBounds = bounds; + arrowBounds.origin.x = bounds.origin.x + bounds.size.width - 16; arrowBounds.size.width = 16; if (state & TTK_STATE_ALTERNATE) { @@ -413,7 +429,6 @@ static CGFloat darkInactiveGradient[8] = {89.0/255, 90.0/255, 93.0/255, 1.0, static CGFloat darkSelectedGradient[8] = {23.0/255, 111.0/255, 232.0/255, 1.0, 20.0/255, 94.0/255, 206.0/255, 1.0}; - /*---------------------------------------------------------------------- * GradientFillRoundedRectangle -- * @@ -424,7 +439,7 @@ static void GradientFillRoundedRectangle( CGContextRef context, CGRect bounds, CGFloat radius, - CGFloat* colors, + CGFloat *colors, int numColors) { NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; @@ -435,6 +450,7 @@ static void GradientFillRoundedRectangle( }; CGGradientRef gradient = CGGradientCreateWithColorComponents( deviceRGB.CGColorSpace, colors, NULL, numColors); + path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL); CGContextBeginPath(context); CGContextAddPath(context, path); @@ -452,14 +468,17 @@ static void DrawUpDownArrows( CGFloat *rgba) { CGFloat x, y; + CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); CGContextSetLineWidth(context, 1.5); x = bounds.origin.x + inset; y = bounds.origin.y + trunc(bounds.size.height/2); CGContextBeginPath(context); + CGPoint bottomArrow[3] = {{x, y+2}, {x+size/2, y+2+size/2}, {x+size, y+2}}; - CGContextAddLines(context, bottomArrow, 3); CGPoint topArrow[3] = {{x, y-2}, {x+size/2, y-2-size/2}, {x+size, y-2}}; + + CGContextAddLines(context, bottomArrow, 3); CGContextAddLines(context, topArrow, 3); CGContextStrokePath(context); } @@ -483,6 +502,7 @@ static void FillButtonBackground( bounds.origin.x, bounds.origin.y + bounds.size.height }; + CGContextBeginPath(context); path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL); CGContextAddPath(context, path); @@ -508,6 +528,7 @@ static void HighlightButtonBorder( CGPoint topEnd = {bounds.origin.x, bounds.origin.y + 3}; CGGradientRef topGradient = CGGradientCreateWithColorComponents( deviceRGB.CGColorSpace, darkTopGradient, NULL, 2); + CGContextSaveGState(context); CGContextBeginPath(context); CGContextAddArc(context, bounds.origin.x + 4, bounds.origin.y + 4, @@ -576,6 +597,7 @@ static void DrawDarkButton( if (kind == kThemePopupButton | kind == kThemeComboBox) { CGRect arrowBounds = bounds; + arrowBounds.size.width = 16; arrowBounds.origin.x += bounds.size.width - 16; @@ -584,9 +606,9 @@ static void DrawDarkButton( */ if (!(state & TTK_STATE_BACKGROUND) && - !(state & TTK_STATE_DISABLED)) { + !(state & TTK_STATE_DISABLED)) { GradientFillRoundedRectangle(context, arrowBounds, 4, - darkSelectedGradient, 2); + darkSelectedGradient, 2); } if (kind == kThemePopupButton) { DrawUpDownArrows(context, arrowBounds, 3, 7, whiteRGBA); @@ -601,8 +623,8 @@ static void DrawDarkButton( /*---------------------------------------------------------------------- * DrawDarkIncDecButton -- * - * This is a standalone drawing procedure which draws an IncDecButton - * (as used in a Spinbox) in the Dark Mode style. + * This is a standalone drawing procedure which draws an IncDecButton (as + * used in a Spinbox) in the Dark Mode style. */ static void DrawDarkIncDecButton( @@ -640,6 +662,7 @@ static void DrawDarkIncDecButton( if (state & TTK_STATE_PRESSED) { CGRect clip = bounds; + clip.size.height /= 2; CGContextSaveGState(context); if (drawState == kThemeStatePressedDown) { @@ -647,7 +670,7 @@ static void DrawDarkIncDecButton( } CGContextClipToRect(context, clip); GradientFillRoundedRectangle(context, bounds, 5, - darkSelectedGradient, 2); + darkSelectedGradient, 2); CGContextRestoreGState(context); } DrawUpDownArrows(context, bounds, 3, 5, whiteRGBA); @@ -714,6 +737,7 @@ static void DrawDarkCheckBox( NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *stroke; CGFloat x, y; + bounds = CGRectOffset(checkbounds, bounds.origin.x, bounds.origin.y); x = bounds.origin.x; y = bounds.origin.y; @@ -741,15 +765,17 @@ static void DrawDarkCheckBox( CGContextSetStrokeColorWithColor(context, stroke.CGColor); } if (state & TTK_STATE_SELECTED) { + CGPoint check[3] = {{x+4, y+8}, {x+7, y+11}, {x+11, y+4}}; + CGContextSetLineWidth(context, 1.5); CGContextBeginPath(context); - CGPoint check[3] = {{x+4, y+8}, {x+7, y+11}, {x+11, y+4}}; CGContextAddLines(context, check, 3); CGContextStrokePath(context); } else if (state & TTK_STATE_ALTERNATE) { + CGPoint bar[2] = {{x+4, y+8}, {x+12, y+8}}; + CGContextSetLineWidth(context, 2.0); CGContextBeginPath(context); - CGPoint bar[2] = {{x+4, y+8}, {x+12, y+8}}; CGContextAddLines(context, bar, 2); CGContextStrokePath(context); } @@ -758,8 +784,8 @@ static void DrawDarkCheckBox( /*---------------------------------------------------------------------- * DrawDarkRadioButton -- * - * This is a standalone drawing procedure which draws RadioButtons - * in the Dark Mode style. + * This is a standalone drawing procedure which draws RadioButtons in the + * Dark Mode style. */ static void DrawDarkRadioButton( @@ -771,6 +797,7 @@ static void DrawDarkRadioButton( NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *fill; CGFloat x, y; + bounds = CGRectOffset(checkbounds, bounds.origin.x, bounds.origin.y); x = bounds.origin.x; y = bounds.origin.y; @@ -798,12 +825,14 @@ static void DrawDarkRadioButton( CGContextSetFillColorWithColor(context, fill.CGColor); } if (state & TTK_STATE_SELECTED) { - CGContextBeginPath(context); CGRect dot = {{x + 6, y + 6}, {6, 6}}; + + CGContextBeginPath(context); CGContextAddEllipseInRect(context, dot); CGContextFillPath(context); } else if (state & TTK_STATE_ALTERNATE) { CGRect bar = {{x + 5, y + 8}, {8, 2}}; + CGContextFillRect(context, bar); } } @@ -873,9 +902,9 @@ static void DrawDarkTab( CGContextSetStrokeColorWithColor(context, stroke.CGColor); CGContextBeginPath(context); CGContextMoveToPoint(context, originalBounds.origin.x, - originalBounds.origin.y + 1); + originalBounds.origin.y + 1); CGContextAddLineToPoint(context, originalBounds.origin.x, - originalBounds.origin.y + originalBounds.size.height - 1); + originalBounds.origin.y + originalBounds.size.height - 1); CGContextStrokePath(context); CGContextRestoreGState(context); } @@ -891,7 +920,7 @@ static void DrawDarkTab( } if (!(state & TTK_STATE_BACKGROUND)) { GradientFillRoundedRectangle(context, bounds, 4, - darkSelectedGradient, 2); + darkSelectedGradient, 2); } else { faceColor = [NSColor colorWithColorSpace: deviceRGB components: darkInactiveSelectedTab @@ -901,12 +930,12 @@ static void DrawDarkTab( HighlightButtonBorder(context, bounds); } } - + /*---------------------------------------------------------------------- * DrawDarkSeparator -- * - * This is a standalone drawing procedure which draws a separator widget - * in Dark Mode. + * This is a standalone drawing procedure which draws a separator widget in + * Dark Mode. */ static void DrawDarkSeparator( @@ -919,15 +948,16 @@ static void DrawDarkSeparator( NSColor *fillColor = [NSColor colorWithColorSpace: deviceRGB components: fill count:4]; + CGContextSetFillColorWithColor(context, fillColor.CGColor); CGContextFillRect(context, bounds); } - + /*---------------------------------------------------------------------- * DrawDarkFrame -- * - * This is a standalone drawing procedure which draws various - * types of borders in Dark Mode. + * This is a standalone drawing procedure which draws various types of + * borders in Dark Mode. */ static void DrawDarkFrame( @@ -937,7 +967,6 @@ static void DrawDarkFrame( { NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *stroke; - CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace); CGFloat x = bounds.origin.x, y = bounds.origin.y; CGFloat w = bounds.size.width, h = bounds.size.height; CGPoint topPart[4] = { @@ -945,7 +974,9 @@ static void DrawDarkFrame( }; CGPoint bottom[2] = {{x, y + h}, {x + w, y + h}}; CGPoint accent[2] = {{x, y + 1}, {x + w, y + 1}}; - switch(kind) { + + CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace); + switch (kind) { case kHIThemeFrameTextFieldSquare: CGContextSaveGState(context); CGContextSetShouldAntialias(context, false); @@ -978,8 +1009,8 @@ static void DrawDarkFrame( /*---------------------------------------------------------------------- * DrawListHeader -- * - * This is a standalone drawing procedure which draws column - * headers for a Treeview in the Dark Mode. + * This is a standalone drawing procedure which draws column headers for a + * Treeview in the Dark Mode. */ static void DrawDarkListHeader( @@ -990,13 +1021,13 @@ static void DrawDarkListHeader( { NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *stroke; - CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace); CGFloat x = bounds.origin.x, y = bounds.origin.y; CGFloat w = bounds.size.width, h = bounds.size.height; CGPoint top[2] = {{x, y}, {x + w, y}}; CGPoint bottom[2] = {{x, y + h}, {x + w, y + h}}; CGPoint separator[2] = {{x + w, y + 3}, {x + w, y + h - 3}}; + CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace); CGContextSaveGState(context); CGContextSetShouldAntialias(context, false); stroke = [NSColor colorWithColorSpace: deviceRGB @@ -1032,8 +1063,8 @@ static void DrawDarkListHeader( */ /* - * When Ttk draws the various types of buttons, a pointer to one of these - * is passed as the clientData. + * When Ttk draws the various types of buttons, a pointer to one of these is + * passed as the clientData. */ typedef struct { @@ -1082,6 +1113,7 @@ static inline HIThemeButtonDrawInfo computeButtonDrawInfo( */ SInt32 HIThemeState; + switch (params->kind) { case kThemePushButton: HIThemeState = kThemeStateActive; @@ -1101,9 +1133,13 @@ static inline HIThemeButtonDrawInfo computeButtonDrawInfo( return info; } -static void ButtonElementMinSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) +static void +ButtonElementMinSize( + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, int *minHeight, + Ttk_Padding *paddingPtr) { ThemeButtonParams *params = clientData; @@ -1111,9 +1147,8 @@ static void ButtonElementMinSize( ChkErr(GetThemeMetric, params->heightMetric, minHeight); /* - * The theme height does not include the 1-pixel border around - * the button, although it does include the 1-pixel shadow at - * the bottom. + * The theme height does not include the 1-pixel border around the + * button, although it does include the 1-pixel shadow at the bottom. */ *minHeight += 2; @@ -1129,9 +1164,13 @@ static void ButtonElementMinSize( } } -static void ButtonElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) +static void +ButtonElementSize( + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, int *minHeight, + Ttk_Padding *paddingPtr) { ThemeButtonParams *params = clientData; const HIThemeButtonDrawInfo info = computeButtonDrawInfo(params, 0, tkwin); @@ -1153,10 +1192,10 @@ static void ButtonElementSize( * to draw a button with a certain bounding rectangle it draws the button * centered within the rectangle. * - * To compute the effective padding around a button we request the - * content and bounding rectangles for a 100x100 button and use the - * padding between those. However, we symmetrize the padding on the - * top and bottom, because that is how the button will be drawn. + * To compute the effective padding around a button we request the content + * and bounding rectangles for a 100x100 button and use the padding between + * those. However, we symmetrize the padding on the top and bottom, because + * that is how the button will be drawn. */ ChkErr(HIThemeGetButtonContentBounds, @@ -1170,16 +1209,21 @@ static void ButtonElementSize( paddingPtr->top = paddingPtr->bottom = verticalPad / 2; } -static void ButtonElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) +static void +ButtonElementDraw( + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { ThemeButtonParams *params = clientData; CGRect bounds = BoxToRect(d, b); HIThemeButtonDrawInfo info = computeButtonDrawInfo(params, state, tkwin); bounds = NormalizeButtonBounds(params->heightMetric, bounds); - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); if (TkMacOSXInDarkMode(tkwin)) { #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 switch (info.kind) { @@ -1235,7 +1279,7 @@ static void ButtonElementDraw( ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL); } - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec ButtonElementSpec = { @@ -1315,18 +1359,26 @@ static Ttk_StateTable TabPositionTable[] = { * TP30000359-TPXREF116> */ -static void TabElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) +static void +TabElementSize( + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, int *minHeight, + Ttk_Padding *paddingPtr) { - GetThemeMetric(kThemeMetricLargeTabHeight, (SInt32 *)minHeight); + GetThemeMetric(kThemeMetricLargeTabHeight, (SInt32 *) minHeight); *paddingPtr = Ttk_MakePadding(0, 0, 0, 2); - } -static void TabElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) +static void +TabElementDraw( + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { CGRect bounds = BoxToRect(d, b); HIThemeTabDrawInfo info = { @@ -1338,7 +1390,8 @@ static void TabElementDraw( .kind = kHIThemeTabKindNormal, .position = Ttk_StateTableLookup(TabPositionTable, state), }; - BEGIN_DRAWING(d) + + BEGIN_DRAWING(d); #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { DrawDarkTab(bounds, state, dc.context); @@ -1348,7 +1401,7 @@ static void TabElementDraw( #else ChkErr(HIThemeDrawTab, &bounds, &info, dc.context, HIOrientation, NULL); #endif - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec TabElementSpec = { @@ -1375,27 +1428,28 @@ static void PaneElementDraw( Drawable d, Ttk_Box b, Ttk_State state) { CGRect bounds = BoxToRect(d, b); + bounds.origin.y -= kThemeMetricTabFrameOverlap; bounds.size.height += kThemeMetricTabFrameOverlap; - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); if ([NSApp macMinorVersion] > 9) { #if MAC_OS_X_VERSION_MAX_ALLOWED > 1080 - DrawGroupBox(bounds, dc.context, tkwin); + DrawGroupBox(bounds, dc.context, tkwin); #endif } else { - HIThemeTabPaneDrawInfo info = { - .version = 1, - .state = Ttk_StateTableLookup(ThemeStateTable, state), - .direction = kThemeTabNorth, - .size = kHIThemeTabSizeNormal, - .kind = kHIThemeTabKindNormal, - .adornment = kHIThemeTabPaneAdornmentNormal, - }; - bounds.origin.y -= kThemeMetricTabFrameOverlap; - bounds.size.height += kThemeMetricTabFrameOverlap; - ChkErr(HIThemeDrawTabPane, &bounds, &info, dc.context, HIOrientation); + HIThemeTabPaneDrawInfo info = { + .version = 1, + .state = Ttk_StateTableLookup(ThemeStateTable, state), + .direction = kThemeTabNorth, + .size = kHIThemeTabSizeNormal, + .kind = kHIThemeTabKindNormal, + .adornment = kHIThemeTabPaneAdornmentNormal, + }; + bounds.origin.y -= kThemeMetricTabFrameOverlap; + bounds.size.height += kThemeMetricTabFrameOverlap; + ChkErr(HIThemeDrawTabPane, &bounds, &info, dc.context, HIOrientation); } - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec PaneElementSpec = { @@ -1418,32 +1472,39 @@ static Ttk_ElementSpec PaneElementSpec = { */ static void GroupElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, int *minHeight, + Ttk_Padding *paddingPtr) { *paddingPtr = Ttk_UniformPadding(4); } static void GroupElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { CGRect bounds = BoxToRect(d, b); - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); if ([NSApp macMinorVersion] > 9) { #if MAC_OS_X_VERSION_MAX_ALLOWED > 1080 - DrawGroupBox(bounds, dc.context, tkwin); + DrawGroupBox(bounds, dc.context, tkwin); #endif } else { - const HIThemeGroupBoxDrawInfo info = { - .version = 0, - .state = Ttk_StateTableLookup(ThemeStateTable, state), - .kind = kHIThemeGroupBoxKindPrimaryOpaque, - }; - ChkErr(HIThemeDrawGroupBox, &bounds, &info, dc.context, HIOrientation); + const HIThemeGroupBoxDrawInfo info = { + .version = 0, + .state = Ttk_StateTableLookup(ThemeStateTable, state), + .kind = kHIThemeGroupBoxKindPrimaryOpaque, + }; + ChkErr(HIThemeDrawGroupBox, &bounds, &info, dc.context, HIOrientation); } - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec GroupElementSpec = { @@ -1469,9 +1530,9 @@ typedef struct { static Ttk_ElementOptionSpec EntryElementOptions[] = { { "-background", TK_OPTION_BORDER, - Tk_Offset(EntryElement,backgroundObj), ENTRY_DEFAULT_BACKGROUND }, + Tk_Offset(EntryElement,backgroundObj), ENTRY_DEFAULT_BACKGROUND }, { "-fieldbackground", TK_OPTION_BORDER, - Tk_Offset(EntryElement,fieldbackgroundObj), ENTRY_DEFAULT_BACKGROUND }, + Tk_Offset(EntryElement,fieldbackgroundObj), ENTRY_DEFAULT_BACKGROUND }, {0} }; @@ -1495,9 +1556,10 @@ static void EntryElementDraw( if (TkMacOSXInDarkMode(tkwin)) { #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; CGFloat fill[4]; + GetBackgroundColor(dc.context, tkwin, 1, fill); background = [NSColor colorWithColorSpace: deviceRGB components: fill @@ -1505,7 +1567,7 @@ static void EntryElementDraw( CGContextSetFillColorWithColor(dc.context, background.CGColor); CGContextFillRect(dc.context, bounds); DrawDarkFrame(bounds, dc.context, kHIThemeFrameTextFieldSquare); - END_DRAWING + END_DRAWING; #endif } else { const HIThemeFrameDrawInfo info = { @@ -1534,7 +1596,7 @@ static void EntryElementDraw( Tk_3DBorderGC(tkwin, backgroundPtr, TK_3D_FLAT_GC), inner.x, inner.y, inner.width, inner.height); } - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); if (backgroundPtr == NULL) { background = [NSColor textBackgroundColor]; #if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 @@ -1545,7 +1607,7 @@ static void EntryElementDraw( CGContextFillRect(dc.context, bounds); } ChkErr(HIThemeDrawFrame, &bounds, &info, dc.context, HIOrientation); - END_DRAWING + END_DRAWING; } /*if (state & TTK_STATE_FOCUS) { ChkErr(DrawThemeFocusRect, &bounds, 1); @@ -1604,26 +1666,26 @@ static void ComboboxElementDraw( .adornment = Ttk_StateTableLookup(ButtonAdornmentTable, state), }; - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); bounds.origin.y += 1; if (TkMacOSXInDarkMode(tkwin)) { #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 bounds.size.height += 1; DrawDarkButton(bounds, info.kind, state, dc.context); #endif - } else - { + } else { #if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 if ((state & TTK_STATE_BACKGROUND) && - !(state & TTK_STATE_DISABLED)) { + !(state & TTK_STATE_DISABLED)) { NSColor *background = [NSColor textBackgroundColor]; CGRect innerBounds = CGRectInset(bounds, 1, 2); + SolidFillRoundedRectangle(dc.context, innerBounds, 4, background); } #endif ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL); } - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec ComboboxElementSpec = { @@ -1674,12 +1736,14 @@ static void SpinButtonUpElementDraw( { CGRect bounds = BoxToRect(d, Ttk_PadBox(b, SpinbuttonMargins)); int infoState; + bounds.size.height *= 2; if (state & TTK_STATE_PRESSED) { infoState = kThemeStatePressedUp; } else { infoState = Ttk_StateTableLookup(ThemeStateTable, state); } + const HIThemeButtonDrawInfo info = { .version = 0, .state = infoState, @@ -1687,7 +1751,8 @@ static void SpinButtonUpElementDraw( .value = Ttk_StateTableLookup(ButtonValueTable, state), .adornment = kThemeAdornmentNone, }; - BEGIN_DRAWING(d) + + BEGIN_DRAWING(d); #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { DrawDarkIncDecButton(bounds, infoState, state, dc.context); @@ -1696,7 +1761,7 @@ static void SpinButtonUpElementDraw( { ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL); } - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec SpinButtonUpElementSpec = { @@ -1725,12 +1790,13 @@ static void SpinButtonDownElementDraw( { CGRect bounds = BoxToRect(d, Ttk_PadBox(b, SpinbuttonMargins)); int infoState = 0; + bounds.origin.y -= bounds.size.height; bounds.size.height *= 2; if (state & TTK_STATE_PRESSED) { infoState = kThemeStatePressedDown; } else { - return; + return; // ??? } const HIThemeButtonDrawInfo info = { .version = 0, @@ -1740,16 +1806,17 @@ static void SpinButtonDownElementDraw( .adornment = kThemeAdornmentNone, }; - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { DrawDarkIncDecButton(bounds, infoState, state, dc.context); } else #endif { - ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL); + ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, + NULL); } - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec SpinButtonDownElementSpec = { @@ -1850,7 +1917,7 @@ static void TrackElementDraw( info.trackInfo.slider.thumbDir = kThemeThumbPlain; } } - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { CGRect bounds = BoxToRect(d, b); @@ -1858,6 +1925,7 @@ static void TrackElementDraw( NSColor *trackColor = [NSColor colorWithColorSpace: deviceRGB components: darkTrack count: 4]; + if (orientation == TTK_ORIENT_HORIZONTAL) { bounds = CGRectInset(bounds, 1, bounds.size.height/2 - 2); } else { @@ -1867,7 +1935,7 @@ static void TrackElementDraw( } #endif ChkErr(HIThemeDrawTrack, &info, NULL, dc.context, HIOrientation); - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec TrackElementSpec = { @@ -1887,6 +1955,7 @@ static Ttk_ElementSpec TrackElementSpec = { * Also buggy: The geometry here is a Wild-Assed-Guess; I can't figure out how * to get the Appearance Manager to tell me the slider size. */ + static void SliderElementSize( void *clientData, void *elementRecord, Tk_Window tkwin, int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) @@ -1971,7 +2040,7 @@ static void PbarElementDraw( .trackInfo.progress.phase = phase, }; - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { CGRect bounds = BoxToRect(d, b); @@ -1988,7 +2057,7 @@ static void PbarElementDraw( } #endif ChkErr(HIThemeDrawTrack, &info, NULL, dc.context, HIOrientation); - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec PbarElementSpec = { @@ -2054,6 +2123,7 @@ static void TroughElementDraw( NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *troughColor; CGFloat *rgba = TkMacOSXInDarkMode(tkwin) ? darkTrough : lightTrough; + Ttk_GetOrientFromObj(NULL, scrollbar->orientObj, &orientation); if (orientation == TTK_ORIENT_HORIZONTAL) { bounds = CGRectInset(bounds, 0, 1); @@ -2063,7 +2133,7 @@ static void TroughElementDraw( troughColor = [NSColor colorWithColorSpace: deviceRGB components: rgba count: 4]; - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); if ([NSApp macMinorVersion] > 8) { #if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 CGContextSetFillColorWithColor(dc.context, troughColor.CGColor); @@ -2073,7 +2143,7 @@ static void TroughElementDraw( dc.context, HIOrientation); } CGContextFillRect(dc.context, bounds); - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec TroughElementSpec = { @@ -2105,6 +2175,7 @@ static void ThumbElementDraw( { ScrollbarElement *scrollbar = elementRecord; int orientation = TTK_ORIENT_HORIZONTAL; + Ttk_GetOrientFromObj(NULL, scrollbar->orientObj, &orientation); /* @@ -2129,15 +2200,18 @@ static void ThumbElementDraw( NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *thumbColor; CGFloat *rgba; - if ((orientation == TTK_ORIENT_HORIZONTAL && - thumbBounds.size.width >= Tk_Width(tkwin) - 8) || - (orientation == TTK_ORIENT_VERTICAL && - thumbBounds.size.height >= Tk_Height(tkwin) - 8)) { + + if ((orientation == TTK_ORIENT_HORIZONTAL + && thumbBounds.size.width >= Tk_Width(tkwin) - 8) + || (orientation == TTK_ORIENT_VERTICAL + && thumbBounds.size.height >= Tk_Height(tkwin) - 8)) { return; } + int isDark = TkMacOSXInDarkMode(tkwin); + if ((state & TTK_STATE_PRESSED) || - (state & TTK_STATE_HOVER) ) { + (state & TTK_STATE_HOVER)) { rgba = isDark ? darkActiveThumb : lightActiveThumb; } else { rgba = isDark ? darkInactiveThumb : lightInactiveThumb; @@ -2145,9 +2219,9 @@ static void ThumbElementDraw( thumbColor = [NSColor colorWithColorSpace: deviceRGB components: rgba count: 4]; - BEGIN_DRAWING(d) - SolidFillRoundedRectangle(dc.context, thumbBounds, 4, thumbColor); - END_DRAWING + BEGIN_DRAWING(d); + SolidFillRoundedRectangle(dc.context, thumbBounds, 4, thumbColor); + END_DRAWING; #endif } else { double thumbSize, trackSize, visibleSize, viewSize; @@ -2164,6 +2238,7 @@ static void ThumbElementDraw( */ viewSize = RangeToFactor(100.0); + HIThemeTrackDrawInfo info = { .version = 0, .bounds = troughBounds, @@ -2171,6 +2246,7 @@ static void ThumbElementDraw( .attributes = kThemeTrackShowThumb | kThemeTrackThumbRgnIsNotGhost, .enableState = kThemeTrackActive }; + info.trackInfo.scrollbar.viewsize = viewSize*.8; if (orientation == TTK_ORIENT_HORIZONTAL) { trackSize = troughBounds.size.width; @@ -2186,7 +2262,7 @@ static void ThumbElementDraw( info.value = info.max * (b.y / (trackSize - thumbSize)); } if ((state & TTK_STATE_PRESSED) || - (state & TTK_STATE_HOVER) ) { + (state & TTK_STATE_HOVER)) { info.trackInfo.scrollbar.pressState = kThemeThumbPressed; } else { info.trackInfo.scrollbar.pressState = 0; @@ -2196,10 +2272,10 @@ static void ThumbElementDraw( } else { info.attributes &= ~kThemeTrackHorizontal; } - BEGIN_DRAWING(d) - HIThemeDrawTrack (&info, 0, dc.context, kHIThemeOrientationNormal); - END_DRAWING - } + BEGIN_DRAWING(d); + HIThemeDrawTrack(&info, 0, dc.context, kHIThemeOrientationNormal); + END_DRAWING; + } } static Ttk_ElementSpec ThumbElementSpec = { @@ -2255,7 +2331,7 @@ static void SeparatorElementDraw( .state = Ttk_StateTableLookup(ThemeStateTable, state & TTK_STATE_BACKGROUND), }; - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { DrawDarkSeparator(bounds, dc.context, tkwin); @@ -2265,7 +2341,7 @@ static void SeparatorElementDraw( #else ChkErr(HIThemeDrawSeparator, &bounds, &info, dc.context, HIOrientation); #endif - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec SeparatorElementSpec = { @@ -2316,9 +2392,9 @@ static void SizegripElementDraw( .size = kHIThemeGrowBoxSizeNormal, }; - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); ChkErr(HIThemeDrawGrowBox, &bounds.origin, &info, dc.context, HIOrientation); - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec SizegripElementSpec = { @@ -2381,23 +2457,25 @@ static void FillElementDraw( NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *bgColor; CGFloat fill[4]; - BEGIN_DRAWING(d) + + BEGIN_DRAWING(d); GetBackgroundColor(dc.context, tkwin, 0, fill); bgColor = [NSColor colorWithColorSpace: deviceRGB components: fill count: 4]; CGContextSetFillColorSpace(dc.context, deviceRGB.CGColorSpace); CGContextSetFillColorWithColor(dc.context, bgColor.CGColor); CGContextFillRect(dc.context, bounds); - END_DRAWING + END_DRAWING; #else ThemeBrush brush = (state & TTK_STATE_BACKGROUND) ? kThemeBrushModelessDialogBackgroundInactive : kThemeBrushModelessDialogBackgroundActive; - BEGIN_DRAWING(d) + + BEGIN_DRAWING(d); ChkErr(HIThemeSetFill, brush, NULL, dc.context, HIOrientation); //QDSetPatternOrigin(PatternOrigin(tkwin, d)); CGContextFillRect(dc.context, bounds); - END_DRAWING + END_DRAWING; #endif } @@ -2406,7 +2484,7 @@ static void BackgroundElementDraw( Drawable d, Ttk_Box b, unsigned int state) { FillElementDraw(clientData, elementRecord, tkwin, d, Ttk_WinBox(tkwin), - state); + state); } static Ttk_ElementSpec FillElementSpec = { @@ -2429,9 +2507,9 @@ static Ttk_ElementSpec BackgroundElementSpec = { * +++ ToolbarBackground element -- toolbar style for frames. * * This is very similar to the normal background element, but uses a - * different ThemeBrush in order to get the lighter pinstripe effect - * used in toolbars. We use SetThemeBackground() rather than - * ApplyThemeBackground() in order to get the right style. + * different ThemeBrush in order to get the lighter pinstripe effect used in + * toolbars. We use SetThemeBackground() rather than ApplyThemeBackground() + * in order to get the right style. * * 8) { #if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 - /* - * Compensate for the padding added in TreeHeaderElementSize, so - * the larger heading will be drawn at the top of the widget. + * Compensate for the padding added in TreeHeaderElementSize, so the + * larger heading will be drawn at the top of the widget. */ bounds.origin.y -= 4; @@ -2586,7 +2663,7 @@ static void TreeHeaderElementDraw( } else { ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL); } - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec TreeHeaderElementSpec = { @@ -2636,9 +2713,9 @@ static void DisclosureElementDraw( .adornment = kThemeAdornmentDrawIndicatorOnly, }; - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL); - END_DRAWING + END_DRAWING; } } @@ -2735,13 +2812,15 @@ TTK_LAYOUT("Horizontal.TScrollbar", TTK_NODE("Horizontal.Scrollbar.rightarrow", TTK_PACK_RIGHT) TTK_NODE("Horizontal.Scrollbar.leftarrow", TTK_PACK_RIGHT))) -TTK_END_LAYOUT_TABLE +TTK_END_LAYOUT_TABLE; /*---------------------------------------------------------------------- * +++ Initialization. */ -static int AquaTheme_Init(Tcl_Interp *interp) +static int +AquaTheme_Init( + Tcl_Interp *interp) { Ttk_Theme themePtr = Ttk_CreateTheme(interp, "aqua", NULL); @@ -2752,38 +2831,41 @@ static int AquaTheme_Init(Tcl_Interp *interp) /* * Elements: */ + Ttk_RegisterElementSpec(themePtr, "background", &BackgroundElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "fill", &FillElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "field", &FieldElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Toolbar.background", - &ToolbarBackgroundElementSpec, 0); + &ToolbarBackgroundElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Button.button", - &ButtonElementSpec, &PushButtonParams); + &ButtonElementSpec, &PushButtonParams); Ttk_RegisterElementSpec(themePtr, "Checkbutton.button", - &ButtonElementSpec, &CheckBoxParams); + &ButtonElementSpec, &CheckBoxParams); Ttk_RegisterElementSpec(themePtr, "Radiobutton.button", - &ButtonElementSpec, &RadioButtonParams); + &ButtonElementSpec, &RadioButtonParams); Ttk_RegisterElementSpec(themePtr, "Toolbutton.border", - &ButtonElementSpec, &BevelButtonParams); + &ButtonElementSpec, &BevelButtonParams); Ttk_RegisterElementSpec(themePtr, "Menubutton.button", - &ButtonElementSpec, &PopupButtonParams); + &ButtonElementSpec, &PopupButtonParams); Ttk_RegisterElementSpec(themePtr, "Spinbox.uparrow", - &SpinButtonUpElementSpec, 0); + &SpinButtonUpElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Spinbox.downarrow", - &SpinButtonDownElementSpec, 0); + &SpinButtonDownElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Combobox.button", - &ComboboxElementSpec, 0); + &ComboboxElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Treeitem.indicator", - &DisclosureElementSpec, &DisclosureParams); + &DisclosureElementSpec, &DisclosureParams); Ttk_RegisterElementSpec(themePtr, "Treeheading.cell", - &TreeHeaderElementSpec, &ListHeaderParams); + &TreeHeaderElementSpec, &ListHeaderParams); - Ttk_RegisterElementSpec(themePtr, "Treeview.treearea", &TreeAreaElementSpec, 0); + Ttk_RegisterElementSpec(themePtr, "Treeview.treearea", + &TreeAreaElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Notebook.tab", &TabElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Notebook.client", &PaneElementSpec, 0); - Ttk_RegisterElementSpec(themePtr, "Labelframe.border", &GroupElementSpec, 0); + Ttk_RegisterElementSpec(themePtr, "Labelframe.border", + &GroupElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Entry.field", &EntryElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Spinbox.field", &EntryElementSpec, 0); @@ -2803,23 +2885,31 @@ static int AquaTheme_Init(Tcl_Interp *interp) Ttk_RegisterElementSpec(themePtr,"Progressbar.track", &PbarElementSpec, 0); Ttk_RegisterElementSpec(themePtr,"Scale.trough", &TrackElementSpec, - &ScaleData); + &ScaleData); Ttk_RegisterElementSpec(themePtr,"Scale.slider", &SliderElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.trough", &TroughElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.thumb", &ThumbElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.trough", &TroughElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.thumb", &ThumbElementSpec, 0); + Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.trough", + &TroughElementSpec, 0); + Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.thumb", + &ThumbElementSpec, 0); + Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.trough", + &TroughElementSpec, 0); + Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.thumb", + &ThumbElementSpec, 0); /* * If we are not in Snow Leopard or Lion the arrows won't actually be * displayed. */ - Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.uparrow", &ArrowElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.downarrow", &ArrowElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.leftarrow", &ArrowElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.rightarrow", &ArrowElementSpec, 0); + Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.uparrow", + &ArrowElementSpec, 0); + Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.downarrow", + &ArrowElementSpec, 0); + Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.leftarrow", + &ArrowElementSpec, 0); + Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.rightarrow", + &ArrowElementSpec, 0); /* * Layouts: -- cgit v0.12 From 7eaee2f2e59cbbb043964d94313d3f22a6d877a5 Mon Sep 17 00:00:00 2001 From: culler Date: Wed, 17 Apr 2019 14:05:33 +0000 Subject: Mitigate future merge conflict headaches. --- macosx/tkMacOSXButton.c | 688 +++++++++++++++++++++---------------------- macosx/tkMacOSXClipboard.c | 8 +- macosx/tkMacOSXCursor.c | 18 +- macosx/tkMacOSXDialog.c | 408 ++++++++++++++++--------- macosx/tkMacOSXDraw.c | 465 ++++++++++++++++------------- macosx/tkMacOSXEmbed.c | 55 ++-- macosx/tkMacOSXFont.c | 193 ++++++------ macosx/tkMacOSXImage.c | 145 ++++----- macosx/tkMacOSXInit.c | 19 +- macosx/tkMacOSXKeyEvent.c | 562 +++++++++++++++++++---------------- macosx/tkMacOSXMenu.c | 142 ++++----- macosx/tkMacOSXMenubutton.c | 415 +++++++++++++------------- macosx/tkMacOSXMenus.c | 1 - macosx/tkMacOSXNotify.c | 103 ++++--- macosx/tkMacOSXRegion.c | 16 +- macosx/tkMacOSXScale.c | 108 ++++--- macosx/tkMacOSXScrlbr.c | 395 +++++++++++++------------ macosx/tkMacOSXSend.c | 4 +- macosx/tkMacOSXSubwindows.c | 115 ++++---- macosx/tkMacOSXWindowEvent.c | 64 ++-- macosx/tkMacOSXWm.c | 82 +++--- macosx/ttkMacOSXTheme.c | 450 +++++++++++++++++----------- 22 files changed, 2426 insertions(+), 2030 deletions(-) diff --git a/macosx/tkMacOSXButton.c b/macosx/tkMacOSXButton.c index ad963e1..ac3c122 100644 --- a/macosx/tkMacOSXButton.c +++ b/macosx/tkMacOSXButton.c @@ -1,8 +1,8 @@ /* * tkMacOSXButton.c -- * - * This file implements the Macintosh specific portion of the - * button widgets. + * This file implements the Macintosh specific portion of the button + * widgets. * * Copyright (c) 1996-1997 by Sun Microsystems, Inc. * Copyright 2001, Apple Computer, Inc. @@ -70,20 +70,23 @@ typedef struct { * Forward declarations for procedures defined later in this file: */ - -static void ButtonBackgroundDrawCB (const HIRect *btnbounds, MacButton *ptr, - SInt16 depth, Boolean isColorDev); -static void ButtonContentDrawCB (const HIRect *bounds, ThemeButtonKind kind, - const HIThemeButtonDrawInfo *info, MacButton *ptr, SInt16 depth, - Boolean isColorDev); -static void ButtonEventProc(ClientData clientData, XEvent *eventPtr); -static void TkMacOSXComputeButtonParams (TkButton * butPtr, ThemeButtonKind* btnkind, - HIThemeButtonDrawInfo* drawinfo); -static int TkMacOSXComputeButtonDrawParams (TkButton * butPtr, DrawParams * dpPtr); -static void TkMacOSXDrawButton (MacButton *butPtr, GC gc, Pixmap pixmap); -static void DrawButtonImageAndText(TkButton* butPtr); -static void PulseDefaultButtonProc(ClientData clientData); - +static void ButtonBackgroundDrawCB(const HIRect *btnbounds, + MacButton *ptr, SInt16 depth, Boolean isColorDev); +static void ButtonContentDrawCB(const HIRect *bounds, + ThemeButtonKind kind, + const HIThemeButtonDrawInfo *info, MacButton *ptr, + SInt16 depth, Boolean isColorDev); +static void ButtonEventProc(ClientData clientData, + XEvent *eventPtr); +static void TkMacOSXComputeButtonParams(TkButton *butPtr, + ThemeButtonKind *btnkind, + HIThemeButtonDrawInfo *drawinfo); +static int TkMacOSXComputeButtonDrawParams(TkButton *butPtr, + DrawParams * dpPtr); +static void TkMacOSXDrawButton(MacButton *butPtr, GC gc, + Pixmap pixmap); +static void DrawButtonImageAndText(TkButton *butPtr); +static void PulseDefaultButtonProc(ClientData clientData); /* * The class procedure table for the button widgets. @@ -95,15 +98,15 @@ const Tk_ClassProcs tkpButtonProcs = { }; static int bCount; - + /* *---------------------------------------------------------------------- * * TkpButtonSetDefaults -- * - * This procedure is invoked before option tables are created for - * buttons. It modifies some of the default values to match the current - * values defined for this platform. + * This procedure is invoked before option tables are created for buttons. + * It modifies some of the default values to match the current values + * defined for this platform. * * Results: * Some of the default values in *specPtr are modified. @@ -117,9 +120,8 @@ static int bCount; void TkpButtonSetDefaults() { -/*No-op.*/ + /*No-op.*/ } - /* *---------------------------------------------------------------------- @@ -141,10 +143,10 @@ TkButton * TkpCreateButton( Tk_Window tkwin) { - MacButton *macButtonPtr = (MacButton *) ckalloc(sizeof(MacButton)); + MacButton *macButtonPtr = ckalloc(sizeof(MacButton)); Tk_CreateEventHandler(tkwin, ActivateMask, - ButtonEventProc, (ClientData) macButtonPtr); + ButtonEventProc, macButtonPtr); macButtonPtr->id = bCount++; macButtonPtr->flags = FIRST_DRAW; macButtonPtr->btnkind = kThemePushButton; @@ -152,7 +154,7 @@ TkpCreateButton( bzero(&macButtonPtr->drawinfo, sizeof(macButtonPtr->drawinfo)); bzero(&macButtonPtr->lastdrawinfo, sizeof(macButtonPtr->lastdrawinfo)); - return (TkButton *)macButtonPtr; + return (TkButton *) macButtonPtr; } /* @@ -160,15 +162,15 @@ TkpCreateButton( * * TkpDisplayButton -- * - * This procedure is invoked to display a button widget. It is - * normally invoked as an idle handler. + * This procedure is invoked to display a button widget. It is normally + * invoked as an idle handler. * * Results: * None. * * Side effects: - * Commands are output to X to display the button in its - * current mode. The REDRAW_PENDING flag is cleared. + * Commands are output to X to display the button in its current mode. The + * REDRAW_PENDING flag is cleared. * *---------------------------------------------------------------------- */ @@ -177,8 +179,8 @@ void TkpDisplayButton( ClientData clientData) /* Information about widget. */ { - MacButton *macButtonPtr = (MacButton *) clientData; - TkButton *butPtr = (TkButton *) clientData; + MacButton *macButtonPtr = clientData; + TkButton *butPtr = clientData; Tk_Window tkwin = butPtr->tkwin; Pixmap pixmap; DrawParams* dpPtr = &macButtonPtr->drawParams; @@ -191,16 +193,15 @@ TkpDisplayButton( pixmap = (Pixmap) Tk_WindowId(tkwin); TkMacOSXSetUpClippingRgn(Tk_WindowId(tkwin)); - if (TkMacOSXComputeButtonDrawParams(butPtr, dpPtr) ) { + if (TkMacOSXComputeButtonDrawParams(butPtr, dpPtr)) { macButtonPtr->useTkText = 0; } else { macButtonPtr->useTkText = 1; } - /* - * Set up clipping region. Make sure the we are using the port - * for this button, or we will set the wrong window's clip. + * Set up clipping region. Make sure the we are using the port for this + * button, or we will set the wrong window's clip. */ if (macButtonPtr->useTkText) { @@ -212,26 +213,36 @@ TkpDisplayButton( Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT); } - /* Display image or bitmap or text for labels or custom controls. */ + /* + * Display image or bitmap or text for labels or custom controls. + */ + DrawButtonImageAndText(butPtr); - needhighlight = 1; + needhighlight = 1; } else { - /* Draw the native portion of the buttons. */ + /* + * Draw the native portion of the buttons. + */ + TkMacOSXDrawButton(macButtonPtr, dpPtr->gc, pixmap); - /* Draw highlight border, if needed. */ + /* + * Ask for the highlight border, if needed. + */ + if (butPtr->highlightWidth < 3) { needhighlight = 1; } } - /* Draw highlight border, if needed. */ - if (needhighlight) { - if ((butPtr->flags & GOT_FOCUS)) { - Tk_Draw3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0, + /* + * Draw highlight border. + */ + + if (needhighlight && (butPtr->flags & GOT_FOCUS)) { + Tk_Draw3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0, Tk_Width(tkwin), Tk_Height(tkwin), butPtr->highlightWidth, TK_RELIEF_SOLID); - } } } @@ -240,9 +251,9 @@ TkpDisplayButton( * * TkpComputeButtonGeometry -- * - * After changes in a button's text or bitmap, this procedure - * recomputes the button's geometry and passes this information - * along to the geometry manager for the window. + * After changes in a button's text or bitmap, this procedure recomputes + * the button's geometry and passes this information along to the geometry + * manager for the window. * * Results: * None. @@ -259,7 +270,7 @@ TkpComputeButtonGeometry( { int width = 0, height = 0, charWidth = 1, haveImage = 0, haveText = 0; int txtWidth = 0, txtHeight = 0; - MacButton *mbPtr = (MacButton*)butPtr; + MacButton *mbPtr = (MacButton *) butPtr; Tk_FontMetrics fm; char *text = Tcl_GetString(butPtr->textPtr); @@ -270,21 +281,27 @@ TkpComputeButtonGeometry( */ if (butPtr->indicatorOn) { - switch (butPtr->type) { - case TYPE_RADIO_BUTTON: - GetThemeMetric(kThemeMetricRadioButtonWidth, (SInt32 *)&butPtr->indicatorDiameter); - break; - case TYPE_CHECK_BUTTON: - GetThemeMetric(kThemeMetricCheckBoxWidth, (SInt32 *)&butPtr->indicatorDiameter); - break; - default: - break; - } - /* Allow 2px extra space next to the indicator. */ - butPtr->indicatorSpace = butPtr->indicatorDiameter + 2; + switch (butPtr->type) { + case TYPE_RADIO_BUTTON: + GetThemeMetric(kThemeMetricRadioButtonWidth, + (SInt32 *) &butPtr->indicatorDiameter); + break; + case TYPE_CHECK_BUTTON: + GetThemeMetric(kThemeMetricCheckBoxWidth, + (SInt32 *) &butPtr->indicatorDiameter); + break; + default: + break; + } + + /* + * Allow 2px extra space next to the indicator. + */ + + butPtr->indicatorSpace = butPtr->indicatorDiameter + 2; } else { - butPtr->indicatorSpace = 0; - butPtr->indicatorDiameter = 0; + butPtr->indicatorSpace = 0; + butPtr->indicatorDiameter = 0; } if (butPtr->image != NULL) { @@ -308,44 +325,43 @@ TkpComputeButtonGeometry( if (haveImage && haveText) { /* Image and Text */ switch ((enum compound) butPtr->compound) { - case COMPOUND_TOP: - case COMPOUND_BOTTOM: - - /* - * Image is above or below text. - */ - - height += txtHeight + butPtr->padY; - width = (width > txtWidth ? width : txtWidth); - break; - case COMPOUND_LEFT: - case COMPOUND_RIGHT: - - /* - * Image is left or right of text. - */ - - width += txtWidth + 2*butPtr->padX; - height = (height > txtHeight ? height : txtHeight); - break; - case COMPOUND_CENTER: - - /* - * Image and text are superimposed. - */ - - width = (width > txtWidth ? width : txtWidth); - height = (height > txtHeight ? height : txtHeight); - break; - default: - break; + case COMPOUND_TOP: + case COMPOUND_BOTTOM: + /* + * Image is above or below text. + */ + + height += txtHeight + butPtr->padY; + width = (width > txtWidth ? width : txtWidth); + break; + case COMPOUND_LEFT: + case COMPOUND_RIGHT: + /* + * Image is left or right of text. + */ + + width += txtWidth + 2*butPtr->padX; + height = (height > txtHeight ? height : txtHeight); + break; + case COMPOUND_CENTER: + /* + * Image and text are superimposed. + */ + + width = (width > txtWidth ? width : txtWidth); + height = (height > txtHeight ? height : txtHeight); + break; + default: + break; } width += butPtr->indicatorSpace; } else if (haveImage) { /* Image only */ width = butPtr->width > 0 ? butPtr->width : width + butPtr->indicatorSpace; height = butPtr->height > 0 ? butPtr->height : height; if (butPtr->type == TYPE_BUTTON) { - /* Allow room to shift the image. */ + /* + * Allow room to shift the image. + */ width += 2; height += 2; } @@ -375,19 +391,19 @@ TkpComputeButtonGeometry( width += butPtr->inset*2; height += butPtr->inset*2; if ([NSApp macMinorVersion] == 6) { - width += 12; + width += 12; } if (mbPtr->btnkind == kThemePushButton) { HIRect tmpRect; HIRect contBounds; /* - * A PushButton has a minimum size. We make sure that we - * are not underestimating the size by requesting the content - * size of a Pushbutton whose overall size is our content size - * expanded by the standard padding. + * A PushButton has a minimum size. We make sure that we are not + * underestimating the size by requesting the content size of a + * Pushbutton whose overall size is our content size expanded by the + * standard padding. */ - + tmpRect = CGRectMake(0, 0, width + 2*HI_PADX, height + 2*HI_PADY); HIThemeGetButtonContentBounds(&tmpRect, &mbPtr->drawinfo, &contBounds); if (height < contBounds.size.height) { @@ -402,51 +418,43 @@ TkpComputeButtonGeometry( Tk_GeometryRequest(butPtr->tkwin, width, height); Tk_SetInternalBorder(butPtr->tkwin, butPtr->inset); } - + /* *---------------------------------------------------------------------- * * DrawButtonImageAndText -- * - * Draws the image and text associated with a button or label. + * Draws the image and text associated with a button or label. * * Results: - * None. + * None. * * Side effects: - * The image and text are drawn. + * The image and text are drawn. * *---------------------------------------------------------------------- */ static void DrawButtonImageAndText( - TkButton* butPtr) + TkButton *butPtr) { - MacButton *mbPtr = (MacButton*)butPtr; - Tk_Window tkwin = butPtr->tkwin; - Pixmap pixmap; - int haveImage = 0; - int haveText = 0; - int imageWidth = 0; - int imageHeight = 0; - int imageXOffset = 0; - int imageYOffset = 0; - int textXOffset = 0; - int textYOffset = 0; - int width = 0; - int height = 0; - int fullWidth = 0; - int fullHeight = 0; - int pressed = 0; - + MacButton *mbPtr = (MacButton *) butPtr; + Tk_Window tkwin = butPtr->tkwin; + Pixmap pixmap; + int haveImage = 0, haveText = 0, pressed = 0; + int imageWidth = 0, imageHeight = 0; + int imageXOffset = 0, imageYOffset = 0; + int textXOffset = 0, textYOffset = 0; + int width = 0, height = 0; + int fullWidth = 0, fullHeight = 0; if (tkwin == NULL || !Tk_IsMapped(tkwin)) { return; } - DrawParams* dpPtr = &mbPtr->drawParams; - pixmap = (Pixmap)Tk_WindowId(tkwin); + DrawParams *dpPtr = &mbPtr->drawParams; + pixmap = (Pixmap) Tk_WindowId(tkwin); if (butPtr->image != None) { Tk_SizeOfImage(butPtr->image, &width, &height); @@ -456,74 +464,68 @@ DrawButtonImageAndText( haveImage = 1; } - imageWidth = width; + imageWidth = width; imageHeight = height; if (mbPtr->drawinfo.state == kThemeStatePressed) { - /* Offset bitmaps by a bit when the button is pressed. */ + /* + * Offset bitmaps by a bit when the button is pressed. + */ + pressed = 1; } haveText = (butPtr->textWidth != 0 && butPtr->textHeight != 0); if (haveImage && haveText) { /* Image and Text */ - int x; - int y; - textXOffset = 0; - textYOffset = 0; - fullWidth = 0; - fullHeight = 0; + int x, y; switch ((enum compound) butPtr->compound) { case COMPOUND_TOP: - case COMPOUND_BOTTOM: { - /* Image is above or below text */ - if (butPtr->compound == COMPOUND_TOP) { - textYOffset = height + butPtr->padY; - } else { - imageYOffset = butPtr->textHeight + butPtr->padY; - } - fullHeight = height + butPtr->textHeight + butPtr->padY; - fullWidth = (width > butPtr->textWidth ? width : - butPtr->textWidth); - textXOffset = (fullWidth - butPtr->textWidth)/2; - imageXOffset = (fullWidth - width)/2; - break; - } + case COMPOUND_BOTTOM: + /* Image is above or below text */ + if (butPtr->compound == COMPOUND_TOP) { + textYOffset = height + butPtr->padY; + } else { + imageYOffset = butPtr->textHeight + butPtr->padY; + } + fullHeight = height + butPtr->textHeight + butPtr->padY; + fullWidth = (width > butPtr->textWidth ? width : butPtr->textWidth); + textXOffset = (fullWidth - butPtr->textWidth)/2; + imageXOffset = (fullWidth - width)/2; + break; case COMPOUND_LEFT: - case COMPOUND_RIGHT: { - /* - * Image is left or right of text - */ - - if (butPtr->compound == COMPOUND_LEFT) { - textXOffset = width + butPtr->padX; - } else { - imageXOffset = butPtr->textWidth + butPtr->padX; - } - fullWidth = butPtr->textWidth + butPtr->padX + width; - fullHeight = (height > butPtr->textHeight ? height : - butPtr->textHeight); - textYOffset = (fullHeight - butPtr->textHeight)/2; - imageYOffset = (fullHeight - height)/2; - break; - } - case COMPOUND_CENTER: { - /* - * Image and text are superimposed - */ - - fullWidth = (width > butPtr->textWidth ? width : - butPtr->textWidth); - fullHeight = (height > butPtr->textHeight ? height : - butPtr->textHeight); - textXOffset = (fullWidth - butPtr->textWidth)/2; - imageXOffset = (fullWidth - width)/2; - textYOffset = (fullHeight - butPtr->textHeight)/2; - imageYOffset = (fullHeight - height)/2; - break; - } + case COMPOUND_RIGHT: + /* + * Image is left or right of text + */ + + if (butPtr->compound == COMPOUND_LEFT) { + textXOffset = width + butPtr->padX; + } else { + imageXOffset = butPtr->textWidth + butPtr->padX; + } + fullWidth = butPtr->textWidth + butPtr->padX + width; + fullHeight = (height > butPtr->textHeight ? height : + butPtr->textHeight); + textYOffset = (fullHeight - butPtr->textHeight)/2; + imageYOffset = (fullHeight - height)/2; + break; + case COMPOUND_CENTER: + /* + * Image and text are superimposed + */ + + fullWidth = (width > butPtr->textWidth ? width : + butPtr->textWidth); + fullHeight = (height > butPtr->textHeight ? height : + butPtr->textHeight); + textXOffset = (fullWidth - butPtr->textWidth)/2; + imageXOffset = (fullWidth - width)/2; + textYOffset = (fullHeight - butPtr->textHeight)/2; + imageYOffset = (fullHeight - height)/2; + break; default: - break; + break; } TkComputeAnchor(butPtr->anchor, tkwin, @@ -547,25 +549,25 @@ DrawButtonImageAndText( imageYOffset += y; if (butPtr->image != NULL) { - if ((butPtr->selectImage != NULL) && - (butPtr->flags & SELECTED)) { - Tk_RedrawImage(butPtr->selectImage, 0, 0, - width, height, pixmap, imageXOffset, imageYOffset); - } else if ((butPtr->tristateImage != NULL) && - (butPtr->flags & TRISTATED)) { - Tk_RedrawImage(butPtr->tristateImage, 0, 0, - width, height, pixmap, imageXOffset, imageYOffset); - } else { - Tk_RedrawImage(butPtr->image, 0, 0, width, - height, pixmap, imageXOffset, imageYOffset); - } + if ((butPtr->selectImage != NULL) && + (butPtr->flags & SELECTED)) { + Tk_RedrawImage(butPtr->selectImage, 0, 0, + width, height, pixmap, imageXOffset, imageYOffset); + } else if ((butPtr->tristateImage != NULL) && + (butPtr->flags & TRISTATED)) { + Tk_RedrawImage(butPtr->tristateImage, 0, 0, + width, height, pixmap, imageXOffset, imageYOffset); + } else { + Tk_RedrawImage(butPtr->image, 0, 0, width, + height, pixmap, imageXOffset, imageYOffset); + } } else { - XSetClipOrigin(butPtr->display, dpPtr->gc, - imageXOffset, imageYOffset); - XCopyPlane(butPtr->display, butPtr->bitmap, pixmap, dpPtr->gc, - 0, 0, (unsigned int) width, (unsigned int) height, - imageXOffset, imageYOffset, 1); - XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0); + XSetClipOrigin(butPtr->display, dpPtr->gc, + imageXOffset, imageYOffset); + XCopyPlane(butPtr->display, butPtr->bitmap, pixmap, dpPtr->gc, + 0, 0, (unsigned int) width, (unsigned int) height, + imageXOffset, imageYOffset, 1); + XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0); } y += 1; /* Tweak to match native buttons. */ @@ -577,60 +579,57 @@ DrawButtonImageAndText( x + textXOffset, y + textYOffset, butPtr->underline); } else if (haveImage) { /* Image only */ - int x = 0; - int y; + int x = 0, y; + TkComputeAnchor(butPtr->anchor, tkwin, - butPtr->padX + butPtr->borderWidth, - butPtr->padY + butPtr->borderWidth, - width + butPtr->indicatorSpace, - height, &x, &y); + butPtr->padX + butPtr->borderWidth, + butPtr->padY + butPtr->borderWidth, + width + butPtr->indicatorSpace, height, &x, &y); x += butPtr->indicatorSpace; if (pressed) { - x += dpPtr->offset; - y += dpPtr->offset; + x += dpPtr->offset; + y += dpPtr->offset; } imageXOffset += x; imageYOffset += y; if (butPtr->image != NULL) { - - if ((butPtr->selectImage != NULL) && - (butPtr->flags & SELECTED)) { - Tk_RedrawImage(butPtr->selectImage, 0, 0, width, - height, pixmap, imageXOffset, imageYOffset); - } else if ((butPtr->tristateImage != NULL) && - (butPtr->flags & TRISTATED)) { - Tk_RedrawImage(butPtr->tristateImage, 0, 0, width, - height, pixmap, imageXOffset, imageYOffset); - } else { - Tk_RedrawImage(butPtr->image, 0, 0, width, height, - pixmap, imageXOffset, imageYOffset); - } + if ((butPtr->selectImage != NULL) && + (butPtr->flags & SELECTED)) { + Tk_RedrawImage(butPtr->selectImage, 0, 0, width, + height, pixmap, imageXOffset, imageYOffset); + } else if ((butPtr->tristateImage != NULL) && + (butPtr->flags & TRISTATED)) { + Tk_RedrawImage(butPtr->tristateImage, 0, 0, width, + height, pixmap, imageXOffset, imageYOffset); + } else { + Tk_RedrawImage(butPtr->image, 0, 0, width, height, + pixmap, imageXOffset, imageYOffset); + } } else { - XSetClipOrigin(butPtr->display, dpPtr->gc, x, y); - XCopyPlane(butPtr->display, butPtr->bitmap, - pixmap, dpPtr->gc, - 0, 0, (unsigned int) width, - (unsigned int) height, - imageXOffset, imageYOffset, 1); - XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0); + XSetClipOrigin(butPtr->display, dpPtr->gc, x, y); + XCopyPlane(butPtr->display, butPtr->bitmap, pixmap, dpPtr->gc, + 0, 0, (unsigned int) width, (unsigned int) height, + imageXOffset, imageYOffset, 1); + XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0); } } else { /* Text only */ int x, y; + TkComputeAnchor(butPtr->anchor, tkwin, butPtr->padX, butPtr->padY, - butPtr->textWidth + butPtr->indicatorSpace, - butPtr->textHeight, &x, &y); + butPtr->textWidth + butPtr->indicatorSpace, + butPtr->textHeight, &x, &y); x += butPtr->indicatorSpace; y += 1; /* Tweak to match native buttons */ - Tk_DrawTextLayout(butPtr->display, pixmap, dpPtr->gc, butPtr->textLayout, - x, y, 0, -1); + Tk_DrawTextLayout(butPtr->display, pixmap, dpPtr->gc, + butPtr->textLayout, x, y, 0, -1); } /* * If the button is disabled with a stipple rather than a special - * foreground color, generate the stippled effect. If the widget - * is selected and we use a different background color when selected, - * must temporarily modify the GC so the stippling is the right color. + * foreground color, generate the stippled effect. If the widget is + * selected and we use a different background color when selected, must + * temporarily modify the GC so the stippling is the right color. */ if (mbPtr->useTkText) { @@ -668,18 +667,15 @@ DrawButtonImageAndText( */ if (dpPtr->relief != TK_RELIEF_FLAT) { - int inset = butPtr->highlightWidth; - Tk_Draw3DRectangle(tkwin, pixmap, dpPtr->border, inset, inset, - Tk_Width(tkwin) - 2*inset, Tk_Height(tkwin) - 2*inset, - butPtr->borderWidth, dpPtr->relief); + int inset = butPtr->highlightWidth; + + Tk_Draw3DRectangle(tkwin, pixmap, dpPtr->border, inset, inset, + Tk_Width(tkwin) - 2*inset, Tk_Height(tkwin) - 2*inset, + butPtr->borderWidth, dpPtr->relief); } } - - } - - - - +} + /* *---------------------------------------------------------------------- * @@ -701,6 +697,7 @@ TkpDestroyButton( TkButton *butPtr) { MacButton *mbPtr = (MacButton *) butPtr; /* Mac button. */ + if (mbPtr->defaultPulseHandler) { Tcl_DeleteTimerHandler(mbPtr->defaultPulseHandler); } @@ -711,9 +708,8 @@ TkpDestroyButton( * * TkMacOSXDrawButton -- * - * This function draws the tk button using Mac controls - * In addition, this code may apply custom colors passed - * in the TkButton. + * This function draws the tk button using Mac controls. In addition, + * this code may apply custom colors passed in the TkButton. * * Results: * None. @@ -732,23 +728,19 @@ TkMacOSXDrawButton( Pixmap pixmap) /* The pixmap we are drawing into - needed * for the bevel button */ { - TkButton * butPtr = ( TkButton *)mbPtr; - TkWindow * winPtr; - HIRect cntrRect; + TkButton *butPtr = (TkButton *) mbPtr; + TkWindow *winPtr = (TkWindow *) butPtr->tkwin; + HIRect cntrRect; TkMacOSXDrawingContext dc; - DrawParams* dpPtr = &mbPtr->drawParams; + DrawParams *dpPtr = &mbPtr->drawParams; int useNewerHITools = 1; - winPtr = (TkWindow *)butPtr->tkwin; - TkMacOSXComputeButtonParams(butPtr, &mbPtr->btnkind, &mbPtr->drawinfo); - cntrRect = CGRectMake(winPtr->privatePtr->xOff, - winPtr->privatePtr->yOff, - Tk_Width(butPtr->tkwin), - Tk_Height(butPtr->tkwin)); + cntrRect = CGRectMake(winPtr->privatePtr->xOff, winPtr->privatePtr->yOff, + Tk_Width(butPtr->tkwin), Tk_Height(butPtr->tkwin)); - cntrRect = CGRectInset(cntrRect, butPtr->inset, butPtr->inset); + cntrRect = CGRectInset(cntrRect, butPtr->inset, butPtr->inset); if (useNewerHITools == 1) { HIRect contHIRec; @@ -762,7 +754,7 @@ TkMacOSXDrawButton( hiinfo.version = 0; hiinfo.state = mbPtr->drawinfo.state; - hiinfo.kind = mbPtr->btnkind; + hiinfo.kind = mbPtr->btnkind; hiinfo.value = mbPtr->drawinfo.value; hiinfo.adornment = mbPtr->drawinfo.adornment; hiinfo.animation.time.current = CFAbsoluteTimeGetCurrent(); @@ -772,21 +764,19 @@ TkMacOSXDrawButton( /* * To avoid buttons with white text on a white background, we always - * set the state to inactive in Dark Mode. It isn't perfect but - * it is usable. Using a ttk::button would be a better choice, - * however. + * set the state to inactive in Dark Mode. It isn't perfect but it is + * usable. Using a ttk::button would be a better choice, however. */ if (TkMacOSXInDarkMode(butPtr->tkwin)) { hiinfo.state = kThemeStateInactive; } - HIThemeDrawButton(&cntrRect, &hiinfo, dc.context, kHIThemeOrientationNormal, - &contHIRec); + HIThemeDrawButton(&cntrRect, &hiinfo, dc.context, + kHIThemeOrientationNormal, &contHIRec); TkMacOSXRestoreDrawingContext(&dc); ButtonContentDrawCB(&contHIRec, mbPtr->btnkind, &mbPtr->drawinfo, - (MacButton *)mbPtr, 32, true); - + (MacButton *) mbPtr, 32, true); } else { if (!TkMacOSXSetupDrawingContext(pixmap, dpPtr->gc, 1, &dc)) { return; @@ -802,8 +792,8 @@ TkMacOSXDrawButton( * * ButtonBackgroundDrawCB -- * - * This function draws the background that - * lies under checkboxes and radiobuttons. + * This function draws the background that lies under checkboxes and + * radiobuttons. * * Results: * None. @@ -813,32 +803,33 @@ TkMacOSXDrawButton( * *-------------------------------------------------------------- */ + static void -ButtonBackgroundDrawCB ( - const HIRect * btnbounds, +ButtonBackgroundDrawCB( + const HIRect *btnbounds, MacButton *ptr, SInt16 depth, Boolean isColorDev) { - MacButton* mbPtr = (MacButton*)ptr; - TkButton* butPtr = (TkButton*)mbPtr; - Tk_Window tkwin = butPtr->tkwin; + MacButton *mbPtr = (MacButton *) ptr; + TkButton *butPtr = (TkButton *) mbPtr; + Tk_Window tkwin = butPtr->tkwin; Pixmap pixmap; int usehlborder = 0; if (tkwin == NULL || !Tk_IsMapped(tkwin)) { return; } - pixmap = (Pixmap)Tk_WindowId(tkwin); + pixmap = (Pixmap) Tk_WindowId(tkwin); if (butPtr->type != TYPE_LABEL) { switch (mbPtr->btnkind) { - case kThemeSmallBevelButton: - case kThemeBevelButton: - case kThemeRoundedBevelButton: - case kThemePushButton: - usehlborder = 1; - break; + case kThemeSmallBevelButton: + case kThemeBevelButton: + case kThemeRoundedBevelButton: + case kThemePushButton: + usehlborder = 1; + break; } } if (usehlborder) { @@ -874,17 +865,18 @@ ButtonContentDrawCB ( SInt16 depth, Boolean isColorDev) { - TkButton *butPtr = (TkButton *)ptr; - Tk_Window tkwin = butPtr->tkwin; + TkButton *butPtr = (TkButton *) ptr; + Tk_Window tkwin = butPtr->tkwin; if (tkwin == NULL || !Tk_IsMapped(tkwin)) { return; } /* - * Overlay Tk elements over button native region: drawing elements - * within button boundaries/native region causes unpredictable metrics. + * Overlay Tk elements over button native region: drawing elements within + * button boundaries/native region causes unpredictable metrics. */ + DrawButtonImageAndText( butPtr); } @@ -893,8 +885,8 @@ ButtonContentDrawCB ( * * ButtonEventProc -- * - * This procedure is invoked by the Tk dispatcher for various - * events on buttons. + * This procedure is invoked by the Tk dispatcher for various events on + * buttons. * * Results: * None. @@ -910,8 +902,8 @@ ButtonEventProc( ClientData clientData, /* Information about window. */ XEvent *eventPtr) /* Information about event. */ { - TkButton *buttonPtr = (TkButton *) clientData; - MacButton *mbPtr = (MacButton *) clientData; + TkButton *buttonPtr = clientData; + MacButton *mbPtr = clientData; if (eventPtr->type == ActivateNotify || eventPtr->type == DeactivateNotify) { @@ -924,7 +916,7 @@ ButtonEventProc( mbPtr->flags &= ~ACTIVE; } if ((buttonPtr->flags & REDRAW_PENDING) == 0) { - Tcl_DoWhenIdle(TkpDisplayButton, (ClientData) buttonPtr); + Tcl_DoWhenIdle(TkpDisplayButton, buttonPtr); buttonPtr->flags |= REDRAW_PENDING; } } @@ -935,9 +927,9 @@ ButtonEventProc( * * TkMacOSXComputeButtonParams -- * - * This procedure computes the various parameters used - * when creating a Carbon Appearance control. - * These are determined by the various tk button parameters + * This procedure computes the various parameters used when creating a + * Carbon Appearance control. These are determined by the various tk + * button parameters * * Results: * None. @@ -950,11 +942,11 @@ ButtonEventProc( static void TkMacOSXComputeButtonParams( - TkButton * butPtr, - ThemeButtonKind* btnkind, - HIThemeButtonDrawInfo *drawinfo) + TkButton *butPtr, + ThemeButtonKind *btnkind, + HIThemeButtonDrawInfo *drawinfo) { - MacButton *mbPtr = (MacButton *)butPtr; + MacButton *mbPtr = (MacButton *) butPtr; if (butPtr->borderWidth <= 2) { *btnkind = kThemeSmallBevelButton; @@ -968,47 +960,46 @@ TkMacOSXComputeButtonParams( if ((butPtr->image == None) && (butPtr->bitmap == None)) { switch (butPtr->type) { - case TYPE_BUTTON: - *btnkind = kThemePushButton; - break; - case TYPE_RADIO_BUTTON: - if (butPtr->borderWidth <= 1) { - *btnkind = kThemeSmallRadioButton; - } else { - *btnkind = kThemeRadioButton; - } - break; - case TYPE_CHECK_BUTTON: - if (butPtr->borderWidth <= 1) { - *btnkind = kThemeSmallCheckBox; - } else { - *btnkind = kThemeCheckBox; - } - break; + case TYPE_BUTTON: + *btnkind = kThemePushButton; + break; + case TYPE_RADIO_BUTTON: + if (butPtr->borderWidth <= 1) { + *btnkind = kThemeSmallRadioButton; + } else { + *btnkind = kThemeRadioButton; + } + break; + case TYPE_CHECK_BUTTON: + if (butPtr->borderWidth <= 1) { + *btnkind = kThemeSmallCheckBox; + } else { + *btnkind = kThemeCheckBox; + } + break; } } if (butPtr->indicatorOn) { switch (butPtr->type) { - case TYPE_RADIO_BUTTON: - if (butPtr->borderWidth <= 1) { - *btnkind = kThemeSmallRadioButton; - } else { - *btnkind = kThemeRadioButton; - } - break; - case TYPE_CHECK_BUTTON: - if (butPtr->borderWidth <= 1) { - *btnkind = kThemeSmallCheckBox; - } else { - *btnkind = kThemeCheckBox; - } - break; + case TYPE_RADIO_BUTTON: + if (butPtr->borderWidth <= 1) { + *btnkind = kThemeSmallRadioButton; + } else { + *btnkind = kThemeRadioButton; + } + break; + case TYPE_CHECK_BUTTON: + if (butPtr->borderWidth <= 1) { + *btnkind = kThemeSmallCheckBox; + } else { + *btnkind = kThemeCheckBox; + } + break; } } else { if (butPtr->type == TYPE_RADIO_BUTTON || - butPtr->type == TYPE_CHECK_BUTTON - ) { + butPtr->type == TYPE_CHECK_BUTTON) { if (*btnkind == kThemePushButton) { *btnkind = kThemeBevelButton; } @@ -1050,8 +1041,7 @@ TkMacOSXComputeButtonParams( drawinfo->adornment |= kThemeAdornmentDefault; if (!mbPtr->defaultPulseHandler) { mbPtr->defaultPulseHandler = Tcl_CreateTimerHandler( - PULSE_TIMER_MSECS, PulseDefaultButtonProc, - (ClientData) butPtr); + PULSE_TIMER_MSECS, PulseDefaultButtonProc, butPtr); } } else if (mbPtr->defaultPulseHandler) { Tcl_DeleteTimerHandler(mbPtr->defaultPulseHandler); @@ -1068,9 +1058,8 @@ TkMacOSXComputeButtonParams( * * TkMacOSXComputeButtonDrawParams -- * - * This procedure computes the various parameters used - * when drawing a button - * These are determined by the various tk button parameters + * This procedure computes the various parameters used when drawing a + * button. These are determined by the various tk button parameters * * Results: * 1 if control will be used, 0 otherwise. @@ -1086,7 +1075,7 @@ TkMacOSXComputeButtonDrawParams( TkButton *butPtr, DrawParams *dpPtr) { - MacButton *mbPtr = (MacButton *)butPtr; + MacButton *mbPtr = (MacButton *) butPtr; dpPtr->hasImageOrBitmap = ((butPtr->image != NULL) || (butPtr->bitmap != None)); @@ -1095,12 +1084,12 @@ TkMacOSXComputeButtonDrawParams( dpPtr->offset = 0; if (dpPtr->hasImageOrBitmap) { switch (mbPtr->btnkind) { - case kThemeSmallBevelButton: - case kThemeBevelButton: - case kThemeRoundedBevelButton: - case kThemePushButton: - dpPtr->offset = 1; - break; + case kThemeSmallBevelButton: + case kThemeBevelButton: + case kThemeRoundedBevelButton: + case kThemePushButton: + dpPtr->offset = 1; + break; } } } @@ -1121,8 +1110,8 @@ TkMacOSXComputeButtonDrawParams( } /* - * Override the relief specified for the button if this is a - * checkbutton or radiobutton and there's no indicator. + * Override the relief specified for the button if this is a checkbutton or + * radiobutton and there's no indicator. */ dpPtr->relief = butPtr->relief; @@ -1134,22 +1123,18 @@ TkMacOSXComputeButtonDrawParams( } } - if (butPtr->type != TYPE_LABEL && - (butPtr->type == TYPE_BUTTON || - butPtr->indicatorOn || - dpPtr->hasImageOrBitmap)) { - + if (butPtr->type != TYPE_LABEL && (butPtr->type == TYPE_BUTTON || + butPtr->indicatorOn || dpPtr->hasImageOrBitmap)) { /* * Draw this widget as a native control. */ - + return 1; } else { - /* * Draw this widget from scratch. */ - + return 0; } } @@ -1173,12 +1158,13 @@ TkMacOSXComputeButtonDrawParams( static void PulseDefaultButtonProc(ClientData clientData) { - MacButton *mbPtr = (MacButton *)clientData; + MacButton *mbPtr = clientData; + TkpDisplayButton(clientData); mbPtr->defaultPulseHandler = Tcl_CreateTimerHandler( PULSE_TIMER_MSECS, PulseDefaultButtonProc, clientData); } - + /* * Local Variables: * mode: objc diff --git a/macosx/tkMacOSXClipboard.c b/macosx/tkMacOSXClipboard.c index efd3c69..6cbcdf6 100644 --- a/macosx/tkMacOSXClipboard.c +++ b/macosx/tkMacOSXClipboard.c @@ -123,8 +123,9 @@ TkSelGetSelection( { int result = TCL_ERROR; TkDisplay *dispPtr = ((TkWindow *) tkwin)->dispPtr; + int haveExternalClip = + ([[NSPasteboard generalPasteboard] changeCount] != changeCount); - int haveExternalClip = ([[NSPasteboard generalPasteboard] changeCount] != changeCount); if (dispPtr && (haveExternalClip || dispPtr->clipboardActive) && selection == dispPtr->clipboardAtom && (target == XA_STRING || target == dispPtr->utf8Atom)) { @@ -177,6 +178,7 @@ XSetSelectionOwner( clipboardOwner = owner ? Tk_IdToWindow(display, owner) : NULL; if (!dispPtr->clipboardActive) { NSPasteboard *pb = [NSPasteboard generalPasteboard]; + changeCount = [pb declareTypes:[NSArray array] owner:NSApp]; } } @@ -188,8 +190,8 @@ XSetSelectionOwner( * * TkMacOSXSelDeadWindow -- * - * This function is invoked just before a TkWindow is deleted. It - * performs selection-related cleanup. + * This function is invoked just before a TkWindow is deleted. It performs + * selection-related cleanup. * * Results: * None. diff --git a/macosx/tkMacOSXCursor.c b/macosx/tkMacOSXCursor.c index b6394b7..03d13dd 100644 --- a/macosx/tkMacOSXCursor.c +++ b/macosx/tkMacOSXCursor.c @@ -185,7 +185,7 @@ static const struct CursorName cursorNames[] = { * Declarations of static variables used in this file. */ -static TkMacOSXCursor * gCurrentCursor = NULL; +static TkMacOSXCursor *gCurrentCursor = NULL; /* A pointer to the current cursor. */ static int gResizeOverride = false; /* A boolean indicating whether we should use @@ -194,7 +194,7 @@ static int gTkOwnsCursor = true;/* A boolean indicating whether Tk owns the * cursor. If not (for instance, in the case * where a Tk window is embedded in another * app's window, and the cursor is out of the - * tk window, we will not attempt to adjust + * Tk window, we will not attempt to adjust * the cursor. */ /* @@ -278,6 +278,7 @@ FindCursorByName( kCGColorSpaceGenericGray); CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, bitmap, pix*pix/8, NULL); + if (provider) { img = CGImageCreate(pix, pix, 1, 1, pix/8, colorspace, kCGBitmapByteOrderDefault, provider, decodeWB, 0, @@ -299,14 +300,21 @@ FindCursorByName( initWithCGImage:maskedImg]; CFRelease(maskedImg); } - if (mask) { CFRelease(mask); } - if (img) { CFRelease(img); } - if (colorspace) { CFRelease(colorspace); } + if (mask) { + CFRelease(mask); + } + if (img) { + CFRelease(img); + } + if (colorspace) { + CFRelease(colorspace); + } if (bitmapImageRep) { image = [[NSImage alloc] initWithSize:NSMakeSize(pix, pix)]; [image addRepresentation:bitmapImageRep]; [bitmapImageRep release]; } + uint16_t *hotSpotData = (uint16_t*)(bitmap + 2*pix*pix/8); hotSpot.y = CFSwapInt16BigToHost(*hotSpotData++); hotSpot.x = CFSwapInt16BigToHost(*hotSpotData); diff --git a/macosx/tkMacOSXDialog.c b/macosx/tkMacOSXDialog.c index c3778f1..a7997f2 100644 --- a/macosx/tkMacOSXDialog.c +++ b/macosx/tkMacOSXDialog.c @@ -22,31 +22,39 @@ #else #define modalOK NSModalResponseOK #define modalCancel NSModalResponseCancel -#endif +#endif // MAC_OS_X_VERSION_MIN_REQUIRED < 1090 #define modalOther -1 #define modalError -2 -/*Vars for filtering in "open file" and "save file" dialogs.*/ -typedef struct { - bool doFileTypes; // show the accessory view which displays the filter menu - bool preselectFilter; // a filter was selected by the typevariable - bool userHasSelectedFilter; // The user has changed the filter in the accessory view - - NSMutableArray *fileTypeNames; // array of names, e.g. "Text document" - NSMutableArray *fileTypeExtensions; // array of allowed extensions per name, e.g. "txt", "doc" - NSMutableArray *fileTypeLabels; // displayed string, e.g. "Text document (.txt, .doc)" - NSMutableArray *fileTypeAllowsAll; // boolean if the all pattern (*.*) is included - - NSMutableArray *allowedExtensions; // set of all allowed extensions - bool allowedExtensionsAllowAll; // set of all allowed extensions includes *.* +/* + * Vars for filtering in "open file" and "save file" dialogs. + */ - NSUInteger fileTypeIndex; // index of currently selected filter +typedef struct { + bool doFileTypes; /* Show the accessory view which + * displays the filter menu */ + bool preselectFilter; /* A filter was selected by the + * typevariable. */ + bool userHasSelectedFilter; /* The user has changed the filter in + * the accessory view. */ + NSMutableArray *fileTypeNames; /* Array of names, e.g. "Text + * document". */ + NSMutableArray *fileTypeExtensions; /* Array of allowed extensions per + * name, e.g. "txt", "doc". */ + NSMutableArray *fileTypeLabels; /* Displayed string, e.g. "Text + * document (.txt, .doc)". */ + NSMutableArray *fileTypeAllowsAll; /* Boolean if the all pattern (*.*) is + * included. */ + NSMutableArray *allowedExtensions; /* Set of all allowed extensions. */ + bool allowedExtensionsAllowAll; /* Set of all allowed extensions + * includes *.* */ + NSUInteger fileTypeIndex; /* Index of currently selected + * filter. */ } filepanelFilterInfo; -filepanelFilterInfo filterInfo; - -NSOpenPanel *openpanel; -NSSavePanel *savepanel; +static filepanelFilterInfo filterInfo; +static NSOpenPanel *openpanel; +static NSSavePanel *savepanel; static const char *const colorOptionStrings[] = { "-initialcolor", "-parent", "-title", NULL @@ -166,10 +174,15 @@ static const short alertNativeButtonIndexAndTypeToButtonIndex[][3] = { }; /* - * Construct a file URL from directory and filename. Either may - * be nil. If both are nil, returns nil. + * Construct a file URL from directory and filename. Either may be nil. If both + * are nil, returns nil. */ -static NSURL *getFileURL(NSString *directory, NSString *filename) { + +static NSURL * +getFileURL( + NSString *directory, + NSString *filename) +{ NSURL *url = nil; if (directory) { url = [NSURL fileURLWithPath:directory isDirectory:YES]; @@ -229,7 +242,6 @@ static NSURL *getFileURL(NSString *directory, NSString *filename) { } } - - (void) tkAlertDidEnd: (NSAlert *) alert returnCode: (NSInteger) returnCode contextInfo: (void *) contextInfo { @@ -272,12 +284,18 @@ static NSURL *getFileURL(NSString *directory, NSString *filename) { if ([[filterInfo.fileTypeAllowsAll objectAtIndex:filterInfo.fileTypeIndex] boolValue]) { [openpanel setAllowsOtherFileTypes:YES]; - /* setAllowsOtherFileTypes might have no effect; it's inherited from the - * NSSavePanel, where it has the effect that it does not append an extension - * Setting the allowed file types to nil allows selecting any file */ + + /* + * setAllowsOtherFileTypes might have no effect; it's inherited from + * the NSSavePanel, where it has the effect that it does not append an + * extension. Setting the allowed file types to nil allows selecting + * any file. + */ + [openpanel setAllowedFileTypes:nil]; } else { - NSMutableArray *allowedtypes = [filterInfo.fileTypeExtensions objectAtIndex:filterInfo.fileTypeIndex]; + NSMutableArray *allowedtypes = + [filterInfo.fileTypeExtensions objectAtIndex:filterInfo.fileTypeIndex]; [openpanel setAllowedFileTypes:allowedtypes]; [openpanel setAllowsOtherFileTypes:NO]; } @@ -293,7 +311,8 @@ static NSURL *getFileURL(NSString *directory, NSString *filename) { [savepanel setAllowsOtherFileTypes:YES]; [savepanel setAllowedFileTypes:nil]; } else { - NSMutableArray *allowedtypes = [filterInfo.fileTypeExtensions objectAtIndex:filterInfo.fileTypeIndex]; + NSMutableArray *allowedtypes = + [filterInfo.fileTypeExtensions objectAtIndex:filterInfo.fileTypeIndex]; [savepanel setAllowedFileTypes:allowedtypes]; [savepanel setAllowsOtherFileTypes:NO]; } @@ -384,6 +403,7 @@ Tk_ChooseColorObjCmd( [colorPanel _setUseModalAppearance:YES]; if (title) { NSString *s = [[NSString alloc] initWithUTF8String:title]; + [colorPanel setTitle:s]; [s release]; } @@ -415,9 +435,17 @@ end: return result; } -/* dissect the -filetype nested lists and store the information - * in the filterInfo structure */ -int parseFileFilters(Tcl_Interp *interp, Tcl_Obj *fileTypesPtr, Tcl_Obj *typeVariablePtr) { +/* + * Dissect the -filetype nested lists and store the information in the + * filterInfo structure. + */ + +static int +parseFileFilters( + Tcl_Interp *interp, + Tcl_Obj *fileTypesPtr, + Tcl_Obj *typeVariablePtr) +{ if (!fileTypesPtr) { filterInfo.doFileTypes = false; @@ -425,6 +453,7 @@ int parseFileFilters(Tcl_Interp *interp, Tcl_Obj *fileTypesPtr, Tcl_Obj *typeVar } FileFilterList fl; + TkInitFileFilters(&fl); if (TkGetFileFilters(interp, &fl, fileTypesPtr, 0) != TCL_OK) { TkFreeFileFilters(&fl); @@ -445,11 +474,12 @@ int parseFileFilters(Tcl_Interp *interp, Tcl_Obj *fileTypesPtr, Tcl_Obj *typeVar if (filterInfo.doFileTypes) { for (FileFilter *filterPtr = fl.filters; filterPtr; filterPtr = filterPtr->next) { - NSString * name = [[NSString alloc] initWithUTF8String: filterPtr -> name]; + NSString *name = [[NSString alloc] initWithUTF8String: filterPtr->name]; + [filterInfo.fileTypeNames addObject:name]; [name release]; - NSMutableArray * clauseextensions = [NSMutableArray array]; - NSMutableArray * displayextensions = [NSMutableArray array]; + NSMutableArray *clauseextensions = [NSMutableArray array]; + NSMutableArray *displayextensions = [NSMutableArray array]; bool allowsAll = NO; for (FileFilterClause *clausePtr = filterPtr->clauses; clausePtr; @@ -460,7 +490,7 @@ int parseFileFilters(Tcl_Interp *interp, Tcl_Obj *fileTypesPtr, Tcl_Obj *typeVar const char *str = globPtr->pattern; while (*str && (*str == '*' || *str == '.')) { str++; - } + } if (*str) { NSString *extension = [[NSString alloc] initWithUTF8String:str]; if (![filterInfo.allowedExtensions containsObject:extension]) { @@ -472,7 +502,10 @@ int parseFileFilters(Tcl_Interp *interp, Tcl_Obj *fileTypesPtr, Tcl_Obj *typeVar [extension release]; } else { - // it is the all pattern (*, .* or *.*) + /* + * It is the all pattern (*, .* or *.*) + */ + allowsAll = YES; filterInfo.allowedExtensionsAllowAll = YES; [displayextensions addObject:@"*"]; @@ -482,27 +515,39 @@ int parseFileFilters(Tcl_Interp *interp, Tcl_Obj *fileTypesPtr, Tcl_Obj *typeVar [filterInfo.fileTypeExtensions addObject:clauseextensions]; [filterInfo.fileTypeAllowsAll addObject:[NSNumber numberWithBool:allowsAll]]; - NSMutableString * label = [[NSMutableString alloc] initWithString:name]; + NSMutableString *label = [[NSMutableString alloc] initWithString:name]; [label appendString:@" ("]; [label appendString:[displayextensions componentsJoinedByString:@", "]]; [label appendString:@")"]; [filterInfo.fileTypeLabels addObject:label]; [label release]; - } - /* Check if the typevariable exists and matches one of the names */ + /* + * Check if the typevariable exists and matches one of the names. + */ + filterInfo.preselectFilter = false; filterInfo.userHasSelectedFilter = false; if (typeVariablePtr) { - /* extract the variable content as a NSString */ - Tcl_Obj *selectedFileTypeObj = Tcl_ObjGetVar2(interp, typeVariablePtr, NULL, TCL_GLOBAL_ONLY); + /* + * Extract the variable content as a NSString. + */ + + Tcl_Obj *selectedFileTypeObj = Tcl_ObjGetVar2(interp, + typeVariablePtr, NULL, TCL_GLOBAL_ONLY); + + /* + * Check that the typevariable exists. + */ - /* check that the typevariable exists */ if (selectedFileTypeObj != NULL) { - const char *selectedFileType = Tcl_GetString(selectedFileTypeObj); - NSString *selectedFileTypeStr = [[NSString alloc] initWithUTF8String:selectedFileType]; - NSUInteger index = [filterInfo.fileTypeNames indexOfObject:selectedFileTypeStr]; + const char *selectedFileType = + Tcl_GetString(selectedFileTypeObj); + NSString *selectedFileTypeStr = + [[NSString alloc] initWithUTF8String:selectedFileType]; + NSUInteger index = + [filterInfo.fileTypeNames indexOfObject:selectedFileTypeStr]; if (index != NSNotFound) { filterInfo.fileTypeIndex = index; @@ -517,17 +562,24 @@ int parseFileFilters(Tcl_Interp *interp, Tcl_Obj *fileTypesPtr, Tcl_Obj *typeVar return TCL_OK; } -bool filterCompatible(NSString *extension, int filterIndex) { - NSMutableArray *allowedExtensions = [filterInfo.fileTypeExtensions objectAtIndex: filterIndex]; +static bool +filterCompatible( + NSString *extension, + int filterIndex) +{ + NSMutableArray *allowedExtensions = + [filterInfo.fileTypeExtensions objectAtIndex: filterIndex]; + + /* + * If this contains the all pattern, accept any extension. + */ - /* If this contains the all pattern, accept any extension */ if ([[filterInfo.fileTypeAllowsAll objectAtIndex:filterIndex] boolValue]) { return true; } return [allowedExtensions containsObject: extension]; } - /* *---------------------------------------------------------------------- @@ -631,13 +683,16 @@ Tk_GetOpenFileObjCmd( if (title) { [openpanel setTitle:title]; - /* From OSX 10.11, the title string is silently ignored in the open panel. - * Prepend the title to the message in this case - * NOTE should be conditional on OSX version, but - * -mmacosx-version-min does not revert this behaviour*/ + /* + * From OSX 10.11, the title string is silently ignored in the open + * panel. Prepend the title to the message in this case. NOTE should + * be conditional on OSX version, but -mmacosx-version-min does not + * revert this behaviour + */ if (message) { - NSString *fullmessage = [[NSString alloc] initWithFormat:@"%@\n%@",title,message]; + NSString *fullmessage = + [[NSString alloc] initWithFormat:@"%@\n%@", title, message]; [message release]; [title release]; message = fullmessage; @@ -658,15 +713,20 @@ Tk_GetOpenFileObjCmd( } if (filterInfo.doFileTypes) { - NSView *accessoryView = [[NSView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 300, 32.0)]; - NSTextField *label = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 60, 22)]; + NSView *accessoryView = [[NSView alloc] + initWithFrame:NSMakeRect(0.0, 0.0, 300, 32.0)]; + NSTextField *label = [[NSTextField alloc] + initWithFrame:NSMakeRect(0, 0, 60, 22)]; + [label setEditable:NO]; [label setStringValue:@"Filter:"]; [label setBordered:NO]; [label setBezeled:NO]; [label setDrawsBackground:NO]; - NSPopUpButton *popupButton = [[NSPopUpButton alloc] initWithFrame:NSMakeRect(50.0, 2, 240, 22.0) pullsDown:NO]; + NSPopUpButton *popupButton = [[NSPopUpButton alloc] + initWithFrame:NSMakeRect(50.0, 2, 240, 22.0) pullsDown:NO]; + [popupButton addItemsWithTitles:filterInfo.fileTypeLabels]; [popupButton setAction:@selector(selectFormat:)]; @@ -674,10 +734,16 @@ Tk_GetOpenFileObjCmd( [accessoryView addSubview:popupButton]; if (filterInfo.preselectFilter) { - /* A specific filter was selected from the typevariable. Select it and - * open the accessory view */ + /* + * A specific filter was selected from the typevariable. Select it + * and open the accessory view. + */ + [popupButton selectItemAtIndex:filterInfo.fileTypeIndex]; - /* on OSX > 10.11, the optons are not visible by default. Ergo allow all file types + + /* + * On OSX > 10.11, the options are not visible by default. Ergo + * allow all file types [openpanel setAllowedFileTypes:filterInfo.fileTypeExtensions[filterInfo.fileTypeIndex]]; */ [openpanel setAllowedFileTypes:filterInfo.allowedExtensions]; @@ -693,7 +759,10 @@ Tk_GetOpenFileObjCmd( [openpanel setAccessoryView:accessoryView]; } else { - /* No filters are given. Allow picking all files */ + /* + * No filters are given. Allow picking all files. + */ + [openpanel setAllowsOtherFileTypes:YES]; } @@ -711,20 +780,24 @@ Tk_GetOpenFileObjCmd( parent = TkMacOSXDrawableWindow(((TkWindow *) tkwin)->window); if (haveParentOption && parent && ![parent attachedSheet]) { parentIsKey = [parent isKeyWindow]; - if (directory || filename ) { - NSURL * fileURL = getFileURL(directory, filename); + if (directory || filename) { + NSURL *fileURL = getFileURL(directory, filename); + [openpanel setDirectoryURL:fileURL]; } [openpanel beginSheetModalForWindow:parent - completionHandler:^(NSInteger returnCode) - { [NSApp tkFilePanelDidEnd:openpanel + completionHandler:^(NSInteger returnCode) { + [NSApp tkFilePanelDidEnd:openpanel returnCode:returnCode - contextInfo:callbackInfo ]; } ]; - modalReturnCode = cmdObj ? modalOther : [NSApp runModalForWindow:openpanel]; + contextInfo:callbackInfo ]; + }]; + modalReturnCode = cmdObj ? modalOther : + [NSApp runModalForWindow:openpanel]; } else { - if (directory || filename ) { - NSURL * fileURL = getFileURL(directory, filename); + if (directory || filename) { + NSURL *fileURL = getFileURL(directory, filename); + [openpanel setDirectoryURL:fileURL]; } @@ -737,38 +810,50 @@ Tk_GetOpenFileObjCmd( [parent makeKeyWindow]; } - if ((typeVariablePtr && (modalReturnCode == NSOKButton)) && - filterInfo.doFileTypes) { + if ((typeVariablePtr && (modalReturnCode == NSOKButton)) + && filterInfo.doFileTypes) { /* - * The -typevariable must be set to the selected file type, if the dialog was not cancelled + * The -typevariable must be set to the selected file type, if the + * dialog was not cancelled. */ + NSUInteger selectedFilterIndex = filterInfo.fileTypeIndex; NSString *selectedFilter = NULL; + if (filterInfo.userHasSelectedFilter) { selectedFilterIndex = filterInfo.fileTypeIndex; selectedFilter = [filterInfo.fileTypeNames objectAtIndex:selectedFilterIndex]; } else { - /* Difficult case: the user has not touched the filter settings, but we must - * return something in the typevariable. First check if the preselected type is compatible - * with the selected file, otherwise choose the first compatible type from the list, - * finally fall back to the empty string */ + /* + * Difficult case: the user has not touched the filter settings, + * but we must return something in the typevariable. First check if + * the preselected type is compatible with the selected file, + * otherwise choose the first compatible type from the list, + * finally fall back to the empty string. + */ + NSURL *selectedFile; + if (multiple) { - // Use the first file in the case of multiple selection - // Anyway it is not overly useful here + /* + * Use the first file in the case of multiple selection. + * Anyway it is not overly useful here. + */ selectedFile = [[openpanel URLs] objectAtIndex:0]; } else { selectedFile = [openpanel URL]; } NSString *extension = [selectedFile pathExtension]; + if (filterInfo.preselectFilter && - filterCompatible(extension, filterInfo.fileTypeIndex)) { + filterCompatible(extension, filterInfo.fileTypeIndex)) { selectedFilterIndex = filterInfo.fileTypeIndex; // The preselection from the typevariable selectedFilter = [filterInfo.fileTypeNames objectAtIndex:selectedFilterIndex]; } else { // scan the list NSUInteger i; + for (i = 0; i < [filterInfo.fileTypeNames count]; i++) { if (filterCompatible(extension, i)) { selectedFilterIndex = i; @@ -780,19 +865,17 @@ Tk_GetOpenFileObjCmd( } else { selectedFilter = @""; } - } } Tcl_ObjSetVar2(interp, typeVariablePtr, NULL, - Tcl_NewStringObj([selectedFilter UTF8String], -1), TCL_GLOBAL_ONLY); + Tcl_NewStringObj([selectedFilter UTF8String], -1), + TCL_GLOBAL_ONLY); } - end: return result; } - /* *---------------------------------------------------------------------- @@ -807,6 +890,7 @@ Tk_GetOpenFileObjCmd( * * Side effects: * See user documentation. + * *---------------------------------------------------------------------- */ @@ -828,7 +912,7 @@ Tk_GetSaveFileObjCmd( NSString *directory = nil, *filename = nil, *defaultType = nil; NSString *message = nil, *title = nil; NSWindow *parent; - savepanel = [NSSavePanel savePanel]; + savepanel = [NSSavePanel savePanel]; NSInteger modalReturnCode = modalError; BOOL parentIsKey = NO; @@ -906,13 +990,17 @@ Tk_GetSaveFileObjCmd( if (title) { [savepanel setTitle:title]; - /* From OSX 10.11, the title string is silently ignored, if the save panel is a sheet. - * Prepend the title to the message in this case - * NOTE should be conditional on OSX version, but - * -mmacosx-version-min does not revert this behaviour*/ + /* + * From OSX 10.11, the title string is silently ignored, if the save + * panel is a sheet. Prepend the title to the message in this case. + * NOTE: should be conditional on OSX version, but -mmacosx-version-min + * does not revert this behaviour. + */ + if (haveParentOption) { if (message) { - NSString *fullmessage = [[NSString alloc] initWithFormat:@"%@\n%@",title,message]; + NSString *fullmessage = + [[NSString alloc] initWithFormat:@"%@\n%@",title,message]; [message release]; [title release]; message = fullmessage; @@ -932,15 +1020,20 @@ Tk_GetSaveFileObjCmd( } if (filterInfo.doFileTypes) { - NSView *accessoryView = [[NSView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 300, 32.0)]; - NSTextField *label = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 60, 22)]; + NSView *accessoryView = [[NSView alloc] + initWithFrame:NSMakeRect(0.0, 0.0, 300, 32.0)]; + NSTextField *label = [[NSTextField alloc] + initWithFrame:NSMakeRect(0, 0, 60, 22)]; + [label setEditable:NO]; [label setStringValue:NSLocalizedString(@"Format:", nil)]; [label setBordered:NO]; [label setBezeled:NO]; [label setDrawsBackground:NO]; - NSPopUpButton *popupButton = [[NSPopUpButton alloc] initWithFrame:NSMakeRect(50.0, 2, 340, 22.0) pullsDown:NO]; + NSPopUpButton *popupButton = [[NSPopUpButton alloc] + initWithFrame:NSMakeRect(50.0, 2, 340, 22.0) pullsDown:NO]; + [popupButton addItemsWithTitles:filterInfo.fileTypeLabels]; [popupButton selectItemAtIndex:filterInfo.fileTypeIndex]; [popupButton setAction:@selector(saveFormat:)]; @@ -953,10 +1046,14 @@ Tk_GetSaveFileObjCmd( [savepanel setAllowedFileTypes:[filterInfo.fileTypeExtensions objectAtIndex:filterInfo.fileTypeIndex]]; [savepanel setAllowsOtherFileTypes:filterInfo.allowedExtensionsAllowAll]; } else if (defaultType) { - /* If no filetypes are given, defaultextension is an alternative way - * to specify the attached extension. Just propose this extension, - * but don't display an accessory view */ + /* + * If no filetypes are given, defaultextension is an alternative way to + * specify the attached extension. Just propose this extension, but + * don't display an accessory view. + */ + NSMutableArray *AllowedFileTypes = [NSMutableArray array]; + [AllowedFileTypes addObject:defaultType]; [savepanel setAllowedFileTypes:AllowedFileTypes]; [savepanel setAllowsOtherFileTypes:YES]; @@ -978,27 +1075,39 @@ Tk_GetSaveFileObjCmd( parent = TkMacOSXDrawableWindow(((TkWindow *) tkwin)->window); if (haveParentOption && parent && ![parent attachedSheet]) { - parentIsKey = [parent isKeyWindow]; - if (directory) { + parentIsKey = [parent isKeyWindow]; + if (directory) { [savepanel setDirectoryURL:[NSURL fileURLWithPath:directory isDirectory:YES]]; } - /*check for file name, otherwise set to empty string; crashes with uncaught exception if set to nil*/ + + /* + * Check for file name, otherwise set to empty string; crashes with + * uncaught exception if set to nil. + */ + if (filename) { [savepanel setNameFieldStringValue:filename]; } else { [savepanel setNameFieldStringValue:@""]; } [savepanel beginSheetModalForWindow:parent - completionHandler:^(NSInteger returnCode) - { [NSApp tkFilePanelDidEnd:savepanel + completionHandler:^(NSInteger returnCode) { + [NSApp tkFilePanelDidEnd:savepanel returnCode:returnCode - contextInfo:callbackInfo ]; } ]; - modalReturnCode = cmdObj ? modalOther : [NSApp runModalForWindow:savepanel]; + contextInfo:callbackInfo]; + }]; + modalReturnCode = cmdObj ? modalOther : + [NSApp runModalForWindow:savepanel]; } else { if (directory) { [savepanel setDirectoryURL:[NSURL fileURLWithPath:directory isDirectory:YES]]; } - /*check for file name, otherwise set to empty string; crashes with uncaught exception if set to nil*/ + + /* + * Check for file name, otherwise set to empty string; crashes with + * uncaught exception if set to nil. + */ + if (filename) { [savepanel setNameFieldStringValue:filename]; } else { @@ -1013,16 +1122,20 @@ Tk_GetSaveFileObjCmd( [parent makeKeyWindow]; } - if ((typeVariablePtr && (modalReturnCode == NSOKButton)) && filterInfo.doFileTypes) { + if (typeVariablePtr && (modalReturnCode == NSOKButton) + && filterInfo.doFileTypes) { /* - * The -typevariable must be set to the selected file type, if the dialog was not cancelled + * The -typevariable must be set to the selected file type, if the + * dialog was not cancelled. */ - NSString * selectedFilter = [filterInfo.fileTypeNames objectAtIndex:filterInfo.fileTypeIndex]; + + NSString *selectedFilter = + [filterInfo.fileTypeNames objectAtIndex:filterInfo.fileTypeIndex]; Tcl_ObjSetVar2(interp, typeVariablePtr, NULL, - Tcl_NewStringObj([selectedFilter UTF8String], -1), TCL_GLOBAL_ONLY); + Tcl_NewStringObj([selectedFilter UTF8String], -1), + TCL_GLOBAL_ONLY); } - end: return result; } @@ -1130,7 +1243,12 @@ Tk_ChooseDirectoryObjCmd( callbackInfo->cmdObj = cmdObj; callbackInfo->interp = interp; callbackInfo->multiple = 0; - /*check for directory value, set to root if not specified; otherwise crashes with exception because of nil string parameter*/ + + /* + * Check for directory value, set to root if not specified; otherwise + * crashes with exception because of nil string parameter. + */ + if (!directory) { directory = @"/"; } @@ -1139,10 +1257,11 @@ Tk_ChooseDirectoryObjCmd( parentIsKey = [parent isKeyWindow]; [panel setDirectoryURL:[NSURL fileURLWithPath:directory isDirectory:YES]]; [panel beginSheetModalForWindow:parent - completionHandler:^(NSInteger returnCode) - { [NSApp tkFilePanelDidEnd:panel - returnCode:returnCode - contextInfo:callbackInfo ]; } ]; + completionHandler:^(NSInteger returnCode) { + [NSApp tkFilePanelDidEnd:panel + returnCode:returnCode + contextInfo:callbackInfo]; + }]; modalReturnCode = cmdObj ? modalOther : [NSApp runModalForWindow:panel]; } else { [panel setDirectoryURL:[NSURL fileURLWithPath:directory isDirectory:YES]]; @@ -1201,11 +1320,12 @@ TkAboutDlg(void) */ NSString *version = @"Tcl " TCL_PATCH_LEVEL " & Tk " TCL_PATCH_LEVEL; - NSString *url = @"www.tcl-lang.org"; + NSString *url = @"www.tcl-lang.org"; NSTextView *credits = [[NSTextView alloc] initWithFrame:NSMakeRect(0,0,300,300)]; NSFont *font = [NSFont systemFontOfSize:[NSFont systemFontSize]]; NSDictionary *textAttributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName]; + [credits insertText: [[NSAttributedString alloc] initWithString:[NSString stringWithFormat: @"\n" "Tcl and Tk are distributed under a modified BSD license: " @@ -1219,11 +1339,13 @@ TkAboutDlg(void) "%1$C 1998-2000 Jim Ingham & Ray Johnson\n\n" "%1$C 1998-2000 Scriptics Inc.\n\n" "%1$C 1996-1997 Sun Microsystems Inc.", 0xA9, year] - attributes:textAttributes] - replacementRange:NSMakeRange(0,0)]; + attributes:textAttributes] + replacementRange:NSMakeRange(0,0)]; [credits setDrawsBackground:NO]; [credits setEditable:NO]; - NSAlert *about = [[NSAlert alloc] init]; + + NSAlert *about = [[NSAlert alloc] init]; + [[about window] setTitle:@"About Tcl & Tk"]; [about setMessageText: version]; [about setInformativeText:url]; @@ -1378,7 +1500,8 @@ Tk_MessageBoxObjCmd( */ if (Tcl_GetIndexFromObjStruct(interp, objv[indexDefaultOption + 1], - alertButtonStrings, sizeof(char *), "-default value", TCL_EXACT, &index) != TCL_OK) { + alertButtonStrings, sizeof(char *), "-default value", + TCL_EXACT, &index) != TCL_OK) { goto end; } @@ -1399,7 +1522,7 @@ Tk_MessageBoxObjCmd( [alert setAlertStyle:alertStyles[iconIndex]]; i = 0; while (i < 3 && alertButtonNames[typeIndex][i]) { - [alert addButtonWithTitle:(NSString*)alertButtonNames[typeIndex][i++]]; + [alert addButtonWithTitle:(NSString*) alertButtonNames[typeIndex][i++]]; } buttons = [alert buttons]; for (NSButton *b in buttons) { @@ -1428,10 +1551,11 @@ Tk_MessageBoxObjCmd( parentIsKey = [parent isKeyWindow]; #if MAC_OS_X_VERSION_MIN_REQUIRED > 1090 [alert beginSheetModalForWindow:parent - completionHandler:^(NSModalResponse returnCode) - { [NSApp tkAlertDidEnd:alert - returnCode:returnCode - contextInfo:callbackInfo ]; } ]; + completionHandler:^(NSModalResponse returnCode) { + [NSApp tkAlertDidEnd:alert + returnCode:returnCode + contextInfo:callbackInfo]; + }]; #else [alert beginSheetModalForWindow:parent modalDelegate:NSApp @@ -1471,7 +1595,10 @@ typedef struct FontchooserData { Tk_Window parent; } FontchooserData; -enum FontchooserEvent { FontchooserClosed, FontchooserSelection }; +enum FontchooserEvent { + FontchooserClosed, + FontchooserSelection +}; static void FontchooserEvent(int kind); static Tcl_Obj * FontchooserCget(FontchooserData *fcdPtr, @@ -1563,8 +1690,8 @@ enum FontchooserOption { * * FontchooserEvent -- * - * This processes events generated by user interaction with the - * font panel. + * This processes events generated by user interaction with the font + * panel. * * Results: * None. @@ -1623,9 +1750,8 @@ FontchooserEvent( * * FontchooserCget -- * - * Helper for the FontchooserConfigure command to return the - * current value of any of the options (which may be NULL in - * the structure) + * Helper for the FontchooserConfigure command to return the current value + * of any of the options (which may be NULL in the structure). * * Results: * Tcl object of option value. @@ -1688,8 +1814,8 @@ FontchooserCget( * * FontchooserConfigureCmd -- * - * Implementation of the 'tk fontchooser configure' ensemble command. - * See the user documentation for what it does. + * Implementation of the 'tk fontchooser configure' ensemble command. See + * the user documentation for what it does. * * Results: * See the user documentation. @@ -1822,7 +1948,8 @@ FontchooserConfigureCmd( [fm setSelectedAttributes:fontPanelFontAttributes isMultiple:NO]; if ([fp isVisible]) { - TkSendVirtualEvent(fcdPtr->parent, "TkFontchooserFontChanged", NULL); + TkSendVirtualEvent(fcdPtr->parent, + "TkFontchooserFontChanged", NULL); } break; case FontchooserCmd: @@ -1850,9 +1977,9 @@ FontchooserConfigureCmd( * * FontchooserShowCmd -- * - * Implements the 'tk fontchooser show' ensemble command. The - * per-interp configuration data for the dialog is held in an interp - * associated structure. + * Implements the 'tk fontchooser show' ensemble command. The per-interp + * configuration data for the dialog is held in an interp associated + * structure. * * Results: * See the user documentation. @@ -1878,8 +2005,10 @@ FontchooserShowCmd( Tk_CreateEventHandler(fcdPtr->parent, StructureNotifyMask, FontchooserParentEventHandler, fcdPtr); } + NSFontManager *fm = [NSFontManager sharedFontManager]; NSFontPanel *fp = [fm fontPanel:YES]; + if ([fp delegate] != NSApp) { [fp setDelegate:NSApp]; } @@ -1897,8 +2026,8 @@ FontchooserShowCmd( * * FontchooserHideCmd -- * - * Implementation of the 'tk fontchooser hide' ensemble. See the - * user documentation for details. + * Implementation of the 'tk fontchooser hide' ensemble. See the user + * documentation for details. * * Results: * See the user documentation. @@ -1917,6 +2046,7 @@ FontchooserHideCmd( Tcl_Obj *const objv[]) { NSFontPanel *fp = [[NSFontManager sharedFontManager] fontPanel:NO]; + if ([fp isVisible]) { [fp orderOut:NSApp]; } @@ -1997,8 +2127,8 @@ DeleteFontchooserData( * * TkInitFontchooser -- * - * Associate the font chooser configuration data with the Tcl - * interpreter. There is one font chooser per interp. + * Associate the font chooser configuration data with the Tcl interpreter. + * There is one font chooser per interp. * * Results: * None. diff --git a/macosx/tkMacOSXDraw.c b/macosx/tkMacOSXDraw.c index faad137..dceb3a6 100644 --- a/macosx/tkMacOSXDraw.c +++ b/macosx/tkMacOSXDraw.c @@ -1,9 +1,8 @@ /* * tkMacOSXDraw.c -- * - * This file contains functions that perform drawing to - * Xlib windows. Most of the functions simple emulate - * Xlib functions. + * This file contains functions that perform drawing to Xlib windows. Most + * of the functions simple emulate Xlib functions. * * Copyright (c) 1995-1997 Sun Microsystems, Inc. * Copyright 2001-2009, Apple Inc. @@ -31,7 +30,7 @@ #endif */ -#define radians(d) ((d) * (M_PI/180.0)) +#define radians(d) ((d) * (M_PI/180.0)) /* * Non-antialiased CG drawing looks better and more like X11 drawing when using @@ -40,7 +39,7 @@ #define NON_AA_CG_OFFSET .999 static int cgAntiAliasLimit = 0; -#define notAA(w) ((w) < cgAntiAliasLimit) +#define notAA(w) ((w) < cgAntiAliasLimit) static int useThemedToplevel = 0; static int useThemedFrame = 0; @@ -119,24 +118,24 @@ TkMacOSXInitCGDrawing( * replacement is [NSView cacheDisplayInRect: toBitmapImageRep:] and that * is what is being used here. However, that method only works when the * view has a valid CGContext, and a view is only guaranteed to have a - * valid context during a call to [NSView drawRect]. To further - * complicate matters, cacheDisplayInRect calls [NSView drawRect]. - * Essentially it is asking the view to draw a subrectangle of itself into - * a special graphics context which is linked to the BitmapImageRep. But - * our implementation of [NSView drawRect] does not allow recursive calls. - * If called recursively it returns immediately without doing any drawing. + * valid context during a call to [NSView drawRect]. To further complicate + * matters, cacheDisplayInRect calls [NSView drawRect]. Essentially it is + * asking the view to draw a subrectangle of itself into a special + * graphics context which is linked to the BitmapImageRep. But our + * implementation of [NSView drawRect] does not allow recursive calls. If + * called recursively it returns immediately without doing any drawing. * So the bottom line is that this function either returns a NULL pointer - * or a black image. To make it useful would require a significant amount - * of rewriting of the drawRect method. Perhaps the next release of OSX + * or a black image. To make it useful would require a significant amount + * of rewriting of the drawRect method. Perhaps the next release of OSX * will include some more helpful ways of doing this. * * Results: - * Returns an NSBitmapRep representing the image of the given - * rectangle of the given drawable. This object is retained. - * The caller is responsible for releasing it. + * Returns an NSBitmapRep representing the image of the given rectangle of + * the given drawable. This object is retained. The caller is responsible + * for releasing it. * - * NOTE: The x,y coordinates should be relative to a coordinate system with - * origin at the top left, as used by XImage and CGImage, not bottom + * NOTE: The x,y coordinates should be relative to a coordinate system + * with origin at the top left, as used by XImage and CGImage, not bottom * left as used by NSView. * * Side effects: @@ -144,46 +143,46 @@ TkMacOSXInitCGDrawing( * *---------------------------------------------------------------------- */ -NSBitmapImageRep* + +NSBitmapImageRep * TkMacOSXBitmapRepFromDrawableRect( - Drawable drawable, - int x, - int y, - unsigned int width, - unsigned int height) + Drawable drawable, + int x, + int y, + unsigned int width, + unsigned int height) { MacDrawable *mac_drawable = (MacDrawable *) drawable; CGContextRef cg_context = NULL; - CGImageRef cg_image=NULL, sub_cg_image = NULL; + CGImageRef cg_image = NULL, sub_cg_image = NULL; NSBitmapImageRep *bitmap_rep = NULL; - NSView *view=NULL; - if ( mac_drawable->flags & TK_IS_PIXMAP ) { - + NSView *view = NULL; + if (mac_drawable->flags & TK_IS_PIXMAP) { /* * This MacDrawable is a bitmap, so its view is NULL. */ - cg_context = TkMacOSXGetCGContextForDrawable(drawable); CGRect image_rect = CGRectMake(x, y, width, height); - cg_image = CGBitmapContextCreateImage( (CGContextRef) cg_context); + + cg_context = TkMacOSXGetCGContextForDrawable(drawable); + cg_image = CGBitmapContextCreateImage((CGContextRef) cg_context); sub_cg_image = CGImageCreateWithImageInRect(cg_image, image_rect); - if ( sub_cg_image ) { + if (sub_cg_image) { bitmap_rep = [NSBitmapImageRep alloc]; [bitmap_rep initWithCGImage:sub_cg_image]; } - if ( cg_image ) { + if (cg_image) { CGImageRelease(cg_image); } - } else if ( (view = TkMacOSXDrawableView(mac_drawable)) ) { - + } else if ((view = TkMacOSXDrawableView(mac_drawable)) != NULL) { /* * Convert Tk top-left to NSView bottom-left coordinates. */ int view_height = [view bounds].size.height; NSRect view_rect = NSMakeRect(x + mac_drawable->xOff, - view_height - height - y - mac_drawable->yOff, - width, height); + view_height - height - y - mac_drawable->yOff, + width, height); /* * Attempt to copy from the view to a bitmapImageRep. If the view does @@ -218,8 +217,7 @@ TkMacOSXBitmapRepFromDrawableRect( * None. * * Side effects: - * Data is moved from a window or bitmap to a second window or - * bitmap. + * Data is moved from a window or bitmap to a second window or bitmap. * *---------------------------------------------------------------------- */ @@ -229,10 +227,10 @@ XCopyArea( Display *display, /* Display. */ Drawable src, /* Source drawable. */ Drawable dst, /* Destination drawable. */ - GC gc, /* GC to use. */ + GC gc, /* GC to use. */ int src_x, /* X & Y, width & height */ int src_y, /* define the source rectangle */ - unsigned int width, /* that will be copied. */ + unsigned int width, /* that will be copied. */ unsigned int height, int dest_x, /* Dest X & Y on dest rect. */ int dest_y) @@ -249,37 +247,36 @@ XCopyArea( } if (!TkMacOSXSetupDrawingContext(dst, gc, 1, &dc)) { - return; TkMacOSXDbgMsg("Failed to setup drawing context."); + return; } - if ( dc.context ) { - if (srcDraw->flags & TK_IS_PIXMAP) { - img = TkMacOSXCreateCGImageWithDrawable(src); - }else if (TkMacOSXDrawableWindow(src)) { - bitmap_rep = TkMacOSXBitmapRepFromDrawableRect(src, - src_x, src_y, width, height); - if ( bitmap_rep ) { - img = [bitmap_rep CGImage]; - } - } else { - TkMacOSXDbgMsg("Invalid source drawable - neither window nor pixmap."); - } + if (!dc.context) { + TkMacOSXDbgMsg("Invalid destination drawable - no context."); + return; + } - if (img) { - bounds = CGRectMake(0, 0, srcDraw->size.width, srcDraw->size.height); - srcRect = CGRectMake(src_x, src_y, width, height); - dstRect = CGRectMake(dest_x, dest_y, width, height); - TkMacOSXDrawCGImage(dst, gc, dc.context, img, - gc->foreground, gc->background, bounds, srcRect, dstRect); - CFRelease(img); - } else { - TkMacOSXDbgMsg("Failed to construct CGImage."); + if (srcDraw->flags & TK_IS_PIXMAP) { + img = TkMacOSXCreateCGImageWithDrawable(src); + } else if (TkMacOSXDrawableWindow(src)) { + bitmap_rep = TkMacOSXBitmapRepFromDrawableRect(src, + src_x, src_y, width, height); + if (bitmap_rep) { + img = [bitmap_rep CGImage]; } + } else { + TkMacOSXDbgMsg("Invalid source drawable - neither window nor pixmap."); + } + if (img) { + bounds = CGRectMake(0, 0, srcDraw->size.width, srcDraw->size.height); + srcRect = CGRectMake(src_x, src_y, width, height); + dstRect = CGRectMake(dest_x, dest_y, width, height); + TkMacOSXDrawCGImage(dst, gc, dc.context, img, + gc->foreground, gc->background, bounds, srcRect, dstRect); + CFRelease(img); } else { - TkMacOSXDbgMsg("Invalid destination drawable - no context."); - return; + TkMacOSXDbgMsg("Failed to construct CGImage."); } TkMacOSXRestoreDrawingContext(&dc); @@ -290,10 +287,9 @@ XCopyArea( * * XCopyPlane -- * - * Copies a bitmap from a source drawable to a destination - * drawable. The plane argument specifies which bit plane of - * the source contains the bitmap. Note that this implementation - * ignores the gc->function. + * Copies a bitmap from a source drawable to a destination drawable. The + * plane argument specifies which bit plane of the source contains the + * bitmap. Note that this implementation ignores the gc->function. * * Results: * None. @@ -334,29 +330,50 @@ XCopyPlane( if (!TkMacOSXSetupDrawingContext(dst, gc, 1, &dc)) { return; } + CGContextRef context = dc.context; + if (context) { CGImageRef img = TkMacOSXCreateCGImageWithDrawable(src); + if (img) { TkpClipMask *clipPtr = (TkpClipMask *) gc->clip_mask; unsigned long imageBackground = gc->background; - if (clipPtr && clipPtr->type == TKP_CLIP_PIXMAP){ + + if (clipPtr && clipPtr->type == TKP_CLIP_PIXMAP) { srcRect = CGRectMake(src_x, src_y, width, height); - CGImageRef mask = TkMacOSXCreateCGImageWithDrawable(clipPtr->value.pixmap); - CGImageRef submask = CGImageCreateWithImageInRect(img, srcRect); + CGImageRef mask = TkMacOSXCreateCGImageWithDrawable( + clipPtr->value.pixmap); + CGImageRef submask = CGImageCreateWithImageInRect( + img, srcRect); CGRect rect = CGRectMake(dest_x, dest_y, width, height); + rect = CGRectOffset(rect, dstDraw->xOff, dstDraw->yOff); CGContextSaveGState(context); - /* Move the origin of the destination to top left. */ - CGContextTranslateCTM(context, 0, rect.origin.y + CGRectGetMaxY(rect)); + + /* + * Move the origin of the destination to top left. + */ + + CGContextTranslateCTM(context, + 0, rect.origin.y + CGRectGetMaxY(rect)); CGContextScaleCTM(context, 1, -1); - /* Fill with the background color, clipping to the mask. */ + + /* + * Fill with the background color, clipping to the mask. + */ + CGContextClipToMask(context, rect, submask); TkMacOSXSetColorInContext(gc, gc->background, dc.context); CGContextFillRect(context, rect); - /* Fill with the foreground color, clipping to the - intersection of img and mask. */ - CGImageRef subimage = CGImageCreateWithImageInRect(img, srcRect); + + /* + * Fill with the foreground color, clipping to the + * intersection of img and mask. + */ + + CGImageRef subimage = CGImageCreateWithImageInRect( + img, srcRect); CGContextClipToMask(context, rect, subimage); TkMacOSXSetColorInContext(gc, gc->foreground, context); CGContextFillRect(context, rect); @@ -366,22 +383,31 @@ XCopyPlane( CGImageRelease(submask); CGImageRelease(subimage); } else { - bounds = CGRectMake(0, 0, srcDraw->size.width, srcDraw->size.height); + bounds = CGRectMake(0, 0, + srcDraw->size.width, srcDraw->size.height); srcRect = CGRectMake(src_x, src_y, width, height); dstRect = CGRectMake(dest_x, dest_y, width, height); - TkMacOSXDrawCGImage(dst, gc, dc.context, img, gc->foreground, - imageBackground, bounds, srcRect, dstRect); + TkMacOSXDrawCGImage(dst, gc, dc.context, img, + gc->foreground, imageBackground, bounds, + srcRect, dstRect); CGImageRelease(img); } - } else { /* no image */ + } else { + /* no image */ TkMacOSXDbgMsg("Invalid source drawable"); } } else { - TkMacOSXDbgMsg("Invalid destination drawable - could not get a bitmap context."); + TkMacOSXDbgMsg("Invalid destination drawable - " + "could not get a bitmap context."); } TkMacOSXRestoreDrawingContext(&dc); - } else { /* source drawable is a window, not a Pixmap */ - XCopyArea(display, src, dst, gc, src_x, src_y, width, height, dest_x, dest_y); + } else { + /* + * Source drawable is a Window, not a Pixmap. + */ + + XCopyArea(display, src, dst, gc, src_x, src_y, width, height, + dest_x, dest_y); } } @@ -430,7 +456,7 @@ TkMacOSXCreateCGImageWithDrawable( *---------------------------------------------------------------------- */ -static NSImage* +static NSImage * CreateNSImageWithPixmap( Pixmap pixmap, int width, @@ -466,7 +492,7 @@ CreateNSImageWithPixmap( *---------------------------------------------------------------------- */ -NSImage* +NSImage * TkMacOSXGetNSImageWithTkImage( Display *display, Tk_Image image, @@ -499,7 +525,7 @@ TkMacOSXGetNSImageWithTkImage( *---------------------------------------------------------------------- */ -NSImage* +NSImage * TkMacOSXGetNSImageWithBitmap( Display *display, Pixmap bitmap, @@ -550,23 +576,24 @@ TkMacOSXGetCGContextForDrawable( CGColorSpaceRef colorspace = NULL; CGBitmapInfo bitmapInfo = #ifdef __LITTLE_ENDIAN__ - kCGBitmapByteOrder32Host; + kCGBitmapByteOrder32Host; #else - kCGBitmapByteOrderDefault; + kCGBitmapByteOrderDefault; #endif char *data; - CGRect bounds = CGRectMake(0, 0, macDraw->size.width, macDraw->size.height); + CGRect bounds = CGRectMake(0, 0, + macDraw->size.width, macDraw->size.height); if (macDraw->flags & TK_IS_BW_PIXMAP) { bitsPerPixel = 8; - bitmapInfo = (CGBitmapInfo)kCGImageAlphaOnly; + bitmapInfo = (CGBitmapInfo) kCGImageAlphaOnly; } else { colorspace = CGColorSpaceCreateDeviceRGB(); bitsPerPixel = 32; bitmapInfo |= kCGImageAlphaPremultipliedFirst; } - bytesPerRow = ((size_t) macDraw->size.width * bitsPerPixel + 127) >> 3 - & ~15; + bytesPerRow = ((size_t) + macDraw->size.width * bitsPerPixel + 127) >> 3 & ~15; len = macDraw->size.height * bytesPerRow; data = ckalloc(len); bzero(data, len); @@ -630,8 +657,8 @@ TkMacOSXDrawCGImage( dstBounds = CGRectOffset(dstBounds, macDraw->xOff, macDraw->yOff); if (CGImageIsMask(image)) { if (macDraw->flags & TK_IS_BW_PIXMAP) { - - /* Set fill color to black; background comes from the context, + /* + * Set fill color to black; background comes from the context, * or is transparent. */ @@ -655,11 +682,13 @@ TkMacOSXDrawCGImage( CGContextSetRGBFillColor(context, 0, 1, 0, 0.1); CGContextFillRect(context, dstBounds); CGContextStrokeRect(context, dstBounds); + CGPoint p[4] = {dstBounds.origin, CGPointMake(CGRectGetMaxX(dstBounds), CGRectGetMaxY(dstBounds)), CGPointMake(CGRectGetMinX(dstBounds), CGRectGetMaxY(dstBounds)), CGPointMake(CGRectGetMaxX(dstBounds), CGRectGetMinY(dstBounds)) }; + CGContextStrokeLineSegments(context, p, 4); CGContextRestoreGState(context); TkMacOSXDbgMsg("Drawing CGImage at (x=%f, y=%f), (w=%f, h=%f)", @@ -736,12 +765,13 @@ XDrawLines( CGContextAddLineToPoint(dc.context, prevx, prevy); } } + /* - * In the case of closed polylines, the first and last points - * are the same. We want miter or bevel join be rendered also - * at this point, this needs telling CoreGraphics that the - * path is closed. + * In the case of closed polylines, the first and last points are the + * same. We want miter or bevel join be rendered also at this point, + * this needs telling CoreGraphics that the path is closed. */ + if ((points[0].x == points[npoints-1].x) && (points[0].y == points[npoints-1].y)) { CGContextClosePath(dc.context); @@ -820,10 +850,10 @@ XDrawSegments( void XFillPolygon( - Display* display, /* Display. */ + Display *display, /* Display. */ Drawable d, /* Draw on this. */ GC gc, /* Use this GC. */ - XPoint* points, /* Array of points. */ + XPoint *points, /* Array of points. */ int npoints, /* Number of points. */ int shape, /* Shape to draw. */ int mode) /* Drawing mode. */ @@ -902,8 +932,7 @@ XDrawRectangle( double o = (lw % 2) ? .5 : 0; rect = CGRectMake( - macWin->xOff + x + o, - macWin->yOff + y + o, + macWin->xOff + x + o, macWin->yOff + y + o, width, height); CGContextStrokeRect(dc.context, rect); } @@ -916,17 +945,15 @@ XDrawRectangle( * * XDrawRectangles -- * - * Draws the outlines of the specified rectangles as if a - * five-point PolyLine protocol request were specified for each - * rectangle: + * Draws the outlines of the specified rectangles as if a five-point + * PolyLine protocol request were specified for each rectangle: * * [x,y] [x+width,y] [x+width,y+height] [x,y+height] [x,y] * - * For the specified rectangles, these functions do not draw a - * pixel more than once. XDrawRectangles draws the rectangles in - * the order listed in the array. If rectangles intersect, the - * intersecting pixels are drawn multiple times. Draws a - * rectangle. + * For the specified rectangles, these functions do not draw a pixel more + * than once. XDrawRectangles draws the rectangles in the order listed in + * the array. If rectangles intersect, the intersecting pixels are drawn + * multiple times. Draws a rectangle. * * Results: * None. @@ -991,7 +1018,7 @@ XDrawRectangles( int XFillRectangles( - Display* display, /* Display. */ + Display *display, /* Display. */ Drawable d, /* Draw on this. */ GC gc, /* Use this GC. */ XRectangle *rectangles, /* Rectangle array. */ @@ -1042,7 +1069,7 @@ XFillRectangles( void XDrawArc( - Display* display, /* Display. */ + Display *display, /* Display. */ Drawable d, /* Draw on this. */ GC gc, /* Use this GC. */ int x, int y, /* Upper left of bounding rect. */ @@ -1099,14 +1126,13 @@ XDrawArc( * * XDrawArcs -- * - * Draws multiple circular or elliptical arcs. Each arc is - * specified by a rectangle and two angles. The center of the - * circle or ellipse is the center of the rect- angle, and the - * major and minor axes are specified by the width and height. - * Positive angles indicate counterclock- wise motion, and - * negative angles indicate clockwise motion. If the magnitude - * of angle2 is greater than 360 degrees, XDrawArcs truncates it - * to 360 degrees. + * Draws multiple circular or elliptical arcs. Each arc is specified by a + * rectangle and two angles. The center of the circle or ellipse is the + * center of the rect- angle, and the major and minor axes are specified + * by the width and height. Positive angles indicate counterclock- wise + * motion, and negative angles indicate clockwise motion. If the magnitude + * of angle2 is greater than 360 degrees, XDrawArcs truncates it to 360 + * degrees. * * Results: * None. @@ -1125,7 +1151,6 @@ XDrawArcs( XArc *arcArr, int nArcs) { - MacDrawable *macWin = (MacDrawable *) d; TkMacOSXDrawingContext dc; XArc *arcPtr; @@ -1195,7 +1220,7 @@ XDrawArcs( void XFillArc( - Display* display, /* Display. */ + Display *display, /* Display. */ Drawable d, /* Draw on this. */ GC gc, /* Use this GC. */ int x, int y, /* Upper left of bounding rect. */ @@ -1360,13 +1385,12 @@ XMaxRequestSize( * * TkScrollWindow -- * - * Scroll a rectangle of the specified window and accumulate - * a damage region. + * Scroll a rectangle of the specified window and accumulate a damage + * region. * * Results: - * Returns 0 if the scroll generated no additional damage. - * Otherwise, sets the region that needs to be repainted after - * scrolling and returns 1. + * Returns 0 if the scroll generated no additional damage. Otherwise, sets + * the region that needs to be repainted after scrolling and returns 1. * * Side effects: * Scrolls the bits in the window. @@ -1385,47 +1409,63 @@ TkScrollWindow( { Drawable drawable = Tk_WindowId(tkwin); MacDrawable *macDraw = (MacDrawable *) drawable; - TKContentView *view = (TKContentView *)TkMacOSXDrawableView(macDraw); + TKContentView *view = (TKContentView *) TkMacOSXDrawableView(macDraw); CGRect srcRect, dstRect; HIShapeRef dmgRgn = NULL, extraRgn = NULL; NSRect bounds, visRect, scrollSrc, scrollDst; int result = 0; - if ( view ) { - /* Get the scroll area in NSView coordinates (origin at bottom left). */ + if (view) { + /* + * Get the scroll area in NSView coordinates (origin at bottom left). + */ + bounds = [view bounds]; scrollSrc = NSMakeRect(macDraw->xOff + x, - bounds.size.height - height - (macDraw->yOff + y), - width, height); + bounds.size.height - height - (macDraw->yOff + y), + width, height); scrollDst = NSOffsetRect(scrollSrc, dx, -dy); - /* Limit scrolling to the window content area. */ + /* + * Limit scrolling to the window content area. + */ + visRect = [view visibleRect]; scrollSrc = NSIntersectionRect(scrollSrc, visRect); scrollDst = NSIntersectionRect(scrollDst, visRect); - if ( !NSIsEmptyRect(scrollSrc) && !NSIsEmptyRect(scrollDst) ) { + if (!NSIsEmptyRect(scrollSrc) && !NSIsEmptyRect(scrollDst)) { /* * Mark the difference between source and destination as damaged. - * This region is described in NSView coordinates (y=0 at the bottom) - * and converted to Tk coordinates later. + * This region is described in NSView coordinates (y=0 at the + * bottom) and converted to Tk coordinates later. */ srcRect = CGRectMake(x, y, width, height); dstRect = CGRectOffset(srcRect, dx, dy); - /* Compute the damage. */ + /* + * Compute the damage. + */ + dmgRgn = HIShapeCreateMutableWithRect(&srcRect); extraRgn = HIShapeCreateWithRect(&dstRect); - ChkErr(HIShapeDifference, dmgRgn, extraRgn, (HIMutableShapeRef) dmgRgn); + ChkErr(HIShapeDifference, dmgRgn, extraRgn, + (HIMutableShapeRef) dmgRgn); result = HIShapeIsEmpty(dmgRgn) ? 0 : 1; - /* Convert to Tk coordinates, offset by the window origin. */ + /* + * Convert to Tk coordinates, offset by the window origin. + */ + TkMacOSXSetWithNativeRegion(damageRgn, dmgRgn); if (extraRgn) { CFRelease(extraRgn); } - /* Scroll the rectangle. */ + /* + * Scroll the rectangle. + */ + [view scrollRect:scrollSrc by:NSMakeSize(dx, -dy)]; } } else { @@ -1472,8 +1512,8 @@ TkMacOSXSetUpGraphicsPort( * Set up a drawing context for the given drawable and GC. * * Results: - * Boolean indicating whether it is ok to draw; if false, drawing - * context was not setup, so do not attempt to draw and do not call + * Boolean indicating whether it is ok to draw; if false, drawing context + * was not setup, so do not attempt to draw and do not call * TkMacOSXRestoreDrawingContext(). * * Side effects: @@ -1486,18 +1526,18 @@ Bool TkMacOSXSetupDrawingContext( Drawable d, GC gc, - int useCG, /* advisory only ! */ + int useCG, /* advisory only ! */ TkMacOSXDrawingContext *dcPtr) { - MacDrawable *macDraw = ((MacDrawable*)d); + MacDrawable *macDraw = (MacDrawable *) d; Bool canDraw = true; NSWindow *win = NULL; TkMacOSXDrawingContext dc = {}; CGRect clipBounds; /* - * If the drawable is not a pixmap and it has an associated - * NSWindow then we know we are drawing to a window. + * If the drawable is not a pixmap and it has an associated NSWindow then + * we know we are drawing to a window. */ if (!(macDraw->flags & TK_IS_PIXMAP)) { @@ -1516,9 +1556,8 @@ TkMacOSXSetupDrawingContext( } /* - * If we already have a CGContext, use it. Otherwise, if we - * are drawing to a window then we can get one from the - * window. + * If we already have a CGContext, use it. Otherwise, if we are drawing to + * a window then we can get one from the window. */ dc.context = TkMacOSXGetCGContextForDrawable(d); @@ -1526,35 +1565,34 @@ TkMacOSXSetupDrawingContext( dc.portBounds = clipBounds = CGContextGetClipBoundingBox(dc.context); } else if (win) { NSView *view = TkMacOSXDrawableView(macDraw); - if (view) { - - /* - * We can only draw into the view when the current CGContext is - * valid and belongs to the view. Validity can only be guaranteed - * inside of a view's drawRect or setFrame methods. The isDrawing - * attribute tells us whether we are being called from one of those - * methods. - * - * If the CGContext is not valid, or belongs to a different View, - * then we mark our view as needing display and return failure. - * It should get drawn in a later call to drawRect. - */ - if (view != [NSView focusView]) { - [view setNeedsDisplay:YES]; - canDraw = false; - goto end; - } - dc.view = view; - dc.context = GET_CGCONTEXT; - dc.portBounds = NSRectToCGRect([view bounds]); - if (dc.clipRgn) { - clipBounds = CGContextGetClipBoundingBox(dc.context); - } - } else { + if (!view) { Tcl_Panic("TkMacOSXSetupDrawingContext(): " "no NSView to draw into !"); } + + /* + * We can only draw into the view when the current CGContext is valid + * and belongs to the view. Validity can only be guaranteed inside of + * a view's drawRect or setFrame methods. The isDrawing attribute + * tells us whether we are being called from one of those methods. + * + * If the CGContext is not valid, or belongs to a different View, then + * we mark our view as needing display and return failure. It should + * get drawn in a later call to drawRect. + */ + + if (view != [NSView focusView]) { + [view setNeedsDisplay:YES]; + canDraw = false; + goto end; + } + dc.view = view; + dc.context = GET_CGCONTEXT; + dc.portBounds = NSRectToCGRect([view bounds]); + if (dc.clipRgn) { + clipBounds = CGContextGetClipBoundingBox(dc.context); + } } else { Tcl_Panic("TkMacOSXSetupDrawingContext(): " "no context to draw into !"); @@ -1565,8 +1603,13 @@ TkMacOSXSetupDrawingContext( */ if (dc.context) { - CGAffineTransform t = { .a = 1, .b = 0, .c = 0, .d = -1, .tx = 0, - .ty = dc.portBounds.size.height}; + CGAffineTransform t = { + .a = 1, .b = 0, + .c = 0, .d = -1, + .tx = 0, + .ty = dc.portBounds.size.height + }; + dc.portBounds.origin.x += macDraw->xOff; dc.portBounds.origin.y += macDraw->yOff; CGContextSaveGState(dc.context); @@ -1581,6 +1624,7 @@ TkMacOSXSetupDrawingContext( CGContextRestoreGState(dc.context); #endif /* TK_MAC_DEBUG_DRAWING */ CGRect r; + if (!HIShapeIsRectangular(dc.clipRgn) || !CGRectContainsRect( *HIShapeGetBounds(dc.clipRgn, &r), CGRectApplyAffineTransform(clipBounds, t))) { @@ -1608,21 +1652,28 @@ TkMacOSXSetupDrawingContext( CGContextSetPatternPhase(dc.context, CGSizeMake( dc.portBounds.size.width, dc.portBounds.size.height)); } - if(gc->function != GXcopy) { + if (gc->function != GXcopy) { TkMacOSXDbgMsg("Logical functions other than GXcopy are " "not supported for CG drawing!"); } - /* When should we antialias? */ + + /* + * When should we antialias? + */ + shouldAntialias = !notAA(gc->line_width); if (!shouldAntialias) { - /* Make non-antialiased CG drawing look more like X11 */ + /* + * Make non-antialiased CG drawing look more like X11. + */ + w -= (gc->line_width ? NON_AA_CG_OFFSET : 0); } CGContextSetShouldAntialias(dc.context, shouldAntialias); CGContextSetLineWidth(dc.context, w); if (gc->line_style != LineSolid) { int num = 0; - char *p = &(gc->dashes); + char *p = &gc->dashes; CGFloat dashOffset = gc->dash_offset; CGFloat lengths[10]; @@ -1632,13 +1683,13 @@ TkMacOSXSetupDrawingContext( } CGContextSetLineDash(dc.context, dashOffset, lengths, num); } - if ((unsigned)gc->cap_style < sizeof(cgCap)/sizeof(CGLineCap)) { + if ((unsigned) gc->cap_style < sizeof(cgCap)/sizeof(CGLineCap)) { CGContextSetLineCap(dc.context, - cgCap[(unsigned)gc->cap_style]); + cgCap[(unsigned) gc->cap_style]); } if ((unsigned)gc->join_style < sizeof(cgJoin)/sizeof(CGLineJoin)) { CGContextSetLineJoin(dc.context, - cgJoin[(unsigned)gc->join_style]); + cgJoin[(unsigned) gc->join_style]); } } } @@ -1647,8 +1698,11 @@ end: #ifdef TK_MAC_DEBUG_DRAWING if (!canDraw && win != NULL) { TkWindow *winPtr = TkMacOSXGetTkWindow(win); - if (winPtr) fprintf(stderr, "Cannot draw in %s - postponing.\n", - Tk_PathName(winPtr)); + + if (winPtr) { + fprintf(stderr, "Cannot draw in %s - postponing.\n", + Tk_PathName(winPtr)); + } } #endif if (!canDraw && dc.clipRgn) { @@ -1719,7 +1773,9 @@ TkMacOSXGetClipRgn( TkMacOSXUpdateClipRgn(macDraw->winPtr); #ifdef TK_MAC_DEBUG_DRAWING TkMacOSXDbgMsg("%s", macDraw->winPtr->pathName); + NSView *view = TkMacOSXDrawableView(macDraw); + CGContextSaveGState(context); CGContextConcatCTM(context, CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, [view bounds].size.height)); @@ -1743,8 +1799,8 @@ TkMacOSXGetClipRgn( * * TkMacOSXSetUpClippingRgn -- * - * Set up the clipping region so that drawing only occurs on the - * specified X subwindow. + * Set up the clipping region so that drawing only occurs on the specified + * X subwindow. * * Results: * None. @@ -1766,8 +1822,8 @@ TkMacOSXSetUpClippingRgn( * * TkpClipDrawableToRect -- * - * Clip all drawing into the drawable d to the given rectangle. - * If width or height are negative, reset to no clipping. + * Clip all drawing into the drawable d to the given rectangle. If width + * or height are negative, reset to no clipping. * * Results: * None. @@ -1832,8 +1888,8 @@ ClipToGC( HIShapeRef *clipRgnPtr) /* must point to initialized variable */ { if (gc && gc->clip_mask && - ((TkpClipMask*)gc->clip_mask)->type == TKP_CLIP_REGION) { - TkRegion gcClip = ((TkpClipMask*)gc->clip_mask)->value.region; + ((TkpClipMask *) gc->clip_mask)->type == TKP_CLIP_REGION) { + TkRegion gcClip = ((TkpClipMask *) gc->clip_mask)->value.region; int xOffset = ((MacDrawable *) d)->xOff + gc->clip_x_origin; int yOffset = ((MacDrawable *) d)->yOff + gc->clip_y_origin; HIShapeRef clipRgn = *clipRgnPtr, gcClipRgn; @@ -1856,10 +1912,9 @@ ClipToGC( * * TkMacOSXMakeStippleMap -- * - * Given a drawable and a stipple pattern this function draws the - * pattern repeatedly over the drawable. The drawable can then - * be used as a mask for bit-bliting a stipple pattern over an - * object. + * Given a drawable and a stipple pattern this function draws the pattern + * repeatedly over the drawable. The drawable can then be used as a mask + * for bit-bliting a stipple pattern over an object. * * Results: * A BitMap data structure. @@ -1883,12 +1938,12 @@ TkMacOSXMakeStippleMap( * * TkpDrawHighlightBorder -- * - * This procedure draws a rectangular ring around the outside of - * a widget to indicate that it has received the input focus. + * This procedure draws a rectangular ring around the outside of a widget + * to indicate that it has received the input focus. * - * On the Macintosh, this puts a 1 pixel border in the bgGC color - * between the widget and the focus ring, except in the case where - * highlightWidth is 1, in which case the border is left out. + * On the Macintosh, this puts a 1 pixel border in the bgGC color between + * the widget and the focus ring, except in the case where highlightWidth + * is 1, in which case the border is left out. * * For proper Mac L&F, use highlightWidth of 3. * @@ -1896,8 +1951,8 @@ TkMacOSXMakeStippleMap( * None. * * Side effects: - * A rectangle "width" pixels wide is drawn in "drawable", - * corresponding to the outer area of "tkwin". + * A rectangle "width" pixels wide is drawn in "drawable", corresponding + * to the outer area of "tkwin". * *---------------------------------------------------------------------- */ @@ -1926,8 +1981,8 @@ TkpDrawHighlightBorder ( * * TkpDrawFrame -- * - * This procedure draws the rectangular frame area. If the user - * has requested themeing, it draws with the background theme. + * This procedure draws the rectangular frame area. If the user has + * requested themeing, it draws with the background theme. * * Results: * None. diff --git a/macosx/tkMacOSXEmbed.c b/macosx/tkMacOSXEmbed.c index 932d4cb..79a2094 100644 --- a/macosx/tkMacOSXEmbed.c +++ b/macosx/tkMacOSXEmbed.c @@ -334,15 +334,15 @@ TkpUseWindow( macWin->flags |= TK_EMBEDDED; macWin->xOff = parent->winPtr->privatePtr->xOff + - parent->winPtr->changes.border_width + - winPtr->changes.x; + parent->winPtr->changes.border_width + + winPtr->changes.x; macWin->yOff = parent->winPtr->privatePtr->yOff + - parent->winPtr->changes.border_width + - winPtr->changes.y; + parent->winPtr->changes.border_width + + winPtr->changes.y; /* - * Finish filling up the container structure with the embedded - * window's information. + * Finish filling up the container structure with the embedded window's + * information. */ containerPtr->embedded = (Window) macWin; @@ -353,8 +353,8 @@ TkpUseWindow( * tkwin is eventually deleted. */ - Tk_CreateEventHandler(tkwin, StructureNotifyMask, EmbeddedEventProc, - winPtr); + Tk_CreateEventHandler(tkwin, StructureNotifyMask, + EmbeddedEventProc, winPtr); return TCL_OK; } @@ -588,7 +588,11 @@ TkpTestembedCmd( continue; } Tcl_DStringStartSublist(&dString); - /* Parent id */ + + /* + * Parent id + */ + if (containerPtr->parent == None) { Tcl_DStringAppendElement(&dString, ""); } else if (all) { @@ -597,7 +601,11 @@ TkpTestembedCmd( } else { Tcl_DStringAppendElement(&dString, "XXX"); } - /* Parent pathName */ + + /* + * Parent pathName + */ + if (containerPtr->parentPtr == NULL || parentInterp != interp) { Tcl_DStringAppendElement(&dString, ""); @@ -605,11 +613,17 @@ TkpTestembedCmd( Tcl_DStringAppendElement(&dString, containerPtr->parentPtr->pathName); } + /* * On X11 embedded is a wrapper, which does not exist on macOS. */ + Tcl_DStringAppendElement(&dString, ""); - /* Embedded window pathName */ + + /* + * Embedded window pathName + */ + if (containerPtr->embeddedPtr == NULL || embeddedInterp != interp) { Tcl_DStringAppendElement(&dString, ""); @@ -768,6 +782,7 @@ ContainerEventProc( /* * When the interpreter is being dismantled this can be nil. */ + return; } @@ -920,6 +935,7 @@ EmbedActivateProc( XEvent *eventPtr) /* ResizeRequest event. */ { Container *containerPtr = clientData; + if (containerPtr->embeddedPtr != NULL) { if (eventPtr->type == ActivateNotify) { TkGenerateActivateEvents(containerPtr->embeddedPtr,1); @@ -1024,11 +1040,10 @@ EmbedGeometryRequest( /* * Forward the requested size into our geometry management hierarchy via * the container window. We need to send a Configure event back to the - * embedded application if we decide not to honor its request; to make - * this happen, process all idle event handlers synchronously here (so - * that the geometry managers have had a chance to do whatever they want - * to do), and if the window's size didn't change then generate a - * configure event. + * embedded application if we decide not to honor its request; to make this + * happen, process all idle event handlers synchronously here (so that the + * geometry managers have had a chance to do whatever they want to do), and + * if the window's size didn't change then generate a configure event. */ Tk_GeometryRequest((Tk_Window) winPtr, width, height); @@ -1050,8 +1065,8 @@ EmbedGeometryRequest( * application of its current size and location. This procedure is called * when the embedded application made a geometry request that we did not * grant, so that the embedded application knows that its geometry didn't - * change after all. It is a response to ConfigureRequest events, which - * we do not currently synthesize on the Mac + * change after all. It is a response to ConfigureRequest events, which we + * do not currently synthesize on the Mac * * Results: * None. @@ -1111,8 +1126,8 @@ EmbedWindowDeleted( containerPtr->parentPtr->flags & TK_BOTH_HALVES) { XEvent event; - event.xany.serial = - LastKnownRequestProcessed(Tk_Display(containerPtr->parentPtr)); + event.xany.serial = LastKnownRequestProcessed( + Tk_Display(containerPtr->parentPtr)); event.xany.send_event = False; event.xany.display = Tk_Display(containerPtr->parentPtr); diff --git a/macosx/tkMacOSXFont.c b/macosx/tkMacOSXFont.c index 353ad6b..0e05ae5 100644 --- a/macosx/tkMacOSXFont.c +++ b/macosx/tkMacOSXFont.c @@ -1,8 +1,8 @@ /* * tkMacOSXFont.c -- * - * Contains the Macintosh implementation of the platform-independant - * font package interface. + * Contains the Macintosh implementation of the platform-independant font + * package interface. * * Copyright 2002-2004 Benjamin Riefenstahl, Benjamin.Riefenstahl@epost.de * Copyright (c) 2006-2009 Daniel A. Steffen @@ -32,9 +32,8 @@ */ typedef struct { - TkFont font; /* Stuff used by generic font package. Must - * be first in structure. */ - + TkFont font; /* Stuff used by generic font package. Must be + * first in structure. */ NSFont *nsFont; NSDictionary *nsAttributes; } MacFont; @@ -83,17 +82,21 @@ static int antialiasedTextEnabled = -1; static NSCharacterSet *whitespaceCharacterSet = nil; static NSCharacterSet *lineendingCharacterSet = nil; -static void GetTkFontAttributesForNSFont(NSFont *nsFont, - TkFontAttributes *faPtr); -static NSFont *FindNSFont(const char *familyName, NSFontTraitMask traits, - NSInteger weight, CGFloat size, int fallbackToDefault); -static void InitFont(NSFont *nsFont, const TkFontAttributes *reqFaPtr, - MacFont * fontPtr); -static int CreateNamedSystemFont(Tcl_Interp *interp, Tk_Window tkwin, - const char* name, TkFontAttributes *faPtr); -static void DrawCharsInContext(Display *display, Drawable drawable, GC gc, - Tk_Font tkfont, const char *source, int numBytes, int rangeStart, - int rangeLength, int x, int y, double angle); +static void GetTkFontAttributesForNSFont(NSFont *nsFont, + TkFontAttributes *faPtr); +static NSFont * FindNSFont(const char *familyName, + NSFontTraitMask traits, NSInteger weight, + CGFloat size, int fallbackToDefault); +static void InitFont(NSFont *nsFont, + const TkFontAttributes *reqFaPtr, + MacFont *fontPtr); +static int CreateNamedSystemFont(Tcl_Interp *interp, + Tk_Window tkwin, const char *name, + TkFontAttributes *faPtr); +static void DrawCharsInContext(Display *display, Drawable drawable, + GC gc, Tk_Font tkfont, const char *source, + int numBytes, int rangeStart, int rangeLength, + int x, int y, double angle); #pragma mark - #pragma mark Font Helpers: @@ -232,7 +235,7 @@ InitFont( int ascent, descent/*, dontAA*/; static const UniChar ch[] = {'.', 'W', ' ', 0xc4, 0xc1, 0xc2, 0xc3, 0xc7}; /* ., W, Space, Auml, Aacute, Acirc, Atilde, Ccedilla */ - #define nCh (sizeof(ch) / sizeof(UniChar)) +#define nCh (sizeof(ch) / sizeof(UniChar)) CGGlyph glyphs[nCh]; CGRect boundingRects[nCh]; @@ -244,7 +247,11 @@ InitFont( TkInitFontAttributes(faPtr); } fontPtr->nsFont = nsFont; - // some don't like antialiasing on fixed-width even if bigger than limit + + /* + * Some don't like antialiasing on fixed-width even if bigger than limit + */ + // dontAA = [nsFont isFixedPitch] && fontPtr->font.fa.size <= 10; if (antialiasedTextEnabled >= 0/* || dontAA*/) { renderingMode = (antialiasedTextEnabled == 0/* || dontAA*/) ? @@ -294,7 +301,7 @@ InitFont( NSLigatureAttributeName, [NSNumber numberWithDouble:kern], NSKernAttributeName, nil]; fontPtr->nsAttributes = [nsAttributes retain]; - #undef nCh +#undef nCh } /* @@ -358,10 +365,14 @@ TkpFontPkgInit( NSFont *nsFont; TkFontAttributes fa; NSMutableCharacterSet *cs; - /* Since we called before TkpInit, we need our own autorelease pool. */ + /* + * Since we called before TkpInit, we need our own autorelease pool. + */ NSAutoreleasePool *pool = [NSAutoreleasePool new]; - /* force this for now */ + /* + * Force this for now. + */ if (!mainPtr->winPtr->mainPtr) { mainPtr->winPtr->mainPtr = mainPtr; } @@ -413,17 +424,17 @@ TkpFontPkgInit( * Map a platform-specific native font name to a TkFont. * * Results: - * The return value is a pointer to a TkFont that represents the - * native font. If a native font by the given name could not be - * found, the return value is NULL. + * The return value is a pointer to a TkFont that represents the native + * font. If a native font by the given name could not be found, the return + * value is NULL. * - * Every call to this procedure returns a new TkFont structure, even - * if the name has already been seen before. The caller should call + * Every call to this procedure returns a new TkFont structure, even if + * the name has already been seen before. The caller should call * TkpDeleteFont() when the font is no longer needed. * - * The caller is responsible for initializing the memory associated - * with the generic TkFont when this function returns and releasing - * the contents of the generics TkFont before calling TkpDeleteFont(). + * The caller is responsible for initializing the memory associated with + * the generic TkFont when this function returns and releasing the + * contents of the generics TkFont before calling TkpDeleteFont(). * * Side effects: * None. @@ -449,8 +460,8 @@ TkpGetNativeFont( } else { return NULL; } - ctFont = CTFontCreateUIFontForLanguage(HIThemeGetUIFontType( - themeFontId), 0, NULL); + ctFont = CTFontCreateUIFontForLanguage( + HIThemeGetUIFontType(themeFontId), 0, NULL); if (ctFont) { fontPtr = ckalloc(sizeof(MacFont)); InitFont((NSFont*) ctFont, NULL, fontPtr); @@ -468,19 +479,18 @@ TkpGetNativeFont( * closest matching attributes. * * Results: - * The return value is a pointer to a TkFont that represents the font - * with the desired attributes. If a font with the desired attributes - * could not be constructed, some other font will be substituted - * automatically. + * The return value is a pointer to a TkFont that represents the font with + * the desired attributes. If a font with the desired attributes could not + * be constructed, some other font will be substituted automatically. * - * Every call to this procedure returns a new TkFont structure, even - * if the specified attributes have already been seen before. The - * caller should call TkpDeleteFont() to free the platform- specific - * data when the font is no longer needed. + * Every call to this procedure returns a new TkFont structure, even if + * the specified attributes have already been seen before. The caller + * should call TkpDeleteFont() to free the platform- specific data when + * the font is no longer needed. * - * The caller is responsible for initializing the memory associated - * with the generic TkFont when this function returns and releasing - * the contents of the generic TkFont before calling TkpDeleteFont(). + * The caller is responsible for initializing the memory associated with + * the generic TkFont when this function returns and releasing the + * contents of the generic TkFont before calling TkpDeleteFont(). * * Side effects: * None. @@ -492,16 +502,16 @@ TkFont * TkpGetFontFromAttributes( TkFont *tkFontPtr, /* If non-NULL, store the information in this * existing TkFont structure, rather than - * allocating a new structure to hold the - * font; the existing contents of the font - * will be released. If NULL, a new TkFont - * structure is allocated. */ + * allocating a new structure to hold the font; + * the existing contents of the font will be + * released. If NULL, a new TkFont structure is + * allocated. */ Tk_Window tkwin, /* For display where font will be used. */ const TkFontAttributes *faPtr) /* Set of attributes to match. */ { MacFont *fontPtr; - int points = (int)(TkFontGetPoints(tkwin, faPtr->size) + 0.5); + int points = (int) (TkFontGetPoints(tkwin, faPtr->size) + 0.5); NSFontTraitMask traits = GetNSFontTraitsFromTkFontAttributes(faPtr); NSInteger weight = (faPtr->weight == TK_FW_BOLD ? 9 : 5); NSFont *nsFont; @@ -538,9 +548,9 @@ TkpGetFontFromAttributes( * TkpDeleteFont -- * * Called to release a font allocated by TkpGetNativeFont() or - * TkpGetFontFromAttributes(). The caller should have already - * released the fields of the TkFont that are used exclusively by the - * generic TkFont code. + * TkpGetFontFromAttributes(). The caller should have already released the + * fields of the TkFont that are used exclusively by the generic TkFont + * code. * * Results: * TkFont is deallocated. @@ -567,8 +577,8 @@ TkpDeleteFont( * * TkpGetFontFamilies -- * - * Return information about the font families that are available on - * the display of the given window. + * Return information about the font families that are available on the + * display of the given window. * * Results: * Modifies interp's result object to hold a list of all the available @@ -600,12 +610,12 @@ TkpGetFontFamilies( * * TkpGetSubFonts -- * - * A function used by the testing package for querying the actual - * screen fonts that make up a font object. + * A function used by the testing package for querying the actual screen + * fonts that make up a font object. * * Results: - * Modifies interp's result object to hold a list containing the names - * of the screen fonts that make up the given font object. + * Modifies interp's result object to hold a list containing the names of + * the screen fonts that make up the given font object. * * Side effects: * None. @@ -642,8 +652,8 @@ TkpGetSubFonts( * * TkpGetFontAttrsForChar -- * - * Retrieve the font attributes of the actual font used to render a - * given character. + * Retrieve the font attributes of the actual font used to render a given + * character. * * Results: * None. @@ -745,10 +755,9 @@ Tk_MeasureChars( * all the characters on the line for context. * * Results: - * The return value is the number of bytes from source that - * fit into the span that extends from 0 to maxLength. *lengthPtr is - * filled with the x-coordinate of the right edge of the last - * character that did fit. + * The return value is the number of bytes from source that fit into the + * span that extends from 0 to maxLength. *lengthPtr is filled with the + * x-coordinate of the right edge of the last character that did fit. * * Side effects: * None. @@ -774,11 +783,11 @@ TkpMeasureCharsInContext( * TK_PARTIAL_OK means include the last char * which only partially fits on this line. * TK_WHOLE_WORDS means stop on a word - * boundary, if possible. TK_AT_LEAST_ONE - * means return at least one character even - * if no characters fit. If TK_WHOLE_WORDS - * and TK_AT_LEAST_ONE are set and the first - * word doesn't fit, we return at least one + * boundary, if possible. TK_AT_LEAST_ONE means + * return at least one character even if no + * characters fit. If TK_WHOLE_WORDS and + * TK_AT_LEAST_ONE are set and the first word + * doesn't fit, we return at least one * character or whatever characters fit into * maxLength. TK_ISOLATE_END means that the * last character should not be considered in @@ -864,14 +873,13 @@ TkpMeasureCharsInContext( } /* - * If there is no line breakpoint in the source string between - * its start and the index position that fits in maxWidth, then + * If there is no line breakpoint in the source string between its + * start and the index position that fits in maxWidth, then * CTTypesetterSuggestLineBreak() returns that very last index. - * However if the TK_WHOLE_WORDS flag is set, we want to break - * at a word boundary. In this situation, unless TK_AT_LEAST_ONE - * is set, we must report that zero chars actually fit (in other - * words the smallest word of the source string is still larger - * than maxWidth). + * However if the TK_WHOLE_WORDS flag is set, we want to break at a + * word boundary. In this situation, unless TK_AT_LEAST_ONE is set, we + * must report that zero chars actually fit (in other words the + * smallest word of the source string is still larger than maxWidth). */ if ((index >= start) && (index < len) && @@ -903,9 +911,12 @@ TkpMeasureCharsInContext( CFRelease(line); } - /* The call to CTTypesetterSuggestClusterBreak above will always - return at least one character regardless of whether it exceeded - it or not. Clean that up now. */ + /* + * The call to CTTypesetterSuggestClusterBreak above will always return + * at least one character regardless of whether it exceeded it or not. + * Clean that up now. + */ + while (width > maxWidth && !(flags & TK_PARTIAL_OK) && index > start+(flags & TK_AT_LEAST_ONE)) { range.length = --index; @@ -946,7 +957,7 @@ done: * actual implementation in TkpDrawCharsInContext(). * * Results: - * None. + * None. * * Side effects: * Information gets drawn on the screen. @@ -964,8 +975,8 @@ Tk_DrawChars( const char *source, /* UTF-8 string to be displayed. Need not be * '\0' terminated. All Tk meta-characters * (tabs, control characters, and newlines) - * should be stripped out of the string that - * is passed to this function. If they are not + * should be stripped out of the string that is + * passed to this function. If they are not * stripped out, they will be displayed as * regular printing characters. */ int numBytes, /* Number of bytes in string. */ @@ -986,8 +997,8 @@ TkDrawAngledChars( const char *source, /* UTF-8 string to be displayed. Need not be * '\0' terminated. All Tk meta-characters * (tabs, control characters, and newlines) - * should be stripped out of the string that - * is passed to this function. If they are not + * should be stripped out of the string that is + * passed to this function. If they are not * stripped out, they will be displayed as * regular printing characters. */ int numBytes, /* Number of bytes in string. */ @@ -1029,8 +1040,8 @@ TkpDrawCharsInContext( const char * source, /* UTF-8 string to be displayed. Need not be * '\0' terminated. All Tk meta-characters * (tabs, control characters, and newlines) - * should be stripped out of the string that - * is passed to this function. If they are not + * should be stripped out of the string that is + * passed to this function. If they are not * stripped out, they will be displayed as * regular printing characters. */ int numBytes, /* Number of bytes in string. */ @@ -1054,8 +1065,8 @@ DrawCharsInContext( const char * source, /* UTF-8 string to be displayed. Need not be * '\0' terminated. All Tk meta-characters * (tabs, control characters, and newlines) - * should be stripped out of the string that - * is passed to this function. If they are not + * should be stripped out of the string that is + * passed to this function. If they are not * stripped out, they will be displayed as * regular printing characters. */ int numBytes, /* Number of bytes in string. */ @@ -1091,6 +1102,7 @@ DrawCharsInContext( if (!string) { return; } + context = drawingContext.context; fg = TkMacOSXCreateCGColor(gc, gc->foreground); attributes = [fontPtr->nsAttributes mutableCopy]; @@ -1119,6 +1131,7 @@ DrawCharsInContext( len = Tcl_NumUtfChars(source, rangeStart + rangeLength); if (start > 0) { CGRect clipRect = CGRectInfinite, startBounds; + line = CTTypesetterCreateLine(typesetter, CFRangeMake(0, start)); startBounds = CTLineGetImageBounds(line, context); CFRelease(line); @@ -1241,9 +1254,10 @@ TkMacOSXFontDescriptionForNSFontAndNSFontAttributes( NSUnderlineStyleAttributeName]; id strikethrough = [nsAttributes objectForKey: NSStrikethroughStyleAttributeName]; + objv[i++] = Tcl_NewStringObj(familyName, -1); objv[i++] = Tcl_NewIntObj([nsFont pointSize]); -#define S(s) Tcl_NewStringObj(STRINGIFY(s),(int)(sizeof(STRINGIFY(s))-1)) +#define S(s) Tcl_NewStringObj(STRINGIFY(s),(int)(sizeof(STRINGIFY(s))-1)) objv[i++] = (traits & NSBoldFontMask) ? S(bold) : S(normal); objv[i++] = (traits & NSItalicFontMask) ? S(italic) : S(roman); if ([underline respondsToSelector:@selector(intValue)] && @@ -1267,8 +1281,9 @@ TkMacOSXFontDescriptionForNSFontAndNSFontAttributes( * TkMacOSXUseAntialiasedText -- * * Enables or disables application-wide use of antialiased text (where - * available). Sets up a linked Tcl global variable to allow - * disabling of antialiased text from tcl. + * available). Sets up a linked Tcl global variable to allow disabling of + * antialiased text from Tcl. + * * The possible values for this variable are: * * -1 - Use system default as configurable in "System Prefs" -> "General". diff --git a/macosx/tkMacOSXImage.c b/macosx/tkMacOSXImage.c index 38f4a70..36f1fc6 100644 --- a/macosx/tkMacOSXImage.c +++ b/macosx/tkMacOSXImage.c @@ -23,7 +23,7 @@ _XInitImageFuncPtrs( { return 0; } - + /* *---------------------------------------------------------------------- * @@ -81,14 +81,15 @@ TkMacOSXCreateCGImageWithXImage( data = memcpy(ckalloc(len), image->data + image->xoffset, len); } if (data) { - provider = CGDataProviderCreateWithData(data, data, len, releaseData); + provider = CGDataProviderCreateWithData(data, data, len, + releaseData); } if (provider) { - img = CGImageMaskCreate(image->width, image->height, bitsPerComponent, - bitsPerPixel, image->bytes_per_line, provider, decode, 0); + img = CGImageMaskCreate(image->width, image->height, + bitsPerComponent, bitsPerPixel, image->bytes_per_line, + provider, decode, 0); } - } else if (image->format == ZPixmap && image->bits_per_pixel == 32) { - + } else if ((image->format == ZPixmap) && (image->bits_per_pixel == 32)) { /* * Color image */ @@ -96,7 +97,6 @@ TkMacOSXCreateCGImageWithXImage( CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB(); if (image->width == 0 && image->height == 0) { - /* * CGCreateImage complains on early macOS releases. */ @@ -106,11 +106,12 @@ TkMacOSXCreateCGImageWithXImage( bitsPerComponent = 8; bitsPerPixel = 32; bitmapInfo = (image->byte_order == MSBFirst ? - kCGBitmapByteOrder32Little : kCGBitmapByteOrder32Big); + kCGBitmapByteOrder32Little : kCGBitmapByteOrder32Big); bitmapInfo |= kCGImageAlphaLast; data = memcpy(ckalloc(len), image->data + image->xoffset, len); if (data) { - provider = CGDataProviderCreateWithData(data, data, len, releaseData); + provider = CGDataProviderCreateWithData(data, data, len, + releaseData); } if (provider) { img = CGImageCreate(image->width, image->height, bitsPerComponent, @@ -127,7 +128,6 @@ TkMacOSXCreateCGImageWithXImage( return img; } - /* *---------------------------------------------------------------------- * @@ -179,15 +179,14 @@ XGetImage( if (win && has_retina == unknown) { #ifdef __clang__ - has_retina = [win respondsToSelector:@selector(backingScaleFactor)]? - yes : no; + has_retina = [win respondsToSelector:@selector(backingScaleFactor)] ? + yes : no; #else has_retina = no; #endif } if (has_retina == yes) { - /* * We only allow scale factors 1 or 2, as Apple currently does. */ @@ -205,7 +204,7 @@ XGetImage( } bitmap_rep = TkMacOSXBitmapRepFromDrawableRect(drawable, - x, y, width, height); + x, y, width, height); if (!bitmap_rep) { TkMacOSXDbgMsg("XGetImage: Failed to construct NSBitmapRep"); return NULL; @@ -214,12 +213,12 @@ XGetImage( size = [bitmap_rep bytesPerPlane]; bytes_per_row = [bitmap_rep bytesPerRow]; bitmap = ckalloc(size); - if (!bitmap || - (bitmap_fmt != 0 && bitmap_fmt != 1) || - [bitmap_rep samplesPerPixel] != 4 || - [bitmap_rep isPlanar] != 0 || - bytes_per_row < 4 * scaled_width || - size != bytes_per_row*scaled_height ) { + if (!bitmap + || (bitmap_fmt != 0 && bitmap_fmt != 1) + || [bitmap_rep samplesPerPixel] != 4 + || [bitmap_rep isPlanar] != 0 + || bytes_per_row < 4 * scaled_width + || size != bytes_per_row * scaled_height) { TkMacOSXDbgMsg("XGetImage: Unrecognized bitmap format"); CFRelease(bitmap_rep); return NULL; @@ -228,8 +227,8 @@ XGetImage( CFRelease(bitmap_rep); /* - * When Apple extracts a bitmap from an NSView, it may be in - * either BGRA or ABGR format. For an XImage we need RGBA. + * When Apple extracts a bitmap from an NSView, it may be in either + * BGRA or ABGR format. For an XImage we need RGBA. */ struct pixel_fmt pixel = bitmap_fmt == 0 ? bgra : abgr; @@ -248,16 +247,16 @@ XGetImage( } } imagePtr = XCreateImage(display, NULL, depth, format, offset, - (char*)bitmap, scaled_width, scaled_height, - bitmap_pad, bytes_per_row); + (char*) bitmap, scaled_width, scaled_height, + bitmap_pad, bytes_per_row); if (scalefactor == 2) { imagePtr->pixelpower = 1; } } else { /* - * There are some calls to XGetImage in the generic Tk - * code which pass an XYPixmap rather than a ZPixmap. - * XYPixmaps should be handled here. + * There are some calls to XGetImage in the generic Tk code which pass + * an XYPixmap rather than a ZPixmap. XYPixmaps should be handled + * here. */ TkMacOSXDbgMsg("XGetImage does not handle XYPixmaps at the moment."); } @@ -323,40 +322,40 @@ ImageGetPixel( + (((image->xoffset + x) * image->bits_per_pixel) / NBBY); switch (image->bits_per_pixel) { - case 32: { - r = (*((unsigned int*) srcPtr) >> 16) & 0xff; - g = (*((unsigned int*) srcPtr) >> 8) & 0xff; - b = (*((unsigned int*) srcPtr) ) & 0xff; - /*if (image->byte_order == LSBFirst) { - r = srcPtr[2]; g = srcPtr[1]; b = srcPtr[0]; - } else { - r = srcPtr[1]; g = srcPtr[2]; b = srcPtr[3]; - }*/ - break; - } - case 16: - r = (*((unsigned short*) srcPtr) >> 7) & 0xf8; - g = (*((unsigned short*) srcPtr) >> 2) & 0xf8; - b = (*((unsigned short*) srcPtr) << 3) & 0xf8; - break; - case 8: - r = (*srcPtr << 2) & 0xc0; - g = (*srcPtr << 4) & 0xc0; - b = (*srcPtr << 6) & 0xc0; - r |= r >> 2 | r >> 4 | r >> 6; - g |= g >> 2 | g >> 4 | g >> 6; - b |= b >> 2 | b >> 4 | b >> 6; - break; - case 4: { - unsigned char c = (x % 2) ? *srcPtr : (*srcPtr >> 4); - r = (c & 0x04) ? 0xff : 0; - g = (c & 0x02) ? 0xff : 0; - b = (c & 0x01) ? 0xff : 0; - break; - } - case 1: - r = g = b = ((*srcPtr) & (0x80 >> (x % 8))) ? 0xff : 0; - break; + case 32: + r = (*((unsigned int*) srcPtr) >> 16) & 0xff; + g = (*((unsigned int*) srcPtr) >> 8) & 0xff; + b = (*((unsigned int*) srcPtr) ) & 0xff; + /*if (image->byte_order == LSBFirst) { + r = srcPtr[2]; g = srcPtr[1]; b = srcPtr[0]; + } else { + r = srcPtr[1]; g = srcPtr[2]; b = srcPtr[3]; + }*/ + break; + case 16: + r = (*((unsigned short*) srcPtr) >> 7) & 0xf8; + g = (*((unsigned short*) srcPtr) >> 2) & 0xf8; + b = (*((unsigned short*) srcPtr) << 3) & 0xf8; + break; + case 8: + r = (*srcPtr << 2) & 0xc0; + g = (*srcPtr << 4) & 0xc0; + b = (*srcPtr << 6) & 0xc0; + r |= r >> 2 | r >> 4 | r >> 6; + g |= g >> 2 | g >> 4 | g >> 6; + b |= b >> 2 | b >> 4 | b >> 6; + break; + case 4: { + unsigned char c = (x % 2) ? *srcPtr : (*srcPtr >> 4); + + r = (c & 0x04) ? 0xff : 0; + g = (c & 0x02) ? 0xff : 0; + b = (c & 0x01) ? 0xff : 0; + break; + } + case 1: + r = g = b = ((*srcPtr) & (0x80 >> (x % 8))) ? 0xff : 0; + break; } } return (PIXEL_MAGIC << 24) | (r << 16) | (g << 8) | b; @@ -389,6 +388,7 @@ ImagePutPixel( unsigned char *dstPtr = ((unsigned char*) image->data) + (y * image->bytes_per_line) + (((image->xoffset + x) * image->bits_per_pixel) / NBBY); + if (image->bits_per_pixel == 32) { *((unsigned int*) dstPtr) = pixel; } else { @@ -420,7 +420,7 @@ ImagePutPixel( } return 0; } - + /* *---------------------------------------------------------------------- * @@ -451,6 +451,7 @@ XCreateImage( int bytes_per_line) { XImage *ximage; + display->request++; ximage = ckalloc(sizeof(XImage)); @@ -461,9 +462,12 @@ XCreateImage( ximage->format = format; ximage->data = data; ximage->obdata = NULL; - /* The default pixelpower is 0. This must be explicitly set to 1 in the + + /* + * The default pixelpower is 0. This must be explicitly set to 1 in the * case of an XImage extracted from a Retina display. */ + ximage->pixelpower = 0; if (format == ZPixmap) { @@ -476,7 +480,10 @@ XCreateImage( if (bitmap_pad) { ximage->bitmap_pad = bitmap_pad; } else { - /* Use 16 byte alignment for best Quartz perfomance */ + /* + * Use 16 byte alignment for best Quartz perfomance. + */ + ximage->bitmap_pad = 128; } if (bytes_per_line) { @@ -511,9 +518,9 @@ XCreateImage( * * TkPutImage -- * - * Copies a rectangular subimage of an XImage into a drawable. - * Currently this is only called by TkImgPhotoDisplay, using - * a Window as the drawable. + * Copies a rectangular subimage of an XImage into a drawable. Currently + * this is only called by TkImgPhotoDisplay, using a Window as the + * drawable. * * Results: * None. @@ -559,13 +566,15 @@ TkPutImage( } if (img) { - /* If the XImage has big pixels, the source is rescaled to reflect + /* + * If the XImage has big pixels, the source is rescaled to reflect * the actual pixel dimensions. This is not currently used, but * could arise if the image were copied from a retina monitor and * redrawn on an ordinary monitor. */ int pp = image->pixelpower; + bounds = CGRectMake(0, 0, image->width, image->height); srcRect = CGRectMake(src_x<dispPtr->grabWinPtr; - if (grabWinPtr && - grabWinPtr != winPtr && - !winPtr->dispPtr->grabFlags && /* this means the grab is local. */ - grabWinPtr->mainPtr == winPtr->mainPtr) { + + if (grabWinPtr + && grabWinPtr != winPtr + && !winPtr->dispPtr->grabFlags /* this means the grab is local. */ + && grabWinPtr->mainPtr == winPtr->mainPtr) { return theEvent; } } else { tkwin = (Tk_Window) winPtr->dispPtr->focusPtr; } if (!tkwin) { - TkMacOSXDbgMsg("tkwin == NULL"); - return theEvent; /* Give up. No window for this event. */ + TkMacOSXDbgMsg("tkwin == NULL"); + return theEvent; /* Give up. No window for this event. */ } /* - * If it's a function key, or we have modifiers other than Shift or Alt, - * pass it straight to Tk. Otherwise we'll send for input processing. + * If it's a function key, or we have modifiers other than Shift or + * Alt, pass it straight to Tk. Otherwise we'll send for input + * processing. */ - int code = (len == 0) ? - 0 : [charactersIgnoringModifiers characterAtIndex: 0]; + int code = (len == 0) ? 0 : + [charactersIgnoringModifiers characterAtIndex: 0]; if (type != NSKeyDown || isFunctionKey(code) - || (len > 0 && state & (ControlMask | Mod1Mask | Mod3Mask | Mod4Mask))) { - + || (len > 0 && state & (ControlMask | Mod1Mask | Mod3Mask | Mod4Mask))) { XEvent xEvent; - setupXEvent(&xEvent, w, state); + setupXEvent(&xEvent, w, state); if (type == NSFlagsChanged) { - if (savedModifiers > modifiers) { - xEvent.xany.type = KeyRelease; - } else { - xEvent.xany.type = KeyPress; - } + if (savedModifiers > modifiers) { + xEvent.xany.type = KeyRelease; + } else { + xEvent.xany.type = KeyPress; + } - /* - * Use special '-1' to signify a special keycode to our platform - * specific code in tkMacOSXKeyboard.c. This is rather like what - * happens on Windows. - */ + /* + * Use special '-1' to signify a special keycode to our + * platform specific code in tkMacOSXKeyboard.c. This is rather + * like what happens on Windows. + */ - xEvent.xany.send_event = -1; + xEvent.xany.send_event = -1; - /* - * Set keycode (which was zero) to the changed modifier - */ + /* + * Set keycode (which was zero) to the changed modifier + */ - xEvent.xkey.keycode = (modifiers ^ savedModifiers); + xEvent.xkey.keycode = (modifiers ^ savedModifiers); } else { - if (type == NSKeyUp || repeat) { - xEvent.xany.type = KeyRelease; - } else { - xEvent.xany.type = KeyPress; - } - - /* For command key, take input manager's word so things - like dvorak / qwerty layout work. */ - if ((modifiers & NSCommandKeyMask) == NSCommandKeyMask - && (modifiers & NSAlternateKeyMask) != NSAlternateKeyMask - && len > 0 && !isFunctionKey(code)) { - // head off keycode-based translation in tkMacOSXKeyboard.c - xEvent.xkey.nbytes = [characters length]; //len - } - - if ([characters length] > 0) { - xEvent.xkey.keycode = - (keyCode << 16) | (UInt16) [characters characterAtIndex:0]; - if (![characters getCString:xEvent.xkey.trans_chars - maxLength:XMaxTransChars encoding:NSUTF8StringEncoding]) { - /* prevent SF bug 2907388 (crash on some composite chars) */ - //PENDING: we might not need this anymore - TkMacOSXDbgMsg("characters too long"); - return theEvent; - } - } - - if (repeat) { - Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL); - xEvent.xany.type = KeyPress; - xEvent.xany.serial = LastKnownRequestProcessed(Tk_Display(tkwin)); - } + if (type == NSKeyUp || repeat) { + xEvent.xany.type = KeyRelease; + } else { + xEvent.xany.type = KeyPress; + } + + /* + * For command key, take input manager's word so things like + * dvorak / qwerty layout work. + */ + + if ((modifiers & NSCommandKeyMask) == NSCommandKeyMask + && (modifiers & NSAlternateKeyMask) != NSAlternateKeyMask + && len > 0 && !isFunctionKey(code)) { + // head off keycode-based translation in tkMacOSXKeyboard.c + xEvent.xkey.nbytes = [characters length]; //len + } + + if ([characters length] > 0) { + xEvent.xkey.keycode = (keyCode << 16) | + (UInt16) [characters characterAtIndex:0]; + if (![characters getCString:xEvent.xkey.trans_chars + maxLength:XMaxTransChars encoding:NSUTF8StringEncoding]) { + /* prevent SF bug 2907388 (crash on some composite chars) */ + //PENDING: we might not need this anymore + TkMacOSXDbgMsg("characters too long"); + return theEvent; + } + } + + if (repeat) { + Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL); + xEvent.xany.type = KeyPress; + xEvent.xany.serial = LastKnownRequestProcessed(Tk_Display(tkwin)); + } } Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL); savedModifiers = modifiers; return theEvent; - } /* if send straight to TK */ - - } /* if not processing compose */ + } /* if send straight to TK */ + } /* if not processing compose */ if (type == NSKeyDown) { - if (NS_KEYLOG) - fprintf (stderr, "keyDown: %s compose sequence.\n", - processingCompose == YES ? "Continue" : "Begin"); + if (NS_KEYLOG) { + TKLog(@"keyDown: %s compose sequence.\n", + processingCompose == YES ? "Continue" : "Begin"); + } processingCompose = YES; [nsEvArray addObject: theEvent]; [[w contentView] interpretKeyEvents: nsEvArray]; [nsEvArray removeObject: theEvent]; - } + } savedModifiers = modifiers; - return theEvent; } @end - @implementation TKContentView @@ -261,163 +264,189 @@ unsigned short releaseCode; by doCommandBySelector: deleteBackward: */ - (void)insertText: (id)aString { - int i, len = [(NSString *)aString length]; - XEvent xEvent; + int i, len = [(NSString *) aString length]; + XEvent xEvent; - if (NS_KEYLOG) - TKLog (@"insertText '%@'\tlen = %d", aString, len); - processingCompose = NO; - finishedCompose = YES; + if (NS_KEYLOG) { + TKLog(@"insertText '%@'\tlen = %d", aString, len); + } + processingCompose = NO; + finishedCompose = YES; - /* first, clear any working text */ - if (privateWorkingText != nil) - [self deleteWorkingText]; + /* + * First, clear any working text. + */ + + if (privateWorkingText != nil) { + [self deleteWorkingText]; + } - /* now insert the string as keystrokes */ - setupXEvent(&xEvent, [self window], 0); - xEvent.xany.type = KeyPress; + /* + * Now insert the string as keystrokes. + */ - for (i =0; i: inserts display of composing characters */ - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange { - NSString *str = [aString respondsToSelector: @selector (string)] ? - [aString string] : aString; - if (NS_KEYLOG) - TKLog (@"setMarkedText '%@' len =%lu range %lu from %lu", str, - (unsigned long) [str length], (unsigned long) selRange.length, - (unsigned long) selRange.location); - - if (privateWorkingText != nil) - [self deleteWorkingText]; - if ([str length] == 0) - return; + NSString *str = [aString respondsToSelector: @selector (string)] ? + [aString string] : aString; + if (NS_KEYLOG) { + TKLog(@"setMarkedText '%@' len =%lu range %lu from %lu", str, + (unsigned long) [str length], (unsigned long) selRange.length, + (unsigned long) selRange.location); + } - processingCompose = YES; - privateWorkingText = [str copy]; + if (privateWorkingText != nil) { + [self deleteWorkingText]; + } + if ([str length] == 0) { + return; + } - //PENDING: insert workingText underlined + processingCompose = YES; + privateWorkingText = [str copy]; + + //PENDING: insert workingText underlined } - (BOOL)hasMarkedText { - return privateWorkingText != nil; + return privateWorkingText != nil; } - (NSRange)markedRange { - NSRange rng = privateWorkingText != nil - ? NSMakeRange (0, [privateWorkingText length]) : NSMakeRange (NSNotFound, 0); - if (NS_KEYLOG) - TKLog (@"markedRange request"); - return rng; + NSRange rng = privateWorkingText != nil + ? NSMakeRange(0, [privateWorkingText length]) + : NSMakeRange(NSNotFound, 0); + + if (NS_KEYLOG) { + TKLog(@"markedRange request"); + } + return rng; } - (void)unmarkText { - if (NS_KEYLOG) - TKLog (@"unmark (accept) text"); - [self deleteWorkingText]; - processingCompose = NO; + if (NS_KEYLOG) { + TKLog(@"unmark (accept) text"); + } + [self deleteWorkingText]; + processingCompose = NO; } /* used to position char selection windows, etc. */ - (NSRect)firstRectForCharacterRange: (NSRange)theRange { - NSRect rect; - NSPoint pt; + NSRect rect; + NSPoint pt; - pt.x = caret_x; - pt.y = caret_y; + pt.x = caret_x; + pt.y = caret_y; - pt = [self convertPoint: pt toView: nil]; - pt = [[self window] tkConvertPointToScreen: pt]; - pt.y -= caret_height; + pt = [self convertPoint: pt toView: nil]; + pt = [[self window] tkConvertPointToScreen: pt]; + pt.y -= caret_height; - rect.origin = pt; - rect.size.width = caret_height; - rect.size.height = caret_height; - return rect; + rect.origin = pt; + rect.size.width = caret_height; + rect.size.height = caret_height; + return rect; } - (NSInteger)conversationIdentifier { - return (NSInteger)self; + return (NSInteger) self; } - (void)doCommandBySelector: (SEL)aSelector { - if (NS_KEYLOG) - TKLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector)); - processingCompose = NO; - if (aSelector == @selector (deleteBackward:)) - { - /* happens when user backspaces over an ongoing composition: - throw a 'delete' into the event queue */ - XEvent xEvent; - setupXEvent(&xEvent, [self window], 0); - xEvent.xany.type = KeyPress; - xEvent.xkey.nbytes = 1; - xEvent.xkey.keycode = (0x33 << 16) | 0x7F; - xEvent.xkey.trans_chars[0] = 0x7F; - xEvent.xkey.trans_chars[1] = 0x0; - Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL); + if (NS_KEYLOG) { + TKLog(@"doCommandBySelector: %@", NSStringFromSelector(aSelector)); + } + processingCompose = NO; + if (aSelector == @selector (deleteBackward:)) { + /* + * Happens when user backspaces over an ongoing composition: + * throw a 'delete' into the event queue. + */ + + XEvent xEvent; + + setupXEvent(&xEvent, [self window], 0); + xEvent.xany.type = KeyPress; + xEvent.xkey.nbytes = 1; + xEvent.xkey.keycode = (0x33 << 16) | 0x7F; + xEvent.xkey.trans_chars[0] = 0x7F; + xEvent.xkey.trans_chars[1] = 0x0; + Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL); } } - (NSArray *)validAttributesForMarkedText { - static NSArray *arr = nil; - if (arr == nil) arr = [NSArray new]; - /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */ - return arr; + static NSArray *arr = nil; + + if (arr == nil) { + arr = [NSArray new]; + } + /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */ + return arr; } - (NSRange)selectedRange { - if (NS_KEYLOG) - TKLog (@"selectedRange request"); - return NSMakeRange (NSNotFound, 0); + if (NS_KEYLOG) { + TKLog(@"selectedRange request"); + } + return NSMakeRange(NSNotFound, 0); } - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint { - if (NS_KEYLOG) - TKLog (@"characterIndexForPoint request"); - return 0; + if (NS_KEYLOG) { + TKLog(@"characterIndexForPoint request"); + } + return 0; } - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange { - static NSAttributedString *str = nil; - if (str == nil) str = [NSAttributedString new]; - if (NS_KEYLOG) - TKLog (@"attributedSubstringFromRange request"); - return str; + static NSAttributedString *str = nil; + if (str == nil) { + str = [NSAttributedString new]; + } + if (NS_KEYLOG) { + TKLog(@"attributedSubstringFromRange request"); + } + return str; } /* End impl. */ @end @@ -427,29 +456,30 @@ unsigned short releaseCode; /* delete display of composing characters [not in ] */ - (void)deleteWorkingText { - if (privateWorkingText == nil) - return; - if (NS_KEYLOG) - TKLog(@"deleteWorkingText len = %lu\n", - (unsigned long)[privateWorkingText length]); - [privateWorkingText release]; - privateWorkingText = nil; - processingCompose = NO; - - //PENDING: delete working text + if (privateWorkingText == nil) { + return; + } + if (NS_KEYLOG) { + TKLog(@"deleteWorkingText len = %lu\n", + (unsigned long)[privateWorkingText length]); + } + [privateWorkingText release]; + privateWorkingText = nil; + processingCompose = NO; + + //PENDING: delete working text } @end - - /* - * Set up basic fields in xevent for keyboard input. + * Set up basic fields in xevent for keyboard input. */ static void setupXEvent(XEvent *xEvent, NSWindow *w, unsigned int state) { TkWindow *winPtr = TkMacOSXGetTkWindow(w); Tk_Window tkwin = (Tk_Window) winPtr; + if (!winPtr) { return; } @@ -497,12 +527,13 @@ XGrabKeyboard( Time time) { keyboardGrabWinPtr = Tk_IdToWindow(display, grab_window); - TkWindow *captureWinPtr = (TkWindow *)TkMacOSXGetCapture(); + TkWindow *captureWinPtr = (TkWindow *) TkMacOSXGetCapture(); + if (keyboardGrabWinPtr && captureWinPtr) { NSWindow *w = TkMacOSXDrawableWindow(grab_window); MacDrawable *macWin = (MacDrawable *) grab_window; - if (w && macWin->toplevel->winPtr == (TkWindow*) captureWinPtr) { + if (w && macWin->toplevel->winPtr == (TkWindow *) captureWinPtr) { if (modalSession) { Tcl_Panic("XGrabKeyboard: already grabbed"); } @@ -621,7 +652,10 @@ Tk_SetCaretPos( } } - /* But adjust for fact that NS uses flipped view. */ + /* + * But adjust for fact that NS uses flipped view. + */ + y = Tk_Height(tkwin) - y; caret_x = x; @@ -632,75 +666,79 @@ Tk_SetCaretPos( static unsigned convert_ns_to_X_keysym[] = { - NSHomeFunctionKey, 0x50, - NSLeftArrowFunctionKey, 0x51, - NSUpArrowFunctionKey, 0x52, - NSRightArrowFunctionKey, 0x53, - NSDownArrowFunctionKey, 0x54, - NSPageUpFunctionKey, 0x55, - NSPageDownFunctionKey, 0x56, - NSEndFunctionKey, 0x57, - NSBeginFunctionKey, 0x58, - NSSelectFunctionKey, 0x60, - NSPrintFunctionKey, 0x61, - NSExecuteFunctionKey, 0x62, - NSInsertFunctionKey, 0x63, - NSUndoFunctionKey, 0x65, - NSRedoFunctionKey, 0x66, - NSMenuFunctionKey, 0x67, - NSFindFunctionKey, 0x68, - NSHelpFunctionKey, 0x6A, - NSBreakFunctionKey, 0x6B, - - NSF1FunctionKey, 0xBE, - NSF2FunctionKey, 0xBF, - NSF3FunctionKey, 0xC0, - NSF4FunctionKey, 0xC1, - NSF5FunctionKey, 0xC2, - NSF6FunctionKey, 0xC3, - NSF7FunctionKey, 0xC4, - NSF8FunctionKey, 0xC5, - NSF9FunctionKey, 0xC6, - NSF10FunctionKey, 0xC7, - NSF11FunctionKey, 0xC8, - NSF12FunctionKey, 0xC9, - NSF13FunctionKey, 0xCA, - NSF14FunctionKey, 0xCB, - NSF15FunctionKey, 0xCC, - NSF16FunctionKey, 0xCD, - NSF17FunctionKey, 0xCE, - NSF18FunctionKey, 0xCF, - NSF19FunctionKey, 0xD0, - NSF20FunctionKey, 0xD1, - NSF21FunctionKey, 0xD2, - NSF22FunctionKey, 0xD3, - NSF23FunctionKey, 0xD4, - NSF24FunctionKey, 0xD5, - - NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */ - NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */ - NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */ - - NSTabCharacter, 0x09, - 0x19, 0x09, /* left tab->regular since pass shift */ - NSCarriageReturnCharacter, 0x0D, - NSNewlineCharacter, 0x0D, - NSEnterCharacter, 0x8D, - - 0x1B, 0x1B /* escape */ + NSHomeFunctionKey, 0x50, + NSLeftArrowFunctionKey, 0x51, + NSUpArrowFunctionKey, 0x52, + NSRightArrowFunctionKey, 0x53, + NSDownArrowFunctionKey, 0x54, + NSPageUpFunctionKey, 0x55, + NSPageDownFunctionKey, 0x56, + NSEndFunctionKey, 0x57, + NSBeginFunctionKey, 0x58, + NSSelectFunctionKey, 0x60, + NSPrintFunctionKey, 0x61, + NSExecuteFunctionKey, 0x62, + NSInsertFunctionKey, 0x63, + NSUndoFunctionKey, 0x65, + NSRedoFunctionKey, 0x66, + NSMenuFunctionKey, 0x67, + NSFindFunctionKey, 0x68, + NSHelpFunctionKey, 0x6A, + NSBreakFunctionKey, 0x6B, + + NSF1FunctionKey, 0xBE, + NSF2FunctionKey, 0xBF, + NSF3FunctionKey, 0xC0, + NSF4FunctionKey, 0xC1, + NSF5FunctionKey, 0xC2, + NSF6FunctionKey, 0xC3, + NSF7FunctionKey, 0xC4, + NSF8FunctionKey, 0xC5, + NSF9FunctionKey, 0xC6, + NSF10FunctionKey, 0xC7, + NSF11FunctionKey, 0xC8, + NSF12FunctionKey, 0xC9, + NSF13FunctionKey, 0xCA, + NSF14FunctionKey, 0xCB, + NSF15FunctionKey, 0xCC, + NSF16FunctionKey, 0xCD, + NSF17FunctionKey, 0xCE, + NSF18FunctionKey, 0xCF, + NSF19FunctionKey, 0xD0, + NSF20FunctionKey, 0xD1, + NSF21FunctionKey, 0xD2, + NSF22FunctionKey, 0xD3, + NSF23FunctionKey, 0xD4, + NSF24FunctionKey, 0xD5, + + NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */ + NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */ + NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */ + + NSTabCharacter, 0x09, + 0x19, 0x09, /* left tab->regular since pass shift */ + NSCarriageReturnCharacter, 0x0D, + NSNewlineCharacter, 0x0D, + NSEnterCharacter, 0x8D, + + 0x1B, 0x1B /* escape */ }; -static unsigned isFunctionKey(unsigned code) +static unsigned +isFunctionKey( + unsigned code) { const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym) / sizeof (convert_ns_to_X_keysym[0])); - unsigned keysym; - for (keysym = 0; keysym < last_keysym; keysym += 2) - if (code == convert_ns_to_X_keysym[keysym]) - return 0xFF00 | convert_ns_to_X_keysym[keysym+1]; - return 0; - } + unsigned keysym; + for (keysym = 0; keysym < last_keysym; keysym += 2) { + if (code == convert_ns_to_X_keysym[keysym]) { + return 0xFF00 | convert_ns_to_X_keysym[keysym+1]; + } + } + return 0; +} /* * Local Variables: diff --git a/macosx/tkMacOSXMenu.c b/macosx/tkMacOSXMenu.c index 227c379..fc1b7c4 100644 --- a/macosx/tkMacOSXMenu.c +++ b/macosx/tkMacOSXMenu.c @@ -193,10 +193,10 @@ static int ModifierCharWidth(Tk_Font tkfont); - (void) insertItem: (NSMenuItem *) newItem atIndex: (NSInteger) index { if (_tkMenu && index >= 0) { - if ((NSUInteger)index <= _tkOffset) { + if ((NSUInteger) index <= _tkOffset) { _tkOffset++; } else { - NSAssert((NSUInteger)index >= _tkItemCount + _tkOffset, + NSAssert((NSUInteger) index >= _tkItemCount + _tkOffset, @"Cannot insert in the middle of Tk menu"); } } @@ -206,9 +206,9 @@ static int ModifierCharWidth(Tk_Font tkfont); - (void) removeItemAtIndex: (NSInteger) index { if (_tkMenu && index >= 0) { - if ((NSUInteger)index < _tkOffset) { + if ((NSUInteger) index < _tkOffset) { _tkOffset--; - } else if ((NSUInteger)index < _tkItemCount + _tkOffset) { + } else if ((NSUInteger) index < _tkItemCount + _tkOffset) { _tkItemCount--; } } @@ -221,7 +221,7 @@ static int ModifierCharWidth(Tk_Font tkfont); action:@selector(tkMenuItemInvoke:) keyEquivalent:@""]; [menuItem setTarget:self]; - [menuItem setTag:(NSInteger)mePtr]; + [menuItem setTag:(NSInteger) mePtr]; return menuItem; } @end @@ -252,15 +252,16 @@ static int ModifierCharWidth(Tk_Font tkfont); */ if ([sender isKindOfClass:[NSMenuItem class]]) { - NSMenuItem *menuItem = (NSMenuItem *)sender; - TkMenu *menuPtr = (TkMenu *)_tkMenu; - TkMenuEntry *mePtr = (TkMenuEntry *)[menuItem tag]; + NSMenuItem *menuItem = (NSMenuItem *) sender; + TkMenu *menuPtr = (TkMenu *) _tkMenu; + TkMenuEntry *mePtr = (TkMenuEntry *) [menuItem tag]; if (menuPtr && mePtr) { Tcl_Interp *interp = menuPtr->interp; - /*Add time for errors to fire if necessary. This is sub-optimal - *but avoids issues with Tcl/Cocoa event loop integration. + /* + * Add time for errors to fire if necessary. This is sub-optimal + * but avoids issues with Tcl/Cocoa event loop integration. */ //Tcl_Sleep(100); @@ -305,8 +306,8 @@ static int ModifierCharWidth(Tk_Font tkfont); return NO; } else if (modifiers == (NSControlKeyMask | NSShiftKeyMask) && [event keyCode] == 48) { - - /* Starting with OSX 10.12 Control-Tab and Control-Shift-Tab are used + /* + * Starting with OSX 10.12 Control-Tab and Control-Shift-Tab are used * to select window tabs. But for some even more mysterious reason the * Control-Shift-Tab event has character 0x19 = NSBackTabCharacter * rather than 0x09 = NSTabCharacter. At the same time, the @@ -317,7 +318,6 @@ static int ModifierCharWidth(Tk_Font tkfont); key = @"\t"; } else if (([event modifierFlags] & NSCommandKeyMask) == NSCommandKeyMask) { - /* * If the command modifier is set, use the full character string so * things like the dvorak / qwerty layout will work. @@ -650,7 +650,7 @@ TkpConfigureMenuEntry( gc->foreground!=defaultFg? gc->foreground:gc->background); attributes = [[attributes mutableCopy] autorelease]; - [(NSMutableDictionary *)attributes setObject:color + [(NSMutableDictionary *) attributes setObject:color forKey:NSForegroundColorAttributeName]; } if (attributes) { @@ -690,21 +690,26 @@ TkpConfigureMenuEntry( [submenu setTitle:title]; if ([menuItem isEnabled]) { - /* This menuItem might have been previously disabled (XXX: - track this), which would have disabled entries; we must - re-enable the entries here. */ - int i = 0; - NSArray *itemArray = [submenu itemArray]; - for (NSMenuItem *item in itemArray) { - TkMenuEntry *submePtr = menuRefPtr->menuPtr->entries[i]; - /* Work around an apparent bug where itemArray can have - more items than the menu's entries[] array. */ - if (i >= menuRefPtr->menuPtr->numEntries) break; - [item setEnabled: !(submePtr->state == ENTRY_DISABLED)]; - i++; - } + + /* This menuItem might have been previously disabled (XXX: + * track this), which would have disabled entries; we must + * re-enable the entries here. + */ + + int i = 0; + NSArray *itemArray = [submenu itemArray]; + for (NSMenuItem *item in itemArray) { + TkMenuEntry *submePtr = menuRefPtr->menuPtr->entries[i]; + + /* Work around an apparent bug where itemArray can have + * more items than the menu's entries[] array. + */ + + if (i >= menuRefPtr->menuPtr->numEntries) break; + [item setEnabled: !(submePtr->state == ENTRY_DISABLED)]; + i++; + } } - } } } @@ -755,10 +760,10 @@ TkpDestroyMenuEntry( * * TkpPostMenu -- * - * Posts a menu on the screen. If entry is < 0 then the menu is - * drawn so its top left corner is located at the point with - * screen coordinates (x, y). Otherwise the top left corner of - * the specified entry is located at that point. + * Posts a menu on the screen. If entry is < 0 then the menu is drawn so + * its top left corner is located at the point with screen coordinates + * (x,y). Otherwise the top left corner of the specified entry is located + * at that point. * * Results: * Returns a standard Tcl result. @@ -828,13 +833,13 @@ TkpPostMenu( * * TkpPostTearoffMenu -- * - * Tearoff menus are not supported on the Mac. This placeholder - * function, which is simply a copy of the unix function, posts a - * completely useless window with a black background on the screen. If - * entry is < 0 then the window is positioned so that its top left corner - * is located at the point with screen coordinates (x, y). Otherwise the - * window position is offset so that top left corner of the specified - * entry would be located at that point, if there actually were a menu. + * Tearoff menus are not supported on the Mac. This placeholder function, + * which is simply a copy of the unix function, posts a completely useless + * window with a black background on the screen. If entry is < 0 then the + * window is positioned so that its top left corner is located at the + * point with screen coordinates (x, y). Otherwise the window position is + * offset so that top left corner of the specified entry would be located + * at that point, if there actually were a menu. * * Mac menus steal all mouse or keyboard input from the application until * the menu is dismissed, with or without a selection, by a mouse or key @@ -862,7 +867,7 @@ TkpPostTearoffMenu( int vRootX, vRootY, vRootWidth, vRootHeight; int result; - if (index >= menuPtr->numEntries) { + if (index >= (int) menuPtr->numEntries) { index = menuPtr->numEntries - 1; } if (index >= 0) { @@ -960,12 +965,12 @@ TkpSetWindowMenuBar( * * TkpSetMainMenubar -- * - * Puts the menu associated with a window into the menubar. Should only - * be called when the window is in front. + * Puts the menu associated with a window into the menubar. Should only be + * called when the window is in front. * * This is a no-op on all other platforms. On OS X it is a no-op when - * passed a NULL menuName or a nonexistent menuName, with an exception - * for the first call in a new interpreter. In that special case, passing a + * passed a NULL menuName or a nonexistent menuName, with an exception for + * the first call in a new interpreter. In that special case, passing a * NULL menuName installs the default menu. * * Results: @@ -993,11 +998,12 @@ TkpSetMainMenubar( */ if (Tk_IsEmbedded(winPtr)) { - return; - } + return; + } if (menuName) { Tk_Window menubar = NULL; + if (winPtr->wmInfoPtr && winPtr->wmInfoPtr->menuPtr && winPtr->wmInfoPtr->menuPtr->masterMenuPtr) { @@ -1005,7 +1011,8 @@ TkpSetMainMenubar( } /* - * Attempt to find the NSMenu directly. If that fails, ask Tk to find it. + * Attempt to find the NSMenu directly. If that fails, ask Tk to find + * it. */ if (menubar != NULL && strcmp(menuName, Tk_PathName(menubar)) == 0) { @@ -1013,6 +1020,7 @@ TkpSetMainMenubar( } else { TkMenuReferences *menuRefPtr = TkFindMenuReferences(interp, menuName); + if (menuRefPtr && menuRefPtr->menuPtr && menuRefPtr->menuPtr->platformData) { menu = (TKMenu *) menuRefPtr->menuPtr->platformData; @@ -1021,9 +1029,8 @@ TkpSetMainMenubar( } /* - * If we couldn't find a menu, do nothing unless the window belongs - * to a different application. In that case, install the default - * menubar. + * If we couldn't find a menu, do nothing unless the window belongs to a + * different application. In that case, install the default menubar. */ if (menu || interp != currentInterp) { @@ -1038,8 +1045,8 @@ TkpSetMainMenubar( * CheckForSpecialMenu -- * * Given a menu, check to see whether or not it is a cascade in a menubar - * with one of the special names ".apple", ".help" or ".window". If it - * is, the entry that points to this menu will be marked. + * with one of the special names ".apple", ".help" or ".window". If it is, + * the entry that points to this menu will be marked. * * Results: * None. @@ -1230,11 +1237,12 @@ TkpComputeStandardMenuGeometry( /* * Do nothing if this menu is a clone. */ + if (menuPtr->tkwin == NULL || menuPtr->masterMenuPtr != menuPtr) { return; } - menuSize = [(NSMenu *)menuPtr->platformData size]; + menuSize = [(NSMenu *) menuPtr->platformData size]; Tk_GetPixelsFromObj(NULL, menuPtr->tkwin, menuPtr->borderWidthPtr, &borderWidth); Tk_GetPixelsFromObj(NULL, menuPtr->tkwin, menuPtr->activeBorderWidthPtr, @@ -1248,16 +1256,16 @@ TkpComputeStandardMenuGeometry( * want to do it intelligently. We are going to precalculate them and pass * them down to all of the measuring and drawing routines. We will measure * the font metrics of the menu once. If an entry does not have its own - * font set, then we give the geometry/drawing routines the menu's font - * and metrics. If an entry has its own font, we will measure that font - * and give all of the geometry/drawing the entry's font and metrics. + * font set, then we give the geometry/drawing routines the menu's font and + * metrics. If an entry has its own font, we will measure that font and + * give all of the geometry/drawing the entry's font and metrics. */ menuFont = Tk_GetFontFromObj(menuPtr->tkwin, menuPtr->fontPtr); Tk_GetFontMetrics(menuFont, &menuMetrics); menuModifierCharWidth = ModifierCharWidth(menuFont); - for (i = 0; i < menuPtr->numEntries; i++) { + for (i = 0; i < (int) menuPtr->numEntries; i++) { mePtr = menuPtr->entries[i]; if (mePtr->type == CASCADE_ENTRY || mePtr->accelLength > 0) { haveAccel = 1; @@ -1265,7 +1273,7 @@ TkpComputeStandardMenuGeometry( } } - for (i = 0; i < menuPtr->numEntries; i++) { + for (i = 0; i < (int) menuPtr->numEntries; i++) { mePtr = menuPtr->entries[i]; if (mePtr->type == TEAROFF_ENTRY) { continue; @@ -1295,6 +1303,7 @@ TkpComputeStandardMenuGeometry( NSMenuItem *menuItem = (NSMenuItem *) mePtr->platformEntryData; int haveImage = 0, width = 0, height = 0; + if (mePtr->image) { Tk_SizeOfImage(mePtr->image, &width, &height); haveImage = 1; @@ -1302,6 +1311,7 @@ TkpComputeStandardMenuGeometry( } else if (mePtr->bitmapPtr) { Pixmap bitmap = Tk_GetBitmapFromObj(menuPtr->tkwin, mePtr->bitmapPtr); + Tk_SizeOfBitmap(menuPtr->display, bitmap, &width, &height); haveImage = 1; height += 2; /* tweak */ @@ -1413,7 +1423,7 @@ GenerateMenuSelectEvent( if (menuPtr) { int index = [menu tkIndexOfItem:menuItem]; - if (index < 0 || index >= menuPtr->numEntries || + if (index < 0 || index >= (int) menuPtr->numEntries || (menuPtr->entries[index])->state == ENTRY_DISABLED) { TkActivateMenuEntry(menuPtr, -1); } else { @@ -1492,7 +1502,7 @@ RecursivelyClearActiveMenu( int i; TkActivateMenuEntry(menuPtr, -1); - for (i = 0; i < menuPtr->numEntries; i++) { + for (i = 0; i < (int) menuPtr->numEntries; i++) { TkMenuEntry *mePtr = menuPtr->entries[i]; if (mePtr->type == CASCADE_ENTRY @@ -1781,7 +1791,7 @@ TkMacOSXPreprocessMenu(void) * TkMacOSXUseID -- * * Take the ID out of the available list for new menus. Used by the - * default menu bar's menus so that they do not get created at the tk + * default menu bar's menus so that they do not get created at the Tk * level. See TkMacOSXGetNewMenuID for more information. * * Results: @@ -1806,8 +1816,7 @@ TkMacOSXUseMenuID( * * TkMacOSXDispatchMenuEvent -- * - * Given a menu id and an item, dispatches the command associated with - * it. + * Given a menu id and an item, dispatches the command associated with it. * * Results: * None. @@ -1857,9 +1866,10 @@ TkMacOSXHandleTearoffMenu(void) * * TkMacOSXSetHelpMenuItemCount -- * - * Has to be called after the first call to InsertMenu. Sets up the - * global variable for the number of items in the unmodified help menu. - * NB. Nobody uses this any more, since you can get the number of system + * Has to be called after the first call to InsertMenu. Sets up the global + * variable for the number of items in the unmodified help menu. + * + * NB: Nobody uses this any more, since you can get the number of system * help items from HMGetHelpMenu trivially. But it is in the stubs * table... * diff --git a/macosx/tkMacOSXMenubutton.c b/macosx/tkMacOSXMenubutton.c index b2b4b76..33ae213 100644 --- a/macosx/tkMacOSXMenubutton.c +++ b/macosx/tkMacOSXMenubutton.c @@ -1,8 +1,8 @@ /* * tkMacOSXMenubutton.c -- * - * This file implements the Macintosh specific portion of the - * menubutton widget. + * This file implements the Macintosh specific portion of the menubutton + * widget. * * Copyright (c) 1996 by Sun Microsystems, Inc. * Copyright 2001, Apple Computer, Inc. @@ -32,7 +32,6 @@ typedef struct { int hasImageOrBitmap; } DrawParams; - /* * Declaration of Mac specific button structure. */ @@ -50,21 +49,24 @@ typedef struct MacMenuButton { * Forward declarations for static functions defined later in this file: */ -static void MenuButtonEventProc(ClientData clientData, XEvent *eventPtr); -static void MenuButtonBackgroundDrawCB (MacMenuButton *ptr, SInt16 depth, - Boolean isColorDev); -static void MenuButtonContentDrawCB (ThemeButtonKind kind, - const HIThemeButtonDrawInfo * info, - MacMenuButton *ptr, SInt16 depth, - Boolean isColorDev); -static void MenuButtonEventProc ( ClientData clientData, XEvent *eventPtr); -static void TkMacOSXComputeMenuButtonParams (TkMenuButton * butPtr, - ThemeButtonKind* btnkind, - HIThemeButtonDrawInfo* drawinfo); -static void TkMacOSXComputeMenuButtonDrawParams (TkMenuButton * butPtr, - DrawParams * dpPtr); -static void TkMacOSXDrawMenuButton (MacMenuButton *butPtr, GC gc, Pixmap pixmap); -static void DrawMenuButtonImageAndText(TkMenuButton* butPtr); +static void MenuButtonEventProc(ClientData clientData, + XEvent *eventPtr); +static void MenuButtonBackgroundDrawCB(MacMenuButton *ptr, + SInt16 depth, Boolean isColorDev); +static void MenuButtonContentDrawCB(ThemeButtonKind kind, + const HIThemeButtonDrawInfo *info, + MacMenuButton *ptr, SInt16 depth, + Boolean isColorDev); +static void MenuButtonEventProc(ClientData clientData, + XEvent *eventPtr); +static void TkMacOSXComputeMenuButtonParams(TkMenuButton *butPtr, + ThemeButtonKind *btnkind, + HIThemeButtonDrawInfo *drawinfo); +static void TkMacOSXComputeMenuButtonDrawParams( + TkMenuButton *butPtr, DrawParams *dpPtr); +static void TkMacOSXDrawMenuButton(MacMenuButton *butPtr, GC gc, + Pixmap pixmap); +static void DrawMenuButtonImageAndText(TkMenuButton *butPtr); /* * The structure below defines menubutton class behavior by means of @@ -133,8 +135,7 @@ TkpCreateMenuButton( { MacMenuButton *mbPtr = (MacMenuButton *) ckalloc(sizeof(MacMenuButton)); - Tk_CreateEventHandler(tkwin, ActivateMask, MenuButtonEventProc, - (ClientData) mbPtr); + Tk_CreateEventHandler(tkwin, ActivateMask, MenuButtonEventProc, mbPtr); mbPtr->flags = FIRST_DRAW; mbPtr->btnkind = kThemePopupButton; bzero(&mbPtr->drawinfo, sizeof(mbPtr->drawinfo)); @@ -153,8 +154,7 @@ TkpCreateMenuButton( * None. * * Side effects: - * Commands are output to X to display the menubutton in its - * current mode. + * Commands are output to X to display the menubutton in its current mode. * *---------------------------------------------------------------------- */ @@ -163,11 +163,11 @@ void TkpDisplayMenuButton( ClientData clientData) /* Information about widget. */ { - MacMenuButton *mbPtr = (MacMenuButton *)clientData; - TkMenuButton *butPtr = (TkMenuButton *) clientData; - Tk_Window tkwin = butPtr->tkwin; + MacMenuButton *mbPtr = clientData; + TkMenuButton *butPtr = clientData; + Tk_Window tkwin = butPtr->tkwin; Pixmap pixmap; - DrawParams* dpPtr = &mbPtr->drawParams; + DrawParams *dpPtr = &mbPtr->drawParams; butPtr->flags &= ~REDRAW_PENDING; if ((butPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) { @@ -179,22 +179,26 @@ TkpDisplayMenuButton( TkMacOSXComputeMenuButtonDrawParams(butPtr, dpPtr); /* - * set up clipping region. Make sure the we are using the port - * for this button, or we will set the wrong window's clip. + * Set up clipping region. Make sure the we are using the port for this + * button, or we will set the wrong window's clip. */ TkMacOSXSetUpClippingRgn(pixmap); - /* Draw the native portion of the buttons. */ + /* + * Draw the native portion of the buttons. + */ + TkMacOSXDrawMenuButton(mbPtr, dpPtr->gc, pixmap); - /* Draw highlight border, if needed. */ - if (butPtr->highlightWidth < 3) { - if ((butPtr->flags & GOT_FOCUS)) { - Tk_Draw3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0, + /* + * Draw highlight border, if needed. + */ + + if ((butPtr->highlightWidth < 3) && (butPtr->flags & GOT_FOCUS)) { + Tk_Draw3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0, Tk_Width(tkwin), Tk_Height(tkwin), butPtr->highlightWidth, TK_RELIEF_SOLID); - } } } @@ -203,8 +207,8 @@ TkpDisplayMenuButton( * * TkpDestroyMenuButton -- * - * Free data structures associated with the menubutton control. - * This is a no-op on the Mac. + * Free data structures associated with the menubutton control. This is a + * no-op on the Mac. * * Results: * None. @@ -279,44 +283,42 @@ TkpComputeMenuButtonGeometry(butPtr) } /* - * If the button is compound (ie, it shows both an image and text), - * the new geometry is a combination of the image and text geometry. - * We only honor the compound bit if the button has both text and an - * image, because otherwise it is not really a compound button. + * If the button is compound (ie, it shows both an image and text), the new + * geometry is a combination of the image and text geometry. We only honor + * the compound bit if the button has both text and an image, because + * otherwise it is not really a compound button. */ if (haveImage && haveText) { switch ((enum compound) butPtr->compound) { - case COMPOUND_TOP: - case COMPOUND_BOTTOM: { - /* - * Image is above or below text - */ - - height += txtHeight + butPtr->padY; - width = (width > txtWidth ? width : txtWidth); - break; - } - case COMPOUND_LEFT: - case COMPOUND_RIGHT: { - /* - * Image is left or right of text - */ - - width += txtWidth + butPtr->padX; - height = (height > txtHeight ? height : txtHeight); - break; - } - case COMPOUND_CENTER: { - /* - * Image and text are superimposed - */ - - width = (width > txtWidth ? width : txtWidth); - height = (height > txtHeight ? height : txtHeight); - break; - } - case COMPOUND_NONE: {break;} + case COMPOUND_TOP: + case COMPOUND_BOTTOM: + /* + * Image is above or below text + */ + + height += txtHeight + butPtr->padY; + width = (width > txtWidth ? width : txtWidth); + break; + case COMPOUND_LEFT: + case COMPOUND_RIGHT: + /* + * Image is left or right of text + */ + + width += txtWidth + butPtr->padX; + height = (height > txtHeight ? height : txtHeight); + break; + case COMPOUND_CENTER: + /* + * Image and text are superimposed + */ + + width = (width > txtWidth ? width : txtWidth); + height = (height > txtHeight ? height : txtHeight); + break; + case COMPOUND_NONE: + break; } if (butPtr->width > 0) { @@ -371,32 +373,24 @@ TkpComputeMenuButtonGeometry(butPtr) */ void DrawMenuButtonImageAndText( - TkMenuButton* butPtr) + TkMenuButton *butPtr) { - MacMenuButton *mbPtr = (MacMenuButton*)butPtr; - Tk_Window tkwin = butPtr->tkwin; - Pixmap pixmap; - int haveImage = 0; - int haveText = 0; - int imageWidth = 0; - int imageHeight = 0; - int imageXOffset = 0; - int imageYOffset = 0; - int textXOffset = 0; - int textYOffset = 0; - int width = 0; - int height = 0; - int fullWidth = 0; - int fullHeight = 0; - int pressed; + MacMenuButton *mbPtr = (MacMenuButton *) butPtr; + Tk_Window tkwin = butPtr->tkwin; + Pixmap pixmap; + int haveImage = 0, haveText = 0; + int imageWidth = 0, imageHeight = 0; + int imageXOffset = 0, imageYOffset = 0; + int textXOffset = 0, textYOffset = 0; + int width = 0, height = 0; + int fullWidth = 0, fullHeight = 0; if (tkwin == NULL || !Tk_IsMapped(tkwin)) { return; } - DrawParams* dpPtr = &mbPtr->drawParams; - pixmap = (Pixmap)Tk_WindowId(tkwin); - + DrawParams *dpPtr = &mbPtr->drawParams; + pixmap = (Pixmap) Tk_WindowId(tkwin); if (butPtr->image != None) { Tk_SizeOfImage(butPtr->image, &width, &height); @@ -406,86 +400,80 @@ DrawMenuButtonImageAndText( haveImage = 1; } - imageWidth = width; + imageWidth = width; imageHeight = height; - if (mbPtr->drawinfo.state == kThemeStatePressed) { - /* Offset bitmaps by a bit when the button is pressed. */ - pressed = 1; - } - haveText = (butPtr->textWidth != 0 && butPtr->textHeight != 0); if (butPtr->compound != COMPOUND_NONE && haveImage && haveText) { - int x = 0; - int y = 0; + int x = 0, y = 0; + textXOffset = 0; textYOffset = 0; fullWidth = 0; fullHeight = 0; switch ((enum compound) butPtr->compound) { - case COMPOUND_TOP: - case COMPOUND_BOTTOM: { - /* Image is above or below text */ - if (butPtr->compound == COMPOUND_TOP) { - textYOffset = height + butPtr->padY; - } else { - imageYOffset = butPtr->textHeight + butPtr->padY; - } - fullHeight = height + butPtr->textHeight + butPtr->padY; - fullWidth = (width > butPtr->textWidth ? - width : butPtr->textWidth); - textXOffset = (fullWidth - butPtr->textWidth)/2; - imageXOffset = (fullWidth - width)/2; - break; - } - case COMPOUND_LEFT: - case COMPOUND_RIGHT: { - /* - * Image is left or right of text - */ - - if (butPtr->compound == COMPOUND_LEFT) { - textXOffset = width + butPtr->padX - 2; - } else { - imageXOffset = butPtr->textWidth + butPtr->padX; - } - fullWidth = butPtr->textWidth + butPtr->padX + width; - fullHeight = (height > butPtr->textHeight ? height : - butPtr->textHeight); - textYOffset = (fullHeight - butPtr->textHeight)/2; - imageYOffset = (fullHeight - height)/2; - break; - } - case COMPOUND_CENTER: { - /* - * Image and text are superimposed - */ - - fullWidth = (width > butPtr->textWidth ? width : - butPtr->textWidth); - fullHeight = (height > butPtr->textHeight ? height : - butPtr->textHeight); - textXOffset = (fullWidth - butPtr->textWidth)/2; - imageXOffset = (fullWidth - width)/2; - textYOffset = (fullHeight - butPtr->textHeight)/2; - imageYOffset = (fullHeight - height)/2; - break; - } - case COMPOUND_NONE: {break;} + case COMPOUND_TOP: + case COMPOUND_BOTTOM: + /* + * Image is above or below text. + */ + + if (butPtr->compound == COMPOUND_TOP) { + textYOffset = height + butPtr->padY; + } else { + imageYOffset = butPtr->textHeight + butPtr->padY; + } + fullHeight = height + butPtr->textHeight + butPtr->padY; + fullWidth = (width > butPtr->textWidth ? + width : butPtr->textWidth); + textXOffset = (fullWidth - butPtr->textWidth)/2; + imageXOffset = (fullWidth - width)/2; + break; + case COMPOUND_LEFT: + case COMPOUND_RIGHT: + /* + * Image is left or right of text + */ + + if (butPtr->compound == COMPOUND_LEFT) { + textXOffset = width + butPtr->padX - 2; + } else { + imageXOffset = butPtr->textWidth + butPtr->padX; + } + fullWidth = butPtr->textWidth + butPtr->padX + width; + fullHeight = (height > butPtr->textHeight ? height : + butPtr->textHeight); + textYOffset = (fullHeight - butPtr->textHeight)/2; + imageYOffset = (fullHeight - height)/2; + break; + case COMPOUND_CENTER: + /* + * Image and text are superimposed + */ + + fullWidth = (width > butPtr->textWidth ? width : butPtr->textWidth); + fullHeight = (height > butPtr->textHeight ? height : + butPtr->textHeight); + textXOffset = (fullWidth - butPtr->textWidth) / 2; + imageXOffset = (fullWidth - width) / 2; + textYOffset = (fullHeight - butPtr->textHeight) / 2; + imageYOffset = (fullHeight - height) / 2; + break; + case COMPOUND_NONE: + break; } TkComputeAnchor(butPtr->anchor, tkwin, - butPtr->padX + butPtr->inset, - butPtr->padY + butPtr->inset, + butPtr->padX + butPtr->inset, butPtr->padY + butPtr->inset, fullWidth, fullHeight, &x, &y); imageXOffset = LEFT_INSET; imageYOffset += y; textYOffset -= 1; if (butPtr->image != NULL) { - Tk_RedrawImage(butPtr->image, 0, 0, width, - height, pixmap, imageXOffset, imageYOffset); + Tk_RedrawImage(butPtr->image, 0, 0, width, + height, pixmap, imageXOffset, imageYOffset); } else { XSetClipOrigin(butPtr->display, dpPtr->gc, imageXOffset, imageYOffset); @@ -499,12 +487,12 @@ DrawMenuButtonImageAndText( dpPtr->gc, butPtr->textLayout, x + textXOffset, y + textYOffset, 0, -1); Tk_UnderlineTextLayout(butPtr->display, pixmap, dpPtr->gc, - butPtr->textLayout, - x + textXOffset, y + textYOffset, + butPtr->textLayout, x + textXOffset, y + textYOffset, butPtr->underline); } else { + int x, y; + if (haveImage) { - int x, y; TkComputeAnchor(butPtr->anchor, tkwin, butPtr->padX + butPtr->borderWidth, butPtr->padY + butPtr->borderWidth, @@ -524,27 +512,24 @@ DrawMenuButtonImageAndText( XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0); } } else { - int x, y; textXOffset = LEFT_INSET; TkComputeAnchor(butPtr->anchor, tkwin, butPtr->padX, butPtr->padY, - butPtr->textWidth, butPtr->textHeight, &x, &y); + butPtr->textWidth, butPtr->textHeight, &x, &y); Tk_DrawTextLayout(butPtr->display, pixmap, dpPtr->gc, - butPtr->textLayout, textXOffset, y, 0, -1); + butPtr->textLayout, textXOffset, y, 0, -1); y += butPtr->textHeight/2; - } + } } } - - - + /* *-------------------------------------------------------------- * * TkMacOSXDrawMenuButton -- * - * This function draws the tk menubutton using Mac controls - * In addition, this code may apply custom colors passed - * in the TkMenubutton. + * This function draws the tk menubutton using Mac controls. In + * addition, this code may apply custom colors passed in the + * TkMenubutton. * * Results: * None. @@ -554,43 +539,39 @@ DrawMenuButtonImageAndText( * *-------------------------------------------------------------- */ + static void TkMacOSXDrawMenuButton( MacMenuButton *mbPtr, /* Mac menubutton. */ - GC gc, /* The GC we are drawing into - needed for - * the bevel button */ - Pixmap pixmap) /* The pixmap we are drawing into - needed - * for the bevel button */ + GC gc, /* The GC we are drawing into - needed for the bevel + * button */ + Pixmap pixmap) /* The pixmap we are drawing into - needed for the + * bevel button */ { - TkMenuButton * butPtr = ( TkMenuButton *)mbPtr; - TkWindow * winPtr; - HIRect cntrRect; + TkMenuButton *butPtr = (TkMenuButton *) mbPtr; + TkWindow *winPtr = (TkWindow *) butPtr->tkwin; + HIRect cntrRect; TkMacOSXDrawingContext dc; - DrawParams* dpPtr = &mbPtr->drawParams; + DrawParams *dpPtr = &mbPtr->drawParams; int useNewerHITools = 1; - winPtr = (TkWindow *)butPtr->tkwin; - TkMacOSXComputeMenuButtonParams(butPtr, &mbPtr->btnkind, &mbPtr->drawinfo); cntrRect = CGRectMake(winPtr->privatePtr->xOff, winPtr->privatePtr->yOff, - Tk_Width(butPtr->tkwin), - Tk_Height(butPtr->tkwin)); + Tk_Width(butPtr->tkwin), Tk_Height(butPtr->tkwin)); if (useNewerHITools == 1) { HIRect contHIRec; static HIThemeButtonDrawInfo hiinfo; - MenuButtonBackgroundDrawCB((MacMenuButton*) mbPtr, 32, true); - + MenuButtonBackgroundDrawCB(mbPtr, 32, true); if (!TkMacOSXSetupDrawingContext(pixmap, dpPtr->gc, 1, &dc)) { return; } - hiinfo.version = 0; hiinfo.state = mbPtr->drawinfo.state; - hiinfo.kind = mbPtr->btnkind; + hiinfo.kind = mbPtr->btnkind; hiinfo.value = mbPtr->drawinfo.value; hiinfo.adornment = mbPtr->drawinfo.adornment; hiinfo.animation.time.current = CFAbsoluteTimeGetCurrent(); @@ -599,10 +580,10 @@ TkMacOSXDrawMenuButton( } HIThemeDrawButton(&cntrRect, &hiinfo, dc.context, - kHIThemeOrientationNormal, &contHIRec); + kHIThemeOrientationNormal, &contHIRec); TkMacOSXRestoreDrawingContext(&dc); - MenuButtonContentDrawCB( mbPtr->btnkind, &mbPtr->drawinfo, - (MacMenuButton *)mbPtr, 32, true); + MenuButtonContentDrawCB(mbPtr->btnkind, &mbPtr->drawinfo, + mbPtr, 32, true); } else { if (!TkMacOSXSetupDrawingContext(pixmap, dpPtr->gc, 1, &dc)) { return; @@ -617,33 +598,34 @@ TkMacOSXDrawMenuButton( * * MenuButtonBackgroundDrawCB -- * - * This function draws the background that - * lies under checkboxes and radiobuttons. + * This function draws the background that lies under checkboxes and + * radiobuttons. * * Results: - * None. + * None. * * Side effects: - * The background gets updated to the current color. + * The background gets updated to the current color. * *-------------------------------------------------------------- */ + static void MenuButtonBackgroundDrawCB ( MacMenuButton *ptr, SInt16 depth, Boolean isColorDev) { - TkMenuButton* butPtr = (TkMenuButton*)ptr; - Tk_Window tkwin = butPtr->tkwin; + TkMenuButton* butPtr = (TkMenuButton *) ptr; + Tk_Window tkwin = butPtr->tkwin; Pixmap pixmap; + if (tkwin == NULL || !Tk_IsMapped(tkwin)) { return; } - pixmap = (Pixmap)Tk_WindowId(tkwin); - + pixmap = (Pixmap) Tk_WindowId(tkwin); Tk_Fill3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0, - Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT); + Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT); } /* @@ -651,16 +633,17 @@ MenuButtonBackgroundDrawCB ( * * MenuButtonContentDrawCB -- * - * This function draws the label and image for the button. + * This function draws the label and image for the button. * * Results: - * None. + * None. * * Side effects: - * The content of the button gets updated. + * The content of the button gets updated. * *-------------------------------------------------------------- */ + static void MenuButtonContentDrawCB ( ThemeButtonKind kind, @@ -669,8 +652,8 @@ MenuButtonContentDrawCB ( SInt16 depth, Boolean isColorDev) { - TkMenuButton *butPtr = (TkMenuButton *)ptr; - Tk_Window tkwin = butPtr->tkwin; + TkMenuButton *butPtr = (TkMenuButton *) ptr; + Tk_Window tkwin = butPtr->tkwin; if (tkwin == NULL || !Tk_IsMapped(tkwin)) { return; @@ -683,8 +666,8 @@ MenuButtonContentDrawCB ( * * MenuButtonEventProc -- * - * This procedure is invoked by the Tk dispatcher for various - * events on buttons. + * This procedure is invoked by the Tk dispatcher for various events on + * buttons. * * Results: * None. @@ -700,8 +683,8 @@ MenuButtonEventProc( ClientData clientData, /* Information about window. */ XEvent *eventPtr) /* Information about event. */ { - TkMenuButton *buttonPtr = (TkMenuButton *) clientData; - MacMenuButton *mbPtr = (MacMenuButton *) clientData; + TkMenuButton *buttonPtr = clientData; + MacMenuButton *mbPtr = clientData; if (eventPtr->type == ActivateNotify || eventPtr->type == DeactivateNotify) { @@ -725,9 +708,9 @@ MenuButtonEventProc( * * TkMacOSXComputeMenuButtonParams -- * - * This procedure computes the various parameters used - * when creating a Carbon Appearance control. - * These are determined by the various tk button parameters + * This procedure computes the various parameters used when creating a + * Carbon Appearance control. These are determined by the various Tk + * button parameters * * Results: * None. @@ -740,11 +723,11 @@ MenuButtonEventProc( static void TkMacOSXComputeMenuButtonParams( - TkMenuButton * butPtr, - ThemeButtonKind* btnkind, + TkMenuButton *butPtr, + ThemeButtonKind *btnkind, HIThemeButtonDrawInfo *drawinfo) { - MacMenuButton *mbPtr = (MacMenuButton *)butPtr; + MacMenuButton *mbPtr = (MacMenuButton *) butPtr; if (butPtr->image || butPtr->bitmap || butPtr->text) { /* TODO: allow for Small and Mini menubuttons. */ @@ -789,25 +772,25 @@ TkMacOSXComputeMenuButtonParams( * * TkMacOSXComputeMenuButtonDrawParams -- * - * This procedure selects an appropriate drawing context for - * drawing a menubutton. + * This procedure selects an appropriate drawing context for drawing a + * menubutton. * * Results: - * None. + * None. * * Side effects: - * Sets the button draw parameters. + * Sets the button draw parameters. * *---------------------------------------------------------------------- */ static void TkMacOSXComputeMenuButtonDrawParams( - TkMenuButton * butPtr, - DrawParams * dpPtr) + TkMenuButton *butPtr, + DrawParams *dpPtr) { - dpPtr->hasImageOrBitmap = ((butPtr->image != NULL) || - (butPtr->bitmap != None)); + dpPtr->hasImageOrBitmap = + ((butPtr->image != NULL) || (butPtr->bitmap != None)); dpPtr->border = butPtr->normalBorder; if ((butPtr->state == STATE_DISABLED) && (butPtr->disabledFg != NULL)) { dpPtr->gc = butPtr->disabledGC; @@ -818,7 +801,7 @@ TkMacOSXComputeMenuButtonDrawParams( dpPtr->gc = butPtr->normalTextGC; } } - + /* * Local Variables: * mode: objc diff --git a/macosx/tkMacOSXMenus.c b/macosx/tkMacOSXMenus.c index 7d77d23..5e6a37c 100644 --- a/macosx/tkMacOSXMenus.c +++ b/macosx/tkMacOSXMenus.c @@ -177,7 +177,6 @@ static Tcl_Obj * GetWidgetDemoPath(Tcl_Interp *interp); SEL action = [anItem action]; if (sel_isEqual(action, @selector(preferences:))) { - return (_eventInterp && Tcl_FindCommand(_eventInterp, "::tk::mac::ShowPreferences", NULL, 0)); } else if (sel_isEqual(action, @selector(tkDemo:))) { diff --git a/macosx/tkMacOSXNotify.c b/macosx/tkMacOSXNotify.c index 3a32527..7267b00 100644 --- a/macosx/tkMacOSXNotify.c +++ b/macosx/tkMacOSXNotify.c @@ -33,7 +33,7 @@ static void TkMacOSXEventsSetupProc(ClientData clientData, int flags); static void TkMacOSXEventsCheckProc(ClientData clientData, int flags); #ifdef TK_MAC_DEBUG_EVENTS -static char* Tk_EventName[39] = { +static const char *Tk_EventName[39] = { "", "", "KeyPress", /*2*/ @@ -136,8 +136,8 @@ void DebugPrintQueue(void) /* * Since the contentView is the first responder for a Tk Window, it is - * responsible for sending events up the responder chain. We also check - * the pasteboard here. + * responsible for sending events up the responder chain. We also check the + * pasteboard here. */ - (void) sendEvent: (NSEvent *) theEvent { @@ -190,8 +190,8 @@ GetRunLoopMode(NSModalSession modalSession) * * Tk_MacOSXSetupTkNotifier -- * - * This procedure is called during Tk initialization to create - * the event source for TkAqua events. + * This procedure is called during Tk initialization to create the event + * source for TkAqua events. * * Results: * None. @@ -224,8 +224,7 @@ Tk_MacOSXSetupTkNotifier(void) "first [load] of TkAqua has to occur in the main thread!"); } Tcl_CreateEventSource(TkMacOSXEventsSetupProc, - TkMacOSXEventsCheckProc, - NULL); + TkMacOSXEventsCheckProc, NULL); TkCreateExitHandler(TkMacOSXNotifyExitHandler, NULL); Tcl_SetServiceMode(TCL_SERVICE_ALL); TclMacOSXNotifierAddRunLoopMode(NSEventTrackingRunLoopMode); @@ -258,8 +257,7 @@ TkMacOSXNotifyExitHandler( TSD_INIT(); Tcl_DeleteEventSource(TkMacOSXEventsSetupProc, - TkMacOSXEventsCheckProc, - NULL); + TkMacOSXEventsCheckProc, NULL); tsdPtr->initialized = 0; } @@ -268,19 +266,19 @@ TkMacOSXNotifyExitHandler( * * TkMacOSXEventsSetupProc -- * - * This procedure implements the setup part of the MacOSX event - * source. It is invoked by Tcl_DoOneEvent before calling - * TkMacOSXEventsProc to process all queued NSEvents. In our - * case, all we need to do is to set the Tcl MaxBlockTime to - * 0 before starting the loop to process all queued NSEvents. + * This procedure implements the setup part of the MacOSX event source. It + * is invoked by Tcl_DoOneEvent before calling TkMacOSXEventsProc to + * process all queued NSEvents. In our case, all we need to do is to set + * the Tcl MaxBlockTime to 0 before starting the loop to process all + * queued NSEvents. * * Results: * None. * * Side effects: * - * If NSEvents are queued, then the maximum block time will be set - * to 0 to ensure that control returns immediately to Tcl. + * If NSEvents are queued, then the maximum block time will be set to 0 to + * ensure that control returns immediately to Tcl. * *---------------------------------------------------------------------- */ @@ -291,15 +289,24 @@ TkMacOSXEventsSetupProc( int flags) { NSString *runloopMode = [[NSRunLoop currentRunLoop] currentMode]; - /* runloopMode will be nil if we are in a Tcl event loop. */ + + /* + * runloopMode will be nil if we are in a Tcl event loop. + */ + if (flags & TCL_WINDOW_EVENTS && !runloopMode) { static const Tcl_Time zeroBlockTime = { 0, 0 }; [NSApp _resetAutoreleasePool]; - /* Call this with dequeue=NO -- just checking if the queue is empty. */ - NSEvent *currentEvent = [NSApp nextEventMatchingMask:NSAnyEventMask - untilDate:[NSDate distantPast] - inMode:GetRunLoopMode(TkMacOSXGetModalSession()) - dequeue:NO]; + + /* + * Call this with dequeue=NO -- just checking if the queue is empty. + */ + + NSEvent *currentEvent = + [NSApp nextEventMatchingMask:NSAnyEventMask + untilDate:[NSDate distantPast] + inMode:GetRunLoopMode(TkMacOSXGetModalSession()) + dequeue:NO]; if (currentEvent) { if (currentEvent.type > 0) { Tcl_SetMaxBlockTime(&zeroBlockTime); @@ -313,15 +320,15 @@ TkMacOSXEventsSetupProc( * * TkMacOSXEventsCheckProc -- * - * This procedure loops through all NSEvents waiting in the - * TKApplication event queue, generating X events from them. + * This procedure loops through all NSEvents waiting in the TKApplication + * event queue, generating X events from them. * * Results: * None. * * Side effects: - * NSevents are used to generate X events, which are added to the - * Tcl event queue. + * NSevents are used to generate X events, which are added to the Tcl + * event queue. * *---------------------------------------------------------------------- */ @@ -331,34 +338,48 @@ TkMacOSXEventsCheckProc( int flags) { NSString *runloopMode = [[NSRunLoop currentRunLoop] currentMode]; - /* runloopMode will be nil if we are in a Tcl event loop. */ + + /* + * runloopMode will be nil if we are in a Tcl event loop. + */ + if (flags & TCL_WINDOW_EVENTS && !runloopMode) { NSEvent *currentEvent = nil; NSEvent *testEvent = nil; NSModalSession modalSession; - /* It is possible for the SetupProc to be called before this function + + /* + * It is possible for the SetupProc to be called before this function * returns. This happens, for example, when we process an event which * opens a modal window. To prevent premature release of our * application-wide autorelease pool by a nested call to the SetupProc, * we must lock it here. */ + [NSApp _lockAutoreleasePool]; do { modalSession = TkMacOSXGetModalSession(); - testEvent = [NSApp nextEventMatchingMask:NSAnyEventMask - untilDate:[NSDate distantPast] - inMode:GetRunLoopMode(modalSession) - dequeue:NO]; - /* We must not steal any events during LiveResize. */ + testEvent = [NSApp nextEventMatchingMask:NSAnyEventMask + untilDate:[NSDate distantPast] + inMode:GetRunLoopMode(modalSession) + dequeue:NO]; + + /* + * We must not steal any events during LiveResize. + */ + if (testEvent && [[testEvent window] inLiveResize]) { break; } currentEvent = [NSApp nextEventMatchingMask:NSAnyEventMask - untilDate:[NSDate distantPast] - inMode:GetRunLoopMode(modalSession) - dequeue:YES]; + untilDate:[NSDate distantPast] + inMode:GetRunLoopMode(modalSession) + dequeue:YES]; if (currentEvent) { - /* Generate Xevents. */ + /* + * Generate Xevents. + */ + int oldServiceMode = Tcl_SetServiceMode(TCL_SERVICE_ALL); NSEvent *processedEvent = [NSApp tkProcessEvent:currentEvent]; Tcl_SetServiceMode(oldServiceMode); @@ -372,16 +393,18 @@ TkMacOSXEventsCheckProc( [NSApp sendEvent:currentEvent]; } } - } else { break; } } while (1); - /* Now we can unlock the pool. */ + + /* + * Now we can unlock the pool. + */ + [NSApp _unlockAutoreleasePool]; } } - /* * Local Variables: diff --git a/macosx/tkMacOSXRegion.c b/macosx/tkMacOSXRegion.c index 0f2a74a..323318c 100644 --- a/macosx/tkMacOSXRegion.c +++ b/macosx/tkMacOSXRegion.c @@ -187,8 +187,8 @@ TkMacOSXIsEmptyRegion( * Xwindow documentation for more details. * * Results: - * Returns RectanglePart or RectangleOut. Note that this is not a - * complete implementation since it doesn't test for RectangleIn. + * Returns RectanglePart or RectangleOut. Note that this is not a complete + * implementation since it doesn't test for RectangleIn. * * Side effects: * None. @@ -204,13 +204,13 @@ TkRectInRegion( unsigned int width, unsigned int height) { - if ( TkMacOSXIsEmptyRegion(region) ) { - return RectangleOut; - } - else { + if (TkMacOSXIsEmptyRegion(region)) { + return RectangleOut; + } else { const CGRect r = CGRectMake(x, y, width, height); + return HIShapeIntersectsRect((HIShapeRef) region, &r) ? - RectanglePart : RectangleOut; + RectanglePart : RectangleOut; } } @@ -234,7 +234,7 @@ TkRectInRegion( void TkClipBox( TkRegion r, - XRectangle* rect_return) + XRectangle *rect_return) { CGRect rect; diff --git a/macosx/tkMacOSXScale.c b/macosx/tkMacOSXScale.c index 8a6a96b..0195ffb 100644 --- a/macosx/tkMacOSXScale.c +++ b/macosx/tkMacOSXScale.c @@ -51,10 +51,10 @@ static ControlActionUPP scaleActionProc = NULL; /* Pointer to func. */ * Forward declarations for procedures defined later in this file: */ -static void MacScaleEventProc(ClientData clientData, XEvent *eventPtr); -static pascal void ScaleActionProc(ControlRef theControl, - ControlPartCode partCode); - +static void MacScaleEventProc(ClientData clientData, + XEvent *eventPtr); +static pascal void ScaleActionProc(ControlRef theControl, + ControlPartCode partCode); /* *---------------------------------------------------------------------- @@ -84,7 +84,7 @@ TkpCreateScale( } Tk_CreateEventHandler(tkwin, ButtonPressMask, - MacScaleEventProc, (ClientData) macScalePtr); + MacScaleEventProc, macScalePtr); return (TkScale *) macScalePtr; } @@ -125,8 +125,8 @@ TkpDestroyScale( * * TkpDisplayScale -- * - * This procedure is invoked as an idle handler to redisplay - * the contents of a scale widget. + * This procedure is invoked as an idle handler to redisplay the contents + * of a scale widget. * * Results: * None. @@ -141,12 +141,12 @@ void TkpDisplayScale( ClientData clientData) /* Widget record for scale. */ { - TkScale *scalePtr = (TkScale *) clientData; + TkScale *scalePtr = clientData; Tk_Window tkwin = scalePtr->tkwin; Tcl_Interp *interp = scalePtr->interp; int result; char string[TCL_DOUBLE_SPACE]; - MacScale *macScalePtr = (MacScale *) clientData; + MacScale *macScalePtr = clientData; Rect r; WindowRef windowRef; CGrafPtr destPort, savePort; @@ -168,9 +168,9 @@ TkpDisplayScale( * Invoke the scale's command if needed. */ - Tcl_Preserve((ClientData) scalePtr); + Tcl_Preserve(scalePtr); if ((scalePtr->flags & INVOKE_COMMAND) && (scalePtr->command != NULL)) { - Tcl_Preserve((ClientData) interp); + Tcl_Preserve(interp); if (snprintf(string, TCL_DOUBLE_SPACE, scalePtr->format, scalePtr->value) < 0) { string[TCL_DOUBLE_SPACE - 1] = '\0'; @@ -185,19 +185,18 @@ TkpDisplayScale( Tcl_AddErrorInfo(interp, "\n (command executed by scale)"); Tcl_BackgroundException(interp, result); } - Tcl_Release((ClientData) interp); + Tcl_Release(interp); } scalePtr->flags &= ~INVOKE_COMMAND; if (scalePtr->flags & SCALE_DELETED) { - Tcl_Release((ClientData) scalePtr); + Tcl_Release(scalePtr); return; } - Tcl_Release((ClientData) scalePtr); + Tcl_Release(scalePtr); /* - * Now handle the part of redisplay that is the same for - * horizontal and vertical scales: border and traversal - * highlight. + * Now handle the part of redisplay that is the same for horizontal and + * vertical scales: border and traversal highlight. */ if (scalePtr->highlightWidth != 0) { @@ -229,7 +228,7 @@ TkpDisplayScale( #define MAC_OSX_SCROLL_WIDTH 10 if (scalePtr->orient == ORIENT_HORIZONTAL) { - int offset = (Tk_Height(tkwin) - MAC_OSX_SCROLL_WIDTH)/2; + int offset = (Tk_Height(tkwin) - MAC_OSX_SCROLL_WIDTH) / 2; if (offset < 0) { offset = 0; @@ -240,7 +239,7 @@ TkpDisplayScale( r.right = macDraw->xOff+Tk_Width(tkwin) - scalePtr->inset; r.bottom = macDraw->yOff + offset + MAC_OSX_SCROLL_WIDTH/2; } else { - int offset = (Tk_Width(tkwin) - MAC_OSX_SCROLL_WIDTH)/2; + int offset = (Tk_Width(tkwin) - MAC_OSX_SCROLL_WIDTH) / 2; if (offset < 0) { offset = 0; @@ -249,7 +248,7 @@ TkpDisplayScale( r.left = macDraw->xOff + offset; r.top = macDraw->yOff + scalePtr->inset; r.right = macDraw->xOff + offset + MAC_OSX_SCROLL_WIDTH/2; - r.bottom = macDraw->yOff+Tk_Height(tkwin) - scalePtr->inset; + r.bottom = macDraw->yOff + Tk_Height(tkwin) - scalePtr->inset; } if (macScalePtr->scaleHandle == NULL) { @@ -273,7 +272,7 @@ TkpDisplayScale( CreateSliderControl(windowRef, &r, initialValue, minValue, maxValue, kControlSliderPointsDownOrRight, numTicks, 1, scaleActionProc, - &(macScalePtr->scaleHandle)); + &macScalePtr->scaleHandle); SetControlReference(macScalePtr->scaleHandle, (UInt32) scalePtr); if (IsWindowActive(windowRef)) { @@ -290,8 +289,8 @@ TkpDisplayScale( * Finally draw the control. */ - SetControlVisibility(macScalePtr->scaleHandle,true,true); - HiliteControl(macScalePtr->scaleHandle,0); + SetControlVisibility(macScalePtr->scaleHandle, true, true); + HiliteControl(macScalePtr->scaleHandle, 0); Draw1Control(macScalePtr->scaleHandle); if (portChanged) { @@ -306,13 +305,12 @@ done: * * TkpScaleElement -- * - * Determine which part of a scale widget lies under a given - * point. + * Determine which part of a scale widget lies under a given point. * * Results: - * The return value is either TROUGH1, SLIDER, TROUGH2, or - * OTHER, depending on which of the scale's active elements - * (if any) is under the point at (x,y). + * The return value is either TROUGH1, SLIDER, TROUGH2, or OTHER, + * depending on which of the scale's active elements (if any) is under the + * point at (x,y). * * Side effects: * None. @@ -357,22 +355,22 @@ TkpScaleElement( #endif switch (part) { - case inSlider: - return SLIDER; - case inInc: - if (scalePtr->orient == ORIENT_VERTICAL) { - return TROUGH1; - } else { - return TROUGH2; - } - case inDecr: - if (scalePtr->orient == ORIENT_VERTICAL) { - return TROUGH2; - } else { - return TROUGH1; - } - default: - return OTHER; + case inSlider: + return SLIDER; + case inInc: + if (scalePtr->orient == ORIENT_VERTICAL) { + return TROUGH1; + } else { + return TROUGH2; + } + case inDecr: + if (scalePtr->orient == ORIENT_VERTICAL) { + return TROUGH2; + } else { + return TROUGH1; + } + default: + return OTHER; } } @@ -381,15 +379,15 @@ TkpScaleElement( * * MacScaleEventProc -- * - * This procedure is invoked by the Tk dispatcher for - * ButtonPress events on scales. + * This procedure is invoked by the Tk dispatcher for ButtonPress events + * on scales. * * Results: * None. * * Side effects: - * When the window gets deleted, internal structures get - * cleaned up. When it gets exposed, it is redisplayed. + * When the window gets deleted, internal structures get cleaned up. When + * it gets exposed, it is redisplayed. * *-------------------------------------------------------------- */ @@ -411,9 +409,9 @@ MacScaleEventProc( #endif /* - * To call Macintosh control routines we must have the port - * set to the window containing the control. We will then test - * which part of the control was hit and act accordingly. + * To call Macintosh control routines we must have the port set to the + * window containing the control. We will then test which part of the + * control was hit and act accordingly. */ destPort = TkMacOSXGetDrawablePort(Tk_WindowId(macScalePtr->info.tkwin)); @@ -461,8 +459,8 @@ MacScaleEventProc( * ScaleActionProc -- * * Callback procedure used by the Macintosh toolbox call - * HandleControlClick. This call will update the display - * while the scrollbar is being manipulated by the user. + * HandleControlClick. This call will update the display while the + * scrollbar is being manipulated by the user. * * Results: * None. @@ -486,9 +484,9 @@ ScaleActionProc( #endif value = GetControlValue(theControl); TkScaleSetValue(scalePtr, value, 1, 1); - Tcl_Preserve((ClientData) scalePtr); + Tcl_Preserve(scalePtr); TkMacOSXRunTclEventLoop(); - Tcl_Release((ClientData) scalePtr); + Tcl_Release(scalePtr); } #endif diff --git a/macosx/tkMacOSXScrlbr.c b/macosx/tkMacOSXScrlbr.c index 4a108db..06e0a64 100644 --- a/macosx/tkMacOSXScrlbr.c +++ b/macosx/tkMacOSXScrlbr.c @@ -9,6 +9,7 @@ * Copyright (c) 2006-2009 Daniel A. Steffen * Copyright (c) 2015 Kevin Walzer/WordTech Commununications LLC. * Copyright (c) 2018 Marc Culler + * * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. */ @@ -17,7 +18,6 @@ #include "tkScrollbar.h" #include "tkMacOSXPrivate.h" - #define MIN_SCROLLBAR_VALUE 0 /* @@ -27,18 +27,21 @@ #define MIN_SLIDER_LENGTH 5 -/*Borrowed from ttkMacOSXTheme.c to provide appropriate scaling.*/ +/* + * Borrowed from ttkMacOSXTheme.c to provide appropriate scaling. + */ + #ifdef __LP64__ -#define RangeToFactor(maximum) (((double) (INT_MAX >> 1)) / (maximum)) +#define RangeToFactor(maximum) (((double) (INT_MAX >> 1)) / (maximum)) #else -#define RangeToFactor(maximum) (((double) (LONG_MAX >> 1)) / (maximum)) +#define RangeToFactor(maximum) (((double) (LONG_MAX >> 1)) / (maximum)) #endif /* __LP64__ */ /* * Apple reversed the scroll direction with the release of OSX 10.7 Lion. */ -#define SNOW_LEOPARD_STYLE (NSAppKitVersionNumber < 1138) +#define SNOW_LEOPARD_STYLE (NSAppKitVersionNumber < 1138) /* * Declaration of an extended scrollbar structure with Mac specific additions. @@ -50,7 +53,7 @@ typedef struct MacScrollbar { GC copyGC; /* Used for copying from pixmap onto screen. */ Bool buttonDown; /* Is the mouse button down? */ Bool mouseOver; /* Is the pointer over the scrollbar. */ - HIThemeTrackDrawInfo info; /* Controls how the scrollbar is drawn. */ + HIThemeTrackDrawInfo info; /* Controls how the scrollbar is drawn. */ } MacScrollbar; /* Used to initialize a MacScrollbar's info field. */ @@ -69,33 +72,35 @@ HIThemeTrackDrawInfo defaultInfo = { const Tk_ClassProcs tkpScrollbarProcs = { sizeof(Tk_ClassProcs), /* size */ - NULL, /* worldChangedProc */ - NULL, /* createProc */ - NULL /* modalProc */ + NULL, /* worldChangedProc */ + NULL, /* createProc */ + NULL /* modalProc */ }; +/* + * Information on scrollbar layout, metrics, and draw info. + */ -/* Information on scrollbar layout, metrics, and draw info.*/ typedef struct ScrollbarMetrics { SInt32 width, minThumbHeight; int minHeight, topArrowHeight, bottomArrowHeight; NSControlSize controlSize; } ScrollbarMetrics; - static ScrollbarMetrics metrics = { - 15, 54, 26, 14, 14, kControlSizeNormal /* kThemeScrollBarMedium */ + 15, 54, 26, 14, 14, kControlSizeNormal /* kThemeScrollBarMedium */ }; - /* * Declarations of static functions defined later in this file: */ -static void ScrollbarEventProc(ClientData clientData, XEvent *eventPtr); -static int ScrollbarEvent(TkScrollbar *scrollPtr, XEvent *eventPtr); -static void UpdateControlValues(TkScrollbar *scrollPtr); - +static void ScrollbarEventProc(ClientData clientData, + XEvent *eventPtr); +static int ScrollbarEvent(TkScrollbar *scrollPtr, + XEvent *eventPtr); +static void UpdateControlValues(TkScrollbar *scrollPtr); + /* *---------------------------------------------------------------------- * @@ -114,10 +119,9 @@ static void UpdateControlValues(TkScrollbar *scrollPtr); TkScrollbar * TkpCreateScrollbar( - Tk_Window tkwin) + Tk_Window tkwin) { - - MacScrollbar *scrollPtr = (MacScrollbar *)ckalloc(sizeof(MacScrollbar)); + MacScrollbar *scrollPtr = ckalloc(sizeof(MacScrollbar)); scrollPtr->troughGC = NULL; scrollPtr->copyGC = NULL; @@ -125,15 +129,15 @@ TkpCreateScrollbar( scrollPtr->buttonDown = false; Tk_CreateEventHandler(tkwin, - ExposureMask | - StructureNotifyMask | - FocusChangeMask | - ButtonPressMask | - ButtonReleaseMask | - EnterWindowMask | - LeaveWindowMask | - VisibilityChangeMask, - ScrollbarEventProc, scrollPtr); + ExposureMask | + StructureNotifyMask | + FocusChangeMask | + ButtonPressMask | + ButtonReleaseMask | + EnterWindowMask | + LeaveWindowMask | + VisibilityChangeMask, + ScrollbarEventProc, scrollPtr); return (TkScrollbar *) scrollPtr; } @@ -144,8 +148,8 @@ TkpCreateScrollbar( * TkpDisplayScrollbar -- * * This procedure redraws the contents of a scrollbar window. It is - * invoked as a do-when-idle handler, so it only runs when there's - * nothing else for the application to do. + * invoked as a do-when-idle handler, so it only runs when there's nothing + * else for the application to do. * * Results: * None. @@ -158,9 +162,9 @@ TkpCreateScrollbar( void TkpDisplayScrollbar( - ClientData clientData) /* Information about window. */ + ClientData clientData) /* Information about window. */ { - register TkScrollbar *scrollPtr = (TkScrollbar *) clientData; + register TkScrollbar *scrollPtr = clientData; MacScrollbar *msPtr = (MacScrollbar *) scrollPtr; register Tk_Window tkwin = scrollPtr->tkwin; TkWindow *winPtr = (TkWindow *) tkwin; @@ -169,23 +173,31 @@ TkpDisplayScrollbar( scrollPtr->flags &= ~REDRAW_PENDING; if (tkwin == NULL || !Tk_IsMapped(tkwin)) { - return; + return; } - MacDrawable *macWin = (MacDrawable *) winPtr->window; + MacDrawable *macWin = (MacDrawable *) winPtr->window; NSView *view = TkMacOSXDrawableView(macWin); - if (!view || - macWin->flags & TK_DO_NOT_DRAW || - !TkMacOSXSetupDrawingContext((Drawable) macWin, NULL, 1, &dc)) { - return; + + if ((view == NULL) + || (macWin->flags & TK_DO_NOT_DRAW) + || !TkMacOSXSetupDrawingContext((Drawable) macWin, NULL, 1, &dc)) { + return; } CGFloat viewHeight = [view bounds].size.height; - CGAffineTransform t = { .a = 1, .b = 0, .c = 0, .d = -1, .tx = 0, - .ty = viewHeight}; + CGAffineTransform t = { + .a = 1, .b = 0, + .c = 0, .d = -1, + .tx = 0, .ty = viewHeight + }; + CGContextConcatCTM(dc.context, t); - /*Draw a 3D rectangle to provide a base for the native scrollbar.*/ + /* + * Draw a 3D rectangle to provide a base for the native scrollbar. + */ + if (scrollPtr->highlightWidth != 0) { GC fgGC, bgGC; @@ -196,32 +208,37 @@ TkpDisplayScrollbar( fgGC = bgGC; } TkpDrawHighlightBorder(tkwin, fgGC, bgGC, scrollPtr->highlightWidth, - (Pixmap) macWin); + (Pixmap) macWin); } Tk_Draw3DRectangle(tkwin, (Pixmap) macWin, scrollPtr->bgBorder, - scrollPtr->highlightWidth, scrollPtr->highlightWidth, - Tk_Width(tkwin) - 2*scrollPtr->highlightWidth, - Tk_Height(tkwin) - 2*scrollPtr->highlightWidth, - scrollPtr->borderWidth, scrollPtr->relief); + scrollPtr->highlightWidth, scrollPtr->highlightWidth, + Tk_Width(tkwin) - 2*scrollPtr->highlightWidth, + Tk_Height(tkwin) - 2*scrollPtr->highlightWidth, + scrollPtr->borderWidth, scrollPtr->relief); Tk_Fill3DRectangle(tkwin, (Pixmap) macWin, scrollPtr->bgBorder, - scrollPtr->inset, scrollPtr->inset, - Tk_Width(tkwin) - 2*scrollPtr->inset, - Tk_Height(tkwin) - 2*scrollPtr->inset, 0, TK_RELIEF_FLAT); + scrollPtr->inset, scrollPtr->inset, + Tk_Width(tkwin) - 2*scrollPtr->inset, + Tk_Height(tkwin) - 2*scrollPtr->inset, 0, TK_RELIEF_FLAT); + + /* + * Update values and then draw the native scrollbar over the rectangle. + */ - /* Update values and then draw the native scrollbar over the rectangle.*/ UpdateControlValues(scrollPtr); if (SNOW_LEOPARD_STYLE) { - HIThemeDrawTrack (&(msPtr->info), 0, dc.context, kHIThemeOrientationInverted); + HIThemeDrawTrack(&msPtr->info, 0, dc.context, + kHIThemeOrientationInverted); } else { - HIThemeDrawTrack (&(msPtr->info), 0, dc.context, kHIThemeOrientationNormal); + HIThemeDrawTrack(&msPtr->info, 0, dc.context, + kHIThemeOrientationNormal); } TkMacOSXRestoreDrawingContext(&dc); scrollPtr->flags &= ~REDRAW_PENDING; } - + /* *---------------------------------------------------------------------- * @@ -240,44 +257,41 @@ TkpDisplayScrollbar( *---------------------------------------------------------------------- */ - - extern void TkpComputeScrollbarGeometry( register TkScrollbar *scrollPtr) - /* Scrollbar whose geometry may have - * changed. */ + /* Scrollbar whose geometry may have + * changed. */ { - - /* - * The code below is borrowed from tkUnixScrlbr.c but has been adjusted to - * account for some differences between macOS and X11. The Unix scrollbar - * has an arrow button on each end. On macOS 10.6 (Snow Leopard) the - * scrollbars by default have both arrow buttons at the bottom or right. - * (There is a preferences setting to use the Unix layout, but we are not - * supporting that!) On more recent versions of macOS there are no arrow - * buttons at all. The case of no arrow buttons can be handled as a special - * case of having both buttons at the end, but where scrollPtr->arrowLength - * happens to be zero. To adjust for having both arrows at the same end we - * shift the scrollbar up by the arrowLength. - */ + /* + * The code below is borrowed from tkUnixScrlbr.c but has been adjusted to + * account for some differences between macOS and X11. The Unix scrollbar + * has an arrow button on each end. On macOS 10.6 (Snow Leopard) the + * scrollbars by default have both arrow buttons at the bottom or right. + * (There is a preferences setting to use the Unix layout, but we are not + * supporting that!) On more recent versions of macOS there are no arrow + * buttons at all. The case of no arrow buttons can be handled as a special + * case of having both buttons at the end, but where scrollPtr->arrowLength + * happens to be zero. To adjust for having both arrows at the same end we + * shift the scrollbar up by the arrowLength. + */ int fieldLength; if (scrollPtr->highlightWidth < 0) { - scrollPtr->highlightWidth = 0; + scrollPtr->highlightWidth = 0; } scrollPtr->inset = scrollPtr->highlightWidth + scrollPtr->borderWidth; if ([NSApp macMinorVersion] == 6) { - scrollPtr->arrowLength = scrollPtr->width; + scrollPtr->arrowLength = scrollPtr->width; } else { - scrollPtr->arrowLength = 0; + scrollPtr->arrowLength = 0; } fieldLength = (scrollPtr->vertical ? Tk_Height(scrollPtr->tkwin) - : Tk_Width(scrollPtr->tkwin)) - - 2*(scrollPtr->arrowLength + scrollPtr->inset); + : Tk_Width(scrollPtr->tkwin)) + - 2*(scrollPtr->arrowLength + scrollPtr->inset); if (fieldLength < 0) { - fieldLength = 0; + fieldLength = 0; } scrollPtr->sliderFirst = fieldLength*scrollPtr->firstFraction; scrollPtr->sliderLast = fieldLength*scrollPtr->lastFraction; @@ -289,16 +303,16 @@ TkpComputeScrollbarGeometry( */ if (scrollPtr->sliderFirst > fieldLength - MIN_SLIDER_LENGTH) { - scrollPtr->sliderFirst = fieldLength - MIN_SLIDER_LENGTH; + scrollPtr->sliderFirst = fieldLength - MIN_SLIDER_LENGTH; } if (scrollPtr->sliderFirst < 0) { - scrollPtr->sliderFirst = 0; + scrollPtr->sliderFirst = 0; } if (scrollPtr->sliderLast < scrollPtr->sliderFirst + MIN_SLIDER_LENGTH) { - scrollPtr->sliderLast = scrollPtr->sliderFirst + MIN_SLIDER_LENGTH; + scrollPtr->sliderLast = scrollPtr->sliderFirst + MIN_SLIDER_LENGTH; } if (scrollPtr->sliderLast > fieldLength) { - scrollPtr->sliderLast = fieldLength; + scrollPtr->sliderLast = fieldLength; } scrollPtr->sliderFirst += -scrollPtr->arrowLength + scrollPtr->inset; scrollPtr->sliderLast += scrollPtr->inset; @@ -310,20 +324,20 @@ TkpComputeScrollbarGeometry( * be redisplayed. */ - if (scrollPtr->vertical) { - Tk_GeometryRequest(scrollPtr->tkwin, - scrollPtr->width + 2*scrollPtr->inset, - 2*(scrollPtr->arrowLength + scrollPtr->borderWidth - + scrollPtr->inset) + metrics.minThumbHeight); + if (scrollPtr->vertical) { + Tk_GeometryRequest(scrollPtr->tkwin, + scrollPtr->width + 2*scrollPtr->inset, + 2*(scrollPtr->arrowLength + scrollPtr->borderWidth + + scrollPtr->inset) + metrics.minThumbHeight); } else { - Tk_GeometryRequest(scrollPtr->tkwin, - 2*(scrollPtr->arrowLength + scrollPtr->borderWidth - + scrollPtr->inset) + metrics.minThumbHeight, - scrollPtr->width + 2*scrollPtr->inset); + Tk_GeometryRequest(scrollPtr->tkwin, + 2*(scrollPtr->arrowLength + scrollPtr->borderWidth + + scrollPtr->inset) + metrics.minThumbHeight, + scrollPtr->width + 2*scrollPtr->inset); } Tk_SetInternalBorder(scrollPtr->tkwin, scrollPtr->inset); } - + /* *---------------------------------------------------------------------- * @@ -342,9 +356,9 @@ TkpComputeScrollbarGeometry( void TkpDestroyScrollbar( - TkScrollbar *scrollPtr) + TkScrollbar *scrollPtr) { - MacScrollbar *macScrollPtr = (MacScrollbar *)scrollPtr; + MacScrollbar *macScrollPtr = (MacScrollbar *) scrollPtr; if (macScrollPtr->troughGC != None) { Tk_FreeGC(scrollPtr->display, macScrollPtr->troughGC); @@ -353,15 +367,15 @@ TkpDestroyScrollbar( Tk_FreeGC(scrollPtr->display, macScrollPtr->copyGC); } } - + /* *---------------------------------------------------------------------- * * TkpConfigureScrollbar -- * - * This procedure is called after the generic code has finished - * processing configuration options, in order to configure platform - * specific options. There are no such option on the Mac, however. + * This procedure is called after the generic code has finished processing + * configuration options, in order to configure platform specific options. + * There are no such option on the Mac, however. * * Results: * None. @@ -374,11 +388,11 @@ TkpDestroyScrollbar( void TkpConfigureScrollbar( - register TkScrollbar *scrollPtr) + register TkScrollbar *scrollPtr) { - + /* empty */ } - + /* *-------------------------------------------------------------- * @@ -403,29 +417,28 @@ TkpScrollbarPosition( /* Scrollbar widget record. */ int x, int y) /* Coordinates within scrollPtr's window. */ { - - /* - * The code below is borrowed from tkUnixScrlbr.c and needs no adjustment - * since it does not involve the arrow buttons. - */ + /* + * The code below is borrowed from tkUnixScrlbr.c and needs no adjustment + * since it does not involve the arrow buttons. + */ int length, width, tmp; register const int inset = scrollPtr->inset; if (scrollPtr->vertical) { - length = Tk_Height(scrollPtr->tkwin); - width = Tk_Width(scrollPtr->tkwin); + length = Tk_Height(scrollPtr->tkwin); + width = Tk_Width(scrollPtr->tkwin); } else { - tmp = x; - x = y; - y = tmp; - length = Tk_Width(scrollPtr->tkwin); - width = Tk_Height(scrollPtr->tkwin); + tmp = x; + x = y; + y = tmp; + length = Tk_Width(scrollPtr->tkwin); + width = Tk_Height(scrollPtr->tkwin); } if (x < inset || x >= width - inset || - y < inset || y >= length - inset) { - return OUTSIDE; + y < inset || y >= length - inset) { + return OUTSIDE; } /* @@ -436,31 +449,34 @@ TkpScrollbarPosition( */ if (y < scrollPtr->sliderFirst + scrollPtr->arrowLength) { - return TOP_GAP; - } - if (y < scrollPtr->sliderLast) { - return SLIDER; - } - if (y < length - (2*scrollPtr->arrowLength + inset)) { - return BOTTOM_GAP; - } - /* On systems newer than 10.6 we have already returned. */ - if (y < length - (scrollPtr->arrowLength + inset)) { - return TOP_ARROW; - } - return BOTTOM_ARROW; -} + return TOP_GAP; + } + if (y < scrollPtr->sliderLast) { + return SLIDER; + } + if (y < length - (2*scrollPtr->arrowLength + inset)) { + return BOTTOM_GAP; + } + /* + * On systems newer than 10.6 we have already returned. + */ + + if (y < length - (scrollPtr->arrowLength + inset)) { + return TOP_ARROW; + } + return BOTTOM_ARROW; +} + /* *-------------------------------------------------------------- * * UpdateControlValues -- * - * This procedure updates the Macintosh scrollbar control to - * display the values defined by the Tk scrollbar. This is the - * key interface to the Mac-native scrollbar; the Unix bindings - * drive scrolling in the Tk window and all the Mac scrollbar has - * to do is redraw itself. + * This procedure updates the Macintosh scrollbar control to display the + * values defined by the Tk scrollbar. This is the key interface to the + * Mac-native scrollbar; the Unix bindings drive scrolling in the Tk + * window and all the Mac scrollbar has to do is redraw itself. * * Results: * None. @@ -473,20 +489,21 @@ TkpScrollbarPosition( static void UpdateControlValues( - TkScrollbar *scrollPtr) /* Scrollbar data struct. */ + TkScrollbar *scrollPtr) /* Scrollbar data struct. */ { - MacScrollbar *msPtr = (MacScrollbar *)scrollPtr; + MacScrollbar *msPtr = (MacScrollbar *) scrollPtr; Tk_Window tkwin = scrollPtr->tkwin; MacDrawable *macWin = (MacDrawable *) Tk_WindowId(scrollPtr->tkwin); double dViewSize; - HIRect contrlRect; + HIRect contrlRect; short width, height; NSView *view = TkMacOSXDrawableView(macWin); CGFloat viewHeight = [view bounds].size.height; NSRect frame; + frame = NSMakeRect(macWin->xOff, macWin->yOff, Tk_Width(tkwin), - Tk_Height(tkwin)); + Tk_Height(tkwin)); frame = NSInsetRect(frame, scrollPtr->inset, scrollPtr->inset); frame.origin.y = viewHeight - (frame.origin.y + frame.size.height); @@ -503,9 +520,9 @@ UpdateControlValues( msPtr->info.bounds = contrlRect; if (scrollPtr->vertical) { - msPtr->info.attributes &= ~kThemeTrackHorizontal; + msPtr->info.attributes &= ~kThemeTrackHorizontal; } else { - msPtr->info.attributes |= kThemeTrackHorizontal; + msPtr->info.attributes |= kThemeTrackHorizontal; } /* @@ -518,69 +535,73 @@ UpdateControlValues( * the view area. */ - double maximum = 100, factor; - factor = RangeToFactor(maximum); - dViewSize = (scrollPtr->lastFraction - scrollPtr->firstFraction) - * factor; - msPtr->info.max = MIN_SCROLLBAR_VALUE + - factor - dViewSize; + double maximum = 100, factor = RangeToFactor(maximum); + + dViewSize = (scrollPtr->lastFraction - scrollPtr->firstFraction) * factor; + msPtr->info.max = MIN_SCROLLBAR_VALUE + factor - dViewSize; msPtr->info.trackInfo.scrollbar.viewsize = dViewSize; if (scrollPtr->vertical) { - if (SNOW_LEOPARD_STYLE) { - msPtr->info.value = factor * scrollPtr->firstFraction; - } else { - msPtr->info.value = msPtr->info.max - factor * scrollPtr->firstFraction; - } + if (SNOW_LEOPARD_STYLE) { + msPtr->info.value = factor * scrollPtr->firstFraction; + } else { + msPtr->info.value = msPtr->info.max - + factor * scrollPtr->firstFraction; + } } else { - msPtr->info.value = MIN_SCROLLBAR_VALUE + factor * scrollPtr->firstFraction; + msPtr->info.value = MIN_SCROLLBAR_VALUE + + factor * scrollPtr->firstFraction; } - if((scrollPtr->firstFraction <= 0.0 && scrollPtr->lastFraction >= 1.0) - || height <= metrics.minHeight) { + if ((scrollPtr->firstFraction <= 0.0 && scrollPtr->lastFraction >= 1.0) + || height <= metrics.minHeight) { msPtr->info.enableState = kThemeTrackHideTrack; } else { msPtr->info.enableState = kThemeTrackActive; - msPtr->info.attributes = kThemeTrackShowThumb | kThemeTrackThumbRgnIsNotGhost; + msPtr->info.attributes = + kThemeTrackShowThumb | kThemeTrackThumbRgnIsNotGhost; } - } - + /* *-------------------------------------------------------------- * * ScrollbarEvent -- * - * This procedure is invoked in response to , , - * , and events. The Scrollbar appearance is - * modified for each event. + * This procedure is invoked in response to , + * , , and events. The + * Scrollbar appearance is modified for each event. * *-------------------------------------------------------------- */ static int -ScrollbarEvent(TkScrollbar *scrollPtr, XEvent *eventPtr) +ScrollbarEvent( + TkScrollbar *scrollPtr, + XEvent *eventPtr) { - MacScrollbar *msPtr = (MacScrollbar *)scrollPtr; - - /* The pressState does not indicate whether the moused button was - * pressed at some location in the Scrollbar. Rather, it indicates - * that the scrollbar should appear as if it were pressed in that - * location. The standard Mac behavior is that once the button is - * pressed inside the Scrollbar the appearance should not change until - * the button is released, even if the mouse moves outside of the - * scrollbar. However, if the mouse lies over the scrollbar but the - * button is not pressed then the appearance should be the same as if - * the button had been pressed on the slider, i.e. kThemeThumbPressed. - * See the file Appearance.r, or HIToolbox.bridgesupport on 10.14. + MacScrollbar *msPtr = (MacScrollbar *) scrollPtr; + + /* + * The pressState does not indicate whether the moused button was pressed + * at some location in the Scrollbar. Rather, it indicates that the + * scrollbar should appear as if it were pressed in that location. The + * standard Mac behavior is that once the button is pressed inside the + * Scrollbar the appearance should not change until the button is released, + * even if the mouse moves outside of the scrollbar. However, if the mouse + * lies over the scrollbar but the button is not pressed then the + * appearance should be the same as if the button had been pressed on the + * slider, i.e. kThemeThumbPressed. See the file Appearance.r, or + * HIToolbox.bridgesupport on 10.14. */ if (eventPtr->type == ButtonPress) { msPtr->buttonDown = true; UpdateControlValues(scrollPtr); + int where = TkpScrollbarPosition(scrollPtr, - eventPtr->xbutton.x, - eventPtr->xbutton.y); - switch(where) { + eventPtr->xbutton.x, eventPtr->xbutton.y); + + switch (where) { case OUTSIDE: msPtr->info.trackInfo.scrollbar.pressState = 0; break; @@ -591,14 +612,20 @@ ScrollbarEvent(TkScrollbar *scrollPtr, XEvent *eventPtr) msPtr->info.trackInfo.scrollbar.pressState = kThemeThumbPressed; break; case BOTTOM_GAP: - msPtr->info.trackInfo.scrollbar.pressState = kThemeBottomTrackPressed; + msPtr->info.trackInfo.scrollbar.pressState = + kThemeBottomTrackPressed; break; case TOP_ARROW: - /* This looks wrong and the docs say it is wrong but it works. */ - msPtr->info.trackInfo.scrollbar.pressState = kThemeTopInsideArrowPressed; + /* + * This looks wrong and the docs say it is wrong but it works. + */ + + msPtr->info.trackInfo.scrollbar.pressState = + kThemeTopInsideArrowPressed; break; case BOTTOM_ARROW: - msPtr->info.trackInfo.scrollbar.pressState = kThemeBottomOutsideArrowPressed; + msPtr->info.trackInfo.scrollbar.pressState = + kThemeBottomOutsideArrowPressed; break; } } @@ -622,9 +649,7 @@ ScrollbarEvent(TkScrollbar *scrollPtr, XEvent *eventPtr) } return TCL_OK; } - - - + /* *-------------------------------------------------------------- * @@ -645,8 +670,8 @@ ScrollbarEvent(TkScrollbar *scrollPtr, XEvent *eventPtr) static void ScrollbarEventProc( - ClientData clientData, /* Information about window. */ - XEvent *eventPtr) /* Information about event. */ + ClientData clientData, /* Information about window. */ + XEvent *eventPtr) /* Information about event. */ { TkScrollbar *scrollPtr = clientData; @@ -668,7 +693,7 @@ ScrollbarEventProc( TkScrollbarEventProc(clientData, eventPtr); } } - + /* * Local Variables: * mode: objc diff --git a/macosx/tkMacOSXSend.c b/macosx/tkMacOSXSend.c index 1fdf048..8b65532 100644 --- a/macosx/tkMacOSXSend.c +++ b/macosx/tkMacOSXSend.c @@ -51,7 +51,7 @@ typedef struct RegisteredInterp { * A registry of all interpreters for a display is kept in a property * "InterpRegistry" on the root window of the display. It is organized as a * series of zero or more concatenated strings (in no particular order), each - * of the form + * of the form: * window space name '\0' * where "window" is the hex id of the comm. window to use to talk to an * interpreter named "name". @@ -78,7 +78,7 @@ typedef struct NameRegistry { * XFree; zero means use ckfree. */ } NameRegistry; -static int initialized = 0; /* A flag to denote if we have initialized +static int initialized = 0; /* A flag to denote if we have initialized * yet. */ static RegisteredInterp *interpListPtr = NULL; diff --git a/macosx/tkMacOSXSubwindows.c b/macosx/tkMacOSXSubwindows.c index 805d58f..06aaa9d 100644 --- a/macosx/tkMacOSXSubwindows.c +++ b/macosx/tkMacOSXSubwindows.c @@ -65,7 +65,7 @@ XDestroyWindow( TkMacOSXSelDeadWindow(macWin->winPtr); macWin->toplevel->referenceCount--; - if (!Tk_IsTopLevel(macWin->winPtr) ) { + if (!Tk_IsTopLevel(macWin->winPtr)) { TkMacOSXInvalidateWindow(macWin, TK_PARENT_WINDOW); if (macWin->winPtr->parentPtr != NULL) { TkMacOSXInvalClipRgns((Tk_Window) macWin->winPtr->parentPtr); @@ -151,19 +151,18 @@ XMapWindow( NSWindow *win = TkMacOSXDrawableWindow(window); /* - * We want to activate Tk when a toplevel is mapped - * but we must not supply YES here. This is because - * during Tk initialization the root window is mapped - * before applicationDidFinishLaunching returns. Forcing - * the app to activate too early can make the menu bar - * unresponsive. + * We want to activate Tk when a toplevel is mapped but we must not + * supply YES here. This is because during Tk initialization the + * root window is mapped before applicationDidFinishLaunching + * returns. Forcing the app to activate too early can make the menu + * bar unresponsive. */ TkMacOSXApplyWindowAttributes(macWin->winPtr, win); [win setExcludedFromWindowsMenu:NO]; [NSApp activateIgnoringOtherApps:NO]; [[win contentView] setNeedsDisplay:YES]; - if ( [win canBecomeKeyWindow] ) { + if ([win canBecomeKeyWindow]) { [win makeKeyAndOrderFront:NSApp]; } else { [win orderFrontRegardless]; @@ -185,7 +184,8 @@ XMapWindow( */ TkWindow *contWinPtr = TkpGetOtherWindow(macWin->winPtr); - TkMacOSXInvalClipRgns((Tk_Window)contWinPtr); + + TkMacOSXInvalClipRgns((Tk_Window) contWinPtr); TkMacOSXInvalidateWindow(macWin, TK_PARENT_WINDOW); } TkMacOSXInvalClipRgns((Tk_Window) macWin->winPtr); @@ -203,12 +203,9 @@ XMapWindow( event.xmap.event = window; event.xmap.override_redirect = macWin->winPtr->atts.override_redirect; Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); - } else { - /* * Rebuild the parent's clipping region and display the window. - * */ TkMacOSXInvalClipRgns((Tk_Window) macWin->winPtr->parentPtr); @@ -298,6 +295,7 @@ XUnmapWindow( if (!Tk_IsEmbedded(winPtr) && winPtr->wmInfoPtr->hints.initial_state!=IconicState) { NSWindow *win = TkMacOSXDrawableWindow(window); + [win orderOut:nil]; } TkMacOSXInvalClipRgns((Tk_Window) winPtr); @@ -316,15 +314,15 @@ XUnmapWindow( event.xunmap.from_configure = false; Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); } else { - /* * Rebuild the visRgn clip region for the parent so it will be allowed * to draw in the space from which this subwindow was removed. */ if (parentPtr && parentPtr->privatePtr->visRgn) { - TkMacOSXInvalidateViewRegion(TkMacOSXDrawableView(parentPtr->privatePtr), - parentPtr->privatePtr->visRgn); + TkMacOSXInvalidateViewRegion( + TkMacOSXDrawableView(parentPtr->privatePtr), + parentPtr->privatePtr->visRgn); } TkMacOSXInvalClipRgns((Tk_Window) parentPtr); TkMacOSXUpdateClipRgn(parentPtr); @@ -357,11 +355,14 @@ XResizeWindow( unsigned int height) { MacDrawable *macWin = (MacDrawable *) window; + display->request++; if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) { NSWindow *w = macWin->winPtr->wmInfoPtr->window; + if (w) { NSRect r = [w contentRectForFrameRect:[w frame]]; + r.origin.y += r.size.height - height; r.size.width = width; r.size.height = height; @@ -377,8 +378,8 @@ XResizeWindow( * * XMoveResizeWindow -- * - * Move or resize a given X window. See X windows documentation - * for further details. + * Move or resize a given X window. See X windows documentation for + * further details. * * Results: * None. @@ -402,22 +403,24 @@ XMoveResizeWindow( display->request++; if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) { NSWindow *w = macWin->winPtr->wmInfoPtr->window; - if (w) { - /* We explicitly convert everything to doubles so we don't get + if (w) { + /* + * We explicitly convert everything to doubles so we don't get * surprised (again) by what happens when you do arithmetic with * unsigned ints. */ - CGFloat X = (CGFloat)x; - CGFloat Y = (CGFloat)y; - CGFloat Width = (CGFloat)width; - CGFloat Height = (CGFloat)height; - CGFloat XOff = (CGFloat)macWin->winPtr->wmInfoPtr->xInParent; - CGFloat YOff = (CGFloat)macWin->winPtr->wmInfoPtr->yInParent; - NSRect r = NSMakeRect(X + XOff, - tkMacOSXZeroScreenHeight - Y - YOff - Height, - Width, Height); + CGFloat X = (CGFloat) x; + CGFloat Y = (CGFloat) y; + CGFloat Width = (CGFloat) width; + CGFloat Height = (CGFloat) height; + CGFloat XOff = (CGFloat) macWin->winPtr->wmInfoPtr->xInParent; + CGFloat YOff = (CGFloat) macWin->winPtr->wmInfoPtr->yInParent; + NSRect r = NSMakeRect( + X + XOff, tkMacOSXZeroScreenHeight - Y - YOff - Height, + Width, Height); + [w setFrame:[w frameRectForContentRect:r] display:YES]; } } else { @@ -430,8 +433,7 @@ XMoveResizeWindow( * * XMoveWindow -- * - * Move a given X window. See X windows documentation for further - * details. + * Move a given X window. See X windows documentation for further details. * * Results: * None. @@ -453,8 +455,10 @@ XMoveWindow( display->request++; if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) { NSWindow *w = macWin->winPtr->wmInfoPtr->window; + if (w) { - [w setFrameTopLeftPoint:NSMakePoint(x, tkMacOSXZeroScreenHeight - y)]; + [w setFrameTopLeftPoint: NSMakePoint( + x, tkMacOSXZeroScreenHeight - y)]; } } else { MoveResizeWindow(macWin); @@ -495,7 +499,6 @@ MoveResizeWindow( if (contWinPtr) { macParent = contWinPtr->privatePtr; } else { - /* * Here we should handle out of process embedding. At this point, * we are assuming that the changes.x,y is not maintained, if you @@ -504,7 +507,6 @@ MoveResizeWindow( */ } } else { - /* * TODO: update all xOff & yOffs */ @@ -596,7 +598,6 @@ XRaiseWindow( if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) { TkWmRestackToplevel(macWin->winPtr, Above, NULL); } else { - /* * TODO: this should generate damage */ @@ -631,7 +632,6 @@ XLowerWindow( if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) { TkWmRestackToplevel(macWin->winPtr, Below, NULL); } else { - /* * TODO: this should generate damage */ @@ -694,14 +694,16 @@ XConfigureWindow( TkMacOSXInvalClipRgns((Tk_Window) winPtr->parentPtr); TkMacOSXWinBounds(winPtr, &bounds); r = NSMakeRect(bounds.left, - [view bounds].size.height - bounds.bottom, - bounds.right - bounds.left, bounds.bottom - bounds.top); + [view bounds].size.height - bounds.bottom, + bounds.right - bounds.left, bounds.bottom - bounds.top); [view setNeedsDisplayInRect:r]; } } - /* TkGenWMMoveRequestEvent(macWin->winPtr, - macWin->winPtr->changes.x, macWin->winPtr->changes.y); */ +#if 0 + TkGenWMMoveRequestEvent(macWin->winPtr, + macWin->winPtr->changes.x, macWin->winPtr->changes.y); +#endif } /* @@ -723,14 +725,14 @@ XConfigureWindow( void TkMacOSXSetDrawingEnabled( - TkWindow *winPtr, - int flag) + TkWindow *winPtr, + int flag) { TkWindow *childPtr; MacDrawable *macWin = winPtr->privatePtr; if (macWin) { - if (flag ) { + if (flag) { macWin->flags &= ~TK_DO_NOT_DRAW; } else { macWin->flags |= TK_DO_NOT_DRAW; @@ -738,8 +740,8 @@ TkMacOSXSetDrawingEnabled( } /* - * Set the flag for all children & their descendants, excluding - * Toplevels. (??? Do we need to exclude Toplevels?) + * Set the flag for all children & their descendants, excluding Toplevels. + * (??? Do we need to exclude Toplevels?) */ childPtr = winPtr->childList; @@ -903,7 +905,6 @@ TkMacOSXUpdateClipRgn( } CFRelease(rgn); } else { - /* * An unmapped window has empty clip regions to prevent any * (erroneous) drawing into it or its children from becoming @@ -933,8 +934,8 @@ TkMacOSXUpdateClipRgn( * TkMacOSXVisableClipRgn -- * * This function returns the Macintosh clipping region for the given - * window. The caller is responsible for disposing of the returned - * region via TkDestroyRegion(). + * window. The caller is responsible for disposing of the returned region + * via TkDestroyRegion(). * * Results: * The region. @@ -952,7 +953,7 @@ TkMacOSXVisableClipRgn( if (winPtr->privatePtr->flags & TK_CLIP_INVALID) { TkMacOSXUpdateClipRgn(winPtr); } - return (TkRegion)HIShapeCreateMutableCopy(winPtr->privatePtr->visRgn); + return (TkRegion) HIShapeCreateMutableCopy(winPtr->privatePtr->visRgn); } /* @@ -972,7 +973,12 @@ TkMacOSXVisableClipRgn( */ static OSStatus -InvalViewRect(int msg, HIShapeRef rgn, const CGRect *rect, void *ref) { +InvalViewRect( + int msg, + HIShapeRef rgn, + const CGRect *rect, + void *ref) +{ static CGAffineTransform t; NSView *view = ref; @@ -1052,7 +1058,7 @@ TkMacOSXInvalidateWindow( *---------------------------------------------------------------------- */ -NSWindow* +NSWindow * TkMacOSXDrawableWindow( Drawable drawable) { @@ -1070,6 +1076,7 @@ TkMacOSXDrawableWindow( result = macWin->winPtr->wmInfoPtr->window; } else if (macWin->toplevel && (macWin->toplevel->flags & TK_EMBEDDED)) { TkWindow *contWinPtr = TkpGetOtherWindow(macWin->toplevel->winPtr); + if (contWinPtr) { result = TkMacOSXDrawableWindow((Drawable) contWinPtr->privatePtr); } @@ -1123,7 +1130,7 @@ TkMacOSXGetDrawablePort( *---------------------------------------------------------------------- */ -NSView* +NSView * TkMacOSXDrawableView( MacDrawable *macWin) { @@ -1137,6 +1144,7 @@ TkMacOSXDrawableView( result = macWin->toplevel->view; } else { TkWindow *contWinPtr = TkpGetOtherWindow(macWin->toplevel->winPtr); + if (contWinPtr) { result = TkMacOSXDrawableView(contWinPtr->privatePtr); } @@ -1164,7 +1172,6 @@ void * TkMacOSXGetRootControl( Drawable drawable) { - /* * will probably need to fix this up for embedding */ @@ -1281,7 +1288,8 @@ TkMacOSXWinBounds( TkWindow *winPtr, void *bounds) { - Rect *b = (Rect *)bounds; + Rect *b = (Rect *) bounds; + b->left = winPtr->privatePtr->xOff; b->top = winPtr->privatePtr->yOff; b->right = b->left + winPtr->changes.width; @@ -1345,7 +1353,6 @@ UpdateOffsets( TkWindow *childPtr; if (winPtr->privatePtr == NULL) { - /* * We haven't called Tk_MakeWindowExist for this window yet. The offset * information will be postponed and calulated at that time. (This will diff --git a/macosx/tkMacOSXWindowEvent.c b/macosx/tkMacOSXWindowEvent.c index 54e1272..6b80761 100644 --- a/macosx/tkMacOSXWindowEvent.c +++ b/macosx/tkMacOSXWindowEvent.c @@ -68,7 +68,7 @@ extern NSString *NSWindowDidOrderOffScreenNotification; TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd, notification); #endif BOOL movedOnly = [[notification name] - isEqualToString:NSWindowDidMoveNotification]; + isEqualToString:NSWindowDidMoveNotification]; NSWindow *w = [notification object]; TkWindow *winPtr = TkMacOSXGetTkWindow(w); @@ -91,7 +91,6 @@ extern NSString *NSWindowDidOrderOffScreenNotification; flags |= TK_SIZE_CHANGED; } if (Tcl_GetServiceMode() != TCL_SERVICE_NONE) { - /* * Propagate geometry changes immediately. */ @@ -140,11 +139,10 @@ extern NSString *NSWindowDidOrderOffScreenNotification; - (NSRect)windowWillUseStandardFrame:(NSWindow *)window defaultFrame:(NSRect)newFrame { - /* - * This method needs to be implemented in order for [NSWindow isZoomed] - * to give the correct answer. But it suffices to always validate - * every request. + * This method needs to be implemented in order for [NSWindow isZoomed] to + * give the correct answer. But it suffices to always validate every + * request. */ return newFrame; @@ -153,13 +151,12 @@ extern NSString *NSWindowDidOrderOffScreenNotification; - (NSSize)window:(NSWindow *)window willUseFullScreenContentSize:(NSSize)proposedSize { - /* - * We don't need to change the proposed size, but we do need to - * implement this method. Otherwise the full screen window will - * be sized to the screen's visibleFrame, leaving black bands at - * the top and bottom. + * We don't need to change the proposed size, but we do need to implement + * this method. Otherwise the full screen window will be sized to the + * screen's visibleFrame, leaving black bands at the top and bottom. */ + return proposedSize; } @@ -208,14 +205,13 @@ extern NSString *NSWindowDidOrderOffScreenNotification; } /* - * If necessary, TkGenWMDestroyEvent() handles [close]ing the window, - * so can always return NO from -windowShouldClose: for a Tk window. + * If necessary, TkGenWMDestroyEvent() handles [close]ing the window, so + * can always return NO from -windowShouldClose: for a Tk window. */ return (winPtr ? NO : YES); } - #ifdef TK_MAC_DEBUG_NOTIFICATIONS - (void) windowDragStart: (NSNotification *) notification @@ -256,7 +252,6 @@ extern NSString *NSWindowDidOrderOffScreenNotification; } } - #endif /* TK_MAC_DEBUG_NOTIFICATIONS */ - (void) _setupWindowNotifications @@ -363,11 +358,11 @@ extern NSString *NSWindowDidOrderOffScreenNotification; * * TkpAppIsDrawing -- * - * A widget display procedure can call this to determine whether it - * is being run inside of the drawRect method. This is needed for - * some tests, especially of the Text widget, which record data in - * a global Tcl variable and assume that display procedures will be - * run in a predictable sequence as Tcl idle tasks. + * A widget display procedure can call this to determine whether it is + * being run inside of the drawRect method. This is needed for some tests, + * especially of the Text widget, which record data in a global Tcl + * variable and assume that display procedures will be run in a + * predictable sequence as Tcl idle tasks. * * Results: * True only while running the drawRect method of a TKContentView; @@ -377,11 +372,11 @@ extern NSString *NSWindowDidOrderOffScreenNotification; * *---------------------------------------------------------------------- */ + MODULE_SCOPE Bool TkpAppIsDrawing(void) { return [NSApp isDrawing]; } - /* *---------------------------------------------------------------------- @@ -670,12 +665,10 @@ TkGenWMConfigureEvent( if ((flags & TK_SIZE_CHANGED) && !(wmPtr->flags & WM_SYNC_PENDING) && ((width != Tk_Width(tkwin)) || (height != Tk_Height(tkwin)))) { if ((wmPtr->width == -1) && (width == winPtr->reqWidth)) { - /* * Don't set external width, since the user didn't change it * from what the widgets asked for. */ - } else if (wmPtr->gridWin != NULL) { wmPtr->width = wmPtr->reqGridWidth + (width - winPtr->reqWidth)/wmPtr->widthInc; @@ -687,12 +680,10 @@ TkGenWMConfigureEvent( } if ((wmPtr->height == -1) && (height == winPtr->reqHeight)) { - /* * Don't set external height, since the user didn't change it * from what the widgets asked for. */ - } else if (wmPtr->gridWin != NULL) { wmPtr->height = wmPtr->reqGridHeight + (height - winPtr->reqHeight)/wmPtr->heightInc; @@ -708,7 +699,6 @@ TkGenWMConfigureEvent( } } - /* * Now set up the changes structure. Under X we wait for the * ConfigureNotify to set these values. On the Mac we know imediatly that @@ -899,8 +889,8 @@ ConfigureRestrictProc( #endif /* - * We do not allow recursive calls to drawRect, but we only log - * them on OSX > 10.13, where they should never happen. + * We do not allow recursive calls to drawRect, but we only log them on OSX + * > 10.13, where they should never happen. */ if ([NSApp isDrawing]) { @@ -955,9 +945,9 @@ ConfigureRestrictProc( Tk_RestrictProc *oldProc; /* - * This can be called from outside the Tk event loop. - * Since it calls Tcl_DoOneEvent, we need to make sure we - * don't clobber the AutoreleasePool set up by the caller. + * This can be called from outside the Tk event loop. Since it calls + * Tcl_DoOneEvent, we need to make sure we don't clobber the + * AutoreleasePool set up by the caller. */ [NSApp _lockAutoreleasePool]; @@ -973,7 +963,7 @@ ConfigureRestrictProc( */ TkGenWMConfigureEvent(tkwin, Tk_X(tkwin), Tk_Y(tkwin), width, height, - TK_SIZE_CHANGED | TK_MACOSX_HANDLE_EVENT_IMMEDIATELY); + TK_SIZE_CHANGED | TK_MACOSX_HANDLE_EVENT_IMMEDIATELY); oldProc = Tk_RestrictEvents(ConfigureRestrictProc, NULL, &oldArg); Tk_RestrictEvents(oldProc, oldArg, &oldArg); @@ -1061,9 +1051,9 @@ ConfigureRestrictProc( } /* - * This method is called when a user changes between light and dark mode. - * The implementation here generates a Tk virtual event which can be bound - * to a function that redraws the window in an appropriate style. + * This method is called when a user changes between light and dark mode. The + * implementation here generates a Tk virtual event which can be bound to a + * function that redraws the window in an appropriate style. */ - (void) viewDidChangeEffectiveAppearance @@ -1099,8 +1089,8 @@ ConfigureRestrictProc( } /* - * This is no-op on 10.7 and up because Apple has removed this widget, - * but we are leaving it here for backwards compatibility. + * This is no-op on 10.7 and up because Apple has removed this widget, but we + * are leaving it here for backwards compatibility. */ - (void) tkToolbarButton: (id) sender diff --git a/macosx/tkMacOSXWm.c b/macosx/tkMacOSXWm.c index 504c73f..d6456f2 100644 --- a/macosx/tkMacOSXWm.c +++ b/macosx/tkMacOSXWm.c @@ -3,8 +3,7 @@ * * This module takes care of the interactions between a Tk-based * application and the window manager. Among other things, it implements - * the "wm" command and passes geometry information to the window - * manager. + * the "wm" command and passes geometry information to the window manager. * * Copyright (c) 1994-1997 Sun Microsystems, Inc. * Copyright 2001-2009, Apple Inc. @@ -392,7 +391,7 @@ static void RemoveTransient(TkWindow *winPtr); if ([self styleMask] & NSFullScreenWindowMask) { frameRect = [NSWindow frameRectForContentRect:NSZeroRect - styleMask:[self styleMask]]; + styleMask:[self styleMask]]; } else { frameRect = [self frameRectForContentRect:NSZeroRect]; } @@ -454,7 +453,7 @@ static void RemoveTransient(TkWindow *winPtr); if (title == nil) { title = "unnamed window"; } - if (DEBUG_ZOMBIES > 1){ + if (DEBUG_ZOMBIES > 1) { fprintf(stderr, "Retained <%s>. Count is: %lu\n", title, [self retainCount]); } @@ -468,7 +467,7 @@ static void RemoveTransient(TkWindow *winPtr); if (title == nil) { title = "unnamed window"; } - if (DEBUG_ZOMBIES > 1){ + if (DEBUG_ZOMBIES > 1) { fprintf(stderr, "Autoreleased <%s>. Count is %lu\n", title, [self retainCount]); } @@ -480,7 +479,7 @@ static void RemoveTransient(TkWindow *winPtr); if (title == nil) { title = "unnamed window"; } - if (DEBUG_ZOMBIES > 1){ + if (DEBUG_ZOMBIES > 1) { fprintf(stderr, "Releasing <%s>. Count is %lu\n", title, [self retainCount]); } @@ -492,7 +491,7 @@ static void RemoveTransient(TkWindow *winPtr); if (title == nil) { title = "unnamed window"; } - if (DEBUG_ZOMBIES > 0){ + if (DEBUG_ZOMBIES > 0) { fprintf(stderr, ">>>> Freeing <%s>. Count is %lu\n", title, [self retainCount]); } @@ -998,25 +997,29 @@ TkWmDeadWindow( if (winPtr2 && nswindow != window) { WmInfo *wmPtr = winPtr2->wmInfoPtr; - BOOL minimized = (wmPtr->hints.initial_state == IconicState || - wmPtr->hints.initial_state == WithdrawnState); + BOOL minimized = (wmPtr->hints.initial_state == IconicState + || wmPtr->hints.initial_state == WithdrawnState); + /* * If no windows are left on the screen and the next window is * iconified or withdrawn, we don't want to make it be the * KeyWindow because that would cause it to be displayed on the * screen. */ + if ([nswindow canBecomeKeyWindow] && !minimized) { [nswindow makeKeyAndOrderFront:NSApp]; break; } } } + /* * Process all window events immediately to force the closed window to * be deallocated. But don't do this for the root window as that is * unnecessary and can lead to segfaults. */ + if (winPtr->parentPtr) { while (Tk_DoOneEvent(TK_WINDOW_EVENTS|TK_DONT_WAIT)) {} } @@ -2624,7 +2627,7 @@ WmIconpositionCmd( wmPtr->hints.flags &= ~IconPositionHint; } else { if ((Tcl_GetIntFromObj(interp, objv[3], &x) != TCL_OK) - || (Tcl_GetIntFromObj(interp, objv[4], &y) != TCL_OK)){ + || (Tcl_GetIntFromObj(interp, objv[4], &y) != TCL_OK)) { return TCL_ERROR; } wmPtr->hints.icon_x = x; @@ -3453,14 +3456,17 @@ WmStateCmd( return TCL_ERROR; } - if (index == OPT_NORMAL) { + switch (index) { + case OPT_NORMAL: TkpWmSetState(winPtr, NormalState); /* * This varies from 'wm deiconify' because it does not force the * window to be raised and receive focus */ - } else if (index == OPT_ICONIC) { + + break; + case OPT_ICONIC: if (Tk_Attributes((Tk_Window) winPtr)->override_redirect) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "can't iconify \"%s\": override-redirect flag is set", @@ -3478,10 +3484,13 @@ WmStateCmd( return TCL_ERROR; } TkpWmSetState(winPtr, IconicState); - } else if (index == OPT_WITHDRAWN) { + break; + case OPT_WITHDRAWN: TkpWmSetState(winPtr, WithdrawnState); - } else { /* OPT_ZOOMED */ + break; + default: /* OPT_ZOOMED */ TkpWmSetState(winPtr, ZoomState); + break; } } else if (wmPtr->iconFor != NULL) { Tcl_SetObjResult(interp, Tcl_NewStringObj("icon", -1)); @@ -3601,14 +3610,12 @@ WmTransientCmd( } if (Tcl_GetString(objv[3])[0] == '\0') { RemoveTransient(winPtr); - } else { if (TkGetWindowFromObj(interp, tkwin, objv[3], &master) != TCL_OK) { return TCL_ERROR; } masterPtr = (TkWindow*) master; while (!Tk_TopWinHierarchy(masterPtr)) { - /* * Ensure that the master window is actually a Tk toplevel. */ @@ -3626,7 +3633,11 @@ WmTransientCmd( } wmPtr2 = masterPtr->wmInfoPtr; - /* Under some circumstances, wmPtr2 is NULL here. */ + + /* + * Under some circumstances, wmPtr2 is NULL here. + */ + if (wmPtr2 != NULL && wmPtr2->iconFor != NULL) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "can't make \"%s\" a master: it is an icon for %s", @@ -3677,7 +3688,7 @@ WmTransientCmd( ApplyMasterOverrideChanges(winPtr, NULL); return TCL_OK; } - + /* *---------------------------------------------------------------------- * @@ -3784,6 +3795,7 @@ WmWithdrawCmd( /* * If this window has a transient, the transient must also be withdrawn. */ + for (Transient *transientPtr = wmPtr->transientPtr; transientPtr != NULL; transientPtr = transientPtr->nextPtr) { TkWindow *winPtr2 = transientPtr->winPtr; @@ -3798,10 +3810,10 @@ WmWithdrawCmd( return TCL_OK; } - + /* - * Invoked by those wm subcommands that affect geometry. - * Schedules a geometry update. + * Invoked by those wm subcommands that affect geometry. Schedules a geometry + * update. */ static void @@ -4415,9 +4427,10 @@ ParseGeometry( if (flags & WM_NEGATIVE_X) { int borderwidth = wmPtr->parentWidth - winPtr->changes.width; int newWidth = width == -1 ? winPtr->changes.width : width; + x = (x == -1) ? - wmPtr->x + winPtr->changes.width - newWidth : - wmPtr->vRootWidth - x - newWidth - borderwidth; + wmPtr->x + winPtr->changes.width - newWidth : + wmPtr->vRootWidth - x - newWidth - borderwidth; } if (x == -1) { x = wmPtr->x; @@ -4425,9 +4438,10 @@ ParseGeometry( if (flags & WM_NEGATIVE_Y) { int borderheight = wmPtr->parentHeight - winPtr->changes.height; int newHeight = height == -1 ? winPtr->changes.height : height; + y = (y == -1) ? - wmPtr->y + winPtr->changes.height - newHeight : - wmPtr->vRootHeight - y - newHeight - borderheight; + wmPtr->y + winPtr->changes.height - newHeight : + wmPtr->vRootHeight - y - newHeight - borderheight; } if (y == -1) { y = wmPtr->y; @@ -4554,8 +4568,7 @@ Tk_GetRootCoords( * * Results: * The return result is either a token for the window corresponding to - * rootX and rootY, or else NULL to indicate that there is no such - * window. + * rootX and rootY, or else NULL to indicate that there is no such window. * * Side effects: * None. @@ -6144,9 +6157,9 @@ TkMacOSXMakeRealWindowExist( * * TkpDisplayWindow -- * - * Mark the contentView of this window as needing display so the - * window will be drawn by the window manager. If this is called - * within the drawRect method, do nothing. + * Mark the contentView of this window as needing display so the window + * will be drawn by the window manager. If this is called within the + * drawRect method, do nothing. * * Results: * None. @@ -6160,7 +6173,7 @@ TkMacOSXMakeRealWindowExist( MODULE_SCOPE void TkpDisplayWindow(Tk_Window tkwin) { if (![NSApp isDrawing]) { - TkWindow *winPtr = (TkWindow*)tkwin; + TkWindow *winPtr = (TkWindow *) tkwin; NSWindow *w = TkMacOSXDrawableWindow(winPtr->window); [[w contentView] setNeedsDisplay: YES]; @@ -6172,8 +6185,8 @@ TkpDisplayWindow(Tk_Window tkwin) { * * TkMacOSXRegisterOffScreenWindow -- * - * This function adds the passed in Off Screen Port to the hash table - * that maps Mac windows to root X windows. + * This function adds the passed in Off Screen Port to the hash table that + * maps Mac windows to root X windows. * * Results: * None. @@ -6981,7 +6994,7 @@ ApplyMasterOverrideChanges( } if (macWindow) { structureRect = [NSWindow frameRectForContentRect:NSZeroRect - styleMask:styleMask]; + styleMask:styleMask]; /* * Synchronize the wmInfoPtr to match the new window configuration @@ -7236,6 +7249,7 @@ RemapWindows( MacDrawable *parentWin) { TkWindow *childPtr; + /* * Remove the OS specific window. It will get rebuilt when the window gets * Mapped. diff --git a/macosx/ttkMacOSXTheme.c b/macosx/ttkMacOSXTheme.c index a890b63..0c474f0 100644 --- a/macosx/ttkMacOSXTheme.c +++ b/macosx/ttkMacOSXTheme.c @@ -60,10 +60,14 @@ /* * BoxToRect -- - * Convert a Ttk_Box in Tk coordinates relative to the given Drawable - * to a native Rect relative to the containing port. + * Convert a Ttk_Box in Tk coordinates relative to the given Drawable to a + * native Rect relative to the containing port. */ -static inline CGRect BoxToRect(Drawable d, Ttk_Box b) + +static inline CGRect +BoxToRect( + Drawable d, + Ttk_Box b) { MacDrawable *md = (MacDrawable*)d; CGRect rect; @@ -102,10 +106,10 @@ static Ttk_StateTable ThemeStateTable[] = { * * Apple's Human Interface Guidelines only allow three specific heights for * most buttons: Regular, small and mini. We always use the regular size. - * However, Ttk may provide an arbitrary bounding rectangle. We always draw - * the button centered vertically on the rectangle, and having the same width - * as the rectangle. This function returns the actual bounding rectangle that - * will be used in drawing the button. + * However, Ttk may provide an arbitrary bounding rectangle. We always draw the + * button centered vertically on the rectangle, and having the same width as + * the rectangle. This function returns the actual bounding rectangle that will + * be used in drawing the button. * * The BevelButton is allowed to have arbitrary size, and also has external * padding. This is handled separately here. @@ -115,8 +119,9 @@ static CGRect NormalizeButtonBounds( SInt32 heightMetric, CGRect bounds) { - SInt32 height; - if (heightMetric != NoThemeMetric) { + if (heightMetric != (SInt32) NoThemeMetric) { + SInt32 height; + ChkErr(GetThemeMetric, heightMetric, &height); bounds.origin.y += (bounds.size.height - height)/2; bounds.size.height = height; @@ -149,8 +154,8 @@ static CGFloat blackRGBA[4] = {0.0, 0.0, 0.0, 1.0}; * Start with the background color of a window's geometry master, or the * standard ttk window background if not. If the contrast parameter is * nonzero modify this color to be darker, for the aqua appearance, or - * lighter for the DarkAqua appearance. This is primarily used by the - * Fill and Background elements. + * lighter for the DarkAqua appearance. This is primarily used by the Fill + * and Background elements. */ static void GetBackgroundColor( @@ -161,11 +166,12 @@ static void GetBackgroundColor( { TkWindow *winPtr = (TkWindow *) tkwin; TkWindow *masterPtr = (TkWindow *) TkGetGeomMaster(tkwin); + while (masterPtr != NULL) { if (masterPtr->privatePtr->flags & TTK_HAS_CONTRASTING_BG) { break; } - masterPtr = (TkWindow *)TkGetGeomMaster(masterPtr); + masterPtr = (TkWindow *) TkGetGeomMaster(masterPtr); } if (masterPtr) { for (int i = 0; i < 4; i++) { @@ -176,6 +182,7 @@ static void GetBackgroundColor( NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *windowColor = [[NSColor windowBackgroundColor] colorUsingColorSpace: deviceRGB]; + [windowColor getComponents: rgba]; } else { for (int i = 0; i < 4; i++) { @@ -219,6 +226,7 @@ static void DrawGroupBox( NSColor *borderColor, *bgColor; static CGFloat border[4] = {1.0, 1.0, 1.0, 0.25}; CGFloat fill[4]; + GetBackgroundColor(context, tkwin, 1, fill); bgColor = [NSColor colorWithColorSpace: deviceRGB components: fill count: 4]; @@ -255,6 +263,7 @@ static void SolidFillRoundedRectangle( NSColor *color) { CGPathRef path; + CGContextSetFillColorWithColor(context, color.CGColor); path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL); CGContextBeginPath(context); @@ -271,14 +280,17 @@ static void DrawDownArrow( CGFloat *rgba) { CGFloat x, y; + CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); CGContextSetLineWidth(context, 1.5); x = bounds.origin.x + inset; y = bounds.origin.y + trunc(bounds.size.height/2); - CGContextBeginPath(context); + CGPoint arrow[3] = { {x, y-size/4}, {x+size/2, y+size/4}, {x+size, y-size/4} }; + + CGContextBeginPath(context); CGContextAddLines(context, arrow, 3); CGContextStrokePath(context); } @@ -291,14 +303,17 @@ static void DrawUpArrow( CGFloat *rgba) { CGFloat x, y; + CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); CGContextSetLineWidth(context, 1.5); x = bounds.origin.x + inset; y = bounds.origin.y + trunc(bounds.size.height/2); - CGContextBeginPath(context); + CGPoint arrow[3] = { {x, y+size/4}, {x+size/2, y-size/4}, {x+size, y+size/4} }; + + CGContextBeginPath(context); CGContextAddLines(context, arrow, 3); CGContextStrokePath(context); } @@ -368,6 +383,7 @@ static void DrawListHeader( if (state & TTK_TREEVIEW_STATE_SORTARROW) { CGRect arrowBounds = bounds; + arrowBounds.origin.x = bounds.origin.x + bounds.size.width - 16; arrowBounds.size.width = 16; if (state & TTK_STATE_ALTERNATE) { @@ -413,7 +429,6 @@ static CGFloat darkInactiveGradient[8] = {89.0/255, 90.0/255, 93.0/255, 1.0, static CGFloat darkSelectedGradient[8] = {23.0/255, 111.0/255, 232.0/255, 1.0, 20.0/255, 94.0/255, 206.0/255, 1.0}; - /*---------------------------------------------------------------------- * GradientFillRoundedRectangle -- * @@ -424,7 +439,7 @@ static void GradientFillRoundedRectangle( CGContextRef context, CGRect bounds, CGFloat radius, - CGFloat* colors, + CGFloat *colors, int numColors) { NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; @@ -435,6 +450,7 @@ static void GradientFillRoundedRectangle( }; CGGradientRef gradient = CGGradientCreateWithColorComponents( deviceRGB.CGColorSpace, colors, NULL, numColors); + path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL); CGContextBeginPath(context); CGContextAddPath(context, path); @@ -452,14 +468,17 @@ static void DrawUpDownArrows( CGFloat *rgba) { CGFloat x, y; + CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); CGContextSetLineWidth(context, 1.5); x = bounds.origin.x + inset; y = bounds.origin.y + trunc(bounds.size.height/2); CGContextBeginPath(context); + CGPoint bottomArrow[3] = {{x, y+2}, {x+size/2, y+2+size/2}, {x+size, y+2}}; - CGContextAddLines(context, bottomArrow, 3); CGPoint topArrow[3] = {{x, y-2}, {x+size/2, y-2-size/2}, {x+size, y-2}}; + + CGContextAddLines(context, bottomArrow, 3); CGContextAddLines(context, topArrow, 3); CGContextStrokePath(context); } @@ -483,6 +502,7 @@ static void FillButtonBackground( bounds.origin.x, bounds.origin.y + bounds.size.height }; + CGContextBeginPath(context); path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL); CGContextAddPath(context, path); @@ -508,6 +528,7 @@ static void HighlightButtonBorder( CGPoint topEnd = {bounds.origin.x, bounds.origin.y + 3}; CGGradientRef topGradient = CGGradientCreateWithColorComponents( deviceRGB.CGColorSpace, darkTopGradient, NULL, 2); + CGContextSaveGState(context); CGContextBeginPath(context); CGContextAddArc(context, bounds.origin.x + 4, bounds.origin.y + 4, @@ -576,6 +597,7 @@ static void DrawDarkButton( if (kind == kThemePopupButton | kind == kThemeComboBox) { CGRect arrowBounds = bounds; + arrowBounds.size.width = 16; arrowBounds.origin.x += bounds.size.width - 16; @@ -584,9 +606,9 @@ static void DrawDarkButton( */ if (!(state & TTK_STATE_BACKGROUND) && - !(state & TTK_STATE_DISABLED)) { + !(state & TTK_STATE_DISABLED)) { GradientFillRoundedRectangle(context, arrowBounds, 4, - darkSelectedGradient, 2); + darkSelectedGradient, 2); } if (kind == kThemePopupButton) { DrawUpDownArrows(context, arrowBounds, 3, 7, whiteRGBA); @@ -601,8 +623,8 @@ static void DrawDarkButton( /*---------------------------------------------------------------------- * DrawDarkIncDecButton -- * - * This is a standalone drawing procedure which draws an IncDecButton - * (as used in a Spinbox) in the Dark Mode style. + * This is a standalone drawing procedure which draws an IncDecButton (as + * used in a Spinbox) in the Dark Mode style. */ static void DrawDarkIncDecButton( @@ -640,6 +662,7 @@ static void DrawDarkIncDecButton( if (state & TTK_STATE_PRESSED) { CGRect clip = bounds; + clip.size.height /= 2; CGContextSaveGState(context); if (drawState == kThemeStatePressedDown) { @@ -647,7 +670,7 @@ static void DrawDarkIncDecButton( } CGContextClipToRect(context, clip); GradientFillRoundedRectangle(context, bounds, 5, - darkSelectedGradient, 2); + darkSelectedGradient, 2); CGContextRestoreGState(context); } DrawUpDownArrows(context, bounds, 3, 5, whiteRGBA); @@ -714,6 +737,7 @@ static void DrawDarkCheckBox( NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *stroke; CGFloat x, y; + bounds = CGRectOffset(checkbounds, bounds.origin.x, bounds.origin.y); x = bounds.origin.x; y = bounds.origin.y; @@ -741,15 +765,17 @@ static void DrawDarkCheckBox( CGContextSetStrokeColorWithColor(context, stroke.CGColor); } if (state & TTK_STATE_SELECTED) { + CGPoint check[3] = {{x+4, y+8}, {x+7, y+11}, {x+11, y+4}}; + CGContextSetLineWidth(context, 1.5); CGContextBeginPath(context); - CGPoint check[3] = {{x+4, y+8}, {x+7, y+11}, {x+11, y+4}}; CGContextAddLines(context, check, 3); CGContextStrokePath(context); } else if (state & TTK_STATE_ALTERNATE) { + CGPoint bar[2] = {{x+4, y+8}, {x+12, y+8}}; + CGContextSetLineWidth(context, 2.0); CGContextBeginPath(context); - CGPoint bar[2] = {{x+4, y+8}, {x+12, y+8}}; CGContextAddLines(context, bar, 2); CGContextStrokePath(context); } @@ -758,8 +784,8 @@ static void DrawDarkCheckBox( /*---------------------------------------------------------------------- * DrawDarkRadioButton -- * - * This is a standalone drawing procedure which draws RadioButtons - * in the Dark Mode style. + * This is a standalone drawing procedure which draws RadioButtons in the + * Dark Mode style. */ static void DrawDarkRadioButton( @@ -771,6 +797,7 @@ static void DrawDarkRadioButton( NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *fill; CGFloat x, y; + bounds = CGRectOffset(checkbounds, bounds.origin.x, bounds.origin.y); x = bounds.origin.x; y = bounds.origin.y; @@ -798,12 +825,14 @@ static void DrawDarkRadioButton( CGContextSetFillColorWithColor(context, fill.CGColor); } if (state & TTK_STATE_SELECTED) { - CGContextBeginPath(context); CGRect dot = {{x + 6, y + 6}, {6, 6}}; + + CGContextBeginPath(context); CGContextAddEllipseInRect(context, dot); CGContextFillPath(context); } else if (state & TTK_STATE_ALTERNATE) { CGRect bar = {{x + 5, y + 8}, {8, 2}}; + CGContextFillRect(context, bar); } } @@ -873,9 +902,9 @@ static void DrawDarkTab( CGContextSetStrokeColorWithColor(context, stroke.CGColor); CGContextBeginPath(context); CGContextMoveToPoint(context, originalBounds.origin.x, - originalBounds.origin.y + 1); + originalBounds.origin.y + 1); CGContextAddLineToPoint(context, originalBounds.origin.x, - originalBounds.origin.y + originalBounds.size.height - 1); + originalBounds.origin.y + originalBounds.size.height - 1); CGContextStrokePath(context); CGContextRestoreGState(context); } @@ -891,7 +920,7 @@ static void DrawDarkTab( } if (!(state & TTK_STATE_BACKGROUND)) { GradientFillRoundedRectangle(context, bounds, 4, - darkSelectedGradient, 2); + darkSelectedGradient, 2); } else { faceColor = [NSColor colorWithColorSpace: deviceRGB components: darkInactiveSelectedTab @@ -901,12 +930,12 @@ static void DrawDarkTab( HighlightButtonBorder(context, bounds); } } - + /*---------------------------------------------------------------------- * DrawDarkSeparator -- * - * This is a standalone drawing procedure which draws a separator widget - * in Dark Mode. + * This is a standalone drawing procedure which draws a separator widget in + * Dark Mode. */ static void DrawDarkSeparator( @@ -919,15 +948,16 @@ static void DrawDarkSeparator( NSColor *fillColor = [NSColor colorWithColorSpace: deviceRGB components: fill count:4]; + CGContextSetFillColorWithColor(context, fillColor.CGColor); CGContextFillRect(context, bounds); } - + /*---------------------------------------------------------------------- * DrawDarkFrame -- * - * This is a standalone drawing procedure which draws various - * types of borders in Dark Mode. + * This is a standalone drawing procedure which draws various types of + * borders in Dark Mode. */ static void DrawDarkFrame( @@ -937,7 +967,6 @@ static void DrawDarkFrame( { NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *stroke; - CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace); CGFloat x = bounds.origin.x, y = bounds.origin.y; CGFloat w = bounds.size.width, h = bounds.size.height; CGPoint topPart[4] = { @@ -945,7 +974,9 @@ static void DrawDarkFrame( }; CGPoint bottom[2] = {{x, y + h}, {x + w, y + h}}; CGPoint accent[2] = {{x, y + 1}, {x + w, y + 1}}; - switch(kind) { + + CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace); + switch (kind) { case kHIThemeFrameTextFieldSquare: CGContextSaveGState(context); CGContextSetShouldAntialias(context, false); @@ -978,8 +1009,8 @@ static void DrawDarkFrame( /*---------------------------------------------------------------------- * DrawListHeader -- * - * This is a standalone drawing procedure which draws column - * headers for a Treeview in the Dark Mode. + * This is a standalone drawing procedure which draws column headers for a + * Treeview in the Dark Mode. */ static void DrawDarkListHeader( @@ -990,13 +1021,13 @@ static void DrawDarkListHeader( { NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *stroke; - CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace); CGFloat x = bounds.origin.x, y = bounds.origin.y; CGFloat w = bounds.size.width, h = bounds.size.height; CGPoint top[2] = {{x, y}, {x + w, y}}; CGPoint bottom[2] = {{x, y + h}, {x + w, y + h}}; CGPoint separator[2] = {{x + w, y + 3}, {x + w, y + h - 3}}; + CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace); CGContextSaveGState(context); CGContextSetShouldAntialias(context, false); stroke = [NSColor colorWithColorSpace: deviceRGB @@ -1032,8 +1063,8 @@ static void DrawDarkListHeader( */ /* - * When Ttk draws the various types of buttons, a pointer to one of these - * is passed as the clientData. + * When Ttk draws the various types of buttons, a pointer to one of these is + * passed as the clientData. */ typedef struct { @@ -1082,6 +1113,7 @@ static inline HIThemeButtonDrawInfo computeButtonDrawInfo( */ SInt32 HIThemeState; + switch (params->kind) { case kThemePushButton: HIThemeState = kThemeStateActive; @@ -1101,9 +1133,13 @@ static inline HIThemeButtonDrawInfo computeButtonDrawInfo( return info; } -static void ButtonElementMinSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) +static void +ButtonElementMinSize( + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, int *minHeight, + Ttk_Padding *paddingPtr) { ThemeButtonParams *params = clientData; @@ -1111,9 +1147,8 @@ static void ButtonElementMinSize( ChkErr(GetThemeMetric, params->heightMetric, minHeight); /* - * The theme height does not include the 1-pixel border around - * the button, although it does include the 1-pixel shadow at - * the bottom. + * The theme height does not include the 1-pixel border around the + * button, although it does include the 1-pixel shadow at the bottom. */ *minHeight += 2; @@ -1129,9 +1164,13 @@ static void ButtonElementMinSize( } } -static void ButtonElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) +static void +ButtonElementSize( + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, int *minHeight, + Ttk_Padding *paddingPtr) { ThemeButtonParams *params = clientData; const HIThemeButtonDrawInfo info = computeButtonDrawInfo(params, 0, tkwin); @@ -1153,10 +1192,10 @@ static void ButtonElementSize( * to draw a button with a certain bounding rectangle it draws the button * centered within the rectangle. * - * To compute the effective padding around a button we request the - * content and bounding rectangles for a 100x100 button and use the - * padding between those. However, we symmetrize the padding on the - * top and bottom, because that is how the button will be drawn. + * To compute the effective padding around a button we request the content + * and bounding rectangles for a 100x100 button and use the padding between + * those. However, we symmetrize the padding on the top and bottom, because + * that is how the button will be drawn. */ ChkErr(HIThemeGetButtonContentBounds, @@ -1170,16 +1209,21 @@ static void ButtonElementSize( paddingPtr->top = paddingPtr->bottom = verticalPad / 2; } -static void ButtonElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) +static void +ButtonElementDraw( + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { ThemeButtonParams *params = clientData; CGRect bounds = BoxToRect(d, b); HIThemeButtonDrawInfo info = computeButtonDrawInfo(params, state, tkwin); bounds = NormalizeButtonBounds(params->heightMetric, bounds); - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); if (TkMacOSXInDarkMode(tkwin)) { #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 switch (info.kind) { @@ -1235,7 +1279,7 @@ static void ButtonElementDraw( ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL); } - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec ButtonElementSpec = { @@ -1315,18 +1359,26 @@ static Ttk_StateTable TabPositionTable[] = { * TP30000359-TPXREF116> */ -static void TabElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) +static void +TabElementSize( + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, int *minHeight, + Ttk_Padding *paddingPtr) { - GetThemeMetric(kThemeMetricLargeTabHeight, (SInt32 *)minHeight); + GetThemeMetric(kThemeMetricLargeTabHeight, (SInt32 *) minHeight); *paddingPtr = Ttk_MakePadding(0, 0, 0, 2); - } -static void TabElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) +static void +TabElementDraw( + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { CGRect bounds = BoxToRect(d, b); HIThemeTabDrawInfo info = { @@ -1338,7 +1390,8 @@ static void TabElementDraw( .kind = kHIThemeTabKindNormal, .position = Ttk_StateTableLookup(TabPositionTable, state), }; - BEGIN_DRAWING(d) + + BEGIN_DRAWING(d); #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { DrawDarkTab(bounds, state, dc.context); @@ -1348,7 +1401,7 @@ static void TabElementDraw( #else ChkErr(HIThemeDrawTab, &bounds, &info, dc.context, HIOrientation, NULL); #endif - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec TabElementSpec = { @@ -1375,27 +1428,28 @@ static void PaneElementDraw( Drawable d, Ttk_Box b, Ttk_State state) { CGRect bounds = BoxToRect(d, b); + bounds.origin.y -= kThemeMetricTabFrameOverlap; bounds.size.height += kThemeMetricTabFrameOverlap; - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); if ([NSApp macMinorVersion] > 9) { #if MAC_OS_X_VERSION_MAX_ALLOWED > 1080 - DrawGroupBox(bounds, dc.context, tkwin); + DrawGroupBox(bounds, dc.context, tkwin); #endif } else { - HIThemeTabPaneDrawInfo info = { - .version = 1, - .state = Ttk_StateTableLookup(ThemeStateTable, state), - .direction = kThemeTabNorth, - .size = kHIThemeTabSizeNormal, - .kind = kHIThemeTabKindNormal, - .adornment = kHIThemeTabPaneAdornmentNormal, - }; - bounds.origin.y -= kThemeMetricTabFrameOverlap; - bounds.size.height += kThemeMetricTabFrameOverlap; - ChkErr(HIThemeDrawTabPane, &bounds, &info, dc.context, HIOrientation); + HIThemeTabPaneDrawInfo info = { + .version = 1, + .state = Ttk_StateTableLookup(ThemeStateTable, state), + .direction = kThemeTabNorth, + .size = kHIThemeTabSizeNormal, + .kind = kHIThemeTabKindNormal, + .adornment = kHIThemeTabPaneAdornmentNormal, + }; + bounds.origin.y -= kThemeMetricTabFrameOverlap; + bounds.size.height += kThemeMetricTabFrameOverlap; + ChkErr(HIThemeDrawTabPane, &bounds, &info, dc.context, HIOrientation); } - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec PaneElementSpec = { @@ -1418,32 +1472,39 @@ static Ttk_ElementSpec PaneElementSpec = { */ static void GroupElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, int *minHeight, + Ttk_Padding *paddingPtr) { *paddingPtr = Ttk_UniformPadding(4); } static void GroupElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { CGRect bounds = BoxToRect(d, b); - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); if ([NSApp macMinorVersion] > 9) { #if MAC_OS_X_VERSION_MAX_ALLOWED > 1080 - DrawGroupBox(bounds, dc.context, tkwin); + DrawGroupBox(bounds, dc.context, tkwin); #endif } else { - const HIThemeGroupBoxDrawInfo info = { - .version = 0, - .state = Ttk_StateTableLookup(ThemeStateTable, state), - .kind = kHIThemeGroupBoxKindPrimaryOpaque, - }; - ChkErr(HIThemeDrawGroupBox, &bounds, &info, dc.context, HIOrientation); + const HIThemeGroupBoxDrawInfo info = { + .version = 0, + .state = Ttk_StateTableLookup(ThemeStateTable, state), + .kind = kHIThemeGroupBoxKindPrimaryOpaque, + }; + ChkErr(HIThemeDrawGroupBox, &bounds, &info, dc.context, HIOrientation); } - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec GroupElementSpec = { @@ -1469,9 +1530,9 @@ typedef struct { static Ttk_ElementOptionSpec EntryElementOptions[] = { { "-background", TK_OPTION_BORDER, - Tk_Offset(EntryElement,backgroundObj), ENTRY_DEFAULT_BACKGROUND }, + Tk_Offset(EntryElement,backgroundObj), ENTRY_DEFAULT_BACKGROUND }, { "-fieldbackground", TK_OPTION_BORDER, - Tk_Offset(EntryElement,fieldbackgroundObj), ENTRY_DEFAULT_BACKGROUND }, + Tk_Offset(EntryElement,fieldbackgroundObj), ENTRY_DEFAULT_BACKGROUND }, {0} }; @@ -1495,9 +1556,10 @@ static void EntryElementDraw( if (TkMacOSXInDarkMode(tkwin)) { #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; CGFloat fill[4]; + GetBackgroundColor(dc.context, tkwin, 1, fill); background = [NSColor colorWithColorSpace: deviceRGB components: fill @@ -1505,7 +1567,7 @@ static void EntryElementDraw( CGContextSetFillColorWithColor(dc.context, background.CGColor); CGContextFillRect(dc.context, bounds); DrawDarkFrame(bounds, dc.context, kHIThemeFrameTextFieldSquare); - END_DRAWING + END_DRAWING; #endif } else { const HIThemeFrameDrawInfo info = { @@ -1534,7 +1596,7 @@ static void EntryElementDraw( Tk_3DBorderGC(tkwin, backgroundPtr, TK_3D_FLAT_GC), inner.x, inner.y, inner.width, inner.height); } - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); if (backgroundPtr == NULL) { background = [NSColor textBackgroundColor]; #if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 @@ -1545,7 +1607,7 @@ static void EntryElementDraw( CGContextFillRect(dc.context, bounds); } ChkErr(HIThemeDrawFrame, &bounds, &info, dc.context, HIOrientation); - END_DRAWING + END_DRAWING; } /*if (state & TTK_STATE_FOCUS) { ChkErr(DrawThemeFocusRect, &bounds, 1); @@ -1604,26 +1666,26 @@ static void ComboboxElementDraw( .adornment = Ttk_StateTableLookup(ButtonAdornmentTable, state), }; - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); bounds.origin.y += 1; if (TkMacOSXInDarkMode(tkwin)) { #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 bounds.size.height += 1; DrawDarkButton(bounds, info.kind, state, dc.context); #endif - } else - { + } else { #if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 if ((state & TTK_STATE_BACKGROUND) && - !(state & TTK_STATE_DISABLED)) { + !(state & TTK_STATE_DISABLED)) { NSColor *background = [NSColor textBackgroundColor]; CGRect innerBounds = CGRectInset(bounds, 1, 2); + SolidFillRoundedRectangle(dc.context, innerBounds, 4, background); } #endif ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL); } - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec ComboboxElementSpec = { @@ -1674,12 +1736,14 @@ static void SpinButtonUpElementDraw( { CGRect bounds = BoxToRect(d, Ttk_PadBox(b, SpinbuttonMargins)); int infoState; + bounds.size.height *= 2; if (state & TTK_STATE_PRESSED) { infoState = kThemeStatePressedUp; } else { infoState = Ttk_StateTableLookup(ThemeStateTable, state); } + const HIThemeButtonDrawInfo info = { .version = 0, .state = infoState, @@ -1687,7 +1751,8 @@ static void SpinButtonUpElementDraw( .value = Ttk_StateTableLookup(ButtonValueTable, state), .adornment = kThemeAdornmentNone, }; - BEGIN_DRAWING(d) + + BEGIN_DRAWING(d); #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { DrawDarkIncDecButton(bounds, infoState, state, dc.context); @@ -1696,7 +1761,7 @@ static void SpinButtonUpElementDraw( { ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL); } - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec SpinButtonUpElementSpec = { @@ -1725,12 +1790,13 @@ static void SpinButtonDownElementDraw( { CGRect bounds = BoxToRect(d, Ttk_PadBox(b, SpinbuttonMargins)); int infoState = 0; + bounds.origin.y -= bounds.size.height; bounds.size.height *= 2; if (state & TTK_STATE_PRESSED) { infoState = kThemeStatePressedDown; } else { - return; + return; // ??? } const HIThemeButtonDrawInfo info = { .version = 0, @@ -1740,16 +1806,17 @@ static void SpinButtonDownElementDraw( .adornment = kThemeAdornmentNone, }; - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { DrawDarkIncDecButton(bounds, infoState, state, dc.context); } else #endif { - ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL); + ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, + NULL); } - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec SpinButtonDownElementSpec = { @@ -1850,7 +1917,7 @@ static void TrackElementDraw( info.trackInfo.slider.thumbDir = kThemeThumbPlain; } } - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { CGRect bounds = BoxToRect(d, b); @@ -1858,6 +1925,7 @@ static void TrackElementDraw( NSColor *trackColor = [NSColor colorWithColorSpace: deviceRGB components: darkTrack count: 4]; + if (orientation == TTK_ORIENT_HORIZONTAL) { bounds = CGRectInset(bounds, 1, bounds.size.height/2 - 2); } else { @@ -1867,7 +1935,7 @@ static void TrackElementDraw( } #endif ChkErr(HIThemeDrawTrack, &info, NULL, dc.context, HIOrientation); - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec TrackElementSpec = { @@ -1887,6 +1955,7 @@ static Ttk_ElementSpec TrackElementSpec = { * Also buggy: The geometry here is a Wild-Assed-Guess; I can't figure out how * to get the Appearance Manager to tell me the slider size. */ + static void SliderElementSize( void *clientData, void *elementRecord, Tk_Window tkwin, int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) @@ -1971,7 +2040,7 @@ static void PbarElementDraw( .trackInfo.progress.phase = phase, }; - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { CGRect bounds = BoxToRect(d, b); @@ -1988,7 +2057,7 @@ static void PbarElementDraw( } #endif ChkErr(HIThemeDrawTrack, &info, NULL, dc.context, HIOrientation); - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec PbarElementSpec = { @@ -2054,6 +2123,7 @@ static void TroughElementDraw( NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *troughColor; CGFloat *rgba = TkMacOSXInDarkMode(tkwin) ? darkTrough : lightTrough; + Ttk_GetOrientFromObj(NULL, scrollbar->orientObj, &orientation); if (orientation == TTK_ORIENT_HORIZONTAL) { bounds = CGRectInset(bounds, 0, 1); @@ -2063,7 +2133,7 @@ static void TroughElementDraw( troughColor = [NSColor colorWithColorSpace: deviceRGB components: rgba count: 4]; - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); if ([NSApp macMinorVersion] > 8) { #if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 CGContextSetFillColorWithColor(dc.context, troughColor.CGColor); @@ -2073,7 +2143,7 @@ static void TroughElementDraw( dc.context, HIOrientation); } CGContextFillRect(dc.context, bounds); - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec TroughElementSpec = { @@ -2105,6 +2175,7 @@ static void ThumbElementDraw( { ScrollbarElement *scrollbar = elementRecord; int orientation = TTK_ORIENT_HORIZONTAL; + Ttk_GetOrientFromObj(NULL, scrollbar->orientObj, &orientation); /* @@ -2129,15 +2200,18 @@ static void ThumbElementDraw( NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *thumbColor; CGFloat *rgba; - if ((orientation == TTK_ORIENT_HORIZONTAL && - thumbBounds.size.width >= Tk_Width(tkwin) - 8) || - (orientation == TTK_ORIENT_VERTICAL && - thumbBounds.size.height >= Tk_Height(tkwin) - 8)) { + + if ((orientation == TTK_ORIENT_HORIZONTAL + && thumbBounds.size.width >= Tk_Width(tkwin) - 8) + || (orientation == TTK_ORIENT_VERTICAL + && thumbBounds.size.height >= Tk_Height(tkwin) - 8)) { return; } + int isDark = TkMacOSXInDarkMode(tkwin); + if ((state & TTK_STATE_PRESSED) || - (state & TTK_STATE_HOVER) ) { + (state & TTK_STATE_HOVER)) { rgba = isDark ? darkActiveThumb : lightActiveThumb; } else { rgba = isDark ? darkInactiveThumb : lightInactiveThumb; @@ -2145,9 +2219,9 @@ static void ThumbElementDraw( thumbColor = [NSColor colorWithColorSpace: deviceRGB components: rgba count: 4]; - BEGIN_DRAWING(d) - SolidFillRoundedRectangle(dc.context, thumbBounds, 4, thumbColor); - END_DRAWING + BEGIN_DRAWING(d); + SolidFillRoundedRectangle(dc.context, thumbBounds, 4, thumbColor); + END_DRAWING; #endif } else { double thumbSize, trackSize, visibleSize, viewSize; @@ -2164,6 +2238,7 @@ static void ThumbElementDraw( */ viewSize = RangeToFactor(100.0); + HIThemeTrackDrawInfo info = { .version = 0, .bounds = troughBounds, @@ -2171,6 +2246,7 @@ static void ThumbElementDraw( .attributes = kThemeTrackShowThumb | kThemeTrackThumbRgnIsNotGhost, .enableState = kThemeTrackActive }; + info.trackInfo.scrollbar.viewsize = viewSize*.8; if (orientation == TTK_ORIENT_HORIZONTAL) { trackSize = troughBounds.size.width; @@ -2186,7 +2262,7 @@ static void ThumbElementDraw( info.value = info.max * (b.y / (trackSize - thumbSize)); } if ((state & TTK_STATE_PRESSED) || - (state & TTK_STATE_HOVER) ) { + (state & TTK_STATE_HOVER)) { info.trackInfo.scrollbar.pressState = kThemeThumbPressed; } else { info.trackInfo.scrollbar.pressState = 0; @@ -2196,10 +2272,10 @@ static void ThumbElementDraw( } else { info.attributes &= ~kThemeTrackHorizontal; } - BEGIN_DRAWING(d) - HIThemeDrawTrack (&info, 0, dc.context, kHIThemeOrientationNormal); - END_DRAWING - } + BEGIN_DRAWING(d); + HIThemeDrawTrack(&info, 0, dc.context, kHIThemeOrientationNormal); + END_DRAWING; + } } static Ttk_ElementSpec ThumbElementSpec = { @@ -2255,7 +2331,7 @@ static void SeparatorElementDraw( .state = Ttk_StateTableLookup(ThemeStateTable, state & TTK_STATE_BACKGROUND), }; - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { DrawDarkSeparator(bounds, dc.context, tkwin); @@ -2265,7 +2341,7 @@ static void SeparatorElementDraw( #else ChkErr(HIThemeDrawSeparator, &bounds, &info, dc.context, HIOrientation); #endif - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec SeparatorElementSpec = { @@ -2316,9 +2392,9 @@ static void SizegripElementDraw( .size = kHIThemeGrowBoxSizeNormal, }; - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); ChkErr(HIThemeDrawGrowBox, &bounds.origin, &info, dc.context, HIOrientation); - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec SizegripElementSpec = { @@ -2381,23 +2457,25 @@ static void FillElementDraw( NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *bgColor; CGFloat fill[4]; - BEGIN_DRAWING(d) + + BEGIN_DRAWING(d); GetBackgroundColor(dc.context, tkwin, 0, fill); bgColor = [NSColor colorWithColorSpace: deviceRGB components: fill count: 4]; CGContextSetFillColorSpace(dc.context, deviceRGB.CGColorSpace); CGContextSetFillColorWithColor(dc.context, bgColor.CGColor); CGContextFillRect(dc.context, bounds); - END_DRAWING + END_DRAWING; #else ThemeBrush brush = (state & TTK_STATE_BACKGROUND) ? kThemeBrushModelessDialogBackgroundInactive : kThemeBrushModelessDialogBackgroundActive; - BEGIN_DRAWING(d) + + BEGIN_DRAWING(d); ChkErr(HIThemeSetFill, brush, NULL, dc.context, HIOrientation); //QDSetPatternOrigin(PatternOrigin(tkwin, d)); CGContextFillRect(dc.context, bounds); - END_DRAWING + END_DRAWING; #endif } @@ -2406,7 +2484,7 @@ static void BackgroundElementDraw( Drawable d, Ttk_Box b, unsigned int state) { FillElementDraw(clientData, elementRecord, tkwin, d, Ttk_WinBox(tkwin), - state); + state); } static Ttk_ElementSpec FillElementSpec = { @@ -2429,9 +2507,9 @@ static Ttk_ElementSpec BackgroundElementSpec = { * +++ ToolbarBackground element -- toolbar style for frames. * * This is very similar to the normal background element, but uses a - * different ThemeBrush in order to get the lighter pinstripe effect - * used in toolbars. We use SetThemeBackground() rather than - * ApplyThemeBackground() in order to get the right style. + * different ThemeBrush in order to get the lighter pinstripe effect used in + * toolbars. We use SetThemeBackground() rather than ApplyThemeBackground() + * in order to get the right style. * * 8) { #if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 - /* - * Compensate for the padding added in TreeHeaderElementSize, so - * the larger heading will be drawn at the top of the widget. + * Compensate for the padding added in TreeHeaderElementSize, so the + * larger heading will be drawn at the top of the widget. */ bounds.origin.y -= 4; @@ -2586,7 +2663,7 @@ static void TreeHeaderElementDraw( } else { ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL); } - END_DRAWING + END_DRAWING; } static Ttk_ElementSpec TreeHeaderElementSpec = { @@ -2636,9 +2713,9 @@ static void DisclosureElementDraw( .adornment = kThemeAdornmentDrawIndicatorOnly, }; - BEGIN_DRAWING(d) + BEGIN_DRAWING(d); ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL); - END_DRAWING + END_DRAWING; } } @@ -2735,13 +2812,15 @@ TTK_LAYOUT("Horizontal.TScrollbar", TTK_NODE("Horizontal.Scrollbar.rightarrow", TTK_PACK_RIGHT) TTK_NODE("Horizontal.Scrollbar.leftarrow", TTK_PACK_RIGHT))) -TTK_END_LAYOUT_TABLE +TTK_END_LAYOUT_TABLE; /*---------------------------------------------------------------------- * +++ Initialization. */ -static int AquaTheme_Init(Tcl_Interp *interp) +static int +AquaTheme_Init( + Tcl_Interp *interp) { Ttk_Theme themePtr = Ttk_CreateTheme(interp, "aqua", NULL); @@ -2752,38 +2831,41 @@ static int AquaTheme_Init(Tcl_Interp *interp) /* * Elements: */ + Ttk_RegisterElementSpec(themePtr, "background", &BackgroundElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "fill", &FillElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "field", &FieldElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Toolbar.background", - &ToolbarBackgroundElementSpec, 0); + &ToolbarBackgroundElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Button.button", - &ButtonElementSpec, &PushButtonParams); + &ButtonElementSpec, &PushButtonParams); Ttk_RegisterElementSpec(themePtr, "Checkbutton.button", - &ButtonElementSpec, &CheckBoxParams); + &ButtonElementSpec, &CheckBoxParams); Ttk_RegisterElementSpec(themePtr, "Radiobutton.button", - &ButtonElementSpec, &RadioButtonParams); + &ButtonElementSpec, &RadioButtonParams); Ttk_RegisterElementSpec(themePtr, "Toolbutton.border", - &ButtonElementSpec, &BevelButtonParams); + &ButtonElementSpec, &BevelButtonParams); Ttk_RegisterElementSpec(themePtr, "Menubutton.button", - &ButtonElementSpec, &PopupButtonParams); + &ButtonElementSpec, &PopupButtonParams); Ttk_RegisterElementSpec(themePtr, "Spinbox.uparrow", - &SpinButtonUpElementSpec, 0); + &SpinButtonUpElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Spinbox.downarrow", - &SpinButtonDownElementSpec, 0); + &SpinButtonDownElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Combobox.button", - &ComboboxElementSpec, 0); + &ComboboxElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Treeitem.indicator", - &DisclosureElementSpec, &DisclosureParams); + &DisclosureElementSpec, &DisclosureParams); Ttk_RegisterElementSpec(themePtr, "Treeheading.cell", - &TreeHeaderElementSpec, &ListHeaderParams); + &TreeHeaderElementSpec, &ListHeaderParams); - Ttk_RegisterElementSpec(themePtr, "Treeview.treearea", &TreeAreaElementSpec, 0); + Ttk_RegisterElementSpec(themePtr, "Treeview.treearea", + &TreeAreaElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Notebook.tab", &TabElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Notebook.client", &PaneElementSpec, 0); - Ttk_RegisterElementSpec(themePtr, "Labelframe.border", &GroupElementSpec, 0); + Ttk_RegisterElementSpec(themePtr, "Labelframe.border", + &GroupElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Entry.field", &EntryElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Spinbox.field", &EntryElementSpec, 0); @@ -2803,23 +2885,31 @@ static int AquaTheme_Init(Tcl_Interp *interp) Ttk_RegisterElementSpec(themePtr,"Progressbar.track", &PbarElementSpec, 0); Ttk_RegisterElementSpec(themePtr,"Scale.trough", &TrackElementSpec, - &ScaleData); + &ScaleData); Ttk_RegisterElementSpec(themePtr,"Scale.slider", &SliderElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.trough", &TroughElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.thumb", &ThumbElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.trough", &TroughElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.thumb", &ThumbElementSpec, 0); + Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.trough", + &TroughElementSpec, 0); + Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.thumb", + &ThumbElementSpec, 0); + Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.trough", + &TroughElementSpec, 0); + Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.thumb", + &ThumbElementSpec, 0); /* * If we are not in Snow Leopard or Lion the arrows won't actually be * displayed. */ - Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.uparrow", &ArrowElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.downarrow", &ArrowElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.leftarrow", &ArrowElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.rightarrow", &ArrowElementSpec, 0); + Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.uparrow", + &ArrowElementSpec, 0); + Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.downarrow", + &ArrowElementSpec, 0); + Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.leftarrow", + &ArrowElementSpec, 0); + Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.rightarrow", + &ArrowElementSpec, 0); /* * Layouts: -- cgit v0.12 From fe47ed884e4c078ce819858ea94ef4319721dd04 Mon Sep 17 00:00:00 2001 From: culler Date: Wed, 17 Apr 2019 14:30:50 +0000 Subject: Add a couple of blank lines. --- macosx/tkMacOSXKeyEvent.c | 1 + macosx/tkMacOSXMenu.c | 1 + 2 files changed, 2 insertions(+) diff --git a/macosx/tkMacOSXKeyEvent.c b/macosx/tkMacOSXKeyEvent.c index 7ff1184..d578c36 100644 --- a/macosx/tkMacOSXKeyEvent.c +++ b/macosx/tkMacOSXKeyEvent.c @@ -732,6 +732,7 @@ isFunctionKey( const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym) / sizeof (convert_ns_to_X_keysym[0])); unsigned keysym; + for (keysym = 0; keysym < last_keysym; keysym += 2) { if (code == convert_ns_to_X_keysym[keysym]) { return 0xFF00 | convert_ns_to_X_keysym[keysym+1]; diff --git a/macosx/tkMacOSXMenu.c b/macosx/tkMacOSXMenu.c index fc1b7c4..e04b413 100644 --- a/macosx/tkMacOSXMenu.c +++ b/macosx/tkMacOSXMenu.c @@ -698,6 +698,7 @@ TkpConfigureMenuEntry( int i = 0; NSArray *itemArray = [submenu itemArray]; + for (NSMenuItem *item in itemArray) { TkMenuEntry *submePtr = menuRefPtr->menuPtr->entries[i]; -- cgit v0.12 From 7d6fc907cfaf28414508b5d86fe39cee99b6168a Mon Sep 17 00:00:00 2001 From: culler Date: Wed, 17 Apr 2019 15:02:23 +0000 Subject: Adjust some whitespace. --- macosx/tkMacOSXKeyEvent.c | 102 +++++++++++++++++++++++----------------------- macosx/tkMacOSXMenu.c | 10 +++-- 2 files changed, 58 insertions(+), 54 deletions(-) diff --git a/macosx/tkMacOSXKeyEvent.c b/macosx/tkMacOSXKeyEvent.c index d578c36..6cf3783 100644 --- a/macosx/tkMacOSXKeyEvent.c +++ b/macosx/tkMacOSXKeyEvent.c @@ -666,54 +666,54 @@ Tk_SetCaretPos( static unsigned convert_ns_to_X_keysym[] = { - NSHomeFunctionKey, 0x50, - NSLeftArrowFunctionKey, 0x51, - NSUpArrowFunctionKey, 0x52, - NSRightArrowFunctionKey, 0x53, - NSDownArrowFunctionKey, 0x54, - NSPageUpFunctionKey, 0x55, - NSPageDownFunctionKey, 0x56, - NSEndFunctionKey, 0x57, - NSBeginFunctionKey, 0x58, - NSSelectFunctionKey, 0x60, - NSPrintFunctionKey, 0x61, - NSExecuteFunctionKey, 0x62, - NSInsertFunctionKey, 0x63, - NSUndoFunctionKey, 0x65, - NSRedoFunctionKey, 0x66, - NSMenuFunctionKey, 0x67, - NSFindFunctionKey, 0x68, - NSHelpFunctionKey, 0x6A, - NSBreakFunctionKey, 0x6B, - - NSF1FunctionKey, 0xBE, - NSF2FunctionKey, 0xBF, - NSF3FunctionKey, 0xC0, - NSF4FunctionKey, 0xC1, - NSF5FunctionKey, 0xC2, - NSF6FunctionKey, 0xC3, - NSF7FunctionKey, 0xC4, - NSF8FunctionKey, 0xC5, - NSF9FunctionKey, 0xC6, - NSF10FunctionKey, 0xC7, - NSF11FunctionKey, 0xC8, - NSF12FunctionKey, 0xC9, - NSF13FunctionKey, 0xCA, - NSF14FunctionKey, 0xCB, - NSF15FunctionKey, 0xCC, - NSF16FunctionKey, 0xCD, - NSF17FunctionKey, 0xCE, - NSF18FunctionKey, 0xCF, - NSF19FunctionKey, 0xD0, - NSF20FunctionKey, 0xD1, - NSF21FunctionKey, 0xD2, - NSF22FunctionKey, 0xD3, - NSF23FunctionKey, 0xD4, - NSF24FunctionKey, 0xD5, - - NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */ - NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */ - NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */ + NSHomeFunctionKey, 0x50, + NSLeftArrowFunctionKey, 0x51, + NSUpArrowFunctionKey, 0x52, + NSRightArrowFunctionKey, 0x53, + NSDownArrowFunctionKey, 0x54, + NSPageUpFunctionKey, 0x55, + NSPageDownFunctionKey, 0x56, + NSEndFunctionKey, 0x57, + NSBeginFunctionKey, 0x58, + NSSelectFunctionKey, 0x60, + NSPrintFunctionKey, 0x61, + NSExecuteFunctionKey, 0x62, + NSInsertFunctionKey, 0x63, + NSUndoFunctionKey, 0x65, + NSRedoFunctionKey, 0x66, + NSMenuFunctionKey, 0x67, + NSFindFunctionKey, 0x68, + NSHelpFunctionKey, 0x6A, + NSBreakFunctionKey, 0x6B, + + NSF1FunctionKey, 0xBE, + NSF2FunctionKey, 0xBF, + NSF3FunctionKey, 0xC0, + NSF4FunctionKey, 0xC1, + NSF5FunctionKey, 0xC2, + NSF6FunctionKey, 0xC3, + NSF7FunctionKey, 0xC4, + NSF8FunctionKey, 0xC5, + NSF9FunctionKey, 0xC6, + NSF10FunctionKey, 0xC7, + NSF11FunctionKey, 0xC8, + NSF12FunctionKey, 0xC9, + NSF13FunctionKey, 0xCA, + NSF14FunctionKey, 0xCB, + NSF15FunctionKey, 0xCC, + NSF16FunctionKey, 0xCD, + NSF17FunctionKey, 0xCE, + NSF18FunctionKey, 0xCF, + NSF19FunctionKey, 0xD0, + NSF20FunctionKey, 0xD1, + NSF21FunctionKey, 0xD2, + NSF22FunctionKey, 0xD3, + NSF23FunctionKey, 0xD4, + NSF24FunctionKey, 0xD5, + + NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */ + NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */ + NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */ NSTabCharacter, 0x09, 0x19, 0x09, /* left tab->regular since pass shift */ @@ -729,13 +729,13 @@ static unsigned isFunctionKey( unsigned code) { - const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym) - / sizeof (convert_ns_to_X_keysym[0])); + const unsigned last_keysym = (sizeof(convert_ns_to_X_keysym) + / sizeof(convert_ns_to_X_keysym[0])); unsigned keysym; for (keysym = 0; keysym < last_keysym; keysym += 2) { if (code == convert_ns_to_X_keysym[keysym]) { - return 0xFF00 | convert_ns_to_X_keysym[keysym+1]; + return 0xFF00 | convert_ns_to_X_keysym[keysym + 1]; } } return 0; diff --git a/macosx/tkMacOSXMenu.c b/macosx/tkMacOSXMenu.c index e04b413..053b374 100644 --- a/macosx/tkMacOSXMenu.c +++ b/macosx/tkMacOSXMenu.c @@ -691,7 +691,8 @@ TkpConfigureMenuEntry( if ([menuItem isEnabled]) { - /* This menuItem might have been previously disabled (XXX: + /* + * This menuItem might have been previously disabled (XXX: * track this), which would have disabled entries; we must * re-enable the entries here. */ @@ -702,11 +703,14 @@ TkpConfigureMenuEntry( for (NSMenuItem *item in itemArray) { TkMenuEntry *submePtr = menuRefPtr->menuPtr->entries[i]; - /* Work around an apparent bug where itemArray can have + /* + * Work around an apparent bug where itemArray can have * more items than the menu's entries[] array. */ - if (i >= menuRefPtr->menuPtr->numEntries) break; + if (i >= (int) menuRefPtr->menuPtr->numEntries) { + break; + } [item setEnabled: !(submePtr->state == ENTRY_DISABLED)]; i++; } -- cgit v0.12 From 3379fb3b181b00a1d943eb3a009f97437fcce779 Mon Sep 17 00:00:00 2001 From: culler Date: Wed, 17 Apr 2019 20:41:37 +0000 Subject: Clean up formatting in ttkMacOSXTheme.c. --- macosx/ttkMacOSXTheme.c | 1939 ++++++++++++++++++++++++++--------------------- 1 file changed, 1062 insertions(+), 877 deletions(-) diff --git a/macosx/ttkMacOSXTheme.c b/macosx/ttkMacOSXTheme.c index 0c474f0..1f231a9 100644 --- a/macosx/ttkMacOSXTheme.c +++ b/macosx/ttkMacOSXTheme.c @@ -1,7 +1,7 @@ /* * ttkMacOSXTheme.c -- * - * Tk theme engine for Mac OSX, using the Appearance Manager API. + * Tk theme engine for Mac OSX, using the Appearance Manager API. * * Copyright (c) 2004 Joe English * Copyright (c) 2005 Neil Madden @@ -16,30 +16,32 @@ * See also: * * + * Appearance_Manager/appearance_manager/APIIndex.html > * * Notes: - * "Active" means different things in Mac and Tk terminology -- - * On Aqua, widgets are "Active" if they belong to the foreground window, - * "Inactive" if they are in a background window. Tk uses the term - * "active" to mean that the mouse cursor is over a widget; aka "hover", - * "prelight", or "hot-tracked". Aqua doesn't use this kind of feedback. + * "Active" means different things in Mac and Tk terminology -- + * On Aqua, widgets are "Active" if they belong to the foreground window, + * "Inactive" if they are in a background window. Tk uses the term + * "active" to mean that the mouse cursor is over a widget; aka "hover", + * "prelight", or "hot-tracked". Aqua doesn't use this kind of feedback. * - * The QuickDraw/Carbon coordinate system is relative to the top-level - * window, not to the Tk_Window. BoxToRect() accounts for this. + * The QuickDraw/Carbon coordinate system is relative to the top-level + * window, not to the Tk_Window. BoxToRect() accounts for this. */ #include "tkMacOSXPrivate.h" #include "ttk/ttkTheme.h" #include + /* * Macros for handling drawing contexts. */ -#define BEGIN_DRAWING(d) { \ - TkMacOSXDrawingContext dc; \ - if (!TkMacOSXSetupDrawingContext((d), NULL, 1, &dc)) {return;} + +#define BEGIN_DRAWING(d) { \ + TkMacOSXDrawingContext dc; \ + if (!TkMacOSXSetupDrawingContext((d), NULL, 1, &dc)) {return;} #define END_DRAWING \ - TkMacOSXRestoreDrawingContext(&dc); } + TkMacOSXRestoreDrawingContext(&dc);} #define HIOrientation kHIThemeOrientationNormal #define NoThemeMetric 0xFFFFFFFF @@ -50,9 +52,9 @@ #define RangeToFactor(maximum) (((double) (LONG_MAX >> 1)) / (maximum)) #endif /* __LP64__ */ -#define TTK_STATE_FIRST_TAB TTK_STATE_USER1 -#define TTK_STATE_LAST_TAB TTK_STATE_USER2 -#define TTK_TREEVIEW_STATE_SORTARROW TTK_STATE_USER1 +#define TTK_STATE_FIRST_TAB TTK_STATE_USER1 +#define TTK_STATE_LAST_TAB TTK_STATE_USER2 +#define TTK_TREEVIEW_STATE_SORTARROW TTK_STATE_USER1 /*---------------------------------------------------------------------- * +++ Utilities. @@ -60,22 +62,21 @@ /* * BoxToRect -- - * Convert a Ttk_Box in Tk coordinates relative to the given Drawable to a - * native Rect relative to the containing port. + * Convert a Ttk_Box in Tk coordinates relative to the given Drawable + * to a native Rect relative to the containing port. */ -static inline CGRect -BoxToRect( +static inline CGRect BoxToRect( Drawable d, Ttk_Box b) { - MacDrawable *md = (MacDrawable*)d; + MacDrawable *md = (MacDrawable *) d; CGRect rect; - rect.origin.y = b.y + md->yOff; - rect.origin.x = b.x + md->xOff; - rect.size.height = b.height; - rect.size.width = b.width; + rect.origin.y = b.y + md->yOff; + rect.origin.x = b.x + md->xOff; + rect.size.height = b.height; + rect.size.width = b.width; return rect; } @@ -89,49 +90,53 @@ static Ttk_StateTable ThemeStateTable[] = { {kThemeStatePressed, TTK_STATE_PRESSED, 0}, {kThemeStateInactive, TTK_STATE_BACKGROUND, 0}, {kThemeStateActive, 0, 0} -/* Others: Not sure what these are supposed to mean. - Up/Down have something to do with "little arrow" increment controls... - Dunno what a "Rollover" is. - NEM: Rollover is TTK_STATE_ACTIVE... but we don't handle that yet, by the - looks of things - {kThemeStateRollover, 0, 0}, - {kThemeStateUnavailableInactive, 0, 0} - {kThemeStatePressedUp, 0, 0}, - {kThemeStatePressedDown, 0, 0} -*/ + + /* Others: Not sure what these are supposed to mean. Up/Down have + * something to do with "little arrow" increment controls... Dunno what + * a "Rollover" is. + * NEM: Rollover is TTK_STATE_ACTIVE... but we don't handle that yet, by + * the looks of things + * + * {kThemeStateRollover, 0, 0}, + * {kThemeStateUnavailableInactive, 0, 0} + * {kThemeStatePressedUp, 0, 0}, + * {kThemeStatePressedDown, 0, 0} + */ }; -/* +/*---------------------------------------------------------------------- * NormalizeButtonBounds -- * - * Apple's Human Interface Guidelines only allow three specific heights for - * most buttons: Regular, small and mini. We always use the regular size. - * However, Ttk may provide an arbitrary bounding rectangle. We always draw the - * button centered vertically on the rectangle, and having the same width as - * the rectangle. This function returns the actual bounding rectangle that will - * be used in drawing the button. + * Apple's Human Interface Guidelines only allow three specific heights + * for most buttons: Regular, small and mini. We always use the regular + * size. However, Ttk may provide an arbitrary bounding rectangle. We + * always draw the button centered vertically on the rectangle, and + * having the same width as the rectangle. This function returns the + * actual bounding rectangle that will be used in drawing the button. * - * The BevelButton is allowed to have arbitrary size, and also has external - * padding. This is handled separately here. + * The BevelButton is allowed to have arbitrary size, and also has + * external padding. This is handled separately here. */ static CGRect NormalizeButtonBounds( SInt32 heightMetric, CGRect bounds) { - if (heightMetric != (SInt32) NoThemeMetric) { - SInt32 height; + SInt32 height; + if (heightMetric != (SInt32) NoThemeMetric) { ChkErr(GetThemeMetric, heightMetric, &height); - bounds.origin.y += (bounds.size.height - height)/2; + bounds.origin.y += (bounds.size.height - height) / 2; bounds.size.height = height; } return bounds; } -#if MAC_OS_X_VERSION_MAX_ALLOWED > 1080 +#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 /*---------------------------------------------------------------------- - * +++ Support for contrasting background colors when GroupBoxes or Tabbed + * +++ Backgrounds + * + * Support for contrasting background colors when GroupBoxes or Tabbed * panes are nested inside each other. Early versions of macOS used ridged * borders, so do not need contrasting backgrounds. */ @@ -144,18 +149,21 @@ static CGRect NormalizeButtonBounds( * support Dark Mode anyway. */ -static CGFloat windowBackground[4] = {236.0/255, 236.0/255, 236.0/255, 1.0}; +static CGFloat windowBackground[4] = { + 235.0 / 255, 235.0 / 255, 235.0 / 255, 1.0 +}; +static CGFloat whiteRGBA[4] = {1.0, 1.0, 1.0, 1.0}; static CGFloat blackRGBA[4] = {0.0, 0.0, 0.0, 1.0}; /*---------------------------------------------------------------------- * GetBackgroundColor -- * - * Fills the array rgba with the color coordinates for a background color. - * Start with the background color of a window's geometry master, or the - * standard ttk window background if not. If the contrast parameter is - * nonzero modify this color to be darker, for the aqua appearance, or - * lighter for the DarkAqua appearance. This is primarily used by the Fill - * and Background elements. + * Fills the array rgba with the color coordinates for a background + * color. Start with the background color of a window's geometry master, + * or the standard ttk window background if not. If the contrast + * parameter is nonzero modify this color to be darker, for the aqua + * appearance, or lighter for the DarkAqua appearance. This is primarily + * used by the Fill and Background elements. */ static void GetBackgroundColor( @@ -181,8 +189,7 @@ static void GetBackgroundColor( if ([NSApp macMinorVersion] > 13) { NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *windowColor = [[NSColor windowBackgroundColor] - colorUsingColorSpace: deviceRGB]; - + colorUsingColorSpace: deviceRGB]; [windowColor getComponents: rgba]; } else { for (int i = 0; i < 4; i++) { @@ -194,12 +201,12 @@ static void GetBackgroundColor( int isDark = (rgba[0] + rgba[1] + rgba[2] < 1.5); if (isDark) { - for (int i=0; i<3; i++) { - rgba[i] += 8.0/255.0; + for (int i = 0; i < 3; i++) { + rgba[i] += 8.0 / 255.0; } } else { - for (int i=0; i<3; i++) { - rgba[i] -= 8.0/255.0; + for (int i = 0; i < 3; i++) { + rgba[i] -= 8.0 / 255.0; } } winPtr->privatePtr->flags |= TTK_HAS_CONTRASTING_BG; @@ -212,8 +219,8 @@ static void GetBackgroundColor( /*---------------------------------------------------------------------- * DrawGroupBox -- * - * This is a standalone drawing procedure which draws the contrasting - * rounded rectangular box for LabelFrames and Notebook panes. + * This is a standalone drawing procedure which draws the contrasting + * rounded rectangular box for LabelFrames and Notebook panes. */ static void DrawGroupBox( @@ -229,7 +236,7 @@ static void DrawGroupBox( GetBackgroundColor(context, tkwin, 1, fill); bgColor = [NSColor colorWithColorSpace: deviceRGB components: fill - count: 4]; + count: 4]; CGContextSetFillColorSpace(context, deviceRGB.CGColorSpace); CGContextSetFillColorWithColor(context, bgColor.CGColor); path = CGPathCreateWithRoundedRect(bounds, 4, 4, NULL); @@ -238,7 +245,7 @@ static void DrawGroupBox( CGContextAddPath(context, path); CGContextFillPath(context); borderColor = [NSColor colorWithColorSpace: deviceRGB components: border - count: 4]; + count: 4]; CGContextSetFillColorWithColor(context, borderColor.CGColor); [borderColor getComponents: fill]; CGContextSetRGBFillColor(context, fill[0], fill[1], fill[2], fill[3]); @@ -253,7 +260,7 @@ static void DrawGroupBox( /*---------------------------------------------------------------------- * SolidFillRoundedRectangle -- * - * Fill a rounded rectangle with a specified solid color. + * Fill a rounded rectangle with a specified solid color. */ static void SolidFillRoundedRectangle( @@ -272,7 +279,44 @@ static void SolidFillRoundedRectangle( CFRelease(path); } -static void DrawDownArrow( +/*---------------------------------------------------------------------- + * GradientFillRoundedRectangle -- + * + * Fill a rounded rectangle with a specified gradient. + */ + +static void GradientFillRoundedRectangle( + CGContextRef context, + CGRect bounds, + CGFloat radius, + CGFloat *colors, + int numColors) +{ + NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; + CGPathRef path; + CGPoint end = { + bounds.origin.x, + bounds.origin.y + bounds.size.height + }; + CGGradientRef gradient = CGGradientCreateWithColorComponents( + deviceRGB.CGColorSpace, colors, NULL, numColors); + + path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL); + CGContextBeginPath(context); + CGContextAddPath(context, path); + CGContextClip(context); + CGContextDrawLinearGradient(context, gradient, bounds.origin, end, 0); + CFRelease(path); + CFRelease(gradient); +} + +/*---------------------------------------------------------------------- + * +++ Arrow Buttons -- + * + * Used in MenuButtons, SpinButtons, ComboBoxes, ListHeaders. + */ + +static void DrawUpDownArrows( CGContextRef context, CGRect bounds, CGFloat inset, @@ -284,13 +328,35 @@ static void DrawDownArrow( CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); CGContextSetLineWidth(context, 1.5); x = bounds.origin.x + inset; - y = bounds.origin.y + trunc(bounds.size.height/2); + y = bounds.origin.y + trunc(bounds.size.height / 2); + CGContextBeginPath(context); + CGPoint bottomArrow[3] = + {{x, y + 2}, {x + size / 2, y + 2 + size / 2}, {x + size, y + 2}}; + CGContextAddLines(context, bottomArrow, 3); + CGPoint topArrow[3] = + {{x, y - 2}, {x + size / 2, y - 2 - size / 2}, {x + size, y - 2}}; + CGContextAddLines(context, topArrow, 3); + CGContextStrokePath(context); +} - CGPoint arrow[3] = { - {x, y-size/4}, {x+size/2, y+size/4}, {x+size, y-size/4} - }; +static void DrawDownArrow( + CGContextRef context, + CGRect bounds, + CGFloat inset, + CGFloat size, + CGFloat *rgba) +{ + CGFloat x, y; + CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); + CGContextSetLineWidth(context, 1.5); + x = bounds.origin.x + inset; + y = bounds.origin.y + trunc(bounds.size.height / 2); CGContextBeginPath(context); + CGPoint arrow[3] = { + {x, y - size / 4}, {x + size / 2, y + size / 4}, + {x + size, y - size / 4} + }; CGContextAddLines(context, arrow, 3); CGContextStrokePath(context); } @@ -307,24 +373,23 @@ static void DrawUpArrow( CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); CGContextSetLineWidth(context, 1.5); x = bounds.origin.x + inset; - y = bounds.origin.y + trunc(bounds.size.height/2); - + y = bounds.origin.y + trunc(bounds.size.height / 2); + CGContextBeginPath(context); CGPoint arrow[3] = { - {x, y+size/4}, {x+size/2, y-size/4}, {x+size, y+size/4} + {x, y + size / 4}, {x + size / 2, y - size / 4}, + {x + size, y + size / 4} }; - - CGContextBeginPath(context); CGContextAddLines(context, arrow, 3); CGContextStrokePath(context); } /*---------------------------------------------------------------------- - * DrawListHeader -- + * +++ DrawListHeader -- * - * This is a standalone drawing procedure which draws column headers for a - * Treeview in the Aqua appearance. The HITheme headers have not matched - * the native ones since OSX 10.8. Note that the header image is ignored, - * but we draw arrows according to the state. + * This is a standalone drawing procedure which draws column headers for + * a Treeview in the Aqua appearance. The HITheme headers have not + * matched the native ones since OSX 10.8. Note that the header image is + * ignored, but we draw arrows according to the state. */ static void DrawListHeader( @@ -335,10 +400,18 @@ static void DrawListHeader( { NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *strokeColor, *bgColor; - static CGFloat borderRGBA[4] = {200.0/255, 200.0/255, 200.0/255, 1.0}; - static CGFloat separatorRGBA[4] = {220.0/255, 220.0/255, 220.0/255, 1.0}; - static CGFloat activeBgRGBA[4] = {238.0/255, 238.0/255, 238.0/255, 1.0}; - static CGFloat inactiveBgRGBA[4] = {246.0/255, 246.0/255, 246.0/255, 1.0}; + static CGFloat borderRGBA[4] = { + 200.0 / 255, 200.0 / 255, 200.0 / 255, 1.0 + }; + static CGFloat separatorRGBA[4] = { + 220.0 / 255, 220.0 / 255, 220.0 / 255, 1.0 + }; + static CGFloat activeBgRGBA[4] = { + 238.0 / 255, 238.0 / 255, 238.0 / 255, 1.0 + }; + static CGFloat inactiveBgRGBA[4] = { + 246.0 / 255, 246.0 / 255, 246.0 / 255, 1.0 + }; /* * Apple changes the background of a list header when the window is not @@ -351,12 +424,12 @@ static void DrawListHeader( CGFloat x = bounds.origin.x, y = bounds.origin.y; CGFloat w = bounds.size.width, h = bounds.size.height; CGPoint top[2] = {{x, y + 1}, {x + w, y + 1}}; - CGPoint bottom[2] = {{x, y + h}, {x + w, y + h}}; + CGPoint bottom[2] = {{x, y + h}, {x + w, y + h}}; CGPoint separator[2] = {{x + w - 1, y + 3}, {x + w - 1, y + h - 3}}; - + bgColor = [NSColor colorWithColorSpace: deviceRGB - components: bgRGBA - count: 4]; + components: bgRGBA + count: 4]; CGContextSaveGState(context); CGContextSetShouldAntialias(context, false); CGContextSetFillColorSpace(context, deviceRGB.CGColorSpace); @@ -366,14 +439,14 @@ static void DrawListHeader( CGContextAddRect(context, bounds); CGContextFillPath(context); strokeColor = [NSColor colorWithColorSpace: deviceRGB - components: separatorRGBA - count: 4]; + components: separatorRGBA + count: 4]; CGContextSetStrokeColorWithColor(context, strokeColor.CGColor); CGContextAddLines(context, separator, 2); CGContextStrokePath(context); strokeColor = [NSColor colorWithColorSpace: deviceRGB - components: borderRGBA - count: 4]; + components: borderRGBA + count: 4]; CGContextSetStrokeColorWithColor(context, strokeColor.CGColor); CGContextAddLines(context, top, 2); CGContextStrokePath(context); @@ -383,7 +456,6 @@ static void DrawListHeader( if (state & TTK_TREEVIEW_STATE_SORTARROW) { CGRect arrowBounds = bounds; - arrowBounds.origin.x = bounds.origin.x + bounds.size.width - 16; arrowBounds.size.width = 16; if (state & TTK_STATE_ALTERNATE) { @@ -394,99 +466,63 @@ static void DrawListHeader( } } -#endif /* MAC_OS_X_VERSION_MAX_ALLOWED > 1080 */ +#endif /* MAC_OS_X_VERSION_MIN_REQUIRED > 1080 */ -#if MAC_OS_X_VERSION_MAX_ALLOWED > 101300 +#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 /*---------------------------------------------------------------------- * +++ Drawing procedures for widgets in Apple's "Dark Mode" (10.14 and up). * - * The HIToolbox does not support Dark Mode, and apparently never will, - * so to make widgets look "native" we have to provide analogues of the - * HITheme drawing functions to be used in DarkAqua. We continue to use - * HITheme in Aqua, since it understands earlier versions of the OS. + * The HIToolbox does not support Dark Mode, and apparently never will, + * so to make widgets look "native" we have to provide analogues of the + * HITheme drawing functions to be used in DarkAqua. We continue to use + * HITheme in Aqua, since it understands earlier versions of the OS. */ /* * Colors and gradients used in Dark Mode. */ -static CGFloat darkButtonFace[4] = {112.0/255, 113.0/255, 115.0/255, 1.0}; -static CGFloat darkPressedBevelFace[4] = {135.0/255, 136.0/255, 138.0/255, 1.0}; -static CGFloat darkSelectedBevelFace[4] = {162.0/255, 163.0/255, 165.0/255, 1.0}; -static CGFloat darkDisabledButtonFace[4] = {86.0/255, 87.0/255, 89.0/255, 1.0}; -static CGFloat darkInactiveSelectedTab[4] = {159.0/255, 160.0/255, 161.0/255, 1.0}; +static CGFloat darkButtonFace[4] = { + 112.0 / 255, 113.0 / 255, 115.0 / 255, 1.0 +}; +static CGFloat darkPressedBevelFace[4] = { + 135.0 / 255, 136.0 / 255, 138.0 / 255, 1.0 +}; +static CGFloat darkSelectedBevelFace[4] = { + 162.0 / 255, 163.0 / 255, 165.0 / 255, 1.0 +}; +static CGFloat darkDisabledButtonFace[4] = { + 86.0 / 255, 87.0 / 255, 89.0 / 255, 1.0 +}; +static CGFloat darkInactiveSelectedTab[4] = { + 159.0 / 255, 160.0 / 255, 161.0 / 255, 1.0 +}; static CGFloat darkTabSeparator[4] = {0.0, 0.0, 0.0, 0.25}; static CGFloat darkTrack[4] = {1.0, 1.0, 1.0, 0.25}; static CGFloat darkFrameTop[4] = {1.0, 1.0, 1.0, 0.0625}; static CGFloat darkFrameBottom[4] = {1.0, 1.0, 1.0, 0.125}; static CGFloat darkFrameAccent[4] = {0.0, 0.0, 0.0, 0.0625}; -static CGFloat darkTopGradient[8] = {1.0, 1.0, 1.0, 0.3, - 1.0, 1.0, 1.0, 0.0}; -static CGFloat darkBackgroundGradient[8] = {0.0, 0.0, 0.0, 0.1, - 0.0, 0.0, 0.0, 0.25}; -static CGFloat darkInactiveGradient[8] = {89.0/255, 90.0/255, 93.0/255, 1.0, - 119.0/255, 120.0/255, 122.0/255, 1.0}; -static CGFloat darkSelectedGradient[8] = {23.0/255, 111.0/255, 232.0/255, 1.0, - 20.0/255, 94.0/255, 206.0/255, 1.0}; - -/*---------------------------------------------------------------------- - * GradientFillRoundedRectangle -- - * - * Fill a rounded rectangle with a specified gradient. - */ - -static void GradientFillRoundedRectangle( - CGContextRef context, - CGRect bounds, - CGFloat radius, - CGFloat *colors, - int numColors) -{ - NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; - CGPathRef path; - CGPoint end = { - bounds.origin.x, - bounds.origin.y + bounds.size.height - }; - CGGradientRef gradient = CGGradientCreateWithColorComponents( - deviceRGB.CGColorSpace, colors, NULL, numColors); - - path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL); - CGContextBeginPath(context); - CGContextAddPath(context, path); - CGContextClip(context); - CGContextDrawLinearGradient(context, gradient, bounds.origin, end, 0); - CFRelease(path); - CFRelease(gradient); -} - -static void DrawUpDownArrows( - CGContextRef context, - CGRect bounds, - CGFloat inset, - CGFloat size, - CGFloat *rgba) -{ - CGFloat x, y; - - CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); - CGContextSetLineWidth(context, 1.5); - x = bounds.origin.x + inset; - y = bounds.origin.y + trunc(bounds.size.height/2); - CGContextBeginPath(context); - - CGPoint bottomArrow[3] = {{x, y+2}, {x+size/2, y+2+size/2}, {x+size, y+2}}; - CGPoint topArrow[3] = {{x, y-2}, {x+size/2, y-2-size/2}, {x+size, y-2}}; - - CGContextAddLines(context, bottomArrow, 3); - CGContextAddLines(context, topArrow, 3); - CGContextStrokePath(context); -} +static CGFloat darkTopGradient[8] = { + 1.0, 1.0, 1.0, 0.3, + 1.0, 1.0, 1.0, 0.0 +}; +static CGFloat darkBackgroundGradient[8] = { + 0.0, 0.0, 0.0, 0.1, + 0.0, 0.0, 0.0, 0.25 +}; +static CGFloat darkInactiveGradient[8] = { + 89.0 / 255, 90.0 / 255, 93.0 / 255, 1.0, + 119.0 / 255, 120.0 / 255, 122.0 / 255, 1.0 +}; +static CGFloat darkSelectedGradient[8] = { + 23.0 / 255, 111.0 / 255, 232.0 / 255, 1.0, + 20.0 / 255, 94.0 / 255, 206.0 / 255, 1.0 +}; /*---------------------------------------------------------------------- - * FillButtonBackground -- + * +++ FillButtonBackground -- * - * Fills a rounded rectangle with a transparent black gradient. + * Fills a rounded rectangle with a transparent black gradient. */ static void FillButtonBackground( @@ -497,7 +533,7 @@ static void FillButtonBackground( CGPathRef path; NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; CGGradientRef backgroundGradient = CGGradientCreateWithColorComponents( - deviceRGB.CGColorSpace, darkBackgroundGradient, NULL, 2); + deviceRGB.CGColorSpace, darkBackgroundGradient, NULL, 2); CGPoint backgroundEnd = { bounds.origin.x, bounds.origin.y + bounds.size.height @@ -508,13 +544,13 @@ static void FillButtonBackground( CGContextAddPath(context, path); CGContextClip(context); CGContextDrawLinearGradient(context, backgroundGradient, - bounds.origin, backgroundEnd, 0); + bounds.origin, backgroundEnd, 0); CFRelease(path); CFRelease(backgroundGradient); } /*---------------------------------------------------------------------- - * HighlightButtonBorder -- + * +++ HighlightButtonBorder -- * * Accent the top border of a rounded rectangle with a transparent * white gradient. @@ -527,30 +563,29 @@ static void HighlightButtonBorder( NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; CGPoint topEnd = {bounds.origin.x, bounds.origin.y + 3}; CGGradientRef topGradient = CGGradientCreateWithColorComponents( - deviceRGB.CGColorSpace, darkTopGradient, NULL, 2); + deviceRGB.CGColorSpace, darkTopGradient, NULL, 2); CGContextSaveGState(context); CGContextBeginPath(context); CGContextAddArc(context, bounds.origin.x + 4, bounds.origin.y + 4, - 4, PI, 3*PI/2, 0); + 4, PI, 3 * PI / 2, 0); CGContextAddArc(context, bounds.origin.x + bounds.size.width - 4, - bounds.origin.y + 4, 4, 3*PI/2, 0, 0); + bounds.origin.y + 4, 4, 3 * PI / 2, 0, 0); CGContextReplacePathWithStrokedPath(context); CGContextClip(context); - CGContextDrawLinearGradient(context, topGradient, bounds.origin, topEnd, 0.0); + CGContextDrawLinearGradient(context, topGradient, bounds.origin, topEnd, + 0.0); CGContextRestoreGState(context); CFRelease(topGradient); } /*---------------------------------------------------------------------- - * DrawDarkButton -- + * +++ DrawDarkButton -- * - * This is a standalone drawing procedure which draws PushButtons and - * PopupButtons in the Dark Mode style. + * This is a standalone drawing procedure which draws PushButtons and + * PopupButtons in the Dark Mode style. */ -static CGFloat whiteRGBA[4] = {1.0, 1.0, 1.0, 1.0}; - static void DrawDarkButton( CGRect bounds, ThemeButtonKind kind, @@ -577,16 +612,16 @@ static void DrawDarkButton( bounds = CGRectInset(bounds, 1, 1); if (kind == kThemePushButton && (state & TTK_STATE_PRESSED)) { GradientFillRoundedRectangle(context, bounds, 4, - darkSelectedGradient, 2); + darkSelectedGradient, 2); } else { if (state & TTK_STATE_DISABLED) { faceColor = [NSColor colorWithColorSpace: deviceRGB - components: darkDisabledButtonFace - count: 4]; + components: darkDisabledButtonFace + count: 4]; } else { faceColor = [NSColor colorWithColorSpace: deviceRGB - components: darkButtonFace - count: 4]; + components: darkButtonFace + count: 4]; } SolidFillRoundedRectangle(context, bounds, 4, faceColor); } @@ -597,18 +632,17 @@ static void DrawDarkButton( if (kind == kThemePopupButton | kind == kThemeComboBox) { CGRect arrowBounds = bounds; - arrowBounds.size.width = 16; arrowBounds.origin.x += bounds.size.width - 16; - /* - * If the toplevel is front, paint the button blue. - */ + /* + * If the toplevel is front, paint the button blue. + */ if (!(state & TTK_STATE_BACKGROUND) && - !(state & TTK_STATE_DISABLED)) { + !(state & TTK_STATE_DISABLED)) { GradientFillRoundedRectangle(context, arrowBounds, 4, - darkSelectedGradient, 2); + darkSelectedGradient, 2); } if (kind == kThemePopupButton) { DrawUpDownArrows(context, arrowBounds, 3, 7, whiteRGBA); @@ -621,10 +655,10 @@ static void DrawDarkButton( } /*---------------------------------------------------------------------- - * DrawDarkIncDecButton -- + * +++ DrawDarkIncDecButton -- * - * This is a standalone drawing procedure which draws an IncDecButton (as - * used in a Spinbox) in the Dark Mode style. + * This is a standalone drawing procedure which draws an IncDecButton + * (as used in a Spinbox) in the Dark Mode style. */ static void DrawDarkIncDecButton( @@ -647,22 +681,21 @@ static void DrawDarkIncDecButton( bounds = CGRectInset(bounds, 1, 1); if (state & TTK_STATE_DISABLED) { faceColor = [NSColor colorWithColorSpace: deviceRGB - components: darkDisabledButtonFace - count: 4]; + components: darkDisabledButtonFace + count: 4]; } else { faceColor = [NSColor colorWithColorSpace: deviceRGB - components: darkButtonFace - count: 4]; + components: darkButtonFace + count: 4]; } SolidFillRoundedRectangle(context, bounds, 4, faceColor); /* * If pressed, paint the appropriate half blue. */ - + if (state & TTK_STATE_PRESSED) { CGRect clip = bounds; - clip.size.height /= 2; CGContextSaveGState(context); if (drawState == kThemeStatePressedDown) { @@ -670,7 +703,7 @@ static void DrawDarkIncDecButton( } CGContextClipToRect(context, clip); GradientFillRoundedRectangle(context, bounds, 5, - darkSelectedGradient, 2); + darkSelectedGradient, 2); CGContextRestoreGState(context); } DrawUpDownArrows(context, bounds, 3, 5, whiteRGBA); @@ -678,10 +711,10 @@ static void DrawDarkIncDecButton( } /*---------------------------------------------------------------------- - * DrawDarkBevelButton -- + * +++ DrawDarkBevelButton -- * - * This is a standalone drawing procedure which draws RoundedBevelButtons - * in the Dark Mode style. + * This is a standalone drawing procedure which draws RoundedBevelButtons + * in the Dark Mode style. */ static void DrawDarkBevelButton( @@ -691,6 +724,7 @@ static void DrawDarkBevelButton( { NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *faceColor; + CGContextClipToRect(context, bounds); FillButtonBackground(context, bounds, 5); @@ -701,31 +735,31 @@ static void DrawDarkBevelButton( bounds = CGRectInset(bounds, 1, 1); if (state & TTK_STATE_PRESSED) { faceColor = [NSColor colorWithColorSpace: deviceRGB - components: darkPressedBevelFace - count: 4]; + components: darkPressedBevelFace + count: 4]; } else if ((state & TTK_STATE_DISABLED) || - (state & TTK_STATE_ALTERNATE)) { + (state & TTK_STATE_ALTERNATE)) { faceColor = [NSColor colorWithColorSpace: deviceRGB - components: darkDisabledButtonFace - count: 4]; + components: darkDisabledButtonFace + count: 4]; } else if (state & TTK_STATE_SELECTED) { faceColor = [NSColor colorWithColorSpace: deviceRGB - components: darkSelectedBevelFace - count: 4]; + components: darkSelectedBevelFace + count: 4]; } else { faceColor = [NSColor colorWithColorSpace: deviceRGB - components: darkButtonFace - count: 4]; + components: darkButtonFace + count: 4]; } SolidFillRoundedRectangle(context, bounds, 4, faceColor); HighlightButtonBorder(context, bounds); } /*---------------------------------------------------------------------- - * DrawDarkCheckBox -- + * +++ DrawDarkCheckBox -- * - * This is a standalone drawing procedure which draws Checkboxes in the - * Dark Mode style. + * This is a standalone drawing procedure which draws Checkboxes in the + * Dark Mode style. */ static void DrawDarkCheckBox( @@ -733,7 +767,7 @@ static void DrawDarkCheckBox( Ttk_State state, CGContextRef context) { - CGRect checkbounds = {{0, bounds.size.height/2 - 8},{16, 16}}; + CGRect checkbounds = {{0, bounds.size.height / 2 - 8}, {16, 16}}; NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *stroke; CGFloat x, y; @@ -746,13 +780,13 @@ static void DrawDarkCheckBox( FillButtonBackground(context, bounds, 4); bounds = CGRectInset(bounds, 1, 1); if (!(state & TTK_STATE_BACKGROUND) && - !(state & TTK_STATE_DISABLED) && - ((state & TTK_STATE_SELECTED) || (state & TTK_STATE_ALTERNATE))) { + !(state & TTK_STATE_DISABLED) && + ((state & TTK_STATE_SELECTED) || (state & TTK_STATE_ALTERNATE))) { GradientFillRoundedRectangle(context, bounds, 3, - darkSelectedGradient, 2); + darkSelectedGradient, 2); } else { GradientFillRoundedRectangle(context, bounds, 3, - darkInactiveGradient, 2); + darkInactiveGradient, 2); } HighlightButtonBorder(context, bounds); if ((state & TTK_STATE_SELECTED) || (state & TTK_STATE_ALTERNATE)) { @@ -765,27 +799,25 @@ static void DrawDarkCheckBox( CGContextSetStrokeColorWithColor(context, stroke.CGColor); } if (state & TTK_STATE_SELECTED) { - CGPoint check[3] = {{x+4, y+8}, {x+7, y+11}, {x+11, y+4}}; - CGContextSetLineWidth(context, 1.5); CGContextBeginPath(context); + CGPoint check[3] = {{x + 4, y + 8}, {x + 7, y + 11}, {x + 11, y + 4}}; CGContextAddLines(context, check, 3); CGContextStrokePath(context); } else if (state & TTK_STATE_ALTERNATE) { - CGPoint bar[2] = {{x+4, y+8}, {x+12, y+8}}; - CGContextSetLineWidth(context, 2.0); CGContextBeginPath(context); + CGPoint bar[2] = {{x + 4, y + 8}, {x + 12, y + 8}}; CGContextAddLines(context, bar, 2); CGContextStrokePath(context); } } /*---------------------------------------------------------------------- - * DrawDarkRadioButton -- + * +++ DrawDarkRadioButton -- * - * This is a standalone drawing procedure which draws RadioButtons in the - * Dark Mode style. + * This is a standalone drawing procedure which draws RadioButtons + * in the Dark Mode style. */ static void DrawDarkRadioButton( @@ -793,7 +825,7 @@ static void DrawDarkRadioButton( Ttk_State state, CGContextRef context) { - CGRect checkbounds = {{0, bounds.size.height/2 - 9},{18, 18}}; + CGRect checkbounds = {{0, bounds.size.height / 2 - 9}, {18, 18}}; NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *fill; CGFloat x, y; @@ -806,13 +838,13 @@ static void DrawDarkRadioButton( FillButtonBackground(context, bounds, 9); bounds = CGRectInset(bounds, 1, 1); if (!(state & TTK_STATE_BACKGROUND) && - !(state & TTK_STATE_DISABLED) && - ((state & TTK_STATE_SELECTED) || (state & TTK_STATE_ALTERNATE))) { + !(state & TTK_STATE_DISABLED) && + ((state & TTK_STATE_SELECTED) || (state & TTK_STATE_ALTERNATE))) { GradientFillRoundedRectangle(context, bounds, 8, - darkSelectedGradient, 2); + darkSelectedGradient, 2); } else { GradientFillRoundedRectangle(context, bounds, 8, - darkInactiveGradient, 2); + darkInactiveGradient, 2); } HighlightButtonBorder(context, bounds); if ((state & TTK_STATE_SELECTED) || (state & TTK_STATE_ALTERNATE)) { @@ -825,23 +857,21 @@ static void DrawDarkRadioButton( CGContextSetFillColorWithColor(context, fill.CGColor); } if (state & TTK_STATE_SELECTED) { - CGRect dot = {{x + 6, y + 6}, {6, 6}}; - CGContextBeginPath(context); + CGRect dot = {{x + 6, y + 6}, {6, 6}}; CGContextAddEllipseInRect(context, dot); CGContextFillPath(context); } else if (state & TTK_STATE_ALTERNATE) { CGRect bar = {{x + 5, y + 8}, {8, 2}}; - CGContextFillRect(context, bar); } } /*---------------------------------------------------------------------- - * DrawDarkTab -- + * +++ DrawDarkTab -- * - * This is a standalone drawing procedure which draws Tabbed Pane - * Tabs in the Dark Mode style. + * This is a standalone drawing procedure which draws Tabbed Pane + * Tabs in the Dark Mode style. */ static void DrawDarkTab( @@ -851,7 +881,7 @@ static void DrawDarkTab( { NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *faceColor, *stroke; - CGRect originalBounds= bounds; + CGRect originalBounds = bounds; CGContextSetLineWidth(context, 1.0); CGContextClipToRect(context, bounds); @@ -872,70 +902,72 @@ static void DrawDarkTab( /* * Fill the tab face with the appropriate color or gradient. Use a solid - * color if the tab is not selected, otherwise use a blue or gray gradient. + * color if the tab is not selected, otherwise use a blue or gray + * gradient. */ bounds = CGRectInset(bounds, 1, 1); if (!(state & TTK_STATE_SELECTED)) { if (state & TTK_STATE_DISABLED) { faceColor = [NSColor colorWithColorSpace: deviceRGB - components: darkDisabledButtonFace - count: 4]; + components: darkDisabledButtonFace + count: 4]; } else { faceColor = [NSColor colorWithColorSpace: deviceRGB - components: darkButtonFace - count: 4]; + components: darkButtonFace + count: 4]; } SolidFillRoundedRectangle(context, bounds, 4, faceColor); - /* - * Draw a separator line on the left side of the tab if it - * not first. - */ + /* + * Draw a separator line on the left side of the tab if it + * not first. + */ if (!(state & TTK_STATE_FIRST_TAB)) { CGContextSaveGState(context); CGContextSetShouldAntialias(context, false); stroke = [NSColor colorWithColorSpace: deviceRGB - components: darkTabSeparator - count: 4]; + components: darkTabSeparator + count: 4]; CGContextSetStrokeColorWithColor(context, stroke.CGColor); CGContextBeginPath(context); CGContextMoveToPoint(context, originalBounds.origin.x, - originalBounds.origin.y + 1); + originalBounds.origin.y + 1); CGContextAddLineToPoint(context, originalBounds.origin.x, - originalBounds.origin.y + originalBounds.size.height - 1); + originalBounds.origin.y + originalBounds.size.height - 1); CGContextStrokePath(context); CGContextRestoreGState(context); } } else { - /* - * This is the selected tab; paint it blue. If it is first, cover up - * the separator line drawn by the second one. (The selected tab is - * always drawn last.) - */ + + /* + * This is the selected tab; paint it blue. If it is first, cover up + * the separator line drawn by the second one. (The selected tab is + * always drawn last.) + */ if ((state & TTK_STATE_FIRST_TAB) && !(state & TTK_STATE_LAST_TAB)) { bounds.size.width += 1; } if (!(state & TTK_STATE_BACKGROUND)) { GradientFillRoundedRectangle(context, bounds, 4, - darkSelectedGradient, 2); + darkSelectedGradient, 2); } else { faceColor = [NSColor colorWithColorSpace: deviceRGB - components: darkInactiveSelectedTab - count: 4]; + components: darkInactiveSelectedTab + count: 4]; SolidFillRoundedRectangle(context, bounds, 4, faceColor); } HighlightButtonBorder(context, bounds); } } - + /*---------------------------------------------------------------------- - * DrawDarkSeparator -- + * +++ DrawDarkSeparator -- * - * This is a standalone drawing procedure which draws a separator widget in - * Dark Mode. + * This is a standalone drawing procedure which draws a separator widget + * in Dark Mode. */ static void DrawDarkSeparator( @@ -946,18 +978,18 @@ static void DrawDarkSeparator( static CGFloat fill[4] = {1.0, 1.0, 1.0, 0.3}; NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *fillColor = [NSColor colorWithColorSpace: deviceRGB - components: fill - count:4]; + components: fill + count:4]; CGContextSetFillColorWithColor(context, fillColor.CGColor); CGContextFillRect(context, bounds); } - + /*---------------------------------------------------------------------- - * DrawDarkFrame -- + * +++ DrawDarkFrame -- * - * This is a standalone drawing procedure which draws various types of - * borders in Dark Mode. + * This is a standalone drawing procedure which draws various + * types of borders in Dark Mode. */ static void DrawDarkFrame( @@ -967,35 +999,35 @@ static void DrawDarkFrame( { NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *stroke; + + CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace); CGFloat x = bounds.origin.x, y = bounds.origin.y; CGFloat w = bounds.size.width, h = bounds.size.height; CGPoint topPart[4] = { {x, y + h - 1}, {x, y}, {x + w, y}, {x + w, y + h - 1} }; - CGPoint bottom[2] = {{x, y + h}, {x + w, y + h}}; + CGPoint bottom[2] = {{x, y + h}, {x + w, y + h}}; CGPoint accent[2] = {{x, y + 1}, {x + w, y + 1}}; - - CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace); switch (kind) { case kHIThemeFrameTextFieldSquare: CGContextSaveGState(context); CGContextSetShouldAntialias(context, false); CGContextBeginPath(context); stroke = [NSColor colorWithColorSpace: deviceRGB - components: darkFrameTop - count: 4]; + components: darkFrameTop + count: 4]; CGContextSetStrokeColorWithColor(context, stroke.CGColor); CGContextAddLines(context, topPart, 4); CGContextStrokePath(context); stroke = [NSColor colorWithColorSpace: deviceRGB - components: darkFrameBottom - count: 4]; + components: darkFrameBottom + count: 4]; CGContextSetStrokeColorWithColor(context, stroke.CGColor); CGContextAddLines(context, bottom, 2); CGContextStrokePath(context); stroke = [NSColor colorWithColorSpace: deviceRGB - components: darkFrameAccent - count: 4]; + components: darkFrameAccent + count: 4]; CGContextSetStrokeColorWithColor(context, stroke.CGColor); CGContextAddLines(context, accent, 2); CGContextStrokePath(context); @@ -1007,10 +1039,10 @@ static void DrawDarkFrame( } /*---------------------------------------------------------------------- - * DrawListHeader -- + * +++ DrawListHeader -- * - * This is a standalone drawing procedure which draws column headers for a - * Treeview in the Dark Mode. + * This is a standalone drawing procedure which draws column + * headers for a Treeview in the Dark Mode. */ static void DrawDarkListHeader( @@ -1021,18 +1053,19 @@ static void DrawDarkListHeader( { NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *stroke; + + CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace); CGFloat x = bounds.origin.x, y = bounds.origin.y; CGFloat w = bounds.size.width, h = bounds.size.height; CGPoint top[2] = {{x, y}, {x + w, y}}; - CGPoint bottom[2] = {{x, y + h}, {x + w, y + h}}; + CGPoint bottom[2] = {{x, y + h}, {x + w, y + h}}; CGPoint separator[2] = {{x + w, y + 3}, {x + w, y + h - 3}}; - CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace); CGContextSaveGState(context); CGContextSetShouldAntialias(context, false); stroke = [NSColor colorWithColorSpace: deviceRGB - components: darkFrameBottom - count: 4]; + components: darkFrameBottom + count: 4]; CGContextSetStrokeColorWithColor(context, stroke.CGColor); CGContextBeginPath(context); CGContextAddLines(context, top, 2); @@ -1063,43 +1096,49 @@ static void DrawDarkListHeader( */ /* - * When Ttk draws the various types of buttons, a pointer to one of these is - * passed as the clientData. + * When Ttk draws the various types of buttons, a pointer to one of these + * is passed as the clientData. */ typedef struct { ThemeButtonKind kind; ThemeMetric heightMetric; } ThemeButtonParams; - static ThemeButtonParams - PushButtonParams = { kThemePushButton, kThemeMetricPushButtonHeight }, - CheckBoxParams = { kThemeCheckBox, kThemeMetricCheckBoxHeight }, - RadioButtonParams = { kThemeRadioButton, kThemeMetricRadioButtonHeight }, - BevelButtonParams = { kThemeRoundedBevelButton, NoThemeMetric }, - PopupButtonParams = { kThemePopupButton, kThemeMetricPopupButtonHeight }, - DisclosureParams = { kThemeDisclosureButton, kThemeMetricDisclosureTriangleHeight }, - ListHeaderParams = { kThemeListHeaderButton, kThemeMetricListHeaderHeight }; - + PushButtonParams = {kThemePushButton, kThemeMetricPushButtonHeight}, + CheckBoxParams = {kThemeCheckBox, kThemeMetricCheckBoxHeight}, + RadioButtonParams = {kThemeRadioButton, kThemeMetricRadioButtonHeight}, + BevelButtonParams = {kThemeRoundedBevelButton, NoThemeMetric}, + PopupButtonParams = {kThemePopupButton, kThemeMetricPopupButtonHeight}, + DisclosureParams = { + kThemeDisclosureButton, kThemeMetricDisclosureTriangleHeight +}, + ListHeaderParams = +{kThemeListHeaderButton, kThemeMetricListHeaderHeight}; static Ttk_StateTable ButtonValueTable[] = { - { kThemeButtonMixed, TTK_STATE_ALTERNATE, 0 }, - { kThemeButtonOn, TTK_STATE_SELECTED, 0 }, - { kThemeButtonOff, 0, 0 } -/* Others: kThemeDisclosureRight, kThemeDisclosureDown, kThemeDisclosureLeft */ -}; + {kThemeButtonMixed, TTK_STATE_ALTERNATE, 0}, + {kThemeButtonOn, TTK_STATE_SELECTED, 0}, + {kThemeButtonOff, 0, 0} + /* + * Others: kThemeDisclosureRight, kThemeDisclosureDown, + * kThemeDisclosureLeft + */ + +}; static Ttk_StateTable ButtonAdornmentTable[] = { - { kThemeAdornmentDefault | kThemeAdornmentFocus, - TTK_STATE_ALTERNATE | TTK_STATE_FOCUS, 0 }, - { kThemeAdornmentDefault, TTK_STATE_ALTERNATE, 0 }, - { kThemeAdornmentNone, TTK_STATE_ALTERNATE, 0 }, - { kThemeAdornmentFocus, TTK_STATE_FOCUS, 0 }, - { kThemeAdornmentNone, 0, 0 } + {kThemeAdornmentDefault | kThemeAdornmentFocus, + TTK_STATE_ALTERNATE | TTK_STATE_FOCUS, 0}, + {kThemeAdornmentDefault, TTK_STATE_ALTERNATE, 0}, + {kThemeAdornmentNone, TTK_STATE_ALTERNATE, 0}, + {kThemeAdornmentFocus, TTK_STATE_FOCUS, 0}, + {kThemeAdornmentNone, 0, 0} }; /*---------------------------------------------------------------------- - * computeButtonDrawInfo -- - * Fill in an appearance manager HIThemeButtonDrawInfo record. + * +++ computeButtonDrawInfo -- + * + * Fill in an appearance manager HIThemeButtonDrawInfo record. */ static inline HIThemeButtonDrawInfo computeButtonDrawInfo( @@ -1107,6 +1146,7 @@ static inline HIThemeButtonDrawInfo computeButtonDrawInfo( Ttk_State state, Tk_Window tkwin) { + /* * See ButtonElementDraw for the explanation of why we always draw * PushButtons in the active state. @@ -1133,12 +1173,16 @@ static inline HIThemeButtonDrawInfo computeButtonDrawInfo( return info; } -static void -ButtonElementMinSize( +/*---------------------------------------------------------------------- + * +++ Button elements. + */ + +static void ButtonElementMinSize( void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, + int *minWidth, + int *minHeight, Ttk_Padding *paddingPtr) { ThemeButtonParams *params = clientData; @@ -1146,40 +1190,43 @@ ButtonElementMinSize( if (params->heightMetric != NoThemeMetric) { ChkErr(GetThemeMetric, params->heightMetric, minHeight); - /* - * The theme height does not include the 1-pixel border around the - * button, although it does include the 1-pixel shadow at the bottom. - */ + /* + * The theme height does not include the 1-pixel border around + * the button, although it does include the 1-pixel shadow at + * the bottom. + */ *minHeight += 2; - /* - * The minwidth must be 0 to force the generic ttk code to compute the - * correct text layout. For example, a non-zero value will cause the - * text to be left justified, no matter what -anchor setting is used in - * the style. - */ + /* + * The minwidth must be 0 to force the generic ttk code to compute the + * correct text layout. For example, a non-zero value will cause the + * text to be left justified, no matter what -anchor setting is used + *in + * the style. + */ *minWidth = 0; } } -static void -ButtonElementSize( +static void ButtonElementSize( void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, + int *minWidth, + int *minHeight, Ttk_Padding *paddingPtr) { ThemeButtonParams *params = clientData; - const HIThemeButtonDrawInfo info = computeButtonDrawInfo(params, 0, tkwin); + const HIThemeButtonDrawInfo info = + computeButtonDrawInfo(params, 0, tkwin); static const CGRect scratchBounds = {{0, 0}, {100, 100}}; CGRect contentBounds, backgroundBounds; int verticalPad; ButtonElementMinSize(clientData, elementRecord, tkwin, - minWidth, minHeight, paddingPtr); + minWidth, minHeight, paddingPtr); /* * Given a hypothetical bounding rectangle for a button, HIToolbox will @@ -1192,25 +1239,24 @@ ButtonElementSize( * to draw a button with a certain bounding rectangle it draws the button * centered within the rectangle. * - * To compute the effective padding around a button we request the content - * and bounding rectangles for a 100x100 button and use the padding between - * those. However, we symmetrize the padding on the top and bottom, because - * that is how the button will be drawn. + * To compute the effective padding around a button we request the + * content and bounding rectangles for a 100x100 button and use the + * padding between those. However, we symmetrize the padding on the + * top and bottom, because that is how the button will be drawn. */ ChkErr(HIThemeGetButtonContentBounds, - &scratchBounds, &info, &contentBounds); + &scratchBounds, &info, &contentBounds); ChkErr(HIThemeGetButtonBackgroundBounds, - &scratchBounds, &info, &backgroundBounds); + &scratchBounds, &info, &backgroundBounds); paddingPtr->left = contentBounds.origin.x - backgroundBounds.origin.x; paddingPtr->right = - CGRectGetMaxX(backgroundBounds) - CGRectGetMaxX(contentBounds); + CGRectGetMaxX(backgroundBounds) - CGRectGetMaxX(contentBounds); verticalPad = backgroundBounds.size.height - contentBounds.size.height; paddingPtr->top = paddingPtr->bottom = verticalPad / 2; } -static void -ButtonElementDraw( +static void ButtonElementDraw( void *clientData, void *elementRecord, Tk_Window tkwin, @@ -1221,9 +1267,10 @@ ButtonElementDraw( ThemeButtonParams *params = clientData; CGRect bounds = BoxToRect(d, b); HIThemeButtonDrawInfo info = computeButtonDrawInfo(params, state, tkwin); + bounds = NormalizeButtonBounds(params->heightMetric, bounds); - - BEGIN_DRAWING(d); + + BEGIN_DRAWING(d) if (TkMacOSXInDarkMode(tkwin)) { #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 switch (info.kind) { @@ -1242,34 +1289,36 @@ ButtonElementDraw( break; default: ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, - HIOrientation, NULL); + HIOrientation, NULL); } -#endif +#endif /* if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 */ } else { - /* - * Apple's PushButton and PopupButton do not change their fill color - * when the window is inactive. However, except in 10.7 (Lion), the - * color of the arrow button on a PopupButton does change. For some - * reason HITheme fills inactive buttons with a transparent color that - * allows the window background to show through, leading to - * inconsistent behavior. We work around this by filling behind an - * inactive PopupButton with a text background color before asking - * HIToolbox to draw it. For PushButtons, we simply draw them in the - * active state. - */ + + /* + * Apple's PushButton and PopupButton do not change their fill color + * when the window is inactive. However, except in 10.7 (Lion), the + * color of the arrow button on a PopupButton does change. For some + * reason HITheme fills inactive buttons with a transparent color that + * allows the window background to show through, leading to + * inconsistent behavior. We work around this by filling behind an + * inactive PopupButton with a text background color before asking + * HIToolbox to draw it. For PushButtons, we simply draw them in the + * active state. + */ #if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 - if (info.kind == kThemePopupButton && (state & TTK_STATE_BACKGROUND)) { + if (info.kind == kThemePopupButton && + (state & TTK_STATE_BACKGROUND)) { CGRect innerBounds = CGRectInset(bounds, 1, 1); NSColor *whiteRGBA = [NSColor whiteColor]; SolidFillRoundedRectangle(dc.context, innerBounds, 4, whiteRGBA); } #endif - /* - * A BevelButton with mixed value is drawn borderless, which does make - * much sense for us. - */ + /* + * A BevelButton with mixed value is drawn borderless, which does make + * much sense for us. + */ if (info.kind == kThemeRoundedBevelButton && info.value == kThemeButtonMixed) { @@ -1277,9 +1326,9 @@ ButtonElementDraw( info.state = kThemeStateInactive; } ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, - NULL); + NULL); } - END_DRAWING; + END_DRAWING } static Ttk_ElementSpec ButtonElementSpec = { @@ -1295,29 +1344,26 @@ static Ttk_ElementSpec ButtonElementSpec = { */ /* Tab position logic, c.f. ttkNotebook.c TabState() */ - static Ttk_StateTable TabStyleTable[] = { - { kThemeTabFrontInactive, TTK_STATE_SELECTED | TTK_STATE_BACKGROUND}, - { kThemeTabNonFrontInactive, TTK_STATE_BACKGROUND}, - { kThemeTabFrontUnavailable, TTK_STATE_DISABLED | TTK_STATE_SELECTED}, - { kThemeTabNonFrontUnavailable, TTK_STATE_DISABLED}, - { kThemeTabFront, TTK_STATE_SELECTED}, - { kThemeTabNonFrontPressed, TTK_STATE_PRESSED}, - { kThemeTabNonFront, 0} + {kThemeTabFrontInactive, TTK_STATE_SELECTED | TTK_STATE_BACKGROUND}, + {kThemeTabNonFrontInactive, TTK_STATE_BACKGROUND}, + {kThemeTabFrontUnavailable, TTK_STATE_DISABLED | TTK_STATE_SELECTED}, + {kThemeTabNonFrontUnavailable, TTK_STATE_DISABLED}, + {kThemeTabFront, TTK_STATE_SELECTED}, + {kThemeTabNonFrontPressed, TTK_STATE_PRESSED}, + {kThemeTabNonFront, 0} }; - static Ttk_StateTable TabAdornmentTable[] = { - { kHIThemeTabAdornmentNone, TTK_STATE_FIRST_TAB | TTK_STATE_LAST_TAB}, - { kHIThemeTabAdornmentTrailingSeparator, TTK_STATE_FIRST_TAB}, - { kHIThemeTabAdornmentNone, TTK_STATE_LAST_TAB}, - { kHIThemeTabAdornmentTrailingSeparator, 0 }, + {kHIThemeTabAdornmentNone, TTK_STATE_FIRST_TAB | TTK_STATE_LAST_TAB}, + {kHIThemeTabAdornmentTrailingSeparator, TTK_STATE_FIRST_TAB}, + {kHIThemeTabAdornmentNone, TTK_STATE_LAST_TAB}, + {kHIThemeTabAdornmentTrailingSeparator, 0}, }; - static Ttk_StateTable TabPositionTable[] = { - { kHIThemeTabPositionOnly, TTK_STATE_FIRST_TAB | TTK_STATE_LAST_TAB}, - { kHIThemeTabPositionFirst, TTK_STATE_FIRST_TAB}, - { kHIThemeTabPositionLast, TTK_STATE_LAST_TAB}, - { kHIThemeTabPositionMiddle, 0 }, + {kHIThemeTabPositionOnly, TTK_STATE_FIRST_TAB | TTK_STATE_LAST_TAB}, + {kHIThemeTabPositionFirst, TTK_STATE_FIRST_TAB}, + {kHIThemeTabPositionLast, TTK_STATE_LAST_TAB}, + {kHIThemeTabPositionMiddle, 0}, }; /* @@ -1335,7 +1381,8 @@ static Ttk_StateTable TabPositionTable[] = { * should be placed so that there are equal margins of space before and after * it. The guidelines below provide the specifications you should use for tab * labels: - * - Regular size: System font. Center in tab, leaving 12 pixels on each side. + * - Regular size: System font. Center in tab, leaving 12 pixels on each + *side. * - Small: Small system font. Center in tab, leaving 10 pixels on each side. * - Mini: Mini system font. Center in tab, leaving 8 pixels on each side. * @@ -1359,20 +1406,20 @@ static Ttk_StateTable TabPositionTable[] = { * TP30000359-TPXREF116> */ -static void -TabElementSize( +static void TabElementSize( void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, + int *minWidth, + int *minHeight, Ttk_Padding *paddingPtr) { GetThemeMetric(kThemeMetricLargeTabHeight, (SInt32 *) minHeight); *paddingPtr = Ttk_MakePadding(0, 0, 0, 2); + } -static void -TabElementDraw( +static void TabElementDraw( void *clientData, void *elementRecord, Tk_Window tkwin, @@ -1391,17 +1438,18 @@ TabElementDraw( .position = Ttk_StateTableLookup(TabPositionTable, state), }; - BEGIN_DRAWING(d); + BEGIN_DRAWING(d) #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { DrawDarkTab(bounds, state, dc.context); } else { - ChkErr(HIThemeDrawTab, &bounds, &info, dc.context, HIOrientation, NULL); + ChkErr(HIThemeDrawTab, &bounds, &info, dc.context, HIOrientation, + NULL); } #else ChkErr(HIThemeDrawTab, &bounds, &info, dc.context, HIOrientation, NULL); #endif - END_DRAWING; + END_DRAWING } static Ttk_ElementSpec TabElementSpec = { @@ -1417,39 +1465,45 @@ static Ttk_ElementSpec TabElementSpec = { */ static void PaneElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, + int *minHeight, + Ttk_Padding *paddingPtr) { *paddingPtr = Ttk_MakePadding(9, 5, 9, 9); } static void PaneElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { CGRect bounds = BoxToRect(d, b); bounds.origin.y -= kThemeMetricTabFrameOverlap; bounds.size.height += kThemeMetricTabFrameOverlap; - BEGIN_DRAWING(d); - if ([NSApp macMinorVersion] > 9) { -#if MAC_OS_X_VERSION_MAX_ALLOWED > 1080 - DrawGroupBox(bounds, dc.context, tkwin); -#endif - } else { - HIThemeTabPaneDrawInfo info = { - .version = 1, - .state = Ttk_StateTableLookup(ThemeStateTable, state), - .direction = kThemeTabNorth, - .size = kHIThemeTabSizeNormal, - .kind = kHIThemeTabKindNormal, - .adornment = kHIThemeTabPaneAdornmentNormal, - }; - bounds.origin.y -= kThemeMetricTabFrameOverlap; - bounds.size.height += kThemeMetricTabFrameOverlap; - ChkErr(HIThemeDrawTabPane, &bounds, &info, dc.context, HIOrientation); - } - END_DRAWING; + BEGIN_DRAWING(d) +#if MAC_OS_X_VERSION_MIN_REQUIRED > 10800 + DrawGroupBox(bounds, dc.context, tkwin); +#else + HIThemeTabPaneDrawInfo info = { + .version = 1, + .state = Ttk_StateTableLookup(ThemeStateTable, state), + .direction = kThemeTabNorth, + .size = kHIThemeTabSizeNormal, + .kind = kHIThemeTabKindNormal, + .adornment = kHIThemeTabPaneAdornmentNormal, + }; + bounds.origin.y -= kThemeMetricTabFrameOverlap; + bounds.size.height += kThemeMetricTabFrameOverlap; + ChkErr(HIThemeDrawTabPane, &bounds, &info, dc.context, HIOrientation); +#endif /* if MAC_OS_X_VERSION_MIN_REQUIRED > 10800 */ + END_DRAWING } static Ttk_ElementSpec PaneElementSpec = { @@ -1460,12 +1514,12 @@ static Ttk_ElementSpec PaneElementSpec = { PaneElementDraw }; -/* - * Labelframe borders: - * Use "primary group box ..." - * Quoth DrawThemePrimaryGroup reference: - * "The primary group box frame is drawn inside the specified rectangle and is - * a maximum of 2 pixels thick." +/*---------------------------------------------------------------------- + * +++ Labelframe elements -- + * + * Labelframe borders: Use "primary group box ..." Quoth + * DrawThemePrimaryGroup reference: "The primary group box frame is drawn + * inside the specified rectangle and is a maximum of 2 pixels thick." * * "Maximum of 2 pixels thick" is apparently a lie; looks more like 4 to me * with shading. @@ -1475,7 +1529,8 @@ static void GroupElementSize( void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, + int *minWidth, + int *minHeight, Ttk_Padding *paddingPtr) { *paddingPtr = Ttk_UniformPadding(4); @@ -1491,20 +1546,18 @@ static void GroupElementDraw( { CGRect bounds = BoxToRect(d, b); - BEGIN_DRAWING(d); - if ([NSApp macMinorVersion] > 9) { -#if MAC_OS_X_VERSION_MAX_ALLOWED > 1080 - DrawGroupBox(bounds, dc.context, tkwin); + BEGIN_DRAWING(d) +#if MAC_OS_X_VERSION_MIN_REQUIRED > 10800 + DrawGroupBox(bounds, dc.context, tkwin); +#else + const HIThemeGroupBoxDrawInfo info = { + .version = 0, + .state = Ttk_StateTableLookup(ThemeStateTable, state), + .kind = kHIThemeGroupBoxKindPrimaryOpaque, + }; + ChkErr(HIThemeDrawGroupBox, &bounds, &info, dc.context, HIOrientation); #endif - } else { - const HIThemeGroupBoxDrawInfo info = { - .version = 0, - .state = Ttk_StateTableLookup(ThemeStateTable, state), - .kind = kHIThemeGroupBoxKindPrimaryOpaque, - }; - ChkErr(HIThemeDrawGroupBox, &bounds, &info, dc.context, HIOrientation); - } - END_DRAWING; + END_DRAWING } static Ttk_ElementSpec GroupElementSpec = { @@ -1516,36 +1569,45 @@ static Ttk_ElementSpec GroupElementSpec = { }; /*---------------------------------------------------------------------- - * +++ Entry element -- + * +++ Entry elements -- + * * 3 pixels padding for focus rectangle * 2 pixels padding for EditTextFrame */ typedef struct { - Tcl_Obj *backgroundObj; - Tcl_Obj *fieldbackgroundObj; + Tcl_Obj *backgroundObj; + Tcl_Obj *fieldbackgroundObj; } EntryElement; #define ENTRY_DEFAULT_BACKGROUND "systemTextBackgroundColor" static Ttk_ElementOptionSpec EntryElementOptions[] = { - { "-background", TK_OPTION_BORDER, - Tk_Offset(EntryElement,backgroundObj), ENTRY_DEFAULT_BACKGROUND }, - { "-fieldbackground", TK_OPTION_BORDER, - Tk_Offset(EntryElement,fieldbackgroundObj), ENTRY_DEFAULT_BACKGROUND }, + {"-background", TK_OPTION_BORDER, + Tk_Offset(EntryElement, backgroundObj), ENTRY_DEFAULT_BACKGROUND}, + {"-fieldbackground", TK_OPTION_BORDER, + Tk_Offset(EntryElement, fieldbackgroundObj), ENTRY_DEFAULT_BACKGROUND}, {0} }; static void EntryElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, + int *minHeight, + Ttk_Padding *paddingPtr) { *paddingPtr = Ttk_UniformPadding(5); } static void EntryElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { EntryElement *e = elementRecord; Ttk_Box inner = Ttk_PadBox(b, Ttk_UniformPadding(3)); @@ -1556,19 +1618,18 @@ static void EntryElementDraw( if (TkMacOSXInDarkMode(tkwin)) { #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 - BEGIN_DRAWING(d); + BEGIN_DRAWING(d) NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; CGFloat fill[4]; - GetBackgroundColor(dc.context, tkwin, 1, fill); background = [NSColor colorWithColorSpace: deviceRGB - components: fill - count: 4]; + components: fill + count: 4]; CGContextSetFillColorWithColor(dc.context, background.CGColor); CGContextFillRect(dc.context, bounds); DrawDarkFrame(bounds, dc.context, kHIThemeFrameTextFieldSquare); - END_DRAWING; -#endif + END_DRAWING +#endif /* if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 */ } else { const HIThemeFrameDrawInfo info = { .version = 0, @@ -1577,26 +1638,27 @@ static void EntryElementDraw( .isFocused = state & TTK_STATE_FOCUS, }; - /* - * Earlier versions of the Aqua theme ignored the -fieldbackground - * option and used the -background as if it were -fieldbackground. - * Here we are enabling -fieldbackground. For backwards compatibility, - * if -fieldbackground is set to the default color and -background is - * set to a different color then we use -background as - * -fieldbackground. - */ + /* + * Earlier versions of the Aqua theme ignored the -fieldbackground + * option and used the -background as if it were -fieldbackground. + * Here we are enabling -fieldbackground. For backwards + * compatibility, if -fieldbackground is set to the default color and + * -background is set to a different color then we use -background as + * -fieldbackground. + */ if (0 != strcmp(Tcl_GetString(e->fieldbackgroundObj), defaultBG)) { - backgroundPtr = Tk_Get3DBorderFromObj(tkwin,e->fieldbackgroundObj); + backgroundPtr = + Tk_Get3DBorderFromObj(tkwin, e->fieldbackgroundObj); } else if (0 != strcmp(Tcl_GetString(e->backgroundObj), defaultBG)) { - backgroundPtr = Tk_Get3DBorderFromObj(tkwin,e->backgroundObj); + backgroundPtr = Tk_Get3DBorderFromObj(tkwin, e->backgroundObj); } if (backgroundPtr != NULL) { XFillRectangle(Tk_Display(tkwin), d, - Tk_3DBorderGC(tkwin, backgroundPtr, TK_3D_FLAT_GC), - inner.x, inner.y, inner.width, inner.height); + Tk_3DBorderGC(tkwin, backgroundPtr, TK_3D_FLAT_GC), + inner.x, inner.y, inner.width, inner.height); } - BEGIN_DRAWING(d); + BEGIN_DRAWING(d) if (backgroundPtr == NULL) { background = [NSColor textBackgroundColor]; #if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 @@ -1607,11 +1669,8 @@ static void EntryElementDraw( CGContextFillRect(dc.context, bounds); } ChkErr(HIThemeDrawFrame, &bounds, &info, dc.context, HIOrientation); - END_DRAWING; + END_DRAWING } - /*if (state & TTK_STATE_FOCUS) { - ChkErr(DrawThemeFocusRect, &bounds, 1); - }*/ } static Ttk_ElementSpec EntryElementSpec = { @@ -1623,30 +1682,34 @@ static Ttk_ElementSpec EntryElementSpec = { }; /*---------------------------------------------------------------------- - * +++ Combobox: + * +++ Combobox elements -- * * NOTES: - * The HIToolbox has incomplete and inconsistent support for ComboBoxes. - * There is no constant available to get the height of a ComboBox with - * GetThemeMetric. In fact, ComboBoxes are the same (fixed) height as - * PopupButtons and PushButtons, but they have no shadow at the bottom. - * As a result, they are drawn 1 pixel above the center of the bounds - * rectangle rather than being centered like the other buttons. One can - * request background bounds for a ComboBox, and it is reported with - * height 23, while the actual button face, including its 1-pixel border - * has height 21. Attempting to request the content bounds returns a 0x0 - * rectangle. Measurement indicates that the arrow button has width 18. + * The HIToolbox has incomplete and inconsistent support for ComboBoxes. + * There is no constant available to get the height of a ComboBox with + * GetThemeMetric. In fact, ComboBoxes are the same (fixed) height as + * PopupButtons and PushButtons, but they have no shadow at the bottom. + * As a result, they are drawn 1 pixel above the center of the bounds + * rectangle rather than being centered like the other buttons. One can + * request background bounds for a ComboBox, and it is reported with + * height 23, while the actual button face, including its 1-pixel border + * has height 21. Attempting to request the content bounds returns a 0x0 + * rectangle. Measurement indicates that the arrow button has width 18. * - * With no help available from HIToolbox, we have to use hard-wired - * constants for the padding. We shift the bounding rectangle downward by - * 1 pixel to account for the fact that the button is not centered. + * With no help available from HIToolbox, we have to use hard-wired + * constants for the padding. We shift the bounding rectangle downward by + * 1 pixel to account for the fact that the button is not centered. */ -static Ttk_Padding ComboboxPadding = {4, 2, 20, 2 }; +static Ttk_Padding ComboboxPadding = {4, 2, 20, 2}; static void ComboboxElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, + int *minHeight, + Ttk_Padding *paddingPtr) { *minWidth = 24; *minHeight = 23; @@ -1654,8 +1717,12 @@ static void ComboboxElementSize( } static void ComboboxElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { CGRect bounds = BoxToRect(d, b); const HIThemeButtonDrawInfo info = { @@ -1666,26 +1733,26 @@ static void ComboboxElementDraw( .adornment = Ttk_StateTableLookup(ButtonAdornmentTable, state), }; - BEGIN_DRAWING(d); + BEGIN_DRAWING(d) bounds.origin.y += 1; if (TkMacOSXInDarkMode(tkwin)) { #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 bounds.size.height += 1; DrawDarkButton(bounds, info.kind, state, dc.context); #endif - } else { + } else{ #if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 if ((state & TTK_STATE_BACKGROUND) && - !(state & TTK_STATE_DISABLED)) { + !(state & TTK_STATE_DISABLED)) { NSColor *background = [NSColor textBackgroundColor]; CGRect innerBounds = CGRectInset(bounds, 1, 2); - SolidFillRoundedRectangle(dc.context, innerBounds, 4, background); } #endif - ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL); + ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, + NULL); } - END_DRAWING; + END_DRAWING } static Ttk_ElementSpec ComboboxElementSpec = { @@ -1697,42 +1764,51 @@ static Ttk_ElementSpec ComboboxElementSpec = { }; /*---------------------------------------------------------------------- - * +++ Spinbuttons. + * +++ Spinbutton elements -- * - * From Apple HIG, part III, section "Controls", "The Stepper Control": - * there should be 2 pixels of space between the stepper control (AKA - * IncDecButton, AKA "little arrows") and the text field it modifies. + * From Apple HIG, part III, section "Controls", "The Stepper Control": + * there should be 2 pixels of space between the stepper control (AKA + * IncDecButton, AKA "little arrows") and the text field it modifies. * - * Ttk expects the up and down arrows to be distinct elements but - * HIToolbox draws them as one widget with two different pressed states. - * We work around this by defining them as separate elements in the - * layout, but making each one have a drawing method which also draws the - * other one. The down button does no drawing when not pressed, and when - * pressed draws the entire IncDecButton in its "pressed down" state. The - * up button draws the entire IncDecButton when not pressed and when - * pressed draws the IncDecButton in its "pressed up" state. NOTE: This - * means that when the down button is pressed the IncDecButton will be - * drawn twice, first in unpressed state by the up arrow and then in - * "pressed down" state by the down button. The drawing must be done in - * that order. So the up button must be listed first in the layout. + * Ttk expects the up and down arrows to be distinct elements but + * HIToolbox draws them as one widget with two different pressed states. + * We work around this by defining them as separate elements in the + * layout, but making each one have a drawing method which also draws the + * other one. The down button does no drawing when not pressed, and when + * pressed draws the entire IncDecButton in its "pressed down" state. + * The up button draws the entire IncDecButton when not pressed and when + * pressed draws the IncDecButton in its "pressed up" state. NOTE: This + * means that when the down button is pressed the IncDecButton will be + * drawn twice, first in unpressed state by the up arrow and then in + * "pressed down" state by the down button. The drawing must be done in + * that order. So the up button must be listed first in the layout. */ static Ttk_Padding SpinbuttonMargins = {0, 0, 2, 0}; + static void SpinButtonUpElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, + int *minHeight, + Ttk_Padding *paddingPtr) { SInt32 s; ChkErr(GetThemeMetric, kThemeMetricLittleArrowsWidth, &s); *minWidth = s + Ttk_PaddingWidth(SpinbuttonMargins); ChkErr(GetThemeMetric, kThemeMetricLittleArrowsHeight, &s); - *minHeight = (s + Ttk_PaddingHeight(SpinbuttonMargins)) / 2; + *minHeight = (s + Ttk_PaddingHeight(SpinbuttonMargins)) / 2; } static void SpinButtonUpElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { CGRect bounds = BoxToRect(d, Ttk_PadBox(b, SpinbuttonMargins)); int infoState; @@ -1743,7 +1819,6 @@ static void SpinButtonUpElementDraw( } else { infoState = Ttk_StateTableLookup(ThemeStateTable, state); } - const HIThemeButtonDrawInfo info = { .version = 0, .state = infoState, @@ -1751,17 +1826,17 @@ static void SpinButtonUpElementDraw( .value = Ttk_StateTableLookup(ButtonValueTable, state), .adornment = kThemeAdornmentNone, }; - - BEGIN_DRAWING(d); + BEGIN_DRAWING(d) #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { DrawDarkIncDecButton(bounds, infoState, state, dc.context); } else #endif { - ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL); + ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, + NULL); } - END_DRAWING; + END_DRAWING } static Ttk_ElementSpec SpinButtonUpElementSpec = { @@ -1771,10 +1846,13 @@ static Ttk_ElementSpec SpinButtonUpElementSpec = { SpinButtonUpElementSize, SpinButtonUpElementDraw }; - static void SpinButtonDownElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, + int *minHeight, + Ttk_Padding *paddingPtr) { SInt32 s; @@ -1785,8 +1863,12 @@ static void SpinButtonDownElementSize( } static void SpinButtonDownElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { CGRect bounds = BoxToRect(d, Ttk_PadBox(b, SpinbuttonMargins)); int infoState = 0; @@ -1796,7 +1878,7 @@ static void SpinButtonDownElementDraw( if (state & TTK_STATE_PRESSED) { infoState = kThemeStatePressedDown; } else { - return; // ??? + return; } const HIThemeButtonDrawInfo info = { .version = 0, @@ -1806,7 +1888,7 @@ static void SpinButtonDownElementDraw( .adornment = kThemeAdornmentNone, }; - BEGIN_DRAWING(d); + BEGIN_DRAWING(d) #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { DrawDarkIncDecButton(bounds, infoState, state, dc.context); @@ -1814,9 +1896,9 @@ static void SpinButtonDownElementDraw( #endif { ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, - NULL); + NULL); } - END_DRAWING; + END_DRAWING } static Ttk_ElementSpec SpinButtonDownElementSpec = { @@ -1829,6 +1911,7 @@ static Ttk_ElementSpec SpinButtonDownElementSpec = { /*---------------------------------------------------------------------- * +++ DrawThemeTrack-based elements -- + * * Progress bars and scales. (See also: <>) */ @@ -1838,15 +1921,15 @@ static Ttk_ElementSpec SpinButtonDownElementSpec = { */ static Ttk_StateTable ThemeTrackEnableTable[] = { - { kThemeTrackDisabled, TTK_STATE_DISABLED, 0 }, - { kThemeTrackActive, TTK_STATE_BACKGROUND, 0 }, - { kThemeTrackActive, 0, 0 } + {kThemeTrackDisabled, TTK_STATE_DISABLED, 0}, + {kThemeTrackActive, TTK_STATE_BACKGROUND, 0}, + {kThemeTrackActive, 0, 0} /* { kThemeTrackNothingToScroll, ?, ? }, */ }; -typedef struct { /* TrackElement client data */ - ThemeTrackKind kind; - SInt32 thicknessMetric; +typedef struct { /* TrackElement client data */ + ThemeTrackKind kind; + SInt32 thicknessMetric; } TrackElementData; static TrackElementData ScaleData = { @@ -1854,34 +1937,41 @@ static TrackElementData ScaleData = { }; typedef struct { - Tcl_Obj *fromObj; /* minimum value */ - Tcl_Obj *toObj; /* maximum value */ - Tcl_Obj *valueObj; /* current value */ - Tcl_Obj *orientObj; /* horizontal / vertical */ + Tcl_Obj *fromObj; /* minimum value */ + Tcl_Obj *toObj; /* maximum value */ + Tcl_Obj *valueObj; /* current value */ + Tcl_Obj *orientObj; /* horizontal / vertical */ } TrackElement; static Ttk_ElementOptionSpec TrackElementOptions[] = { - { "-from", TK_OPTION_DOUBLE, Tk_Offset(TrackElement,fromObj) }, - { "-to", TK_OPTION_DOUBLE, Tk_Offset(TrackElement,toObj) }, - { "-value", TK_OPTION_DOUBLE, Tk_Offset(TrackElement,valueObj) }, - { "-orient", TK_OPTION_STRING, Tk_Offset(TrackElement,orientObj) }, - {0,0,0} + {"-from", TK_OPTION_DOUBLE, Tk_Offset(TrackElement, fromObj)}, + {"-to", TK_OPTION_DOUBLE, Tk_Offset(TrackElement, toObj)}, + {"-value", TK_OPTION_DOUBLE, Tk_Offset(TrackElement, valueObj)}, + {"-orient", TK_OPTION_STRING, Tk_Offset(TrackElement, orientObj)}, + {0, 0, 0} }; - static void TrackElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, + int *minHeight, + Ttk_Padding *paddingPtr) { TrackElementData *data = clientData; - SInt32 size = 24; /* reasonable default ... */ + SInt32 size = 24; /* reasonable default ... */ ChkErr(GetThemeMetric, data->thicknessMetric, &size); *minWidth = *minHeight = size; } static void TrackElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { TrackElementData *data = clientData; TrackElement *elem = elementRecord; @@ -1902,40 +1992,39 @@ static void TrackElementDraw( .max = to * factor, .value = value * factor, .attributes = kThemeTrackShowThumb | - (orientation == TTK_ORIENT_HORIZONTAL ? - kThemeTrackHorizontal : 0), + (orientation == TTK_ORIENT_HORIZONTAL ? + kThemeTrackHorizontal : 0), .enableState = Ttk_StateTableLookup(ThemeTrackEnableTable, state), .trackInfo.progress.phase = 0, }; if (info.kind == kThemeSlider) { info.trackInfo.slider.pressState = state & TTK_STATE_PRESSED ? - kThemeThumbPressed : 0; + kThemeThumbPressed : 0; if (state & TTK_STATE_ALTERNATE) { info.trackInfo.slider.thumbDir = kThemeThumbDownward; } else { info.trackInfo.slider.thumbDir = kThemeThumbPlain; } } - BEGIN_DRAWING(d); + BEGIN_DRAWING(d) #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { CGRect bounds = BoxToRect(d, b); NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *trackColor = [NSColor colorWithColorSpace: deviceRGB - components: darkTrack - count: 4]; - + components: darkTrack + count: 4]; if (orientation == TTK_ORIENT_HORIZONTAL) { - bounds = CGRectInset(bounds, 1, bounds.size.height/2 - 2); + bounds = CGRectInset(bounds, 1, bounds.size.height / 2 - 2); } else { - bounds = CGRectInset(bounds, bounds.size.width/2 - 3, 2); + bounds = CGRectInset(bounds, bounds.size.width / 2 - 3, 2); } SolidFillRoundedRectangle(dc.context, bounds, 2, trackColor); } -#endif +#endif /* if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 */ ChkErr(HIThemeDrawTrack, &info, NULL, dc.context, HIOrientation); - END_DRAWING; + END_DRAWING } static Ttk_ElementSpec TrackElementSpec = { @@ -1946,19 +2035,22 @@ static Ttk_ElementSpec TrackElementSpec = { TrackElementDraw }; -/* - * Slider element -- <> +/*---------------------------------------------------------------------- + * Slider elements -- <> + * * Has geometry only. The Scale widget adjusts the position of this element, * and uses it for hit detection. In the Aqua theme, the slider is actually * drawn as part of the trough element. * - * Also buggy: The geometry here is a Wild-Assed-Guess; I can't figure out how - * to get the Appearance Manager to tell me the slider size. */ static void SliderElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, + int *minHeight, + Ttk_Padding *paddingPtr) { *minWidth = *minHeight = 24; } @@ -1972,7 +2064,7 @@ static Ttk_ElementSpec SliderElementSpec = { }; /*---------------------------------------------------------------------- - * +++ Progress bar element: + * +++ Progress bar elements -- * * @@@ NOTE: According to an older revision of the Aqua reference docs, * @@@ the 'phase' field is between 0 and 4. Newer revisions say @@ -1980,40 +2072,47 @@ static Ttk_ElementSpec SliderElementSpec = { */ typedef struct { - Tcl_Obj *orientObj; /* horizontal / vertical */ - Tcl_Obj *valueObj; /* current value */ - Tcl_Obj *maximumObj; /* maximum value */ - Tcl_Obj *phaseObj; /* animation phase */ - Tcl_Obj *modeObj; /* progress bar mode */ + Tcl_Obj *orientObj; /* horizontal / vertical */ + Tcl_Obj *valueObj; /* current value */ + Tcl_Obj *maximumObj; /* maximum value */ + Tcl_Obj *phaseObj; /* animation phase */ + Tcl_Obj *modeObj; /* progress bar mode */ } PbarElement; static Ttk_ElementOptionSpec PbarElementOptions[] = { - { "-orient", TK_OPTION_STRING, - Tk_Offset(PbarElement,orientObj), "horizontal" }, - { "-value", TK_OPTION_DOUBLE, - Tk_Offset(PbarElement,valueObj), "0" }, - { "-maximum", TK_OPTION_DOUBLE, - Tk_Offset(PbarElement,maximumObj), "100" }, - { "-phase", TK_OPTION_INT, - Tk_Offset(PbarElement,phaseObj), "0" }, - { "-mode", TK_OPTION_STRING, - Tk_Offset(PbarElement,modeObj), "determinate" }, - {0,0,0,0} + {"-orient", TK_OPTION_STRING, + Tk_Offset(PbarElement, orientObj), "horizontal"}, + {"-value", TK_OPTION_DOUBLE, + Tk_Offset(PbarElement, valueObj), "0"}, + {"-maximum", TK_OPTION_DOUBLE, + Tk_Offset(PbarElement, maximumObj), "100"}, + {"-phase", TK_OPTION_INT, + Tk_Offset(PbarElement, phaseObj), "0"}, + {"-mode", TK_OPTION_STRING, + Tk_Offset(PbarElement, modeObj), "determinate"}, + {0, 0, 0, 0} }; - static void PbarElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, + int *minHeight, + Ttk_Padding *paddingPtr) { - SInt32 size = 24; /* @@@ Check HIG for correct default */ + SInt32 size = 24; /* @@@ Check HIG for correct default */ ChkErr(GetThemeMetric, kThemeMetricLargeProgressBarThickness, &size); *minWidth = *minHeight = size; } static void PbarElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { PbarElement *pbar = elementRecord; int orientation = TTK_ORIENT_HORIZONTAL, phase = 0; @@ -2027,37 +2126,39 @@ static void PbarElementDraw( HIThemeTrackDrawInfo info = { .version = 0, - .kind = (!strcmp("indeterminate", Tcl_GetString(pbar->modeObj)) && value) ? - kThemeIndeterminateBar : kThemeProgressBar, + .kind = + (!strcmp("indeterminate", + Tcl_GetString(pbar->modeObj)) && value) ? + kThemeIndeterminateBar : kThemeProgressBar, .bounds = BoxToRect(d, b), .min = 0, .max = maximum * factor, .value = value * factor, .attributes = kThemeTrackShowThumb | - (orientation == TTK_ORIENT_HORIZONTAL ? - kThemeTrackHorizontal : 0), + (orientation == TTK_ORIENT_HORIZONTAL ? + kThemeTrackHorizontal : 0), .enableState = Ttk_StateTableLookup(ThemeTrackEnableTable, state), .trackInfo.progress.phase = phase, }; - BEGIN_DRAWING(d); + BEGIN_DRAWING(d) #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { CGRect bounds = BoxToRect(d, b); NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *trackColor = [NSColor colorWithColorSpace: deviceRGB - components: darkTrack - count: 4]; + components: darkTrack + count: 4]; if (orientation == TTK_ORIENT_HORIZONTAL) { - bounds = CGRectInset(bounds, 1, bounds.size.height/2 - 3); + bounds = CGRectInset(bounds, 1, bounds.size.height / 2 - 3); } else { - bounds = CGRectInset(bounds, bounds.size.width/2 - 3, 1); + bounds = CGRectInset(bounds, bounds.size.width / 2 - 3, 1); } SolidFillRoundedRectangle(dc.context, bounds, 3, trackColor); } -#endif +#endif /* if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 */ ChkErr(HIThemeDrawTrack, &info, NULL, dc.context, HIOrientation); - END_DRAWING; + END_DRAWING } static Ttk_ElementSpec PbarElementSpec = { @@ -2069,7 +2170,7 @@ static Ttk_ElementSpec PbarElementSpec = { }; /*---------------------------------------------------------------------- - * +++ Scrollbar element + * +++ Scrollbar elements */ typedef struct @@ -2078,14 +2179,17 @@ typedef struct } ScrollbarElement; static Ttk_ElementOptionSpec ScrollbarElementOptions[] = { - { "-orient", TK_OPTION_STRING, - Tk_Offset(ScrollbarElement,orientObj), "horizontal" }, - {0,0,0,0} + {"-orient", TK_OPTION_STRING, + Tk_Offset(ScrollbarElement, orientObj), "horizontal"}, + {0, 0, 0, 0} }; - static void TroughElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, + int *minHeight, + Ttk_Padding *paddingPtr) { ScrollbarElement *scrollbar = elementRecord; int orientation = TTK_ORIENT_HORIZONTAL; @@ -2094,28 +2198,39 @@ static void TroughElementSize( Ttk_GetOrientFromObj(NULL, scrollbar->orientObj, &orientation); ChkErr(GetThemeMetric, kThemeMetricScrollBarWidth, &thickness); if (orientation == TTK_ORIENT_HORIZONTAL) { - *minHeight = thickness; + *minHeight = thickness; if ([NSApp macMinorVersion] > 7) { *paddingPtr = Ttk_MakePadding(4, 4, 4, 3); } } else { - *minWidth = thickness; + *minWidth = thickness; if ([NSApp macMinorVersion] > 7) { *paddingPtr = Ttk_MakePadding(4, 4, 3, 4); } } } -static CGFloat lightTrough[4] = {250.0/255, 250.0/255, 250.0/255, 1.0}; -static CGFloat darkTrough[4] = {45.0/255, 46.0/255, 49.0/255, 1.0}; -static CGFloat lightInactiveThumb[4] = {200.0/255, 200.0/255, 200.0/255, 1.0}; -static CGFloat lightActiveThumb[4] = {133.0/255, 133.0/255, 133.0/255, 1.0}; -static CGFloat darkInactiveThumb[4] = {116.0/255, 117.0/255, 118.0/255, 1.0}; -static CGFloat darkActiveThumb[4] = {158.0/255, 158.0/255, 159.0/255, 1.0}; - +static CGFloat lightTrough[4] = {250.0 / 255, 250.0 / 255, 250.0 / 255, 1.0}; +static CGFloat darkTrough[4] = {45.0 / 255, 46.0 / 255, 49.0 / 255, 1.0}; +static CGFloat lightInactiveThumb[4] = { + 200.0 / 255, 200.0 / 255, 200.0 / 255, 1.0 +}; +static CGFloat lightActiveThumb[4] = { + 133.0 / 255, 133.0 / 255, 133.0 / 255, 1.0 +}; +static CGFloat darkInactiveThumb[4] = { + 116.0 / 255, 117.0 / 255, 118.0 / 255, 1.0 +}; +static CGFloat darkActiveThumb[4] = { + 158.0 / 255, 158.0 / 255, 159.0 / 255, 1.0 +}; static void TroughElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { ScrollbarElement *scrollbar = elementRecord; int orientation = TTK_ORIENT_HORIZONTAL; @@ -2131,19 +2246,19 @@ static void TroughElementDraw( bounds = CGRectInset(bounds, 1, 0); } troughColor = [NSColor colorWithColorSpace: deviceRGB - components: rgba - count: 4]; - BEGIN_DRAWING(d); + components: rgba + count: 4]; + BEGIN_DRAWING(d) if ([NSApp macMinorVersion] > 8) { #if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 CGContextSetFillColorWithColor(dc.context, troughColor.CGColor); #endif } else { ChkErr(HIThemeSetFill, kThemeBrushDocumentWindowBackground, NULL, - dc.context, HIOrientation); + dc.context, HIOrientation); } CGContextFillRect(dc.context, bounds); - END_DRAWING; + END_DRAWING } static Ttk_ElementSpec TroughElementSpec = { @@ -2153,10 +2268,13 @@ static Ttk_ElementSpec TroughElementSpec = { TroughElementSize, TroughElementDraw }; - static void ThumbElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, + int *minHeight, + Ttk_Padding *paddingPtr) { ScrollbarElement *scrollbar = elementRecord; int orientation = TTK_ORIENT_HORIZONTAL; @@ -2165,13 +2283,17 @@ static void ThumbElementSize( if (orientation == TTK_ORIENT_HORIZONTAL) { *minHeight = 8; } else { - *minWidth = 8; + *minWidth = 8; } } static void ThumbElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { ScrollbarElement *scrollbar = elementRecord; int orientation = TTK_ORIENT_HORIZONTAL; @@ -2180,18 +2302,18 @@ static void ThumbElementDraw( /* * In order to make ttk scrollbars work correctly it is necessary to be - * able to display the thumb element at the size and location which the ttk - * scrollbar widget requests. The algorithm that HIToolbox uses to + * able to display the thumb element at the size and location which the + * ttk scrollbar widget requests. The algorithm that HIToolbox uses to * determine the thumb geometry from the input values of min, max, value * and viewSizeis, of course, undocumented. And this turns out to be a * hard reverse engineering problem. A seemingly natural algorithm is * implemented below, but it does not correctly compute the same thumb * geometry as HITools (which also apparently does not agree with * NSScrollbar). This code uses that algorithm for older OS versions, - * because using HITools also handles drawing the buttons and 3D thumb used - * on those systems. The incorrect geometry is annoying but not unusable. - * For newer systems the cleanest approach is to just draw the thumb - * directly. + * because using HITools also handles drawing the buttons and 3D thumb + * used on those systems. The incorrect geometry is annoying but not + * unusable. For newer systems the cleanest approach is to just draw the + * thumb directly. */ if ([NSApp macMinorVersion] > 8) { @@ -2200,69 +2322,66 @@ static void ThumbElementDraw( NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *thumbColor; CGFloat *rgba; - - if ((orientation == TTK_ORIENT_HORIZONTAL - && thumbBounds.size.width >= Tk_Width(tkwin) - 8) - || (orientation == TTK_ORIENT_VERTICAL - && thumbBounds.size.height >= Tk_Height(tkwin) - 8)) { + if ((orientation == TTK_ORIENT_HORIZONTAL && + thumbBounds.size.width >= Tk_Width(tkwin) - 8) || + (orientation == TTK_ORIENT_VERTICAL && + thumbBounds.size.height >= Tk_Height(tkwin) - 8)) { return; } - int isDark = TkMacOSXInDarkMode(tkwin); - if ((state & TTK_STATE_PRESSED) || - (state & TTK_STATE_HOVER)) { + (state & TTK_STATE_HOVER)) { rgba = isDark ? darkActiveThumb : lightActiveThumb; } else { rgba = isDark ? darkInactiveThumb : lightInactiveThumb; } thumbColor = [NSColor colorWithColorSpace: deviceRGB - components: rgba - count: 4]; - BEGIN_DRAWING(d); + components: rgba + count: 4]; + BEGIN_DRAWING(d) SolidFillRoundedRectangle(dc.context, thumbBounds, 4, thumbColor); - END_DRAWING; -#endif + END_DRAWING +#endif /* if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 */ } else { double thumbSize, trackSize, visibleSize, viewSize; MacDrawable *macWin = (MacDrawable *) Tk_WindowId(tkwin); CGRect troughBounds = {{macWin->xOff, macWin->yOff}, {Tk_Width(tkwin), Tk_Height(tkwin)}}; - /* - * The info struct has integer fields, which will be converted to - * floats in the drawing routine. All of values provided in the info - * struct, namely min, max, value, and viewSize are only defined up to - * an arbitrary scale factor. To avoid roundoff error we scale so that - * the viewSize is a large float which is smaller than the largest int. - */ - - viewSize = RangeToFactor(100.0); + /* + * The info struct has integer fields, which will be converted to + * floats in the drawing routine. All of values provided in the info + * struct, namely min, max, value, and viewSize are only defined up to + * an arbitrary scale factor. To avoid roundoff error we scale so + * that the viewSize is a large float which is smaller than the + * largest int. + */ + viewSize = RangeToFactor(100.0); HIThemeTrackDrawInfo info = { .version = 0, .bounds = troughBounds, .min = 0, - .attributes = kThemeTrackShowThumb | kThemeTrackThumbRgnIsNotGhost, + .attributes = kThemeTrackShowThumb | + kThemeTrackThumbRgnIsNotGhost, .enableState = kThemeTrackActive }; - - info.trackInfo.scrollbar.viewsize = viewSize*.8; + info.trackInfo.scrollbar.viewsize = viewSize * .8; if (orientation == TTK_ORIENT_HORIZONTAL) { trackSize = troughBounds.size.width; thumbSize = b.width; visibleSize = (thumbSize / trackSize) * viewSize; info.max = viewSize - visibleSize; - info.value = info.max * (b.x / (trackSize - thumbSize)); + info.value = info.max * (b.x / (trackSize - thumbSize)); } else { thumbSize = b.height; trackSize = troughBounds.size.height; visibleSize = (thumbSize / trackSize) * viewSize; info.max = viewSize - visibleSize; - info.value = info.max * (b.y / (trackSize - thumbSize)); + info.value = info.max * (b.y / (trackSize - thumbSize)); } if ((state & TTK_STATE_PRESSED) || - (state & TTK_STATE_HOVER)) { + (state & TTK_STATE_HOVER)) { info.trackInfo.scrollbar.pressState = kThemeThumbPressed; } else { info.trackInfo.scrollbar.pressState = 0; @@ -2272,9 +2391,9 @@ static void ThumbElementDraw( } else { info.attributes &= ~kThemeTrackHorizontal; } - BEGIN_DRAWING(d); + BEGIN_DRAWING(d) HIThemeDrawTrack(&info, 0, dc.context, kHIThemeOrientationNormal); - END_DRAWING; + END_DRAWING } } @@ -2285,10 +2404,13 @@ static Ttk_ElementSpec ThumbElementSpec = { ThumbElementSize, ThumbElementDraw }; - static void ArrowElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, + int *minHeight, + Ttk_Padding *paddingPtr) { if ([NSApp macMinorVersion] < 8) { *minHeight = *minWidth = 14; @@ -2314,34 +2436,44 @@ static Ttk_ElementSpec ArrowElementSpec = { */ static void SeparatorElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, + int *minHeight, + Ttk_Padding *paddingPtr) { *minWidth = *minHeight = 1; } static void SeparatorElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, unsigned int state) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + unsigned int state) { CGRect bounds = BoxToRect(d, b); const HIThemeSeparatorDrawInfo info = { .version = 0, - /* Separator only supports kThemeStateActive, kThemeStateInactive */ - .state = Ttk_StateTableLookup(ThemeStateTable, state & TTK_STATE_BACKGROUND), + /* Separator only supports kThemeStateActive, kThemeStateInactive */ + .state = Ttk_StateTableLookup(ThemeStateTable, + state & TTK_STATE_BACKGROUND), }; - BEGIN_DRAWING(d); + BEGIN_DRAWING(d) #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { DrawDarkSeparator(bounds, dc.context, tkwin); } else { - ChkErr(HIThemeDrawSeparator, &bounds, &info, dc.context, HIOrientation); + ChkErr(HIThemeDrawSeparator, &bounds, &info, dc.context, + HIOrientation); } #else ChkErr(HIThemeDrawSeparator, &bounds, &info, dc.context, HIOrientation); #endif - END_DRAWING; + END_DRAWING } static Ttk_ElementSpec SeparatorElementSpec = { @@ -2353,15 +2485,19 @@ static Ttk_ElementSpec SeparatorElementSpec = { }; /*---------------------------------------------------------------------- - * +++ Size grip element. + * +++ Size grip elements -- (obsolete) */ static const ThemeGrowDirection sizegripGrowDirection - = kThemeGrowRight|kThemeGrowDown; + = kThemeGrowRight | kThemeGrowDown; static void SizegripElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, + int *minHeight, + Ttk_Padding *paddingPtr) { HIThemeGrowBoxDrawInfo info = { .version = 0, @@ -2378,23 +2514,28 @@ static void SizegripElementSize( } static void SizegripElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, unsigned int state) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + unsigned int state) { CGRect bounds = BoxToRect(d, b); HIThemeGrowBoxDrawInfo info = { .version = 0, - /* Grow box only supports kThemeStateActive, kThemeStateInactive */ + /* Grow box only supports kThemeStateActive, kThemeStateInactive */ .state = Ttk_StateTableLookup(ThemeStateTable, - state & TTK_STATE_BACKGROUND), + state & TTK_STATE_BACKGROUND), .kind = kHIThemeGrowBoxKindNormal, .direction = sizegripGrowDirection, .size = kHIThemeGrowBoxSizeNormal, }; - BEGIN_DRAWING(d); - ChkErr(HIThemeDrawGrowBox, &bounds.origin, &info, dc.context, HIOrientation); - END_DRAWING; + BEGIN_DRAWING(d) + ChkErr(HIThemeDrawGrowBox, &bounds.origin, &info, dc.context, + HIOrientation); + END_DRAWING } static Ttk_ElementSpec SizegripElementSpec = { @@ -2406,85 +2547,93 @@ static Ttk_ElementSpec SizegripElementSpec = { }; /*---------------------------------------------------------------------- - * +++ Background and fill elements. + * +++ Background and fill elements -- * - * Before drawing any ttk widget, its bounding rectangle is filled with a - * background color. This color must match the background color of the - * containing widget to avoid looking ugly. The need for care when doing - * this is exacerbated by the fact that ttk enforces its "native look" by - * not allowing user control of the background or highlight colors of ttk - * widgets. + * Before drawing any ttk widget, its bounding rectangle is filled with a + * background color. This color must match the background color of the + * containing widget to avoid looking ugly. The need for care when doing + * this is exacerbated by the fact that ttk enforces its "native look" by + * not allowing user control of the background or highlight colors of ttk + * widgets. * - * This job is made more complicated in recent versions of macOS by the - * fact that the Appkit GroupBox (used for ttk LabelFrames) and TabbedPane - * (used for the Notebook widget) both place their content inside a - * rectangle with rounded corners that has a color which contrasts with - * the dialog background color. Moreover, although the Apple human - * interface guidelines recommend against doing so, there are times when - * one wants to nest these widgets, for example having a GroupBox inside - * of a TabbedPane. To have the right contrast, each level of nesting - * requires a different color. + * This job is made more complicated in recent versions of macOS by the + * fact that the Appkit GroupBox (used for ttk LabelFrames) and + * TabbedPane (used for the Notebook widget) both place their content + * inside a rectangle with rounded corners that has a color which + * contrasts with the dialog background color. Moreover, although the + * Apple human interface guidelines recommend against doing so, there are + * times when one wants to nest these widgets, for example having a + * GroupBox inside of a TabbedPane. To have the right contrast, each + * level of nesting requires a different color. * - * Previous Tk releases used the HIThemeDrawGroupBox routine to draw - * GroupBoxes and TabbedPanes. This meant that the best that could be done - * was to set the GroupBox to be of kind - * kHIThemeGroupBoxKindPrimaryOpaque, and set its fill color to be the - * system background color. If widgets inside the box were drawn with the - * system background color the backgrounds would match. But this produces - * a GroupBox with no contrast, the only visual clue being a faint - * highlighting around the top of the GroupBox. Moreover, the TabbedPane - * does not have an Opaque version, so while it is drawn inside a - * contrasting rounded rectangle, the widgets inside the pane needed to be - * enclosed in a frame with the system background color. This added a - * visual artifact since the frame's background color does not match the - * Pane's background color. That code has now been replaced with the - * standalone drawing procedure macOSXDrawGroupBox, which draws a rounded - * rectangle with an appropriate contrasting background color. + * Previous Tk releases used the HIThemeDrawGroupBox routine to draw + * GroupBoxes and TabbedPanes. This meant that the best that could be + * done was to set the GroupBox to be of kind + * kHIThemeGroupBoxKindPrimaryOpaque, and set its fill color to be the + * system background color. If widgets inside the box were drawn with + * the system background color the backgrounds would match. But this + * produces a GroupBox with no contrast, the only visual clue being a + * faint highlighting around the top of the GroupBox. Moreover, the + * TabbedPane does not have an Opaque version, so while it is drawn + * inside a contrasting rounded rectangle, the widgets inside the pane + * needed to be enclosed in a frame with the system background + * color. This added a visual artifact since the frame's background color + * does not match the Pane's background color. That code has now been + * replaced with the standalone drawing procedure macOSXDrawGroupBox, + * which draws a rounded rectangle with an appropriate contrasting + * background color. * - * Patterned backgrounds, which are now obsolete, should be aligned with - * the coordinate system of the top-level window. Apparently failing to - * do this used to cause graphics anomalies when drawing into an - * off-screen graphics port. The code for handling this is currently - * commented out. + * Patterned backgrounds, which are now obsolete, should be aligned with + * the coordinate system of the top-level window. Apparently failing to + * do this used to cause graphics anomalies when drawing into an + * off-screen graphics port. The code for handling this is currently + * commented out. */ static void FillElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { CGRect bounds = BoxToRect(d, b); + #if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *bgColor; CGFloat fill[4]; - - BEGIN_DRAWING(d); + BEGIN_DRAWING(d) GetBackgroundColor(dc.context, tkwin, 0, fill); bgColor = [NSColor colorWithColorSpace: deviceRGB components: fill - count: 4]; + count: 4]; CGContextSetFillColorSpace(dc.context, deviceRGB.CGColorSpace); CGContextSetFillColorWithColor(dc.context, bgColor.CGColor); CGContextFillRect(dc.context, bounds); - END_DRAWING; -#else + END_DRAWING +#else /* if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 */ ThemeBrush brush = (state & TTK_STATE_BACKGROUND) - ? kThemeBrushModelessDialogBackgroundInactive - : kThemeBrushModelessDialogBackgroundActive; - - BEGIN_DRAWING(d); + ? kThemeBrushModelessDialogBackgroundInactive + : kThemeBrushModelessDialogBackgroundActive; + BEGIN_DRAWING(d) ChkErr(HIThemeSetFill, brush, NULL, dc.context, HIOrientation); //QDSetPatternOrigin(PatternOrigin(tkwin, d)); CGContextFillRect(dc.context, bounds); - END_DRAWING; -#endif + END_DRAWING +#endif /* if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 */ } static void BackgroundElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, unsigned int state) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + unsigned int state) { FillElementDraw(clientData, elementRecord, tkwin, d, Ttk_WinBox(tkwin), - state); + state); } static Ttk_ElementSpec FillElementSpec = { @@ -2494,7 +2643,6 @@ static Ttk_ElementSpec FillElementSpec = { TtkNullElementSize, FillElementDraw }; - static Ttk_ElementSpec BackgroundElementSpec = { TK_STYLE_VERSION_2, sizeof(NullElement), @@ -2507,28 +2655,32 @@ static Ttk_ElementSpec BackgroundElementSpec = { * +++ ToolbarBackground element -- toolbar style for frames. * * This is very similar to the normal background element, but uses a - * different ThemeBrush in order to get the lighter pinstripe effect used in - * toolbars. We use SetThemeBackground() rather than ApplyThemeBackground() - * in order to get the right style. + * different ThemeBrush in order to get the lighter pinstripe effect + * used in toolbars. We use SetThemeBackground() rather than + * ApplyThemeBackground() in order to get the right style. * - * * */ static void ToolbarBackgroundElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { ThemeBrush brush = kThemeBrushToolbarBackground; CGRect bounds = BoxToRect(d, Ttk_WinBox(tkwin)); - BEGIN_DRAWING(d); + BEGIN_DRAWING(d) ChkErr(HIThemeSetFill, brush, NULL, dc.context, HIOrientation); //QDSetPatternOrigin(PatternOrigin(tkwin, d)); CGContextFillRect(dc.context, bounds); - END_DRAWING; + END_DRAWING } static Ttk_ElementSpec ToolbarBackgroundElementSpec = { @@ -2540,30 +2692,36 @@ static Ttk_ElementSpec ToolbarBackgroundElementSpec = { }; /*---------------------------------------------------------------------- - * +++ Field element: - * Used for the Treeview widget. This is like the BackgroundElement + * +++ Field elements -- + * + * Used for the Treeview widget. This is like the BackgroundElement * except that the fieldbackground color is configureable. */ typedef struct { - Tcl_Obj *backgroundObj; + Tcl_Obj *backgroundObj; } FieldElement; static Ttk_ElementOptionSpec FieldElementOptions[] = { - { "-fieldbackground", TK_OPTION_BORDER, - Tk_Offset(FieldElement, backgroundObj), "white" }, - { NULL, 0, 0, NULL } + {"-fieldbackground", TK_OPTION_BORDER, + Tk_Offset(FieldElement, backgroundObj), "white"}, + {NULL, 0, 0, NULL} }; - static void FieldElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { FieldElement *e = elementRecord; - Tk_3DBorder backgroundPtr = Tk_Get3DBorderFromObj(tkwin,e->backgroundObj); + Tk_3DBorder backgroundPtr = + Tk_Get3DBorderFromObj(tkwin, e->backgroundObj); + XFillRectangle(Tk_Display(tkwin), d, - Tk_3DBorderGC(tkwin, backgroundPtr, TK_3D_FLAT_GC), - b.x, b.y, b.width, b.height); + Tk_3DBorderGC(tkwin, backgroundPtr, TK_3D_FLAT_GC), + b.x, b.y, b.width, b.height); } static Ttk_ElementSpec FieldElementSpec = { @@ -2575,30 +2733,35 @@ static Ttk_ElementSpec FieldElementSpec = { }; /*---------------------------------------------------------------------- - * +++ Treeview header + * +++ Treeview headers -- + * * Redefine the header to use a kThemeListHeaderButton. */ static Ttk_StateTable TreeHeaderValueTable[] = { - { kThemeButtonOn, TTK_STATE_ALTERNATE}, - { kThemeButtonOn, TTK_STATE_SELECTED}, - { kThemeButtonOff, 0} + {kThemeButtonOn, TTK_STATE_ALTERNATE}, + {kThemeButtonOn, TTK_STATE_SELECTED}, + {kThemeButtonOff, 0} }; static Ttk_StateTable TreeHeaderAdornmentTable[] = { - { kThemeAdornmentHeaderButtonSortUp, - TTK_STATE_ALTERNATE|TTK_TREEVIEW_STATE_SORTARROW}, - { kThemeAdornmentDefault, - TTK_STATE_SELECTED|TTK_TREEVIEW_STATE_SORTARROW}, - { kThemeAdornmentHeaderButtonNoSortArrow, TTK_STATE_ALTERNATE}, - { kThemeAdornmentHeaderButtonNoSortArrow, TTK_STATE_SELECTED}, - { kThemeAdornmentFocus, TTK_STATE_FOCUS}, - { kThemeAdornmentNone, 0} + {kThemeAdornmentHeaderButtonSortUp, + TTK_STATE_ALTERNATE | TTK_TREEVIEW_STATE_SORTARROW}, + {kThemeAdornmentDefault, + TTK_STATE_SELECTED | TTK_TREEVIEW_STATE_SORTARROW}, + {kThemeAdornmentHeaderButtonNoSortArrow, TTK_STATE_ALTERNATE}, + {kThemeAdornmentHeaderButtonNoSortArrow, TTK_STATE_SELECTED}, + {kThemeAdornmentFocus, TTK_STATE_FOCUS}, + {kThemeAdornmentNone, 0} }; +static void TreeAreaElementSize ( + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, + int *minHeight, + Ttk_Padding *paddingPtr) +{ -static void TreeAreaElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) -{ /* * Padding is needed to get the heading text to align correctly, since the * widget expects the heading to be the same height as a row. @@ -2616,22 +2779,29 @@ static Ttk_ElementSpec TreeAreaElementSpec = { TreeAreaElementSize, TtkNullElementDraw }; - static void TreeHeaderElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, + int *minHeight, + Ttk_Padding *paddingPtr) { if ([NSApp macMinorVersion] > 8) { *minHeight = 24; } else { ButtonElementSize(clientData, elementRecord, tkwin, minWidth, - minHeight, paddingPtr); + minHeight, paddingPtr); } } static void TreeHeaderElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { ThemeButtonParams *params = clientData; CGRect bounds = BoxToRect(d, b); @@ -2643,14 +2813,15 @@ static void TreeHeaderElementDraw( .adornment = Ttk_StateTableLookup(TreeHeaderAdornmentTable, state), }; - BEGIN_DRAWING(d); + BEGIN_DRAWING(d) if ([NSApp macMinorVersion] > 8) { #if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 - /* - * Compensate for the padding added in TreeHeaderElementSize, so the - * larger heading will be drawn at the top of the widget. - */ - + + /* + * Compensate for the padding added in TreeHeaderElementSize, so + * the larger heading will be drawn at the top of the widget. + */ + bounds.origin.y -= 4; if (TkMacOSXInDarkMode(tkwin)) { #if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 @@ -2661,9 +2832,10 @@ static void TreeHeaderElementDraw( } #endif /* MAC_OS_X_VERSION_MIN_REQUIRED > 1080 */ } else { - ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL); + ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, + NULL); } - END_DRAWING; + END_DRAWING } static Ttk_ElementSpec TreeHeaderElementSpec = { @@ -2674,20 +2846,23 @@ static Ttk_ElementSpec TreeHeaderElementSpec = { TreeHeaderElementDraw }; -/* - * Disclosure triangle: +/*---------------------------------------------------------------------- + * +++ Disclosure triangles -- */ -#define TTK_TREEVIEW_STATE_OPEN TTK_STATE_USER1 -#define TTK_TREEVIEW_STATE_LEAF TTK_STATE_USER2 +#define TTK_TREEVIEW_STATE_OPEN TTK_STATE_USER1 +#define TTK_TREEVIEW_STATE_LEAF TTK_STATE_USER2 static Ttk_StateTable DisclosureValueTable[] = { - { kThemeDisclosureDown, TTK_TREEVIEW_STATE_OPEN, 0 }, - { kThemeDisclosureRight, 0, 0 }, + {kThemeDisclosureDown, TTK_TREEVIEW_STATE_OPEN, 0}, + {kThemeDisclosureRight, 0, 0}, }; - static void DisclosureElementSize( - void *clientData, void *elementRecord, Tk_Window tkwin, - int *minWidth, int *minHeight, Ttk_Padding *paddingPtr) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + int *minWidth, + int *minHeight, + Ttk_Padding *paddingPtr) { SInt32 s; @@ -2698,8 +2873,12 @@ static void DisclosureElementSize( } static void DisclosureElementDraw( - void *clientData, void *elementRecord, Tk_Window tkwin, - Drawable d, Ttk_Box b, Ttk_State state) + void *clientData, + void *elementRecord, + Tk_Window tkwin, + Drawable d, + Ttk_Box b, + Ttk_State state) { if (!(state & TTK_TREEVIEW_STATE_LEAF)) { int triangleState = TkMacOSXInDarkMode(tkwin) ? @@ -2713,9 +2892,10 @@ static void DisclosureElementDraw( .adornment = kThemeAdornmentDrawIndicatorOnly, }; - BEGIN_DRAWING(d); - ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL); - END_DRAWING; + BEGIN_DRAWING(d) + ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, + NULL); + END_DRAWING } } @@ -2728,7 +2908,7 @@ static Ttk_ElementSpec DisclosureElementSpec = { }; /*---------------------------------------------------------------------- - * +++ Widget layouts. + * +++ Widget layouts -- */ TTK_BEGIN_LAYOUT_TABLE(LayoutTable) @@ -2738,52 +2918,52 @@ TTK_LAYOUT("Toolbar", TTK_LAYOUT("TButton", TTK_GROUP("Button.button", TTK_FILL_BOTH, - TTK_GROUP("Button.padding", TTK_FILL_BOTH, - TTK_NODE("Button.label", TTK_FILL_BOTH)))) + TTK_GROUP("Button.padding", TTK_FILL_BOTH, + TTK_NODE("Button.label", TTK_FILL_BOTH)))) TTK_LAYOUT("TRadiobutton", TTK_GROUP("Radiobutton.button", TTK_FILL_BOTH, - TTK_GROUP("Radiobutton.padding", TTK_FILL_BOTH, - TTK_NODE("Radiobutton.label", TTK_PACK_LEFT)))) + TTK_GROUP("Radiobutton.padding", TTK_FILL_BOTH, + TTK_NODE("Radiobutton.label", TTK_PACK_LEFT)))) TTK_LAYOUT("TCheckbutton", TTK_GROUP("Checkbutton.button", TTK_FILL_BOTH, - TTK_GROUP("Checkbutton.padding", TTK_FILL_BOTH, - TTK_NODE("Checkbutton.label", TTK_PACK_LEFT)))) + TTK_GROUP("Checkbutton.padding", TTK_FILL_BOTH, + TTK_NODE("Checkbutton.label", TTK_PACK_LEFT)))) TTK_LAYOUT("TMenubutton", TTK_GROUP("Menubutton.button", TTK_FILL_BOTH, - TTK_GROUP("Menubutton.padding", TTK_FILL_BOTH, - TTK_NODE("Menubutton.label", TTK_PACK_LEFT)))) + TTK_GROUP("Menubutton.padding", TTK_FILL_BOTH, + TTK_NODE("Menubutton.label", TTK_PACK_LEFT)))) TTK_LAYOUT("TCombobox", - TTK_GROUP("Combobox.button", TTK_FILL_BOTH, - TTK_GROUP("Combobox.padding", TTK_FILL_BOTH, - TTK_NODE("Combobox.textarea", TTK_FILL_BOTH)))) + TTK_GROUP("Combobox.button", TTK_FILL_BOTH, + TTK_GROUP("Combobox.padding", TTK_FILL_BOTH, + TTK_NODE("Combobox.textarea", TTK_FILL_BOTH)))) /* Notebook tabs -- no focus ring */ TTK_LAYOUT("Tab", TTK_GROUP("Notebook.tab", TTK_FILL_BOTH, - TTK_GROUP("Notebook.padding", TTK_EXPAND|TTK_FILL_BOTH, - TTK_NODE("Notebook.label", TTK_EXPAND|TTK_FILL_BOTH)))) + TTK_GROUP("Notebook.padding", TTK_EXPAND | TTK_FILL_BOTH, + TTK_NODE("Notebook.label", TTK_EXPAND | TTK_FILL_BOTH)))) /* Spinbox -- buttons 2px to the right of the field. */ - TTK_LAYOUT("TSpinbox", - TTK_GROUP("Spinbox.buttons", TTK_PACK_RIGHT, - TTK_NODE("Spinbox.uparrow", TTK_PACK_TOP|TTK_STICK_E) - TTK_NODE("Spinbox.downarrow", TTK_PACK_BOTTOM|TTK_STICK_E)) - TTK_GROUP("Spinbox.field", TTK_EXPAND|TTK_FILL_X, - TTK_NODE("Spinbox.textarea", TTK_EXPAND|TTK_FILL_X))) +TTK_LAYOUT("TSpinbox", + TTK_GROUP("Spinbox.buttons", TTK_PACK_RIGHT, + TTK_NODE("Spinbox.uparrow", TTK_PACK_TOP | TTK_STICK_E) + TTK_NODE("Spinbox.downarrow", TTK_PACK_BOTTOM | TTK_STICK_E)) + TTK_GROUP("Spinbox.field", TTK_EXPAND | TTK_FILL_X, + TTK_NODE("Spinbox.textarea", TTK_EXPAND | TTK_FILL_X))) /* Progress bars -- track only */ TTK_LAYOUT("TProgressbar", - TTK_NODE("Progressbar.track", TTK_EXPAND|TTK_FILL_BOTH)) + TTK_NODE("Progressbar.track", TTK_EXPAND | TTK_FILL_BOTH)) /* Treeview -- no border. */ TTK_LAYOUT("Treeview", TTK_GROUP("Treeview.field", TTK_FILL_BOTH, - TTK_GROUP("Treeview.padding", TTK_FILL_BOTH, - TTK_NODE("Treeview.treearea", TTK_FILL_BOTH)))) + TTK_GROUP("Treeview.padding", TTK_FILL_BOTH, + TTK_NODE("Treeview.treearea", TTK_FILL_BOTH)))) /* Tree heading -- no border, fixed height */ TTK_LAYOUT("Heading", @@ -2794,32 +2974,33 @@ TTK_LAYOUT("Heading", /* Tree items -- omit focus ring */ TTK_LAYOUT("Item", TTK_GROUP("Treeitem.padding", TTK_FILL_BOTH, - TTK_NODE("Treeitem.indicator", TTK_PACK_LEFT) - TTK_NODE("Treeitem.image", TTK_PACK_LEFT) - TTK_NODE("Treeitem.text", TTK_PACK_LEFT))) + TTK_NODE("Treeitem.indicator", TTK_PACK_LEFT) + TTK_NODE("Treeitem.image", TTK_PACK_LEFT) + TTK_NODE("Treeitem.text", TTK_PACK_LEFT))) /* Scrollbar Layout -- Buttons at the bottom (Snow Leopard and Lion only) */ TTK_LAYOUT("Vertical.TScrollbar", TTK_GROUP("Vertical.Scrollbar.trough", TTK_FILL_Y, - TTK_NODE("Vertical.Scrollbar.thumb", TTK_PACK_TOP|TTK_EXPAND|TTK_FILL_BOTH) - TTK_NODE("Vertical.Scrollbar.downarrow", TTK_PACK_BOTTOM) - TTK_NODE("Vertical.Scrollbar.uparrow", TTK_PACK_BOTTOM))) + TTK_NODE("Vertical.Scrollbar.thumb", + TTK_PACK_TOP | TTK_EXPAND | TTK_FILL_BOTH) + TTK_NODE("Vertical.Scrollbar.downarrow", TTK_PACK_BOTTOM) + TTK_NODE("Vertical.Scrollbar.uparrow", TTK_PACK_BOTTOM))) TTK_LAYOUT("Horizontal.TScrollbar", TTK_GROUP("Horizontal.Scrollbar.trough", TTK_FILL_X, - TTK_NODE("Horizontal.Scrollbar.thumb", TTK_PACK_LEFT|TTK_EXPAND|TTK_FILL_BOTH) - TTK_NODE("Horizontal.Scrollbar.rightarrow", TTK_PACK_RIGHT) - TTK_NODE("Horizontal.Scrollbar.leftarrow", TTK_PACK_RIGHT))) + TTK_NODE("Horizontal.Scrollbar.thumb", + TTK_PACK_LEFT | TTK_EXPAND | TTK_FILL_BOTH) + TTK_NODE("Horizontal.Scrollbar.rightarrow", TTK_PACK_RIGHT) + TTK_NODE("Horizontal.Scrollbar.leftarrow", TTK_PACK_RIGHT))) -TTK_END_LAYOUT_TABLE; +TTK_END_LAYOUT_TABLE /*---------------------------------------------------------------------- - * +++ Initialization. + * +++ Initialization -- */ -static int -AquaTheme_Init( +static int AquaTheme_Init( Tcl_Interp *interp) { Ttk_Theme themePtr = Ttk_CreateTheme(interp, "aqua", NULL); @@ -2832,40 +3013,41 @@ AquaTheme_Init( * Elements: */ - Ttk_RegisterElementSpec(themePtr, "background", &BackgroundElementSpec, 0); + Ttk_RegisterElementSpec(themePtr, "background", &BackgroundElementSpec, + 0); Ttk_RegisterElementSpec(themePtr, "fill", &FillElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "field", &FieldElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Toolbar.background", - &ToolbarBackgroundElementSpec, 0); + &ToolbarBackgroundElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Button.button", - &ButtonElementSpec, &PushButtonParams); + &ButtonElementSpec, &PushButtonParams); Ttk_RegisterElementSpec(themePtr, "Checkbutton.button", - &ButtonElementSpec, &CheckBoxParams); + &ButtonElementSpec, &CheckBoxParams); Ttk_RegisterElementSpec(themePtr, "Radiobutton.button", - &ButtonElementSpec, &RadioButtonParams); + &ButtonElementSpec, &RadioButtonParams); Ttk_RegisterElementSpec(themePtr, "Toolbutton.border", - &ButtonElementSpec, &BevelButtonParams); + &ButtonElementSpec, &BevelButtonParams); Ttk_RegisterElementSpec(themePtr, "Menubutton.button", - &ButtonElementSpec, &PopupButtonParams); + &ButtonElementSpec, &PopupButtonParams); Ttk_RegisterElementSpec(themePtr, "Spinbox.uparrow", - &SpinButtonUpElementSpec, 0); + &SpinButtonUpElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Spinbox.downarrow", - &SpinButtonDownElementSpec, 0); + &SpinButtonDownElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Combobox.button", - &ComboboxElementSpec, 0); + &ComboboxElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Treeitem.indicator", - &DisclosureElementSpec, &DisclosureParams); + &DisclosureElementSpec, &DisclosureParams); Ttk_RegisterElementSpec(themePtr, "Treeheading.cell", - &TreeHeaderElementSpec, &ListHeaderParams); + &TreeHeaderElementSpec, &ListHeaderParams); Ttk_RegisterElementSpec(themePtr, "Treeview.treearea", - &TreeAreaElementSpec, 0); + &TreeAreaElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Notebook.tab", &TabElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Notebook.client", &PaneElementSpec, 0); - Ttk_RegisterElementSpec(themePtr, "Labelframe.border", - &GroupElementSpec, 0); + Ttk_RegisterElementSpec(themePtr, "Labelframe.border", &GroupElementSpec, + 0); Ttk_RegisterElementSpec(themePtr, "Entry.field", &EntryElementSpec, 0); Ttk_RegisterElementSpec(themePtr, "Spinbox.field", &EntryElementSpec, 0); @@ -2877,39 +3059,41 @@ AquaTheme_Init( /* * <> - * In some themes the Layouts for a progress bar has a trough element and a + * In some themes the Layouts for a progress bar has a trough element and + *a * pbar element. But in our case the appearance manager draws both parts * of the progress bar, so we just have a single element called ".track". */ - Ttk_RegisterElementSpec(themePtr,"Progressbar.track", &PbarElementSpec, 0); + Ttk_RegisterElementSpec(themePtr, "Progressbar.track", &PbarElementSpec, + 0); - Ttk_RegisterElementSpec(themePtr,"Scale.trough", &TrackElementSpec, - &ScaleData); - Ttk_RegisterElementSpec(themePtr,"Scale.slider", &SliderElementSpec, 0); + Ttk_RegisterElementSpec(themePtr, "Scale.trough", &TrackElementSpec, + &ScaleData); + Ttk_RegisterElementSpec(themePtr, "Scale.slider", &SliderElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.trough", - &TroughElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.thumb", - &ThumbElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.trough", - &TroughElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.thumb", - &ThumbElementSpec, 0); + Ttk_RegisterElementSpec(themePtr, "Vertical.Scrollbar.trough", + &TroughElementSpec, 0); + Ttk_RegisterElementSpec(themePtr, "Vertical.Scrollbar.thumb", + &ThumbElementSpec, 0); + Ttk_RegisterElementSpec(themePtr, "Horizontal.Scrollbar.trough", + &TroughElementSpec, 0); + Ttk_RegisterElementSpec(themePtr, "Horizontal.Scrollbar.thumb", + &ThumbElementSpec, 0); /* * If we are not in Snow Leopard or Lion the arrows won't actually be * displayed. */ - Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.uparrow", - &ArrowElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.downarrow", - &ArrowElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.leftarrow", - &ArrowElementSpec, 0); - Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.rightarrow", - &ArrowElementSpec, 0); + Ttk_RegisterElementSpec(themePtr, "Vertical.Scrollbar.uparrow", + &ArrowElementSpec, 0); + Ttk_RegisterElementSpec(themePtr, "Vertical.Scrollbar.downarrow", + &ArrowElementSpec, 0); + Ttk_RegisterElementSpec(themePtr, "Horizontal.Scrollbar.leftarrow", + &ArrowElementSpec, 0); + Ttk_RegisterElementSpec(themePtr, "Horizontal.Scrollbar.rightarrow", + &ArrowElementSpec, 0); /* * Layouts: @@ -2922,11 +3106,12 @@ AquaTheme_Init( } MODULE_SCOPE -int Ttk_MacOSXPlatformInit(Tcl_Interp *interp) +int Ttk_MacOSXPlatformInit( + Tcl_Interp *interp) { return AquaTheme_Init(interp); } - + /* * Local Variables: * mode: objc -- cgit v0.12 From 23928a5f10c089cf05427e29d77b268e60ab7fc6 Mon Sep 17 00:00:00 2001 From: culler Date: Wed, 17 Apr 2019 21:06:14 +0000 Subject: Restore code ordering which avoids unused function warnings in old systems. --- macosx/ttkMacOSXTheme.c | 118 +++++++++++++++++++++++++----------------------- 1 file changed, 62 insertions(+), 56 deletions(-) diff --git a/macosx/ttkMacOSXTheme.c b/macosx/ttkMacOSXTheme.c index 1f231a9..49082b3 100644 --- a/macosx/ttkMacOSXTheme.c +++ b/macosx/ttkMacOSXTheme.c @@ -280,65 +280,11 @@ static void SolidFillRoundedRectangle( } /*---------------------------------------------------------------------- - * GradientFillRoundedRectangle -- - * - * Fill a rounded rectangle with a specified gradient. - */ - -static void GradientFillRoundedRectangle( - CGContextRef context, - CGRect bounds, - CGFloat radius, - CGFloat *colors, - int numColors) -{ - NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; - CGPathRef path; - CGPoint end = { - bounds.origin.x, - bounds.origin.y + bounds.size.height - }; - CGGradientRef gradient = CGGradientCreateWithColorComponents( - deviceRGB.CGColorSpace, colors, NULL, numColors); - - path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL); - CGContextBeginPath(context); - CGContextAddPath(context, path); - CGContextClip(context); - CGContextDrawLinearGradient(context, gradient, bounds.origin, end, 0); - CFRelease(path); - CFRelease(gradient); -} - -/*---------------------------------------------------------------------- - * +++ Arrow Buttons -- + * +++ Single Arrow Buttons -- * - * Used in MenuButtons, SpinButtons, ComboBoxes, ListHeaders. + * Used in ListHeaders and Comboboxes. */ -static void DrawUpDownArrows( - CGContextRef context, - CGRect bounds, - CGFloat inset, - CGFloat size, - CGFloat *rgba) -{ - CGFloat x, y; - - CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); - CGContextSetLineWidth(context, 1.5); - x = bounds.origin.x + inset; - y = bounds.origin.y + trunc(bounds.size.height / 2); - CGContextBeginPath(context); - CGPoint bottomArrow[3] = - {{x, y + 2}, {x + size / 2, y + 2 + size / 2}, {x + size, y + 2}}; - CGContextAddLines(context, bottomArrow, 3); - CGPoint topArrow[3] = - {{x, y - 2}, {x + size / 2, y - 2 - size / 2}, {x + size, y - 2}}; - CGContextAddLines(context, topArrow, 3); - CGContextStrokePath(context); -} - static void DrawDownArrow( CGContextRef context, CGRect bounds, @@ -520,6 +466,66 @@ static CGFloat darkSelectedGradient[8] = { }; /*---------------------------------------------------------------------- + * GradientFillRoundedRectangle -- + * + * Fill a rounded rectangle with a specified gradient. + */ + +static void GradientFillRoundedRectangle( + CGContextRef context, + CGRect bounds, + CGFloat radius, + CGFloat *colors, + int numColors) +{ + NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; + CGPathRef path; + CGPoint end = { + bounds.origin.x, + bounds.origin.y + bounds.size.height + }; + CGGradientRef gradient = CGGradientCreateWithColorComponents( + deviceRGB.CGColorSpace, colors, NULL, numColors); + + path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL); + CGContextBeginPath(context); + CGContextAddPath(context, path); + CGContextClip(context); + CGContextDrawLinearGradient(context, gradient, bounds.origin, end, 0); + CFRelease(path); + CFRelease(gradient); +} + +/*---------------------------------------------------------------------- + * +++ Double Arrow Buttons -- + * + * Used in MenuButtons and SpinButtons. + */ + +static void DrawUpDownArrows( + CGContextRef context, + CGRect bounds, + CGFloat inset, + CGFloat size, + CGFloat *rgba) +{ + CGFloat x, y; + + CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); + CGContextSetLineWidth(context, 1.5); + x = bounds.origin.x + inset; + y = bounds.origin.y + trunc(bounds.size.height / 2); + CGContextBeginPath(context); + CGPoint bottomArrow[3] = + {{x, y + 2}, {x + size / 2, y + 2 + size / 2}, {x + size, y + 2}}; + CGContextAddLines(context, bottomArrow, 3); + CGPoint topArrow[3] = + {{x, y - 2}, {x + size / 2, y - 2 - size / 2}, {x + size, y - 2}}; + CGContextAddLines(context, topArrow, 3); + CGContextStrokePath(context); +} + +/*---------------------------------------------------------------------- * +++ FillButtonBackground -- * * Fills a rounded rectangle with a transparent black gradient. -- cgit v0.12 From 2922de7aa8539798cbae60aefd0d7a9cfe35283d Mon Sep 17 00:00:00 2001 From: culler Date: Thu, 18 Apr 2019 16:13:18 +0000 Subject: Eliminate the confusing conditional code from ttkMacOSXTheme.c. --- library/ttk/aquaTheme.tcl | 2 +- macosx/tkMacOSXWm.c | 18 +- macosx/ttkMacOSXTheme.c | 586 ++++++++++++++++++++++------------------------ 3 files changed, 295 insertions(+), 311 deletions(-) diff --git a/library/ttk/aquaTheme.tcl b/library/ttk/aquaTheme.tcl index 4b0740f..ffcad2c 100644 --- a/library/ttk/aquaTheme.tcl +++ b/library/ttk/aquaTheme.tcl @@ -62,7 +62,7 @@ namespace eval ttk::theme::aqua { ttk::style configure TNotebook -tabmargins {10 0} -tabposition n ttk::style configure TNotebook -padding {18 8 18 17} ttk::style configure TNotebook.Tab -padding {12 3 12 2} - ttk::style configure TNotebook.Tab -foreground white + ttk::style configure TNotebook.Tab -foreground systemControlTextColor ttk::style map TNotebook.Tab \ -foreground { {background !disabled !selected} systemControlTextColor diff --git a/macosx/tkMacOSXWm.c b/macosx/tkMacOSXWm.c index d6456f2..07230bd 100644 --- a/macosx/tkMacOSXWm.c +++ b/macosx/tkMacOSXWm.c @@ -5927,15 +5927,15 @@ WmWinAppearance( resultString = appearanceStrings[APPEARANCE_AUTO]; } else if (appearance == NSAppearanceNameAqua) { resultString = appearanceStrings[APPEARANCE_AQUA]; -#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 - } else if (appearance == NSAppearanceNameDarkAqua) { - resultString = appearanceStrings[APPEARANCE_DARKAQUA]; -#endif + } else if (@available(macOS 10.14, *)) { + if (appearance == NSAppearanceNameDarkAqua) { + resultString = appearanceStrings[APPEARANCE_DARKAQUA]; + } } else { resultString = "unrecognized"; } #else - resultString = appearanceStrings[APPEARANCE_AQUA]; + resultString = appearanceStrings[APPEARANCE_AQUA]; #endif result = Tcl_NewStringObj(resultString, strlen(resultString)); } @@ -5952,11 +5952,13 @@ WmWinAppearance( switch ((enum appearances) index) { case APPEARANCE_AQUA: win.appearance = [NSAppearance appearanceNamed: - NSAppearanceNameAqua]; + NSAppearanceNameAqua]; break; case APPEARANCE_DARKAQUA: - win.appearance = [NSAppearance appearanceNamed: - NSAppearanceNameDarkAqua]; + if (@available(macOS 10.14, *)) { + win.appearance = [NSAppearance appearanceNamed: + NSAppearanceNameDarkAqua]; + } break; default: win.appearance = nil; diff --git a/macosx/ttkMacOSXTheme.c b/macosx/ttkMacOSXTheme.c index 49082b3..ec606ac 100644 --- a/macosx/ttkMacOSXTheme.c +++ b/macosx/ttkMacOSXTheme.c @@ -56,6 +56,64 @@ #define TTK_STATE_LAST_TAB TTK_STATE_USER2 #define TTK_TREEVIEW_STATE_SORTARROW TTK_STATE_USER1 +/* + * Colors and gradients used in Dark Mode. + */ + +static CGFloat darkButtonFace[4] = { + 112.0 / 255, 113.0 / 255, 115.0 / 255, 1.0 +}; +static CGFloat darkPressedBevelFace[4] = { + 135.0 / 255, 136.0 / 255, 138.0 / 255, 1.0 +}; +static CGFloat darkSelectedBevelFace[4] = { + 162.0 / 255, 163.0 / 255, 165.0 / 255, 1.0 +}; +static CGFloat darkDisabledButtonFace[4] = { + 86.0 / 255, 87.0 / 255, 89.0 / 255, 1.0 +}; +static CGFloat darkInactiveSelectedTab[4] = { + 159.0 / 255, 160.0 / 255, 161.0 / 255, 1.0 +}; +static CGFloat darkTabSeparator[4] = {0.0, 0.0, 0.0, 0.25}; +static CGFloat darkTrack[4] = {1.0, 1.0, 1.0, 0.25}; +static CGFloat darkFrameTop[4] = {1.0, 1.0, 1.0, 0.0625}; +static CGFloat darkFrameBottom[4] = {1.0, 1.0, 1.0, 0.125}; +static CGFloat darkFrameAccent[4] = {0.0, 0.0, 0.0, 0.0625}; +static CGFloat darkTopGradient[8] = { + 1.0, 1.0, 1.0, 0.3, + 1.0, 1.0, 1.0, 0.0 +}; +static CGFloat darkBackgroundGradient[8] = { + 0.0, 0.0, 0.0, 0.1, + 0.0, 0.0, 0.0, 0.25 +}; +static CGFloat darkInactiveGradient[8] = { + 89.0 / 255, 90.0 / 255, 93.0 / 255, 1.0, + 119.0 / 255, 120.0 / 255, 122.0 / 255, 1.0 +}; +static CGFloat darkSelectedGradient[8] = { + 23.0 / 255, 111.0 / 255, 232.0 / 255, 1.0, + 20.0 / 255, 94.0 / 255, 206.0 / 255, 1.0 +}; + +/* + * When building on systems earlier than 10.8 there is no reasonable way to + * convert an NSColor to a CGColor. We do run-time checking of the OS version, + * and never need the CGColor property on older systems, so we can use this + * CGCOLOR macro, which evaluates to NULL without raising compiler + * warnings. designed to. Similarly, we never draw rounded rectangles on older + * systems which did not have CGPathCreateWithRoundedRect, so we just redefine + * it to + */ + +#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1080 +#define CGCOLOR(nscolor) nscolor.CGColor +#else +#define CGCOLOR(nscolor) (0 ? (CGColorRef) nscolor : NULL) +#define CGPathCreateWithRoundedRect(w, x, y, z) NULL +#endif + /*---------------------------------------------------------------------- * +++ Utilities. */ @@ -132,7 +190,6 @@ static CGRect NormalizeButtonBounds( return bounds; } -#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 /*---------------------------------------------------------------------- * +++ Backgrounds * @@ -216,6 +273,148 @@ static void GetBackgroundColor( } } + +/*---------------------------------------------------------------------- + * +++ Single Arrow Buttons -- + * + * Used in ListHeaders and Comboboxes. + */ + +static void DrawDownArrow( + CGContextRef context, + CGRect bounds, + CGFloat inset, + CGFloat size, + CGFloat *rgba) +{ + CGFloat x, y; + + CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); + CGContextSetLineWidth(context, 1.5); + x = bounds.origin.x + inset; + y = bounds.origin.y + trunc(bounds.size.height / 2); + CGContextBeginPath(context); + CGPoint arrow[3] = { + {x, y - size / 4}, {x + size / 2, y + size / 4}, + {x + size, y - size / 4} + }; + CGContextAddLines(context, arrow, 3); + CGContextStrokePath(context); +} + +static void DrawUpArrow( + CGContextRef context, + CGRect bounds, + CGFloat inset, + CGFloat size, + CGFloat *rgba) +{ + CGFloat x, y; + + CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); + CGContextSetLineWidth(context, 1.5); + x = bounds.origin.x + inset; + y = bounds.origin.y + trunc(bounds.size.height / 2); + CGContextBeginPath(context); + CGPoint arrow[3] = { + {x, y + size / 4}, {x + size / 2, y - size / 4}, + {x + size, y + size / 4} + }; + CGContextAddLines(context, arrow, 3); + CGContextStrokePath(context); +} + +/*---------------------------------------------------------------------- + * +++ Double Arrow Buttons -- + * + * Used in MenuButtons and SpinButtons. + */ + +static void DrawUpDownArrows( + CGContextRef context, + CGRect bounds, + CGFloat inset, + CGFloat size, + CGFloat *rgba) +{ + CGFloat x, y; + + CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); + CGContextSetLineWidth(context, 1.5); + x = bounds.origin.x + inset; + y = bounds.origin.y + trunc(bounds.size.height / 2); + CGContextBeginPath(context); + CGPoint bottomArrow[3] = + {{x, y + 2}, {x + size / 2, y + 2 + size / 2}, {x + size, y + 2}}; + CGContextAddLines(context, bottomArrow, 3); + CGPoint topArrow[3] = + {{x, y - 2}, {x + size / 2, y - 2 - size / 2}, {x + size, y - 2}}; + CGContextAddLines(context, topArrow, 3); + CGContextStrokePath(context); +} + + +/*---------------------------------------------------------------------- + * +++ FillButtonBackground -- + * + * Fills a rounded rectangle with a transparent black gradient. + * This is a no-op if not building on 10.9 or higher. + */ + +static void FillButtonBackground( + CGContextRef context, + CGRect bounds, + CGFloat radius) +{ + CGPathRef path; + NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; + CGGradientRef backgroundGradient = CGGradientCreateWithColorComponents( + deviceRGB.CGColorSpace, darkBackgroundGradient, NULL, 2); + CGPoint backgroundEnd = { + bounds.origin.x, + bounds.origin.y + bounds.size.height + }; + + CGContextBeginPath(context); + path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL); + CGContextAddPath(context, path); + CGContextClip(context); + CGContextDrawLinearGradient(context, backgroundGradient, + bounds.origin, backgroundEnd, 0); + CFRelease(path); + CFRelease(backgroundGradient); +} + +/*---------------------------------------------------------------------- + * +++ HighlightButtonBorder -- + * + * Accent the top border of a rounded rectangle with a transparent + * white gradient. + */ + +static void HighlightButtonBorder( + CGContextRef context, + CGRect bounds) +{ + NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; + CGPoint topEnd = {bounds.origin.x, bounds.origin.y + 3}; + CGGradientRef topGradient = CGGradientCreateWithColorComponents( + deviceRGB.CGColorSpace, darkTopGradient, NULL, 2); + + CGContextSaveGState(context); + CGContextBeginPath(context); + CGContextAddArc(context, bounds.origin.x + 4, bounds.origin.y + 4, + 4, PI, 3 * PI / 2, 0); + CGContextAddArc(context, bounds.origin.x + bounds.size.width - 4, + bounds.origin.y + 4, 4, 3 * PI / 2, 0, 0); + CGContextReplacePathWithStrokedPath(context); + CGContextClip(context); + CGContextDrawLinearGradient(context, topGradient, bounds.origin, topEnd, + 0.0); + CGContextRestoreGState(context); + CFRelease(topGradient); +} + /*---------------------------------------------------------------------- * DrawGroupBox -- * @@ -238,7 +437,7 @@ static void DrawGroupBox( bgColor = [NSColor colorWithColorSpace: deviceRGB components: fill count: 4]; CGContextSetFillColorSpace(context, deviceRGB.CGColorSpace); - CGContextSetFillColorWithColor(context, bgColor.CGColor); + CGContextSetFillColorWithColor(context, CGCOLOR(bgColor)); path = CGPathCreateWithRoundedRect(bounds, 4, 4, NULL); CGContextClipToRect(context, bounds); CGContextBeginPath(context); @@ -246,7 +445,7 @@ static void DrawGroupBox( CGContextFillPath(context); borderColor = [NSColor colorWithColorSpace: deviceRGB components: border count: 4]; - CGContextSetFillColorWithColor(context, borderColor.CGColor); + CGContextSetFillColorWithColor(context, CGCOLOR(borderColor)); [borderColor getComponents: fill]; CGContextSetRGBFillColor(context, fill[0], fill[1], fill[2], fill[3]); @@ -271,7 +470,7 @@ static void SolidFillRoundedRectangle( { CGPathRef path; - CGContextSetFillColorWithColor(context, color.CGColor); + CGContextSetFillColorWithColor(context, CGCOLOR(color)); path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL); CGContextBeginPath(context); CGContextAddPath(context, path); @@ -280,56 +479,6 @@ static void SolidFillRoundedRectangle( } /*---------------------------------------------------------------------- - * +++ Single Arrow Buttons -- - * - * Used in ListHeaders and Comboboxes. - */ - -static void DrawDownArrow( - CGContextRef context, - CGRect bounds, - CGFloat inset, - CGFloat size, - CGFloat *rgba) -{ - CGFloat x, y; - - CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); - CGContextSetLineWidth(context, 1.5); - x = bounds.origin.x + inset; - y = bounds.origin.y + trunc(bounds.size.height / 2); - CGContextBeginPath(context); - CGPoint arrow[3] = { - {x, y - size / 4}, {x + size / 2, y + size / 4}, - {x + size, y - size / 4} - }; - CGContextAddLines(context, arrow, 3); - CGContextStrokePath(context); -} - -static void DrawUpArrow( - CGContextRef context, - CGRect bounds, - CGFloat inset, - CGFloat size, - CGFloat *rgba) -{ - CGFloat x, y; - - CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); - CGContextSetLineWidth(context, 1.5); - x = bounds.origin.x + inset; - y = bounds.origin.y + trunc(bounds.size.height / 2); - CGContextBeginPath(context); - CGPoint arrow[3] = { - {x, y + size / 4}, {x + size / 2, y - size / 4}, - {x + size, y + size / 4} - }; - CGContextAddLines(context, arrow, 3); - CGContextStrokePath(context); -} - -/*---------------------------------------------------------------------- * +++ DrawListHeader -- * * This is a standalone drawing procedure which draws column headers for @@ -381,19 +530,19 @@ static void DrawListHeader( CGContextSetFillColorSpace(context, deviceRGB.CGColorSpace); CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace); CGContextBeginPath(context); - CGContextSetFillColorWithColor(context, bgColor.CGColor); + CGContextSetFillColorWithColor(context, CGCOLOR(bgColor)); CGContextAddRect(context, bounds); CGContextFillPath(context); strokeColor = [NSColor colorWithColorSpace: deviceRGB components: separatorRGBA count: 4]; - CGContextSetStrokeColorWithColor(context, strokeColor.CGColor); + CGContextSetStrokeColorWithColor(context, CGCOLOR(strokeColor)); CGContextAddLines(context, separator, 2); CGContextStrokePath(context); strokeColor = [NSColor colorWithColorSpace: deviceRGB components: borderRGBA count: 4]; - CGContextSetStrokeColorWithColor(context, strokeColor.CGColor); + CGContextSetStrokeColorWithColor(context, CGCOLOR(strokeColor)); CGContextAddLines(context, top, 2); CGContextStrokePath(context); CGContextAddLines(context, bottom, 2); @@ -412,9 +561,6 @@ static void DrawListHeader( } } -#endif /* MAC_OS_X_VERSION_MIN_REQUIRED > 1080 */ - -#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 /*---------------------------------------------------------------------- * +++ Drawing procedures for widgets in Apple's "Dark Mode" (10.14 and up). * @@ -422,49 +568,12 @@ static void DrawListHeader( * so to make widgets look "native" we have to provide analogues of the * HITheme drawing functions to be used in DarkAqua. We continue to use * HITheme in Aqua, since it understands earlier versions of the OS. + * + * Drawing the dark widgets requires NSColors that were introduced in OSX + * 10.14, so we make some of these functions be no-ops when building on + * systems older than 10.14. */ -/* - * Colors and gradients used in Dark Mode. - */ - -static CGFloat darkButtonFace[4] = { - 112.0 / 255, 113.0 / 255, 115.0 / 255, 1.0 -}; -static CGFloat darkPressedBevelFace[4] = { - 135.0 / 255, 136.0 / 255, 138.0 / 255, 1.0 -}; -static CGFloat darkSelectedBevelFace[4] = { - 162.0 / 255, 163.0 / 255, 165.0 / 255, 1.0 -}; -static CGFloat darkDisabledButtonFace[4] = { - 86.0 / 255, 87.0 / 255, 89.0 / 255, 1.0 -}; -static CGFloat darkInactiveSelectedTab[4] = { - 159.0 / 255, 160.0 / 255, 161.0 / 255, 1.0 -}; -static CGFloat darkTabSeparator[4] = {0.0, 0.0, 0.0, 0.25}; -static CGFloat darkTrack[4] = {1.0, 1.0, 1.0, 0.25}; -static CGFloat darkFrameTop[4] = {1.0, 1.0, 1.0, 0.0625}; -static CGFloat darkFrameBottom[4] = {1.0, 1.0, 1.0, 0.125}; -static CGFloat darkFrameAccent[4] = {0.0, 0.0, 0.0, 0.0625}; -static CGFloat darkTopGradient[8] = { - 1.0, 1.0, 1.0, 0.3, - 1.0, 1.0, 1.0, 0.0 -}; -static CGFloat darkBackgroundGradient[8] = { - 0.0, 0.0, 0.0, 0.1, - 0.0, 0.0, 0.0, 0.25 -}; -static CGFloat darkInactiveGradient[8] = { - 89.0 / 255, 90.0 / 255, 93.0 / 255, 1.0, - 119.0 / 255, 120.0 / 255, 122.0 / 255, 1.0 -}; -static CGFloat darkSelectedGradient[8] = { - 23.0 / 255, 111.0 / 255, 232.0 / 255, 1.0, - 20.0 / 255, 94.0 / 255, 206.0 / 255, 1.0 -}; - /*---------------------------------------------------------------------- * GradientFillRoundedRectangle -- * @@ -497,95 +606,6 @@ static void GradientFillRoundedRectangle( } /*---------------------------------------------------------------------- - * +++ Double Arrow Buttons -- - * - * Used in MenuButtons and SpinButtons. - */ - -static void DrawUpDownArrows( - CGContextRef context, - CGRect bounds, - CGFloat inset, - CGFloat size, - CGFloat *rgba) -{ - CGFloat x, y; - - CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]); - CGContextSetLineWidth(context, 1.5); - x = bounds.origin.x + inset; - y = bounds.origin.y + trunc(bounds.size.height / 2); - CGContextBeginPath(context); - CGPoint bottomArrow[3] = - {{x, y + 2}, {x + size / 2, y + 2 + size / 2}, {x + size, y + 2}}; - CGContextAddLines(context, bottomArrow, 3); - CGPoint topArrow[3] = - {{x, y - 2}, {x + size / 2, y - 2 - size / 2}, {x + size, y - 2}}; - CGContextAddLines(context, topArrow, 3); - CGContextStrokePath(context); -} - -/*---------------------------------------------------------------------- - * +++ FillButtonBackground -- - * - * Fills a rounded rectangle with a transparent black gradient. - */ - -static void FillButtonBackground( - CGContextRef context, - CGRect bounds, - CGFloat radius) -{ - CGPathRef path; - NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; - CGGradientRef backgroundGradient = CGGradientCreateWithColorComponents( - deviceRGB.CGColorSpace, darkBackgroundGradient, NULL, 2); - CGPoint backgroundEnd = { - bounds.origin.x, - bounds.origin.y + bounds.size.height - }; - - CGContextBeginPath(context); - path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL); - CGContextAddPath(context, path); - CGContextClip(context); - CGContextDrawLinearGradient(context, backgroundGradient, - bounds.origin, backgroundEnd, 0); - CFRelease(path); - CFRelease(backgroundGradient); -} - -/*---------------------------------------------------------------------- - * +++ HighlightButtonBorder -- - * - * Accent the top border of a rounded rectangle with a transparent - * white gradient. - */ - -static void HighlightButtonBorder( - CGContextRef context, - CGRect bounds) -{ - NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; - CGPoint topEnd = {bounds.origin.x, bounds.origin.y + 3}; - CGGradientRef topGradient = CGGradientCreateWithColorComponents( - deviceRGB.CGColorSpace, darkTopGradient, NULL, 2); - - CGContextSaveGState(context); - CGContextBeginPath(context); - CGContextAddArc(context, bounds.origin.x + 4, bounds.origin.y + 4, - 4, PI, 3 * PI / 2, 0); - CGContextAddArc(context, bounds.origin.x + bounds.size.width - 4, - bounds.origin.y + 4, 4, 3 * PI / 2, 0, 0); - CGContextReplacePathWithStrokedPath(context); - CGContextClip(context); - CGContextDrawLinearGradient(context, topGradient, bounds.origin, topEnd, - 0.0); - CGContextRestoreGState(context); - CFRelease(topGradient); -} - -/*---------------------------------------------------------------------- * +++ DrawDarkButton -- * * This is a standalone drawing procedure which draws PushButtons and @@ -636,7 +656,7 @@ static void DrawDarkButton( * If this is a popup, draw the arrow button. */ - if (kind == kThemePopupButton | kind == kThemeComboBox) { + if ((kind == kThemePopupButton) | (kind == kThemeComboBox)) { CGRect arrowBounds = bounds; arrowBounds.size.width = 16; arrowBounds.origin.x += bounds.size.width - 16; @@ -802,7 +822,7 @@ static void DrawDarkCheckBox( } else { stroke = [NSColor controlTextColor]; } - CGContextSetStrokeColorWithColor(context, stroke.CGColor); + CGContextSetStrokeColorWithColor(context, CGCOLOR(stroke)); } if (state & TTK_STATE_SELECTED) { CGContextSetLineWidth(context, 1.5); @@ -860,7 +880,7 @@ static void DrawDarkRadioButton( } else { fill = [NSColor controlTextColor]; } - CGContextSetFillColorWithColor(context, fill.CGColor); + CGContextSetFillColorWithColor(context, CGCOLOR(fill)); } if (state & TTK_STATE_SELECTED) { CGContextBeginPath(context); @@ -936,7 +956,7 @@ static void DrawDarkTab( stroke = [NSColor colorWithColorSpace: deviceRGB components: darkTabSeparator count: 4]; - CGContextSetStrokeColorWithColor(context, stroke.CGColor); + CGContextSetStrokeColorWithColor(context, CGCOLOR(stroke)); CGContextBeginPath(context); CGContextMoveToPoint(context, originalBounds.origin.x, originalBounds.origin.y + 1); @@ -987,7 +1007,7 @@ static void DrawDarkSeparator( components: fill count:4]; - CGContextSetFillColorWithColor(context, fillColor.CGColor); + CGContextSetFillColorWithColor(context, CGCOLOR(fillColor)); CGContextFillRect(context, bounds); } @@ -1022,19 +1042,19 @@ static void DrawDarkFrame( stroke = [NSColor colorWithColorSpace: deviceRGB components: darkFrameTop count: 4]; - CGContextSetStrokeColorWithColor(context, stroke.CGColor); + CGContextSetStrokeColorWithColor(context, CGCOLOR(stroke)); CGContextAddLines(context, topPart, 4); CGContextStrokePath(context); stroke = [NSColor colorWithColorSpace: deviceRGB components: darkFrameBottom count: 4]; - CGContextSetStrokeColorWithColor(context, stroke.CGColor); + CGContextSetStrokeColorWithColor(context, CGCOLOR(stroke)); CGContextAddLines(context, bottom, 2); CGContextStrokePath(context); stroke = [NSColor colorWithColorSpace: deviceRGB components: darkFrameAccent count: 4]; - CGContextSetStrokeColorWithColor(context, stroke.CGColor); + CGContextSetStrokeColorWithColor(context, CGCOLOR(stroke)); CGContextAddLines(context, accent, 2); CGContextStrokePath(context); CGContextRestoreGState(context); @@ -1072,7 +1092,7 @@ static void DrawDarkListHeader( stroke = [NSColor colorWithColorSpace: deviceRGB components: darkFrameBottom count: 4]; - CGContextSetStrokeColorWithColor(context, stroke.CGColor); + CGContextSetStrokeColorWithColor(context, CGCOLOR(stroke)); CGContextBeginPath(context); CGContextAddLines(context, top, 2); CGContextStrokePath(context); @@ -1095,8 +1115,6 @@ static void DrawDarkListHeader( } } -#endif /* MAC_OS_X_VERSION_MIN_REQUIRED >101300 */ - /*---------------------------------------------------------------------- * +++ Button element: Used for elements drawn with DrawThemeButton. */ @@ -1278,7 +1296,6 @@ static void ButtonElementDraw( BEGIN_DRAWING(d) if (TkMacOSXInDarkMode(tkwin)) { -#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 switch (info.kind) { case kThemePushButton: case kThemePopupButton: @@ -1297,7 +1314,6 @@ static void ButtonElementDraw( ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL); } -#endif /* if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 */ } else { /* @@ -1312,14 +1328,12 @@ static void ButtonElementDraw( * active state. */ -#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 if (info.kind == kThemePopupButton && (state & TTK_STATE_BACKGROUND)) { CGRect innerBounds = CGRectInset(bounds, 1, 1); NSColor *whiteRGBA = [NSColor whiteColor]; SolidFillRoundedRectangle(dc.context, innerBounds, 4, whiteRGBA); } -#endif /* * A BevelButton with mixed value is drawn borderless, which does make @@ -1445,16 +1459,12 @@ static void TabElementDraw( }; BEGIN_DRAWING(d) -#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { DrawDarkTab(bounds, state, dc.context); } else { ChkErr(HIThemeDrawTab, &bounds, &info, dc.context, HIOrientation, NULL); } -#else - ChkErr(HIThemeDrawTab, &bounds, &info, dc.context, HIOrientation, NULL); -#endif END_DRAWING } @@ -1494,21 +1504,21 @@ static void PaneElementDraw( bounds.origin.y -= kThemeMetricTabFrameOverlap; bounds.size.height += kThemeMetricTabFrameOverlap; BEGIN_DRAWING(d) -#if MAC_OS_X_VERSION_MIN_REQUIRED > 10800 - DrawGroupBox(bounds, dc.context, tkwin); -#else - HIThemeTabPaneDrawInfo info = { - .version = 1, - .state = Ttk_StateTableLookup(ThemeStateTable, state), - .direction = kThemeTabNorth, - .size = kHIThemeTabSizeNormal, - .kind = kHIThemeTabKindNormal, - .adornment = kHIThemeTabPaneAdornmentNormal, - }; - bounds.origin.y -= kThemeMetricTabFrameOverlap; - bounds.size.height += kThemeMetricTabFrameOverlap; - ChkErr(HIThemeDrawTabPane, &bounds, &info, dc.context, HIOrientation); -#endif /* if MAC_OS_X_VERSION_MIN_REQUIRED > 10800 */ + if ([NSApp macMinorVersion] > 8) { + DrawGroupBox(bounds, dc.context, tkwin); + } else { + HIThemeTabPaneDrawInfo info = { + .version = 1, + .state = Ttk_StateTableLookup(ThemeStateTable, state), + .direction = kThemeTabNorth, + .size = kHIThemeTabSizeNormal, + .kind = kHIThemeTabKindNormal, + .adornment = kHIThemeTabPaneAdornmentNormal, + }; + bounds.origin.y -= kThemeMetricTabFrameOverlap; + bounds.size.height += kThemeMetricTabFrameOverlap; + ChkErr(HIThemeDrawTabPane, &bounds, &info, dc.context, HIOrientation); + } END_DRAWING } @@ -1553,16 +1563,16 @@ static void GroupElementDraw( CGRect bounds = BoxToRect(d, b); BEGIN_DRAWING(d) -#if MAC_OS_X_VERSION_MIN_REQUIRED > 10800 - DrawGroupBox(bounds, dc.context, tkwin); -#else - const HIThemeGroupBoxDrawInfo info = { - .version = 0, - .state = Ttk_StateTableLookup(ThemeStateTable, state), - .kind = kHIThemeGroupBoxKindPrimaryOpaque, - }; - ChkErr(HIThemeDrawGroupBox, &bounds, &info, dc.context, HIOrientation); -#endif + if ([NSApp macMinorVersion] > 8) { + DrawGroupBox(bounds, dc.context, tkwin); + } else { + const HIThemeGroupBoxDrawInfo info = { + .version = 0, + .state = Ttk_StateTableLookup(ThemeStateTable, state), + .kind = kHIThemeGroupBoxKindPrimaryOpaque, + }; + ChkErr(HIThemeDrawGroupBox, &bounds, &info, dc.context, HIOrientation); + } END_DRAWING } @@ -1623,7 +1633,6 @@ static void EntryElementDraw( static const char *defaultBG = ENTRY_DEFAULT_BACKGROUND; if (TkMacOSXInDarkMode(tkwin)) { -#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 BEGIN_DRAWING(d) NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; CGFloat fill[4]; @@ -1631,11 +1640,10 @@ static void EntryElementDraw( background = [NSColor colorWithColorSpace: deviceRGB components: fill count: 4]; - CGContextSetFillColorWithColor(dc.context, background.CGColor); + CGContextSetFillColorWithColor(dc.context, CGCOLOR(background)); CGContextFillRect(dc.context, bounds); DrawDarkFrame(bounds, dc.context, kHIThemeFrameTextFieldSquare); END_DRAWING -#endif /* if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 */ } else { const HIThemeFrameDrawInfo info = { .version = 0, @@ -1666,12 +1674,12 @@ static void EntryElementDraw( } BEGIN_DRAWING(d) if (backgroundPtr == NULL) { - background = [NSColor textBackgroundColor]; -#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 - CGContextSetFillColorWithColor(dc.context, background.CGColor); -#else - CGContextSetRGBFillColor(dc.context, 1.0, 1.0, 1.0, 1.0); -#endif + if ([NSApp macMinorVersion] > 8) { + background = [NSColor textBackgroundColor]; + CGContextSetFillColorWithColor(dc.context, CGCOLOR(background)); + } else { + CGContextSetRGBFillColor(dc.context, 1.0, 1.0, 1.0, 1.0); + } CGContextFillRect(dc.context, bounds); } ChkErr(HIThemeDrawFrame, &bounds, &info, dc.context, HIOrientation); @@ -1742,21 +1750,17 @@ static void ComboboxElementDraw( BEGIN_DRAWING(d) bounds.origin.y += 1; if (TkMacOSXInDarkMode(tkwin)) { -#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 - bounds.size.height += 1; + bounds.size.height += 1; DrawDarkButton(bounds, info.kind, state, dc.context); -#endif - } else{ -#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 - if ((state & TTK_STATE_BACKGROUND) && - !(state & TTK_STATE_DISABLED)) { + } else if ([NSApp macMinorVersion] > 8) { + if ((state & TTK_STATE_BACKGROUND) && + !(state & TTK_STATE_DISABLED)) { NSColor *background = [NSColor textBackgroundColor]; CGRect innerBounds = CGRectInset(bounds, 1, 2); SolidFillRoundedRectangle(dc.context, innerBounds, 4, background); } -#endif - ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, - NULL); + ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, + NULL); } END_DRAWING } @@ -1833,14 +1837,11 @@ static void SpinButtonUpElementDraw( .adornment = kThemeAdornmentNone, }; BEGIN_DRAWING(d) -#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { DrawDarkIncDecButton(bounds, infoState, state, dc.context); - } else -#endif - { + } else { ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, - NULL); + NULL); } END_DRAWING } @@ -1895,14 +1896,11 @@ static void SpinButtonDownElementDraw( }; BEGIN_DRAWING(d) -#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { DrawDarkIncDecButton(bounds, infoState, state, dc.context); - } else -#endif - { + } else { ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, - NULL); + NULL); } END_DRAWING } @@ -2014,7 +2012,6 @@ static void TrackElementDraw( } } BEGIN_DRAWING(d) -#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { CGRect bounds = BoxToRect(d, b); NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; @@ -2028,7 +2025,6 @@ static void TrackElementDraw( } SolidFillRoundedRectangle(dc.context, bounds, 2, trackColor); } -#endif /* if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 */ ChkErr(HIThemeDrawTrack, &info, NULL, dc.context, HIOrientation); END_DRAWING } @@ -2148,7 +2144,6 @@ static void PbarElementDraw( }; BEGIN_DRAWING(d) -#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { CGRect bounds = BoxToRect(d, b); NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; @@ -2162,7 +2157,6 @@ static void PbarElementDraw( } SolidFillRoundedRectangle(dc.context, bounds, 3, trackColor); } -#endif /* if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 */ ChkErr(HIThemeDrawTrack, &info, NULL, dc.context, HIOrientation); END_DRAWING } @@ -2256,9 +2250,7 @@ static void TroughElementDraw( count: 4]; BEGIN_DRAWING(d) if ([NSApp macMinorVersion] > 8) { -#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 - CGContextSetFillColorWithColor(dc.context, troughColor.CGColor); -#endif + CGContextSetFillColorWithColor(dc.context, CGCOLOR(troughColor)); } else { ChkErr(HIThemeSetFill, kThemeBrushDocumentWindowBackground, NULL, dc.context, HIOrientation); @@ -2323,7 +2315,6 @@ static void ThumbElementDraw( */ if ([NSApp macMinorVersion] > 8) { -#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 CGRect thumbBounds = BoxToRect(d, b); NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; NSColor *thumbColor; @@ -2347,7 +2338,6 @@ static void ThumbElementDraw( BEGIN_DRAWING(d) SolidFillRoundedRectangle(dc.context, thumbBounds, 4, thumbColor); END_DRAWING -#endif /* if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 */ } else { double thumbSize, trackSize, visibleSize, viewSize; MacDrawable *macWin = (MacDrawable *) Tk_WindowId(tkwin); @@ -2469,16 +2459,12 @@ static void SeparatorElementDraw( }; BEGIN_DRAWING(d) -#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 if (TkMacOSXInDarkMode(tkwin)) { DrawDarkSeparator(bounds, dc.context, tkwin); } else { ChkErr(HIThemeDrawSeparator, &bounds, &info, dc.context, HIOrientation); } -#else - ChkErr(HIThemeDrawSeparator, &bounds, &info, dc.context, HIOrientation); -#endif END_DRAWING } @@ -2606,28 +2592,28 @@ static void FillElementDraw( { CGRect bounds = BoxToRect(d, b); -#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 - NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; - NSColor *bgColor; - CGFloat fill[4]; - BEGIN_DRAWING(d) - GetBackgroundColor(dc.context, tkwin, 0, fill); - bgColor = [NSColor colorWithColorSpace: deviceRGB components: fill - count: 4]; - CGContextSetFillColorSpace(dc.context, deviceRGB.CGColorSpace); - CGContextSetFillColorWithColor(dc.context, bgColor.CGColor); - CGContextFillRect(dc.context, bounds); - END_DRAWING -#else /* if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 */ - ThemeBrush brush = (state & TTK_STATE_BACKGROUND) - ? kThemeBrushModelessDialogBackgroundInactive - : kThemeBrushModelessDialogBackgroundActive; - BEGIN_DRAWING(d) - ChkErr(HIThemeSetFill, brush, NULL, dc.context, HIOrientation); - //QDSetPatternOrigin(PatternOrigin(tkwin, d)); - CGContextFillRect(dc.context, bounds); - END_DRAWING -#endif /* if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 */ + if ([NSApp macMinorVersion] > 8) { + NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace]; + NSColor *bgColor; + CGFloat fill[4]; + BEGIN_DRAWING(d) + GetBackgroundColor(dc.context, tkwin, 0, fill); + bgColor = [NSColor colorWithColorSpace: deviceRGB components: fill + count: 4]; + CGContextSetFillColorSpace(dc.context, deviceRGB.CGColorSpace); + CGContextSetFillColorWithColor(dc.context, CGCOLOR(bgColor)); + CGContextFillRect(dc.context, bounds); + END_DRAWING + } else { + ThemeBrush brush = (state & TTK_STATE_BACKGROUND) + ? kThemeBrushModelessDialogBackgroundInactive + : kThemeBrushModelessDialogBackgroundActive; + BEGIN_DRAWING(d) + ChkErr(HIThemeSetFill, brush, NULL, dc.context, HIOrientation); + //QDSetPatternOrigin(PatternOrigin(tkwin, d)); + CGContextFillRect(dc.context, bounds); + END_DRAWING + } } static void BackgroundElementDraw( @@ -2821,7 +2807,6 @@ static void TreeHeaderElementDraw( BEGIN_DRAWING(d) if ([NSApp macMinorVersion] > 8) { -#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080 /* * Compensate for the padding added in TreeHeaderElementSize, so @@ -2830,13 +2815,10 @@ static void TreeHeaderElementDraw( bounds.origin.y -= 4; if (TkMacOSXInDarkMode(tkwin)) { -#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300 DrawDarkListHeader(bounds, dc.context, tkwin, state); -#endif } else { DrawListHeader(bounds, dc.context, tkwin, state); } -#endif /* MAC_OS_X_VERSION_MIN_REQUIRED > 1080 */ } else { ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL); -- cgit v0.12 From 499f1f0cf306ed7d7956828bd464ac0e802a2040 Mon Sep 17 00:00:00 2001 From: dkf Date: Fri, 19 Apr 2019 00:13:27 +0000 Subject: Some things must be conditionally compiled. Really. --- macosx/tkMacOSXWm.c | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/macosx/tkMacOSXWm.c b/macosx/tkMacOSXWm.c index 94e9302..ecbd556 100644 --- a/macosx/tkMacOSXWm.c +++ b/macosx/tkMacOSXWm.c @@ -5919,26 +5919,21 @@ WmWinAppearance( NSAppearanceName appearance; #else NSString *appearance; -#endif - const char *resultString; +#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= 101300 + const char *resultString = "unrecognized"; NSWindow *win = TkMacOSXDrawableWindow(winPtr->window); if (win) { -#if MAC_OS_X_VERSION_MAX_ALLOWED > 1090 appearance = win.appearance.name; if (appearance == nil) { resultString = appearanceStrings[APPEARANCE_AUTO]; } else if (appearance == NSAppearanceNameAqua) { resultString = appearanceStrings[APPEARANCE_AQUA]; - } else if (@available(macOS 10.14, *)) { - if (appearance == NSAppearanceNameDarkAqua) { - resultString = appearanceStrings[APPEARANCE_DARKAQUA]; - } - } else { - resultString = "unrecognized"; +#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 + } else if (@available(macOS 10.14, *) && + appearance == NSAppearanceNameDarkAqua) { + resultString = appearanceStrings[APPEARANCE_DARKAQUA]; +#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 } -#else - resultString = appearanceStrings[APPEARANCE_AQUA]; -#endif result = Tcl_NewStringObj(resultString, strlen(resultString)); } if (result == NULL) { @@ -5965,11 +5960,11 @@ WmWinAppearance( default: win.appearance = nil; } -#endif +#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 } Tcl_SetObjResult(interp, result); return TCL_OK; -#endif +#endif // MAC_OS_X_VERSION_MAX_ALLOWED > 1090 return TCL_ERROR; } -- cgit v0.12 From 460822733ea7bd7f99696e4a0f90e02467e707a1 Mon Sep 17 00:00:00 2001 From: dkf Date: Fri, 19 Apr 2019 07:16:38 +0000 Subject: Some things must be conditionally compiled. Really. --- macosx/tkMacOSXWm.c | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/macosx/tkMacOSXWm.c b/macosx/tkMacOSXWm.c index 07230bd..18bbf21 100644 --- a/macosx/tkMacOSXWm.c +++ b/macosx/tkMacOSXWm.c @@ -5917,26 +5917,21 @@ WmWinAppearance( NSAppearanceName appearance; #else NSString *appearance; -#endif - const char *resultString; +#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= 101300 + const char *resultString = "unrecognized"; NSWindow *win = TkMacOSXDrawableWindow(winPtr->window); if (win) { -#if MAC_OS_X_VERSION_MAX_ALLOWED > 1090 appearance = win.appearance.name; if (appearance == nil) { resultString = appearanceStrings[APPEARANCE_AUTO]; } else if (appearance == NSAppearanceNameAqua) { resultString = appearanceStrings[APPEARANCE_AQUA]; - } else if (@available(macOS 10.14, *)) { - if (appearance == NSAppearanceNameDarkAqua) { - resultString = appearanceStrings[APPEARANCE_DARKAQUA]; - } - } else { - resultString = "unrecognized"; +#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 + } else if (@available(macOS 10.14, *) && + appearance == NSAppearanceNameDarkAqua) { + resultString = appearanceStrings[APPEARANCE_DARKAQUA]; +#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 } -#else - resultString = appearanceStrings[APPEARANCE_AQUA]; -#endif result = Tcl_NewStringObj(resultString, strlen(resultString)); } if (result == NULL) { @@ -5963,11 +5958,11 @@ WmWinAppearance( default: win.appearance = nil; } -#endif +#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 } Tcl_SetObjResult(interp, result); return TCL_OK; -#endif +#endif // MAC_OS_X_VERSION_MAX_ALLOWED > 1090 return TCL_ERROR; } -- cgit v0.12 From a4dc7397e54ece7f5b18a85917c0d30b6bf372f0 Mon Sep 17 00:00:00 2001 From: culler Date: Fri, 19 Apr 2019 14:40:07 +0000 Subject: Fine tune aqua ttk colors. Fix availability errors introduced in 6cafd6f7. --- library/ttk/aquaTheme.tcl | 34 +++++++--------------------- macosx/tkMacOSXColor.c | 57 ++++++++++++++++++++++++++++++----------------- macosx/tkMacOSXWm.c | 16 +++++++------ 3 files changed, 54 insertions(+), 53 deletions(-) diff --git a/library/ttk/aquaTheme.tcl b/library/ttk/aquaTheme.tcl index ffcad2c..92689d8 100644 --- a/library/ttk/aquaTheme.tcl +++ b/library/ttk/aquaTheme.tcl @@ -15,43 +15,26 @@ namespace eval ttk::theme::aqua { -insertwidth 1 ttk::style map . \ - -foreground { - disabled systemLabelColor + -foreground { + disabled systemDisabledControlTextColor background systemLabelColor} \ -selectbackground { - background systemHighlight - !focus systemHighlightSecondary} \ + background systemSelectedTextBackgroundColor + !focus systemSelectedTextBackgroundColor} \ -selectforeground { - background systemLabelColor - !focus systemDialogActiveText} + background systemSelectedTextColor + !focus systemSelectedTextColor} # Button ttk::style configure TButton -anchor center -width -6\ -foreground systemControlTextColor - ttk::style map TButton \ - -foreground { - disabled systemDisabledControlTextColor} - ttk::style map TCheckbutton \ - -foreground { - disabled systemDisabledControlTextColor} - ttk::style map TRadiobutton \ - -foreground { - disabled systemDisabledControlTextColor} ttk::style configure TMenubutton -anchor center -padding {2 0 0 2} ttk::style configure Toolbutton -anchor center - ttk::style map Toolbutton \ - -foreground { - disabled systemDisabledControlTextColor - } # Entry ttk::style configure TEntry \ -foreground systemTextColor \ -background systemTextBackgroundColor \ - -selectforeground systemSelectedTextColor - ttk::style map TEntry \ - -foreground { - disabled systemDisabledControlTextColor} # Workaround for #1100117: # Actually, on Aqua we probably shouldn't stipple images in @@ -65,10 +48,9 @@ namespace eval ttk::theme::aqua { ttk::style configure TNotebook.Tab -foreground systemControlTextColor ttk::style map TNotebook.Tab \ -foreground { - {background !disabled !selected} systemControlTextColor - {background selected} systemTextBackgroundColor + background systemControlTextColor disabled systemDisabledControlTextColor - !selected systemControlTextColor} + selected systemSelectedTabTextColor} # Combobox: ttk::style configure TCombobox \ diff --git a/macosx/tkMacOSXColor.c b/macosx/tkMacOSXColor.c index e89d42d..8372ccc 100644 --- a/macosx/tkMacOSXColor.c +++ b/macosx/tkMacOSXColor.c @@ -207,13 +207,14 @@ static const struct SystemColorMapEntry systemColorMap[] = { { "LabelColor", semantic, 2 }, /* 176 */ { "ControlTextColor", semantic, 3 }, /* 177 */ { "DisabledControlTextColor", semantic, 4 }, /* 178 */ - { "TextBackgroundColor", semantic, 5 }, /* 179 */ - { "SelectedTextBackgroundColor", semantic, 6 }, /* 180 */ - { "ControlAccentColor", semantic, 7 }, /* 181 */ + { "SelectedTabTextColor", semantic, 5 }, /* 179 */ + { "TextBackgroundColor", semantic, 6 }, /* 180 */ + { "SelectedTextBackgroundColor", semantic, 7 }, /* 181 */ + { "ControlAccentColor", semantic, 8 }, /* 182 */ { NULL, 0, 0 } }; #define FIRST_SEMANTIC_COLOR 166 -#define MAX_PIXELCODE 181 +#define MAX_PIXELCODE 182 /* *---------------------------------------------------------------------- @@ -349,31 +350,47 @@ SetCGColorComponents( deviceRGB]; break; case 5: + if ([NSApp macMinorVersion] > 6) { + color = [[NSColor whiteColor] colorUsingColorSpace: + deviceRGB]; + } else { + color = [[NSColor blackColor] colorUsingColorSpace: + deviceRGB]; + } + break; + case 6: color = [[NSColor textBackgroundColor] colorUsingColorSpace: deviceRGB]; break; - case 6: + case 7: color = [[NSColor selectedTextBackgroundColor] colorUsingColorSpace: deviceRGB]; break; - case 7: -#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 + case 8: if ([NSApp macMinorVersion] >= 14) { - color = [[NSColor controlAccentColor] colorUsingColorSpace: - deviceRGB]; - break; - } +#if MAC_OS_X_VERSION_MAX_ALLOWED > 1090 + if (@available(macOS 10.14, *)) { + color = [[NSColor controlAccentColor] colorUsingColorSpace: + deviceRGB]; + break; + } else { + color = [NSColor colorWithColorSpace: deviceRGB + components: blueAccentRGBA + count: 4]; + } #endif - colorVariant = [[NSUserDefaults standardUserDefaults] - integerForKey:@"AppleAquaColorVariant"]; - if (colorVariant == 6) { - color = [NSColor colorWithColorSpace: deviceRGB - components: graphiteAccentRGBA - count: 4]; } else { - color = [NSColor colorWithColorSpace: deviceRGB - components: blueAccentRGBA - count: 4]; + colorVariant = [[NSUserDefaults standardUserDefaults] + integerForKey:@"AppleAquaColorVariant"]; + if (colorVariant == 6) { + color = [NSColor colorWithColorSpace: deviceRGB + components: graphiteAccentRGBA + count: 4]; + } else { + color = [NSColor colorWithColorSpace: deviceRGB + components: blueAccentRGBA + count: 4]; + } } break; default: diff --git a/macosx/tkMacOSXWm.c b/macosx/tkMacOSXWm.c index 18bbf21..8c30fe7 100644 --- a/macosx/tkMacOSXWm.c +++ b/macosx/tkMacOSXWm.c @@ -5927,11 +5927,12 @@ WmWinAppearance( } else if (appearance == NSAppearanceNameAqua) { resultString = appearanceStrings[APPEARANCE_AQUA]; #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 - } else if (@available(macOS 10.14, *) && - appearance == NSAppearanceNameDarkAqua) { - resultString = appearanceStrings[APPEARANCE_DARKAQUA]; -#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 + } else if (@available(macOS 10.14, *)) { + if (appearance == NSAppearanceNameDarkAqua) { + resultString = appearanceStrings[APPEARANCE_DARKAQUA]; + } } +#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 result = Tcl_NewStringObj(resultString, strlen(resultString)); } if (result == NULL) { @@ -5943,27 +5944,28 @@ WmWinAppearance( sizeof(char *), "appearancename", 0, &index) != TCL_OK) { return TCL_ERROR; } -#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 switch ((enum appearances) index) { case APPEARANCE_AQUA: win.appearance = [NSAppearance appearanceNamed: NSAppearanceNameAqua]; break; case APPEARANCE_DARKAQUA: +#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 if (@available(macOS 10.14, *)) { win.appearance = [NSAppearance appearanceNamed: NSAppearanceNameDarkAqua]; } +#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 break; default: win.appearance = nil; } -#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 } Tcl_SetObjResult(interp, result); return TCL_OK; -#endif // MAC_OS_X_VERSION_MAX_ALLOWED > 1090 +#else // MAC_OS_X_VERSION_MAX_ALLOWED > 1090 return TCL_ERROR; +#endif } /* -- cgit v0.12 From 2700604e2ded309b8fa397c011e6df5ac33b9682 Mon Sep 17 00:00:00 2001 From: culler Date: Fri, 19 Apr 2019 19:03:00 +0000 Subject: Put the brace outside the #endif where it belongs. --- macosx/tkMacOSXWm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/macosx/tkMacOSXWm.c b/macosx/tkMacOSXWm.c index 8c30fe7..e68f1d5 100644 --- a/macosx/tkMacOSXWm.c +++ b/macosx/tkMacOSXWm.c @@ -5931,8 +5931,8 @@ WmWinAppearance( if (appearance == NSAppearanceNameDarkAqua) { resultString = appearanceStrings[APPEARANCE_DARKAQUA]; } - } #endif // MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 + } result = Tcl_NewStringObj(resultString, strlen(resultString)); } if (result == NULL) { -- cgit v0.12 From ce9b2bd67a12a2007fa58b7de76f4c36a6296b2c Mon Sep 17 00:00:00 2001 From: fvogel Date: Fri, 19 Apr 2019 21:01:36 +0000 Subject: Fix [6286fda787]: unix: checkbutton -selectcolor not restored properly when changed in -command. Patch by ralfixx --- library/button.tcl | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/library/button.tcl b/library/button.tcl index 80d8bf9..88e26e5 100644 --- a/library/button.tcl +++ b/library/button.tcl @@ -748,11 +748,15 @@ proc ::tk::CheckLeave {w} { $w configure -state normal } - # Restore the original button "selected" color; assume that the user - # wasn't monkeying around with things too much. + # Restore the original button "selected" color; but only if the user + # has not changed it in the meantime. if {![$w cget -indicatoron] && [info exist Priv($w,selectcolor)]} { - $w configure -selectcolor $Priv($w,selectcolor) + if {[$w cget -selectcolor] eq $Priv($w,selectcolor) + || ([info exist Priv($w,aselectcolor)] && + [$w cget -selectcolor] eq $Priv($w,aselectcolor))} { + $w configure -selectcolor $Priv($w,selectcolor) + } } unset -nocomplain Priv($w,selectcolor) Priv($w,aselectcolor) -- cgit v0.12 From 8c0226fa4dd91e69502960bebbee4a44bba73fca Mon Sep 17 00:00:00 2001 From: culler Date: Sat, 20 Apr 2019 03:40:21 +0000 Subject: On macOS, squelch more availability warnings. Fix a hard to find bug [40ada90762] which could sometimes cause a segfault. --- macosx/tkMacOSXButton.c | 5 +++- macosx/tkMacOSXColor.c | 64 +++++++++++++++++++++++++------------------------ tests/frame.test | 7 +++++- 3 files changed, 43 insertions(+), 33 deletions(-) diff --git a/macosx/tkMacOSXButton.c b/macosx/tkMacOSXButton.c index ac3c122..1b40e5e 100644 --- a/macosx/tkMacOSXButton.c +++ b/macosx/tkMacOSXButton.c @@ -185,7 +185,10 @@ TkpDisplayButton( Pixmap pixmap; DrawParams* dpPtr = &macButtonPtr->drawParams; int needhighlight = 0; - + + if (butPtr->flags & BUTTON_DELETED) { + return; + } butPtr->flags &= ~REDRAW_PENDING; if ((butPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) { return; diff --git a/macosx/tkMacOSXColor.c b/macosx/tkMacOSXColor.c index 8372ccc..cb3bde3 100644 --- a/macosx/tkMacOSXColor.c +++ b/macosx/tkMacOSXColor.c @@ -265,9 +265,9 @@ GetEntryFromPixelCode( */ static NSColorSpace* deviceRGB = NULL; -static CGFloat blueAccentRGBA[4] = {0, 122.0/255, 1.0, 1.0}; -static CGFloat graphiteAccentRGBA[4] = {152.0/255, 152.0/255, 152.0/255, 1.0}; -static CGFloat windowBackground[4] = {236.0/255, 236.0/255, 236.0/255, 1.0}; +static CGFloat blueAccentRGBA[4] = {0, 122.0 / 255, 1.0, 1.0}; +static CGFloat windowBackground[4] = + {236.0 / 255, 236.0 / 255, 236.0 / 255, 1.0}; static OSStatus SetCGColorComponents( @@ -278,7 +278,11 @@ SetCGColorComponents( OSStatus err = noErr; NSColor *bgColor, *color; CGFloat rgba[4] = {0, 0, 0, 1}; - NSInteger colorVariant = 1; +#if MAC_OS_X_VERSION_MAX_ALLOWED < 101400 + NSInteger colorVariant; + static CGFloat graphiteAccentRGBA[4] = + {152.0 / 255, 152.0 / 255, 152.0 / 255, 1.0}; +#endif if (!deviceRGB) { deviceRGB = [NSColorSpace deviceRGBColorSpace]; @@ -318,11 +322,11 @@ SetCGColorComponents( } if (rgba[0] + rgba[1] + rgba[2] < 1.5) { for (int i=0; i<3; i++) { - rgba[i] += entry.value*8.0/255.0; + rgba[i] += entry.value*8.0 / 255.0; } } else { for (int i=0; i<3; i++) { - rgba[i] -= entry.value*8.0/255.0; + rgba[i] -= entry.value*8.0 / 255.0; } } break; @@ -335,7 +339,7 @@ SetCGColorComponents( color = [[NSColor selectedTextColor] colorUsingColorSpace: deviceRGB]; break; case 2: -#if MAC_OS_X_VERSION_MIN_REQUIRED > 101000 +#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101000 color = [[NSColor labelColor] colorUsingColorSpace: deviceRGB]; #else color = [[NSColor textColor] colorUsingColorSpace: deviceRGB]; @@ -367,31 +371,28 @@ SetCGColorComponents( deviceRGB]; break; case 8: - if ([NSApp macMinorVersion] >= 14) { -#if MAC_OS_X_VERSION_MAX_ALLOWED > 1090 - if (@available(macOS 10.14, *)) { - color = [[NSColor controlAccentColor] colorUsingColorSpace: - deviceRGB]; - break; - } else { - color = [NSColor colorWithColorSpace: deviceRGB - components: blueAccentRGBA - count: 4]; - } -#endif +#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 + if (@available(macOS 10.14, *)) { + color = [[NSColor controlAccentColor] colorUsingColorSpace: + deviceRGB]; } else { - colorVariant = [[NSUserDefaults standardUserDefaults] - integerForKey:@"AppleAquaColorVariant"]; - if (colorVariant == 6) { - color = [NSColor colorWithColorSpace: deviceRGB - components: graphiteAccentRGBA - count: 4]; - } else { - color = [NSColor colorWithColorSpace: deviceRGB - components: blueAccentRGBA - count: 4]; - } + color = [NSColor colorWithColorSpace: deviceRGB + components: blueAccentRGBA + count: 4]; } +#else + colorVariant = [[NSUserDefaults standardUserDefaults] + integerForKey:@"AppleAquaColorVariant"]; + if (colorVariant == 6) { + color = [NSColor colorWithColorSpace: deviceRGB + components: graphiteAccentRGBA + count: 4]; + } else { + color = [NSColor colorWithColorSpace: deviceRGB + components: blueAccentRGBA + count: 4]; + } +#endif break; default: #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101000 @@ -674,7 +675,7 @@ TkMacOSXSetColorInContext( struct SystemColorMapEntry entry; CGRect rect; int code = (pixel >> 24) & 0xff; - HIThemeBackgroundDrawInfo info = { 0, kThemeStateActive, entry.value }; + HIThemeBackgroundDrawInfo info = {0, kThemeStateActive, 0};; static CGColorSpaceRef deviceRGBSpace = NULL; if (!deviceRGBSpace) { @@ -698,6 +699,7 @@ TkMacOSXSetColorInContext( kHIThemeOrientationNormal); break; case HIBackground: + info.kind = entry.value; rect = CGContextGetClipBoundingBox(context); err = ChkErr(HIThemeApplyBackground, &rect, &info, context, kHIThemeOrientationNormal); diff --git a/tests/frame.test b/tests/frame.test index 45a91b3..e374326 100644 --- a/tests/frame.test +++ b/tests/frame.test @@ -664,11 +664,16 @@ test frame-3.9 {TkCreateFrame procedure, -use option} -constraints { wm geometry .t +0+0 toplevel .x -width 140 -height 300 -use [winfo id .t] -bg green tkwait visibility .x - update idletasks list [expr {[winfo rootx .x] - [winfo rootx .t]}] \ [expr {[winfo rooty .x] - [winfo rooty .t]}] \ [winfo width .t] [winfo height .t] } -cleanup { +# This call to update idletasks was added to prevent a crash that was +# observed on OSX 10.12 (Sierra) only. Any change, such as using the +# Development version to make debugging symbols available, adding a print +# statement, or calling update idletasks here, would make the test pass +# with no segfault. + update idletasks deleteWindows } -result {0 0 140 300} test frame-3.10 {TkCreateFrame procedure, -use option} -constraints { -- cgit v0.12 From e2d80191d706d8c9efed09c06b55ba96f48fdc7f Mon Sep 17 00:00:00 2001 From: culler Date: Sat, 20 Apr 2019 15:03:00 +0000 Subject: On macOS, edit comments and documentation; fix compiler warnings. --- doc/colors.n | 1 + macosx/README | 6 ++++-- macosx/tkMacOSXInit.c | 2 +- macosx/tkMacOSXTest.c | 12 ++++++++++-- macosx/tkMacOSXXStubs.c | 2 +- macosx/ttkMacOSXTheme.c | 42 +++++++++++++++++++++++------------------- 6 files changed, 40 insertions(+), 25 deletions(-) diff --git a/doc/colors.n b/doc/colors.n index 41d6ed0..7a7b5b3 100644 --- a/doc/colors.n +++ b/doc/colors.n @@ -901,6 +901,7 @@ systemScrollBarDelimiterActive systemScrollBarDelimiterInactive systemSecondaryGroupBoxBackground systemSecondaryHighlightColor +systemSelectedTabTextColor systemSheetBackground systemSheetBackgroundOpaque systemSheetBackgroundTransparent diff --git a/macosx/README b/macosx/README index 37225c8..d7333e8 100644 --- a/macosx/README +++ b/macosx/README @@ -303,7 +303,7 @@ but rather refers to the context in which the color should be used. Tk now provides the following semantic colors as system colors: systemTextColor, systemTextBackgroundColor, systemSelectedTextColor, systemSelectedTextBackgroundColor, systemControlTextColor, -systemDisabledControlTextColor, systemLabelColor and +systemDisabledControlTextColor, systemLabelColor, and systemControlAccentColor. All of these except the last two were present in OSX 10.0 (and those two are simulated in systems where they do not exist). The change in 10.14 was that the RGB color value of @@ -311,7 +311,9 @@ these colors became dynamic, meaning that the color value can change when the application appearance changes. In particular, when a user selects Dark Mode in the system preferences these colors change appearance. For example systemTextColor is dark in Aqua and light in -DarkAqua. +DarkAqua. One additional color, systemSelectedTabTextColor, does not +exist in macOS but is used by Tk to match the different colors used +for Notebook tab text in different OS versions. The default background and foreground colors of most of the Tk widgets have been set to semantic colors, which means that the widgets will change diff --git a/macosx/tkMacOSXInit.c b/macosx/tkMacOSXInit.c index e90e97b..89d6983 100644 --- a/macosx/tkMacOSXInit.c +++ b/macosx/tkMacOSXInit.c @@ -151,7 +151,7 @@ static char scriptPath[PATH_MAX + 1] = ""; * Record the OS version we are running on. */ int minorVersion; -#if MAC_OS_X_VERSION_MIN_REQUIRED < 101000 +#if MAC_OS_X_VERSION_MAX_ALLOWED < 101000 Gestalt(gestaltSystemVersionMinor, (SInt32*)&minorVersion); #else NSOperatingSystemVersion systemVersion; diff --git a/macosx/tkMacOSXTest.c b/macosx/tkMacOSXTest.c index b7923b0..9192fd6 100644 --- a/macosx/tkMacOSXTest.c +++ b/macosx/tkMacOSXTest.c @@ -18,8 +18,11 @@ * Forward declarations of procedures defined later in this file: */ +#if MAC_OS_X_VERSION_MAX_ALLOWED < 1080 static int DebuggerObjCmd (ClientData dummy, Tcl_Interp *interp, - int objc, Tcl_Obj *const objv[]); + int objc, Tcl_Obj *const objv[]); +#endif + /* *---------------------------------------------------------------------- @@ -46,8 +49,10 @@ TkplatformtestInit( * Add commands for platform specific tests on MacOS here. */ +#if MAC_OS_X_VERSION_MAX_ALLOWED < 1080 Tcl_CreateObjCommand(interp, "debugger", DebuggerObjCmd, (ClientData) 0, (Tcl_CmdDeleteProc *) NULL); +#endif return TCL_OK; } @@ -57,7 +62,8 @@ TkplatformtestInit( * * DebuggerObjCmd -- * - * This procedure simply calls the low level debugger. + * This procedure simply calls the low level debugger, which was + * deprecated in OSX 10.8. * * Results: * A standard Tcl result. @@ -68,6 +74,7 @@ TkplatformtestInit( *---------------------------------------------------------------------- */ +#if MAC_OS_X_VERSION_MAX_ALLOWED < 1080 static int DebuggerObjCmd( ClientData clientData, /* Not used. */ @@ -78,6 +85,7 @@ DebuggerObjCmd( Debugger(); return TCL_OK; } +#endif /* *---------------------------------------------------------------------- diff --git a/macosx/tkMacOSXXStubs.c b/macosx/tkMacOSXXStubs.c index 448736e..13cba84 100644 --- a/macosx/tkMacOSXXStubs.c +++ b/macosx/tkMacOSXXStubs.c @@ -178,7 +178,7 @@ TkpOpenDisplay( { int major, minor, patch; -#if MAC_OS_X_VERSION_MIN_REQUIRED < 101000 +#if MAC_OS_X_VERSION_MAX_ALLOWED < 101000 Gestalt(gestaltSystemVersionMajor, (SInt32*)&major); Gestalt(gestaltSystemVersionMinor, (SInt32*)&minor); Gestalt(gestaltSystemVersionBugFix, (SInt32*)&patch); diff --git a/macosx/ttkMacOSXTheme.c b/macosx/ttkMacOSXTheme.c index ec606ac..82b94f3 100644 --- a/macosx/ttkMacOSXTheme.c +++ b/macosx/ttkMacOSXTheme.c @@ -101,10 +101,9 @@ static CGFloat darkSelectedGradient[8] = { * When building on systems earlier than 10.8 there is no reasonable way to * convert an NSColor to a CGColor. We do run-time checking of the OS version, * and never need the CGColor property on older systems, so we can use this - * CGCOLOR macro, which evaluates to NULL without raising compiler - * warnings. designed to. Similarly, we never draw rounded rectangles on older - * systems which did not have CGPathCreateWithRoundedRect, so we just redefine - * it to + * CGCOLOR macro, which evaluates to NULL without raising compiler warnings. + * Similarly, we never draw rounded rectangles on older systems which did not + * have CGPathCreateWithRoundedRect, so we just redefine it to return NULL. */ #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1080 @@ -215,10 +214,10 @@ static CGFloat blackRGBA[4] = {0.0, 0.0, 0.0, 1.0}; /*---------------------------------------------------------------------- * GetBackgroundColor -- * - * Fills the array rgba with the color coordinates for a background - * color. Start with the background color of a window's geometry master, - * or the standard ttk window background if not. If the contrast - * parameter is nonzero modify this color to be darker, for the aqua + * Fills the array rgba with the color coordinates for a background color. + * Start with the background color of a window's geometry master, or the + * standard ttk window background if there is no master. If the contrast + * parameter is nonzero, modify this color to be darker, for the aqua * appearance, or lighter for the DarkAqua appearance. This is primarily * used by the Fill and Background elements. */ @@ -358,7 +357,7 @@ static void DrawUpDownArrows( * +++ FillButtonBackground -- * * Fills a rounded rectangle with a transparent black gradient. - * This is a no-op if not building on 10.9 or higher. + * This is a no-op if building on 10.8 or older. */ static void FillButtonBackground( @@ -419,7 +418,8 @@ static void HighlightButtonBorder( * DrawGroupBox -- * * This is a standalone drawing procedure which draws the contrasting - * rounded rectangular box for LabelFrames and Notebook panes. + * rounded rectangular box for LabelFrames and Notebook panes used in + * more recent versions of macOS. */ static void DrawGroupBox( @@ -1225,8 +1225,7 @@ static void ButtonElementMinSize( /* * The minwidth must be 0 to force the generic ttk code to compute the * correct text layout. For example, a non-zero value will cause the - * text to be left justified, no matter what -anchor setting is used - *in + * text to be left justified, no matter what -anchor setting is used in * the style. */ @@ -2300,16 +2299,16 @@ static void ThumbElementDraw( /* * In order to make ttk scrollbars work correctly it is necessary to be - * able to display the thumb element at the size and location which the - * ttk scrollbar widget requests. The algorithm that HIToolbox uses to + * able to display the thumb element at the size and location which the ttk + * scrollbar widget requests. The algorithm that HIToolbox uses to * determine the thumb geometry from the input values of min, max, value - * and viewSizeis, of course, undocumented. And this turns out to be a + * and viewSize is, of course, undocumented. And this turns out to be a * hard reverse engineering problem. A seemingly natural algorithm is * implemented below, but it does not correctly compute the same thumb * geometry as HITools (which also apparently does not agree with * NSScrollbar). This code uses that algorithm for older OS versions, - * because using HITools also handles drawing the buttons and 3D thumb - * used on those systems. The incorrect geometry is annoying but not + * because using HITools also handles drawing the buttons and 3D thumb used + * on those systems. The incorrect geometry is annoying but not completely * unusable. For newer systems the cleanest approach is to just draw the * thumb directly. */ @@ -2554,7 +2553,7 @@ static Ttk_ElementSpec SizegripElementSpec = { * inside a rectangle with rounded corners that has a color which * contrasts with the dialog background color. Moreover, although the * Apple human interface guidelines recommend against doing so, there are - * times when one wants to nest these widgets, for example having a + * times when one wants to nest these widgets, for example placing a * GroupBox inside of a TabbedPane. To have the right contrast, each * level of nesting requires a different color. * @@ -2699,6 +2698,7 @@ static Ttk_ElementOptionSpec FieldElementOptions[] = { Tk_Offset(FieldElement, backgroundObj), "white"}, {NULL, 0, 0, NULL} }; + static void FieldElementDraw( void *clientData, void *elementRecord, @@ -2727,7 +2727,9 @@ static Ttk_ElementSpec FieldElementSpec = { /*---------------------------------------------------------------------- * +++ Treeview headers -- * - * Redefine the header to use a kThemeListHeaderButton. + * On systems older than 10.9 The header is a kThemeListHeaderButton drawn + * by HIToolbox. On newer systems those buttons do not match the Apple + * buttons, so we draw them from scratch. */ static Ttk_StateTable TreeHeaderValueTable[] = { @@ -2735,6 +2737,7 @@ static Ttk_StateTable TreeHeaderValueTable[] = { {kThemeButtonOn, TTK_STATE_SELECTED}, {kThemeButtonOff, 0} }; + static Ttk_StateTable TreeHeaderAdornmentTable[] = { {kThemeAdornmentHeaderButtonSortUp, TTK_STATE_ALTERNATE | TTK_TREEVIEW_STATE_SORTARROW}, @@ -2745,6 +2748,7 @@ static Ttk_StateTable TreeHeaderAdornmentTable[] = { {kThemeAdornmentFocus, TTK_STATE_FOCUS}, {kThemeAdornmentNone, 0} }; + static void TreeAreaElementSize ( void *clientData, void *elementRecord, -- cgit v0.12 From f43a38c216438267b70e6141ecb1b6fd5194fd9c Mon Sep 17 00:00:00 2001 From: fvogel Date: Mon, 22 Apr 2019 22:09:50 +0000 Subject: Fix [2513186fff] and [f9343d8f72]: ttk::entry xview sub-command forces use of update idletasks. Thanks to cjmcdonald. --- generic/ttk/ttkEntry.c | 7 +++++++ library/ttk/entry.tcl | 1 - 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/generic/ttk/ttkEntry.c b/generic/ttk/ttkEntry.c index ebc485e..0f1707b 100644 --- a/generic/ttk/ttkEntry.c +++ b/generic/ttk/ttkEntry.c @@ -1651,6 +1651,13 @@ static int EntryXViewCommand( void *recordPtr, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]) { Entry *entryPtr = recordPtr; + + /* + * Ensure that the scroll info is up-to-date before a scrolling command. + */ + + EntryDoLayout(recordPtr); + if (objc == 3) { int newFirst; if (EntryIndex(interp, entryPtr, objv[2], &newFirst) != TCL_OK) { diff --git a/library/ttk/entry.tcl b/library/ttk/entry.tcl index c123bc9..e9f249c 100644 --- a/library/ttk/entry.tcl +++ b/library/ttk/entry.tcl @@ -211,7 +211,6 @@ proc ttk::entry::ClosestGap {w x} { ## See $index -- Make sure that the character at $index is visible. # proc ttk::entry::See {w {index insert}} { - update idletasks ;# ensure scroll data up-to-date set c [$w index $index] # @@@ OR: check [$w index left] / [$w index right] if {$c < [$w index @0] || $c >= [$w index @[winfo width $w]]} { -- cgit v0.12 From 40eb1fce5bbde4a49fd24fa146e34c292b729131 Mon Sep 17 00:00:00 2001 From: culler Date: Wed, 24 Apr 2019 15:52:16 +0000 Subject: Fix bug [4d2e8d4d5c]: Aqua notebooks sometimes do not draw a new pane immediately --- macosx/tkMacOSXKeyEvent.c | 10 ++++++++++ macosx/tkMacOSXPrivate.h | 6 ++++++ macosx/tkMacOSXSubwindows.c | 39 ++++++++++++++++++++------------------- macosx/tkMacOSXWindowEvent.c | 39 +++++++++++++++++++++++++++++++++++++-- 4 files changed, 73 insertions(+), 21 deletions(-) diff --git a/macosx/tkMacOSXKeyEvent.c b/macosx/tkMacOSXKeyEvent.c index 6cf3783..8691ce2 100644 --- a/macosx/tkMacOSXKeyEvent.c +++ b/macosx/tkMacOSXKeyEvent.c @@ -257,6 +257,14 @@ unsigned short releaseCode; @implementation TKContentView + +-(id)init { + if (self = [super init]) { + _needsRedisplay = NO; + } + return self; +} + /* implementation (called through interpretKeyEvents:]). */ /* : called when done composing; @@ -449,6 +457,8 @@ unsigned short releaseCode; return str; } /* End impl. */ + +@synthesize needsRedisplay = _needsRedisplay; @end diff --git a/macosx/tkMacOSXPrivate.h b/macosx/tkMacOSXPrivate.h index 105317d..fe913ec 100644 --- a/macosx/tkMacOSXPrivate.h +++ b/macosx/tkMacOSXPrivate.h @@ -332,8 +332,14 @@ VISIBILITY_HIDDEN VISIBILITY_HIDDEN @interface TKContentView : NSView { +@private NSString *privateWorkingText; +#ifdef __i386__ + /* The Objective C runtime used on i386 requires this. */ + Bool _needsRedisplay; +#endif } +@property Bool needsRedisplay; @end @interface TKContentView(TKKeyEvent) diff --git a/macosx/tkMacOSXSubwindows.c b/macosx/tkMacOSXSubwindows.c index 06aaa9d..853abc2 100644 --- a/macosx/tkMacOSXSubwindows.c +++ b/macosx/tkMacOSXSubwindows.c @@ -130,6 +130,8 @@ XMapWindow( Window window) /* Window. */ { MacDrawable *macWin = (MacDrawable *) window; + TkWindow *winPtr = macWin->winPtr; + NSWindow *win = TkMacOSXDrawableWindow(window); XEvent event; /* @@ -145,10 +147,9 @@ XMapWindow( } display->request++; - macWin->winPtr->flags |= TK_MAPPED; - if (Tk_IsTopLevel(macWin->winPtr)) { - if (!Tk_IsEmbedded(macWin->winPtr)) { - NSWindow *win = TkMacOSXDrawableWindow(window); + winPtr->flags |= TK_MAPPED; + if (Tk_IsTopLevel(winPtr)) { + if (!Tk_IsEmbedded(winPtr)) { /* * We want to activate Tk when a toplevel is mapped but we must not @@ -158,7 +159,7 @@ XMapWindow( * bar unresponsive. */ - TkMacOSXApplyWindowAttributes(macWin->winPtr, win); + TkMacOSXApplyWindowAttributes(winPtr, win); [win setExcludedFromWindowsMenu:NO]; [NSApp activateIgnoringOtherApps:NO]; [[win contentView] setNeedsDisplay:YES]; @@ -177,18 +178,18 @@ XMapWindow( while (Tcl_DoOneEvent(TCL_WINDOW_EVENTS| TCL_DONT_WAIT)) {} [NSApp _unlockAutoreleasePool]; } else { + TkWindow *contWinPtr = TkpGetOtherWindow(winPtr); /* * Rebuild the container's clipping region and display * the window. */ - TkWindow *contWinPtr = TkpGetOtherWindow(macWin->winPtr); - TkMacOSXInvalClipRgns((Tk_Window) contWinPtr); TkMacOSXInvalidateWindow(macWin, TK_PARENT_WINDOW); } - TkMacOSXInvalClipRgns((Tk_Window) macWin->winPtr); + + TkMacOSXInvalClipRgns((Tk_Window) winPtr); /* * We only need to send the MapNotify event for toplevel windows. @@ -201,15 +202,21 @@ XMapWindow( event.xmap.window = window; event.xmap.type = MapNotify; event.xmap.event = window; - event.xmap.override_redirect = macWin->winPtr->atts.override_redirect; + event.xmap.override_redirect = winPtr->atts.override_redirect; Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL); } else { + /* - * Rebuild the parent's clipping region and display the window. + * For non-toplevel windows, rebuild the parent's clipping region + * and redisplay the window. */ - TkMacOSXInvalClipRgns((Tk_Window) macWin->winPtr->parentPtr); - TkMacOSXInvalidateWindow(macWin, TK_PARENT_WINDOW); + TkMacOSXInvalClipRgns((Tk_Window) winPtr->parentPtr); + if ([NSApp isDrawing]) { + [[win contentView] setNeedsRedisplay:YES]; + } else { + [[win contentView] setNeedsDisplay:YES]; + } } /* @@ -220,13 +227,7 @@ XMapWindow( event.xany.display = display; event.xvisibility.type = VisibilityNotify; event.xvisibility.state = VisibilityUnobscured; - NotifyVisibility(macWin->winPtr, &event); - - /* - * This seems to be needed to ensure that all subwindows get displayed. - */ - - GenerateConfigureNotify(macWin->winPtr, 1); + NotifyVisibility(winPtr, &event); } /* diff --git a/macosx/tkMacOSXWindowEvent.c b/macosx/tkMacOSXWindowEvent.c index 6b80761..327132c 100644 --- a/macosx/tkMacOSXWindowEvent.c +++ b/macosx/tkMacOSXWindowEvent.c @@ -856,7 +856,10 @@ Tk_MacOSXIsAppInFront(void) * */ -/*Restrict event processing to Expose events.*/ +/* + * Restrict event processing to Expose events. + */ + static Tk_RestrictAction ExposeRestrictProc( ClientData arg, @@ -866,7 +869,10 @@ ExposeRestrictProc( ? TK_PROCESS_EVENT : TK_DEFER_EVENT); } -/*Restrict event processing to ConfigureNotify events.*/ +/* + * Restrict event processing to ConfigureNotify events. + */ + static Tk_RestrictAction ConfigureRestrictProc( ClientData arg, @@ -875,6 +881,30 @@ ConfigureRestrictProc( return (eventPtr->type==ConfigureNotify ? TK_PROCESS_EVENT : TK_DEFER_EVENT); } +/* + * If a window gets mapped inside the drawRect method, this will be run as an + * idle task, after drawRect returns, to clean up the mess. + */ + +static void +RedisplayView( + ClientData clientdata) +{ + NSView *view = (NSView *) clientdata; + + /* + * Make sure that we are not trying to displaying a view that no longer + * exists. + */ + + for (NSWindow *w in [NSApp orderedWindows]) { + if ([w contentView] == view) { + [view setNeedsDisplay:YES]; + break; + } + } +} + @implementation TKContentView(TKWindowEvent) - (void) drawRect: (NSRect) rect @@ -921,6 +951,11 @@ ConfigureRestrictProc( CFRelease(drawShape); [NSApp setIsDrawing: NO]; + if ([self needsRedisplay]) { + [self setNeedsRedisplay:NO]; + Tcl_DoWhenIdle(RedisplayView, self); + } + #ifdef TK_MAC_DEBUG_DRAWING fprintf(stderr, "drawRect: done.\n"); #endif -- cgit v0.12 From 70af19ebc9a255f667aa2a143a8f57fe2576a2e4 Mon Sep 17 00:00:00 2001 From: culler Date: Thu, 25 Apr 2019 18:16:49 +0000 Subject: Fix textWind.test: make sure that the test window is mapped before running tests (needed on macOS). --- tests/textWind.test | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/textWind.test b/tests/textWind.test index e189663..788c245 100644 --- a/tests/textWind.test +++ b/tests/textWind.test @@ -39,6 +39,11 @@ wm minsize . 1 1 wm positionfrom . user wm deiconify . +# This update is needed on MacOS to make sure that the window is mapped +# when the tests begin. + +update + set bw [.t cget -borderwidth] set px [.t cget -padx] set py [.t cget -pady] -- cgit v0.12 From 35782df88f307dee00acfea69fa902c13291bc14 Mon Sep 17 00:00:00 2001 From: fvogel Date: Fri, 26 Apr 2019 21:11:42 +0000 Subject: Optimize the fix: the layout calculation is only needed if the display is out of date. --- generic/ttk/ttkEntry.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/generic/ttk/ttkEntry.c b/generic/ttk/ttkEntry.c index 0f1707b..148bc47 100644 --- a/generic/ttk/ttkEntry.c +++ b/generic/ttk/ttkEntry.c @@ -1651,12 +1651,15 @@ static int EntryXViewCommand( void *recordPtr, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]) { Entry *entryPtr = recordPtr; + WidgetCore *corePtr = recordPtr; /* * Ensure that the scroll info is up-to-date before a scrolling command. */ - EntryDoLayout(recordPtr); + if (corePtr->flags & REDISPLAY_PENDING) { + EntryDoLayout(recordPtr); + } if (objc == 3) { int newFirst; -- cgit v0.12 From c31fa24c60b3a3c8a9d5687f627f660d3649fdc0 Mon Sep 17 00:00:00 2001 From: fvogel Date: Fri, 26 Apr 2019 22:02:59 +0000 Subject: Write code more consistently with the rest of the ttkEntry.c file --- generic/ttk/ttkEntry.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/generic/ttk/ttkEntry.c b/generic/ttk/ttkEntry.c index 148bc47..1ef2423 100644 --- a/generic/ttk/ttkEntry.c +++ b/generic/ttk/ttkEntry.c @@ -1651,14 +1651,13 @@ static int EntryXViewCommand( void *recordPtr, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]) { Entry *entryPtr = recordPtr; - WidgetCore *corePtr = recordPtr; /* * Ensure that the scroll info is up-to-date before a scrolling command. */ - if (corePtr->flags & REDISPLAY_PENDING) { - EntryDoLayout(recordPtr); + if (entryPtr->core.flags & REDISPLAY_PENDING) { + EntryDoLayout(entryPtr); } if (objc == 3) { -- cgit v0.12 From 24b4a3cdfb7412ee9337695296ec28a02a1f08ad Mon Sep 17 00:00:00 2001 From: fvogel Date: Sat, 27 Apr 2019 15:49:23 +0000 Subject: More generic fix, for [8261c517af] and [2513186fff]. --- generic/ttk/ttkEntry.c | 8 -------- generic/ttk/ttkScroll.c | 19 ++++++++++++++++++- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/generic/ttk/ttkEntry.c b/generic/ttk/ttkEntry.c index 1ef2423..e6365b2 100644 --- a/generic/ttk/ttkEntry.c +++ b/generic/ttk/ttkEntry.c @@ -1652,14 +1652,6 @@ static int EntryXViewCommand( { Entry *entryPtr = recordPtr; - /* - * Ensure that the scroll info is up-to-date before a scrolling command. - */ - - if (entryPtr->core.flags & REDISPLAY_PENDING) { - EntryDoLayout(entryPtr); - } - if (objc == 3) { int newFirst; if (EntryIndex(interp, entryPtr, objv[2], &newFirst) != TCL_OK) { diff --git a/generic/ttk/ttkScroll.c b/generic/ttk/ttkScroll.c index 184f5f2..60f0480 100644 --- a/generic/ttk/ttkScroll.c +++ b/generic/ttk/ttkScroll.c @@ -197,7 +197,16 @@ int TtkScrollviewCommand( if (objc == 2) { Tcl_Obj *result[2]; - result[0] = Tcl_NewDoubleObj((double)s->first / s->total); + + /* + * Update the scroll info (first, last, total) if needed. + */ + + if (h->corePtr->flags & REDISPLAY_PENDING) { + h->corePtr->widgetSpec->layoutProc(h->corePtr); + } + + result[0] = Tcl_NewDoubleObj((double)s->first / s->total); result[1] = Tcl_NewDoubleObj((double)s->last / s->total); Tcl_SetObjResult(interp, Tcl_NewListObj(2, result)); return TCL_OK; @@ -235,6 +244,14 @@ void TtkScrollTo(ScrollHandle h, int newFirst) { Scrollable *s = h->scrollPtr; + /* + * Update the scroll info (first, last, total) if needed. + */ + + if (h->corePtr->flags & REDISPLAY_PENDING) { + h->corePtr->widgetSpec->layoutProc(h->corePtr); + } + if (newFirst >= s->total) newFirst = s->total - 1; if (newFirst > s->first && s->last >= s->total) /* don't scroll past end */ -- cgit v0.12 From 4c2a79de161bcf55a617eba4a6f0eb8a1e27ed8b Mon Sep 17 00:00:00 2001 From: fvogel Date: Sat, 27 Apr 2019 15:55:08 +0000 Subject: Revert irrelevant blank changes --- generic/ttk/ttkEntry.c | 1 - generic/ttk/ttkScroll.c | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/generic/ttk/ttkEntry.c b/generic/ttk/ttkEntry.c index e6365b2..ebc485e 100644 --- a/generic/ttk/ttkEntry.c +++ b/generic/ttk/ttkEntry.c @@ -1651,7 +1651,6 @@ static int EntryXViewCommand( void *recordPtr, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]) { Entry *entryPtr = recordPtr; - if (objc == 3) { int newFirst; if (EntryIndex(interp, entryPtr, objv[2], &newFirst) != TCL_OK) { diff --git a/generic/ttk/ttkScroll.c b/generic/ttk/ttkScroll.c index 60f0480..21b23b8 100644 --- a/generic/ttk/ttkScroll.c +++ b/generic/ttk/ttkScroll.c @@ -206,7 +206,7 @@ int TtkScrollviewCommand( h->corePtr->widgetSpec->layoutProc(h->corePtr); } - result[0] = Tcl_NewDoubleObj((double)s->first / s->total); + result[0] = Tcl_NewDoubleObj((double)s->first / s->total); result[1] = Tcl_NewDoubleObj((double)s->last / s->total); Tcl_SetObjResult(interp, Tcl_NewListObj(2, result)); return TCL_OK; -- cgit v0.12 From a45cd9e5e3fc6da137e7a23ebd4b507b3905c142 Mon Sep 17 00:00:00 2001 From: fvogel Date: Sun, 28 Apr 2019 10:45:38 +0000 Subject: Add a missing scroll info update needed to make x|yview moveto|units|pages work without an update idletasks call beforehand. --- generic/ttk/ttkScroll.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/generic/ttk/ttkScroll.c b/generic/ttk/ttkScroll.c index 21b23b8..84fbff2 100644 --- a/generic/ttk/ttkScroll.c +++ b/generic/ttk/ttkScroll.c @@ -218,6 +218,14 @@ int TtkScrollviewCommand( double fraction; int count; + /* + * Update the scroll info (first, last, total) if needed. + */ + + if (h->corePtr->flags & REDISPLAY_PENDING) { + h->corePtr->widgetSpec->layoutProc(h->corePtr); + } + switch (Tk_GetScrollInfoObj(interp, objc, objv, &fraction, &count)) { case TK_SCROLL_ERROR: return TCL_ERROR; -- cgit v0.12 From faf3d3197da965a56835db30b149ef85ce2384f1 Mon Sep 17 00:00:00 2001 From: fvogel Date: Sun, 28 Apr 2019 12:52:43 +0000 Subject: Factorize the code a bit, and avoid calling the layoutProc twice when calling xview moveto|units|pages. --- generic/ttk/ttkEntry.c | 2 +- generic/ttk/ttkScroll.c | 47 +++++++++++++++++++++-------------------------- generic/ttk/ttkTreeview.c | 4 ++-- generic/ttk/ttkWidget.h | 2 +- 4 files changed, 25 insertions(+), 30 deletions(-) diff --git a/generic/ttk/ttkEntry.c b/generic/ttk/ttkEntry.c index ebc485e..e306953 100644 --- a/generic/ttk/ttkEntry.c +++ b/generic/ttk/ttkEntry.c @@ -1656,7 +1656,7 @@ static int EntryXViewCommand( if (EntryIndex(interp, entryPtr, objv[2], &newFirst) != TCL_OK) { return TCL_ERROR; } - TtkScrollTo(entryPtr->entry.xscrollHandle, newFirst); + TtkScrollTo(entryPtr->entry.xscrollHandle, newFirst, 1); return TCL_OK; } return TtkScrollviewCommand(interp, objc, objv, entryPtr->entry.xscrollHandle); diff --git a/generic/ttk/ttkScroll.c b/generic/ttk/ttkScroll.c index 84fbff2..47db6ac 100644 --- a/generic/ttk/ttkScroll.c +++ b/generic/ttk/ttkScroll.c @@ -181,6 +181,19 @@ void TtkScrollbarUpdateRequired(ScrollHandle h) h->flags |= SCROLL_UPDATE_REQUIRED; } +/* TtkUpdateScrollInfo -- + * Call the layoutProc to update the scroll info first, last, and total. + * Do it only if needed, that is when a redisplay is pending (which + * indicates scroll info are possibly out of date). + */ + +void TtkUpdateScrollInfo(ScrollHandle h) +{ + if (h->corePtr->flags & REDISPLAY_PENDING) { + h->corePtr->widgetSpec->layoutProc(h->corePtr); + } +} + /* TtkScrollviewCommand -- * Widget [xy]view command implementation. * @@ -193,19 +206,13 @@ int TtkScrollviewCommand( Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], ScrollHandle h) { Scrollable *s = h->scrollPtr; - int newFirst = s->first; + int newFirst; + + TtkUpdateScrollInfo(h); + newFirst = s->first; if (objc == 2) { Tcl_Obj *result[2]; - - /* - * Update the scroll info (first, last, total) if needed. - */ - - if (h->corePtr->flags & REDISPLAY_PENDING) { - h->corePtr->widgetSpec->layoutProc(h->corePtr); - } - result[0] = Tcl_NewDoubleObj((double)s->first / s->total); result[1] = Tcl_NewDoubleObj((double)s->last / s->total); Tcl_SetObjResult(interp, Tcl_NewListObj(2, result)); @@ -218,14 +225,6 @@ int TtkScrollviewCommand( double fraction; int count; - /* - * Update the scroll info (first, last, total) if needed. - */ - - if (h->corePtr->flags & REDISPLAY_PENDING) { - h->corePtr->widgetSpec->layoutProc(h->corePtr); - } - switch (Tk_GetScrollInfoObj(interp, objc, objv, &fraction, &count)) { case TK_SCROLL_ERROR: return TCL_ERROR; @@ -243,21 +242,17 @@ int TtkScrollviewCommand( } } - TtkScrollTo(h, newFirst); + TtkScrollTo(h, newFirst, 0); return TCL_OK; } -void TtkScrollTo(ScrollHandle h, int newFirst) +void TtkScrollTo(ScrollHandle h, int newFirst, int updateScrollInfo) { Scrollable *s = h->scrollPtr; - /* - * Update the scroll info (first, last, total) if needed. - */ - - if (h->corePtr->flags & REDISPLAY_PENDING) { - h->corePtr->widgetSpec->layoutProc(h->corePtr); + if (updateScrollInfo) { + TtkUpdateScrollInfo(h); } if (newFirst >= s->total) diff --git a/generic/ttk/ttkTreeview.c b/generic/ttk/ttkTreeview.c index 68a9b6d..d78df5f 100644 --- a/generic/ttk/ttkTreeview.c +++ b/generic/ttk/ttkTreeview.c @@ -2845,10 +2845,10 @@ static int TreeviewSeeCommand( */ rowNumber = RowNumber(tv, item); if (rowNumber < tv->tree.yscroll.first) { - TtkScrollTo(tv->tree.yscrollHandle, rowNumber); + TtkScrollTo(tv->tree.yscrollHandle, rowNumber, 1); } else if (rowNumber >= tv->tree.yscroll.last) { TtkScrollTo(tv->tree.yscrollHandle, - tv->tree.yscroll.first + (1+rowNumber - tv->tree.yscroll.last)); + tv->tree.yscroll.first + (1+rowNumber - tv->tree.yscroll.last), 1); } return TCL_OK; diff --git a/generic/ttk/ttkWidget.h b/generic/ttk/ttkWidget.h index e4dd712..7ccc1f3 100644 --- a/generic/ttk/ttkWidget.h +++ b/generic/ttk/ttkWidget.h @@ -195,7 +195,7 @@ MODULE_SCOPE void TtkFreeScrollHandle(ScrollHandle); MODULE_SCOPE int TtkScrollviewCommand( Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], ScrollHandle); -MODULE_SCOPE void TtkScrollTo(ScrollHandle, int newFirst); +MODULE_SCOPE void TtkScrollTo(ScrollHandle, int newFirst, int updateScrollInfo); MODULE_SCOPE void TtkScrolled(ScrollHandle, int first, int last, int total); MODULE_SCOPE void TtkScrollbarUpdateRequired(ScrollHandle); -- cgit v0.12 From 6afd4e02fc9f197853203afaa1df7347a989e8cf Mon Sep 17 00:00:00 2001 From: fvogel Date: Sun, 28 Apr 2019 13:57:09 +0000 Subject: Fix '.e index @'. The returned answer could be wrong if the scroll info was not yet updated. --- generic/ttk/ttkEntry.c | 1 + generic/ttk/ttkWidget.h | 1 + 2 files changed, 2 insertions(+) diff --git a/generic/ttk/ttkEntry.c b/generic/ttk/ttkEntry.c index e306953..186ded0 100644 --- a/generic/ttk/ttkEntry.c +++ b/generic/ttk/ttkEntry.c @@ -1362,6 +1362,7 @@ EntryIndex( *indexPtr = Tk_PointToChar(entryPtr->entry.textLayout, x - entryPtr->entry.layoutX, 0); + TtkUpdateScrollInfo(entryPtr->entry.xscrollHandle); if (*indexPtr < entryPtr->entry.xscroll.first) { *indexPtr = entryPtr->entry.xscroll.first; } diff --git a/generic/ttk/ttkWidget.h b/generic/ttk/ttkWidget.h index 7ccc1f3..8a94bb7 100644 --- a/generic/ttk/ttkWidget.h +++ b/generic/ttk/ttkWidget.h @@ -195,6 +195,7 @@ MODULE_SCOPE void TtkFreeScrollHandle(ScrollHandle); MODULE_SCOPE int TtkScrollviewCommand( Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], ScrollHandle); +MODULE_SCOPE void TtkUpdateScrollInfo(ScrollHandle h); MODULE_SCOPE void TtkScrollTo(ScrollHandle, int newFirst, int updateScrollInfo); MODULE_SCOPE void TtkScrolled(ScrollHandle, int first, int last, int total); MODULE_SCOPE void TtkScrollbarUpdateRequired(ScrollHandle); -- cgit v0.12 From 8769a171d064001c6ee11448139a564f91bd29ca Mon Sep 17 00:00:00 2001 From: fvogel Date: Sun, 28 Apr 2019 14:34:41 +0000 Subject: Add tests checking the scroll info correct update when xview / yview is called. All the new (or modified) tests fail in core-8-6-branch. --- tests/ttk/entry.test | 29 ++++++++++++++++++++++++++++- tests/ttk/treeview.test | 12 ++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/tests/ttk/entry.test b/tests/ttk/entry.test index d95ef31..a920042 100644 --- a/tests/ttk/entry.test +++ b/tests/ttk/entry.test @@ -103,10 +103,37 @@ test entry-3.1 "bbox widget command" -body { test entry-3.2 "xview" -body { .e delete 0 end; .e insert end [string repeat "0" 40] - update idletasks set result [.e xview] } -result {0.0 0.5} +test entry-3.3 "xview" -body { + .e delete 0 end; + .e insert end abcdefghijklmnopqrstuvwxyz + .e xview end + set result [.e index @0] +} -result {7} + +test entry-3.4 "xview" -body { + .e delete 0 end; + .e insert end abcdefghijklmnopqrstuvwxyz + .e xview moveto 1.0 + set result [.e index @0] +} -result {7} + +test entry-3.5 "xview" -body { + .e delete 0 end; + .e insert end abcdefghijklmnopqrstuvwxyz + .e xview scroll 5 units + set result [.e index @0] +} -result {5} + +test entry-3.6 "xview" -body { + .e delete 0 end; + .e insert end [string repeat abcdefghijklmnopqrstuvwxyz 5] + .e xview scroll 2 pages + set result [.e index @0] +} -result {40} + test entry-3.last "Series 3 cleanup" -body { destroy .e } diff --git a/tests/ttk/treeview.test b/tests/ttk/treeview.test index be82f68..a36e3d1 100644 --- a/tests/ttk/treeview.test +++ b/tests/ttk/treeview.test @@ -471,6 +471,18 @@ test treeview-9.0 "scroll callback - empty tree" -body { set ::scrolldata } -result [list 0.0 1.0] +test treeview-9.1 "scrolling" -setup { + pack [ttk::treeview .tree -show tree] -fill y + for {set i 1} {$i < 100} {incr i} { + .tree insert {} end -text $i + } +} -body { + .tree yview scroll 5 units + .tree identify item 2 2 +} -cleanup { + destroy .tree +} -result {I006} + ### identify tests: # proc identify* {tv comps args} { -- cgit v0.12 From e1c72469006c017837637353b241baf64dbb5e38 Mon Sep 17 00:00:00 2001 From: fvogel Date: Sun, 28 Apr 2019 19:27:22 +0000 Subject: Fix documentation for xview/yview: make it generic and available for ttk::entry and ttk::treeview --- doc/ttk_entry.n | 41 +--------------------------- doc/ttk_treeview.n | 13 ++++----- doc/ttk_widget.n | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 86 insertions(+), 46 deletions(-) diff --git a/doc/ttk_entry.n b/doc/ttk_entry.n index 3a30e4d..adc4f16 100644 --- a/doc/ttk_entry.n +++ b/doc/ttk_entry.n @@ -222,52 +222,13 @@ by the \fB\-validate\fR option. Returns 0 if validation fails, 1 if it succeeds. Sets or clears the \fBinvalid\fR state accordingly. See \fBVALIDATION\fR below for more details. -.TP -\fIpathName \fBxview \fIargs\fR -This command is used to query and change the horizontal position of the -text in the widget's window. It can take any of the following -forms: -.RS -.TP -\fIpathName \fBxview\fR -Returns a list containing two elements. -Each element is a real fraction between 0 and 1; together they describe -the horizontal span that is visible in the window. -For example, if the first element is .2 and the second element is .6, -20% of the entry's text is off-screen to the left, the middle 40% is visible -in the window, and 40% of the text is off-screen to the right. -These are the same values passed to scrollbars via the \fB\-xscrollcommand\fR -option. -.TP -\fIpathName \fBxview\fR \fIindex\fR -Adjusts the view in the window so that the character given by \fIindex\fR -is displayed at the left edge of the window. -.TP -\fIpathName \fBxview moveto\fI fraction\fR -Adjusts the view in the window so that the character \fIfraction\fR of the -way through the text appears at the left edge of the window. -\fIFraction\fR must be a fraction between 0 and 1. -.TP -\fIpathName \fBxview scroll \fInumber what\fR -This command shifts the view in the window left or right according to -\fInumber\fR and \fIwhat\fR. -\fINumber\fR must be an integer. -\fIWhat\fR must be either \fBunits\fR or \fBpages\fR. -'\" or an abbreviation of one of these, but we don't document that. -If \fIwhat\fR is \fBunits\fR, the view adjusts left or right by -\fInumber\fR average-width characters on the display; if it is -\fBpages\fR then the view adjusts by \fInumber\fR screenfuls. -If \fInumber\fR is negative then characters farther to the left -become visible; if it is positive then characters farther to the right -become visible. -.RE .PP The entry widget also supports the following generic \fBttk::widget\fR widget subcommands (see \fIttk::widget(n)\fR for details): .DS .ta 5.5c 11c \fBcget\fR \fBconfigure\fR \fBidentify\fR -\fBinstate\fR \fBstate\fR +\fBinstate\fR \fBstate\fR \fBxview\fR .DE .SH VALIDATION .PP diff --git a/doc/ttk_treeview.n b/doc/ttk_treeview.n index 96565a3..5fd5e6d 100644 --- a/doc/ttk_treeview.n +++ b/doc/ttk_treeview.n @@ -388,12 +388,13 @@ If \fIitems\fR is omitted, removes \fItag\fR from each item in the tree. If \fItag\fR is not present for a particular item, then the \fB\-tags\fR for that item are unchanged. .RE -.TP -\fIpathName \fBxview \fIargs\fR -Standard command for horizontal scrolling; see \fIwidget(n)\fR. -.TP -\fIpathName \fByview \fIargs\fR -Standard command for vertical scrolling; see \fIttk::widget(n)\fR. +.PP +The treeview widget also supports the following generic \fBttk::widget\fR +widget subcommands (see \fIttk::widget(n)\fR for details): +.DS +.ta 5.5c 11c +\fBxview\fR \fByview\fR +.DE .SH "ITEM OPTIONS" .PP The following item options may be specified for items diff --git a/doc/ttk_widget.n b/doc/ttk_widget.n index ad90e99..2e47b46 100644 --- a/doc/ttk_widget.n +++ b/doc/ttk_widget.n @@ -192,6 +192,84 @@ will restore \fIpathName\fR to the original state. If \fIstateSpec\fR is not specified, returns a list of the currently-enabled state flags. .RE +.TP +\fIpathName \fBxview \fIargs\fR +This command is used to query and change the horizontal position of the +content in the widget's window. It can take any of the following +forms: +.RS +.TP +\fIpathName \fBxview\fR +Returns a list containing two elements. +Each element is a real fraction between 0 and 1; together they describe +the horizontal span that is visible in the window. +For example, if the first element is .2 and the second element is .6, +20% of the widget's content is off-screen to the left, the middle 40% is visible +in the window, and 40% of the content is off-screen to the right. +These are the same values passed to scrollbars via the \fB\-xscrollcommand\fR +option. +.TP +\fIpathName \fBxview\fR \fIindex\fR +Adjusts the view in the window so that the content given by \fIindex\fR +is displayed at the left edge of the window. +.TP +\fIpathName \fBxview moveto\fI fraction\fR +Adjusts the view in the window so that the character \fIfraction\fR of the +way through the content appears at the left edge of the window. +\fIFraction\fR must be a fraction between 0 and 1. +.TP +\fIpathName \fBxview scroll \fInumber what\fR +This command shifts the view in the window left or right according to +\fInumber\fR and \fIwhat\fR. +\fINumber\fR must be an integer. +\fIWhat\fR must be either \fBunits\fR or \fBpages\fR. +'\" or an abbreviation of one of these, but we don't document that. +If \fIwhat\fR is \fBunits\fR, the view adjusts left or right by +\fInumber\fR average-width characters on the display; if it is +\fBpages\fR then the view adjusts by \fInumber\fR screenfuls. +If \fInumber\fR is negative then characters farther to the left +become visible; if it is positive then characters farther to the right +become visible. +.RE +.TP +\fIpathName \fByview \fIargs\fR +This command is used to query and change the vertical position of the +content in the widget's window. It can take any of the following +forms: +.RS +.TP +\fIpathName \fByview\fR +Returns a list containing two elements. +Each element is a real fraction between 0 and 1; together they describe +the vertical span that is visible in the window. +For example, if the first element is .2 and the second element is .6, +20% of the widget's content is off-screen to the top, the middle 40% is visible +in the window, and 40% of the content is off-screen to the bottom. +These are the same values passed to scrollbars via the \fB\-yscrollcommand\fR +option. +.TP +\fIpathName \fByview\fR \fIindex\fR +Adjusts the view in the window so that the content given by \fIindex\fR +is displayed at the top edge of the window. +.TP +\fIpathName \fByview moveto\fI fraction\fR +Adjusts the view in the window so that the item \fIfraction\fR of the +way through the content appears at the top edge of the window. +\fIFraction\fR must be a fraction between 0 and 1. +.TP +\fIpathName \fBxview scroll \fInumber what\fR +This command shifts the view in the window up or down according to +\fInumber\fR and \fIwhat\fR. +\fINumber\fR must be an integer. +\fIWhat\fR must be either \fBunits\fR or \fBpages\fR. +'\" or an abbreviation of one of these, but we don't document that. +If \fIwhat\fR is \fBunits\fR, the view adjusts up or down by +\fInumber\fR average-width characters on the display; if it is +\fBpages\fR then the view adjusts by \fInumber\fR screenfuls. +If \fInumber\fR is negative then items farther to the top +become visible; if it is positive then items farther to the bottom +become visible. +.RE .SH "WIDGET STATES" The widget state is a bitmap of independent state flags. Widget state flags include: -- cgit v0.12 From e57c2944853f97d7e668f937db46ac3cd40b3994 Mon Sep 17 00:00:00 2001 From: fvogel Date: Sun, 28 Apr 2019 20:12:52 +0000 Subject: Fix typo in man page --- doc/ttk_widget.n | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/ttk_widget.n b/doc/ttk_widget.n index 2e47b46..281ce74 100644 --- a/doc/ttk_widget.n +++ b/doc/ttk_widget.n @@ -257,7 +257,7 @@ Adjusts the view in the window so that the item \fIfraction\fR of the way through the content appears at the top edge of the window. \fIFraction\fR must be a fraction between 0 and 1. .TP -\fIpathName \fBxview scroll \fInumber what\fR +\fIpathName \fByview scroll \fInumber what\fR This command shifts the view in the window up or down according to \fInumber\fR and \fIwhat\fR. \fINumber\fR must be an integer. -- cgit v0.12 From 2fa09ced062e7964597b77f6ec9c04fd00001ee4 Mon Sep 17 00:00:00 2001 From: fvogel Date: Sun, 28 Apr 2019 20:27:59 +0000 Subject: Fix inconsistency in the Tk_GetScrollInfoObj man page. Apparently this was a leftover from [a99dde78] --- doc/GetScroll.3 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/GetScroll.3 b/doc/GetScroll.3 index abd0880..a71986d 100644 --- a/doc/GetScroll.3 +++ b/doc/GetScroll.3 @@ -15,10 +15,10 @@ Tk_GetScrollInfoObj, Tk_GetScrollInfo \- parse arguments for scrolling commands \fB#include \fR .sp int -\fBTk_GetScrollInfoObj(\fIinterp, objc, objv, dblPtr, intPtr\fB)\fR +\fBTk_GetScrollInfoObj(\fIinterp, objc, objv, fractionPtr, stepsPtr\fB)\fR .sp int -\fBTk_GetScrollInfo(\fIinterp, argc, argv, dblPtr, intPtr\fB)\fR +\fBTk_GetScrollInfo(\fIinterp, argc, argv, fractionPtr, stepsPtr\fB)\fR .SH ARGUMENTS .AS "Tcl_Interp" *fractionPtr .AP Tcl_Interp *interp in -- cgit v0.12 From b410e77f82bae835dc0daa2606553b43a1442aba Mon Sep 17 00:00:00 2001 From: fvogel Date: Mon, 29 Apr 2019 20:10:46 +0000 Subject: Fix [1ff193f1e3]: style name is Horizontal.TScrollbar or Vertical.TScrollbar in ttk::scrollbar documentation --- doc/ttk_scrollbar.n | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/doc/ttk_scrollbar.n b/doc/ttk_scrollbar.n index 49681a1..cc3dec5 100644 --- a/doc/ttk_scrollbar.n +++ b/doc/ttk_scrollbar.n @@ -76,7 +76,7 @@ Modify or query the widget state; see \fIttk::widget(n)\fR. .SH "INTERNAL COMMANDS" .PP The following widget commands are used internally -by the TScrollbar widget class bindings. +by the \fBTScrollbar\fP widget class bindings. .TP \fIpathName \fBdelta \fIdeltaX deltaY\fR Returns a real number indicating the fractional change in @@ -153,6 +153,7 @@ grid $f.vsb \-row 0 \-column 1 \-sticky nsew grid $f.hsb \-row 1 \-column 0 \-sticky nsew grid columnconfigure $f 0 \-weight 1 grid rowconfigure $f 0 \-weight 1 +pack $f .CE .SH "STYLING OPTIONS" .PP @@ -160,8 +161,8 @@ The class name for a \fBttk::scrollbar\fP is \fBTScrollbar\fP. .PP Dynamic states: \fBactive\fP, \fBdisabled\fP. .PP -\fBTScrollbar\fP styling options configurable with \fBttk::style\fP -are: +\fBVertical.TScrollbar\fP and \fBHorizontal.TScrollbar\fP styling options +that are configurable with \fBttk::style\fP are: .PP \fB\-arrowcolor\fP \fIcolor\fP .br -- cgit v0.12 From 433304287898f929f4b40917815bc1dfe6bb834b Mon Sep 17 00:00:00 2001 From: fvogel Date: Tue, 30 Apr 2019 06:03:24 +0000 Subject: Add missing documentation for -arrowsize in ttk::scrollbar and ttk::combobox man pages. --- doc/ttk_combobox.n | 2 ++ doc/ttk_scrollbar.n | 2 ++ 2 files changed, 4 insertions(+) diff --git a/doc/ttk_combobox.n b/doc/ttk_combobox.n index 9c01409..b8fd2bc 100644 --- a/doc/ttk_combobox.n +++ b/doc/ttk_combobox.n @@ -124,6 +124,8 @@ are: .PP \fB\-arrowcolor\fP \fIcolor\fP .br +\fB\-arrowsize\fP \fIamount\fP +.br \fB\-background\fP \fIcolor\fP .br \fB\-bordercolor\fP \fIcolor\fP diff --git a/doc/ttk_scrollbar.n b/doc/ttk_scrollbar.n index cc3dec5..6e9854f 100644 --- a/doc/ttk_scrollbar.n +++ b/doc/ttk_scrollbar.n @@ -166,6 +166,8 @@ that are configurable with \fBttk::style\fP are: .PP \fB\-arrowcolor\fP \fIcolor\fP .br +\fB\-arrowsize\fP \fIamount\fP +.br \fB\-background\fP \fIcolor\fP .br \fB\-bordercolor\fP \fIcolor\fP -- cgit v0.12 From 43d7f5fb0f3b37902bb0628d71254bf281fe241d Mon Sep 17 00:00:00 2001 From: fvogel Date: Tue, 30 Apr 2019 17:28:13 +0000 Subject: Fix [4f9a99e20b]: crash when specifying wrong -syssize option in ttk::style element create ... vsapi --- win/ttkWinXPTheme.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/win/ttkWinXPTheme.c b/win/ttkWinXPTheme.c index b828221..c19ed65 100644 --- a/win/ttkWinXPTheme.c +++ b/win/ttkWinXPTheme.c @@ -1062,7 +1062,7 @@ GetSysFlagFromObj(Tcl_Interp *interp, Tcl_Obj *objPtr, int *resultPtr) "SM_CXBORDER", "SM_CYBORDER", "SM_CXVSCROLL", "SM_CYVSCROLL", "SM_CXHSCROLL", "SM_CYHSCROLL", "SM_CXMENUCHECK", "SM_CYMENUCHECK", "SM_CXMENUSIZE", "SM_CYMENUSIZE", "SM_CXSIZE", "SM_CYSIZE", "SM_CXSMSIZE", - "SM_CYSMSIZE" + "SM_CYSMSIZE", NULL }; int flags[] = { SM_CXBORDER, SM_CYBORDER, SM_CXVSCROLL, SM_CYVSCROLL, -- cgit v0.12 From a1e66021e7f53ce1485757afa0c700a5ad6ef560 Mon Sep 17 00:00:00 2001 From: fvogel Date: Tue, 30 Apr 2019 17:54:34 +0000 Subject: Refine documentation in ttk::scrollbar --- doc/ttk_scrollbar.n | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/doc/ttk_scrollbar.n b/doc/ttk_scrollbar.n index 6e9854f..6baab04 100644 --- a/doc/ttk_scrollbar.n +++ b/doc/ttk_scrollbar.n @@ -161,8 +161,9 @@ The class name for a \fBttk::scrollbar\fP is \fBTScrollbar\fP. .PP Dynamic states: \fBactive\fP, \fBdisabled\fP. .PP -\fBVertical.TScrollbar\fP and \fBHorizontal.TScrollbar\fP styling options -that are configurable with \fBttk::style\fP are: +\fBTScrollbar\fP (or more specifically \fBVertical.TScrollbar\fP and +\fBHorizontal.TScrollbar\fP) styling options that are configurable with +\fBttk::style\fP are: .PP \fB\-arrowcolor\fP \fIcolor\fP .br -- cgit v0.12 From de3209189e8860aa1a88ed83e190dd8b7e4c9847 Mon Sep 17 00:00:00 2001 From: fvogel Date: Wed, 1 May 2019 18:30:30 +0000 Subject: Fix [51b4b18394]: mac os x: combobox.tcl has old scrollbar for its listbox --- library/ttk/combobox.tcl | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/library/ttk/combobox.tcl b/library/ttk/combobox.tcl index c1b6da6..1355a04 100644 --- a/library/ttk/combobox.tcl +++ b/library/ttk/combobox.tcl @@ -251,30 +251,16 @@ proc ttk::combobox::UnmapPopdown {w} { ttk::releaseGrab $w } -### -# - -namespace eval ::ttk::combobox { - # @@@ Until we have a proper native scrollbar on Aqua, use - # @@@ the regular Tk one. Use ttk::scrollbar on other platforms. - variable scrollbar ttk::scrollbar - if {[tk windowingsystem] eq "aqua"} { - set scrollbar ::scrollbar - } -} - ## PopdownWindow -- # Returns the popdown widget associated with a combobox, # creating it if necessary. # proc ttk::combobox::PopdownWindow {cb} { - variable scrollbar - if {![winfo exists $cb.popdown]} { set poplevel [PopdownToplevel $cb.popdown] set popdown [ttk::frame $poplevel.f -style ComboboxPopdownFrame] - $scrollbar $popdown.sb \ + ttk::scrollbar $popdown.sb \ -orient vertical -command [list $popdown.l yview] listbox $popdown.l \ -listvariable ttk::combobox::Values($cb) \ -- cgit v0.12 From 85ca666e03be25f5cd07ecf59bac5ba1af607f01 Mon Sep 17 00:00:00 2001 From: oehhar Date: Thu, 2 May 2019 16:00:41 +0000 Subject: ttk::scrollbar documentation: added styling options -gripcound and -sliderlength and some explanatory text --- doc/ttk_scrollbar.n | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/ttk_scrollbar.n b/doc/ttk_scrollbar.n index 6baab04..e356b91 100644 --- a/doc/ttk_scrollbar.n +++ b/doc/ttk_scrollbar.n @@ -173,11 +173,15 @@ Dynamic states: \fBactive\fP, \fBdisabled\fP. .br \fB\-bordercolor\fP \fIcolor\fP .br -\fB\-darkcolor\fP \fIcolor\fP +\fB\-darkcolor\fP \fIcolor\fP (color of the dark 3d relief) .br \fB\-foreground\fP \fIcolor\fP .br -\fB\-lightcolor\fP \fIcolor\fP +\fB\-gripcount\fP \fInumber\fP (number of lines on the thumb) +.br +\fB\-lightcolor\fP \fIcolor\fP (color of the light 3d relief) +.br +\fB\-sliderlength\fP \fIamount\fP (minimum length of the thumb) .br \fB\-troughcolor\fP \fIcolor\fP .PP -- cgit v0.12 From 6f3240df379bab104d9d81e2103d74a8de4d6eca Mon Sep 17 00:00:00 2001 From: fvogel Date: Thu, 2 May 2019 20:55:15 +0000 Subject: Homogenize with existing doc for -gripcount in the man page for ttk::panedwindow --- doc/ttk_scrollbar.n | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/ttk_scrollbar.n b/doc/ttk_scrollbar.n index e356b91..a93c706 100644 --- a/doc/ttk_scrollbar.n +++ b/doc/ttk_scrollbar.n @@ -177,7 +177,7 @@ Dynamic states: \fBactive\fP, \fBdisabled\fP. .br \fB\-foreground\fP \fIcolor\fP .br -\fB\-gripcount\fP \fInumber\fP (number of lines on the thumb) +\fB\-gripcount\fP \fIcount\fP (number of lines on the thumb) .br \fB\-lightcolor\fP \fIcolor\fP (color of the light 3d relief) .br -- cgit v0.12 From 8f871f2b97e1c60ed300763ff7986bfd0bca168b Mon Sep 17 00:00:00 2001 From: oehhar Date: Fri, 3 May 2019 06:44:14 +0000 Subject: ttk::scrollbar documentation: marked -sliderlength as depreciated as it has no effect --- doc/ttk_scrollbar.n | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/ttk_scrollbar.n b/doc/ttk_scrollbar.n index a93c706..5b9bbfb 100644 --- a/doc/ttk_scrollbar.n +++ b/doc/ttk_scrollbar.n @@ -181,7 +181,7 @@ Dynamic states: \fBactive\fP, \fBdisabled\fP. .br \fB\-lightcolor\fP \fIcolor\fP (color of the light 3d relief) .br -\fB\-sliderlength\fP \fIamount\fP (minimum length of the thumb) +\fB\-sliderlength\fP \fIamount\fP (depreciated, no effect) .br \fB\-troughcolor\fP \fIcolor\fP .PP -- cgit v0.12 From 5def4ba26dcbe1563f4bf4a29a68472414f5cbcd Mon Sep 17 00:00:00 2001 From: fvogel Date: Fri, 3 May 2019 19:49:31 +0000 Subject: Remove wrong info from ttk::scrollbar man page --- doc/ttk_scrollbar.n | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/doc/ttk_scrollbar.n b/doc/ttk_scrollbar.n index 5b9bbfb..bd80760 100644 --- a/doc/ttk_scrollbar.n +++ b/doc/ttk_scrollbar.n @@ -173,15 +173,13 @@ Dynamic states: \fBactive\fP, \fBdisabled\fP. .br \fB\-bordercolor\fP \fIcolor\fP .br -\fB\-darkcolor\fP \fIcolor\fP (color of the dark 3d relief) +\fB\-darkcolor\fP \fIcolor\fP (color of the dark part of the 3D relief) .br \fB\-foreground\fP \fIcolor\fP .br \fB\-gripcount\fP \fIcount\fP (number of lines on the thumb) .br -\fB\-lightcolor\fP \fIcolor\fP (color of the light 3d relief) -.br -\fB\-sliderlength\fP \fIamount\fP (depreciated, no effect) +\fB\-lightcolor\fP \fIcolor\fP (color of the light part of the 3D relief) .br \fB\-troughcolor\fP \fIcolor\fP .PP -- cgit v0.12 From 2ec7162d109eca92bb2ef89add0826b71e241e95 Mon Sep 17 00:00:00 2001 From: fvogel Date: Fri, 3 May 2019 19:51:54 +0000 Subject: Fix class name in ttk::scale man page (this copy/paste error was introduced in [d0576d63ff]) --- doc/ttk_scale.n | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/ttk_scale.n b/doc/ttk_scale.n index 4e16999..f8f5072 100644 --- a/doc/ttk_scale.n +++ b/doc/ttk_scale.n @@ -93,7 +93,7 @@ corresponding to the current value of the \fB\-value\fR option if \fIvalue\fR is omitted. .SH "STYLING OPTIONS" .PP -The class name for a \fBttk::scale\fP is \fBTProgressbar\fP. +The class name for a \fBttk::scale\fP is \fBTScale\fP. .PP Dynamic states: \fBactive\fP. .PP -- cgit v0.12 From 6b305ada3d3a68c00bc6ddaf163ae327f1c44e05 Mon Sep 17 00:00:00 2001 From: "jan.nijtmans" Date: Thu, 9 May 2019 15:21:43 +0000 Subject: Whitespace cleanup, syncronize a little with "trunk" version. --- generic/tkButton.c | 2 +- generic/tkPlace.c | 2 +- generic/ttk/ttkEntry.c | 2 +- library/button.tcl | 2 +- macosx/tkMacOSXBitmap.c | 2 +- macosx/tkMacOSXButton.c | 5 +++-- macosx/tkMacOSXColor.c | 8 ++++---- macosx/tkMacOSXDefault.h | 7 +++---- macosx/tkMacOSXDialog.c | 2 +- macosx/tkMacOSXInit.c | 3 +-- macosx/tkMacOSXMenu.c | 12 ++++++------ macosx/tkMacOSXMenubutton.c | 2 +- macosx/tkMacOSXMouseEvent.c | 3 +-- macosx/tkMacOSXSubwindows.c | 2 +- macosx/tkMacOSXWindowEvent.c | 2 +- macosx/tkMacOSXWm.c | 4 ++-- macosx/tkMacOSXWm.h | 2 +- macosx/ttkMacOSXTheme.c | 8 ++++---- 18 files changed, 34 insertions(+), 36 deletions(-) diff --git a/generic/tkButton.c b/generic/tkButton.c index dc44189..42d63a7 100644 --- a/generic/tkButton.c +++ b/generic/tkButton.c @@ -1175,7 +1175,7 @@ ConfigureButton( */ if ((butPtr->type == TYPE_RADIO_BUTTON) && - (*Tcl_GetString(butPtr->onValuePtr) == 0)) { + (*Tcl_GetString(butPtr->onValuePtr) == '\0')) { butPtr->flags |= SELECTED; } } diff --git a/generic/tkPlace.c b/generic/tkPlace.c index 1a52114..7aa9b04 100644 --- a/generic/tkPlace.c +++ b/generic/tkPlace.c @@ -695,7 +695,7 @@ ConfigureSlave( Tcl_SetErrorCode(interp, "TK", "GEOMETRY", "LOOP", NULL); goto error; } - + /* * Check for management loops. */ diff --git a/generic/ttk/ttkEntry.c b/generic/ttk/ttkEntry.c index 186ded0..36edf38 100644 --- a/generic/ttk/ttkEntry.c +++ b/generic/ttk/ttkEntry.c @@ -975,7 +975,7 @@ static int EntryConfigure(Tcl_Interp *interp, void *recordPtr, int mask) Ttk_TraceHandle *vt = 0; if (mask & TEXTVAR_CHANGED) { - if (textVarName && *Tcl_GetString(textVarName)) { + if (textVarName && *Tcl_GetString(textVarName) != '\0') { vt = Ttk_TraceVariable(interp, textVarName,EntryTextVariableTrace,entryPtr); if (!vt) return TCL_ERROR; diff --git a/library/button.tcl b/library/button.tcl index 88e26e5..9b13607 100644 --- a/library/button.tcl +++ b/library/button.tcl @@ -753,7 +753,7 @@ proc ::tk::CheckLeave {w} { if {![$w cget -indicatoron] && [info exist Priv($w,selectcolor)]} { if {[$w cget -selectcolor] eq $Priv($w,selectcolor) - || ([info exist Priv($w,aselectcolor)] && + || ([info exist Priv($w,aselectcolor)] && [$w cget -selectcolor] eq $Priv($w,aselectcolor))} { $w configure -selectcolor $Priv($w,selectcolor) } diff --git a/macosx/tkMacOSXBitmap.c b/macosx/tkMacOSXBitmap.c index 1a20bd5..cf46202 100644 --- a/macosx/tkMacOSXBitmap.c +++ b/macosx/tkMacOSXBitmap.c @@ -210,7 +210,7 @@ OSTypeFromString(const char *s, OSType *t) { Tcl_UtfToExternalDString(encoding, s, -1, &ds); if (Tcl_DStringLength(&ds) <= 4) { char string[4] = {}; - memcpy(string, Tcl_DStringValue(&ds), (size_t) Tcl_DStringLength(&ds)); + memcpy(string, Tcl_DStringValue(&ds), Tcl_DStringLength(&ds)); *t = (OSType) string[0] << 24 | (OSType) string[1] << 16 | (OSType) string[2] << 8 | (OSType) string[3]; result = TCL_OK; diff --git a/macosx/tkMacOSXButton.c b/macosx/tkMacOSXButton.c index 25452a4..00c7c9b 100644 --- a/macosx/tkMacOSXButton.c +++ b/macosx/tkMacOSXButton.c @@ -185,7 +185,7 @@ TkpDisplayButton( Pixmap pixmap; DrawParams* dpPtr = &macButtonPtr->drawParams; int needhighlight = 0; - + if (butPtr->flags & BUTTON_DELETED) { return; } @@ -199,7 +199,7 @@ TkpDisplayButton( * Set up clipping region. Make sure the we are using the port * for this button, or we will set the wrong window's clip. */ - + TkMacOSXSetUpClippingRgn(Tk_WindowId(tkwin)); if (TkMacOSXComputeButtonDrawParams(butPtr, dpPtr)) { @@ -1164,6 +1164,7 @@ TkMacOSXComputeButtonDrawParams( * *-------------------------------------------------------------- */ + static void PulseDefaultButtonProc(ClientData clientData) { diff --git a/macosx/tkMacOSXColor.c b/macosx/tkMacOSXColor.c index cb3bde3..f291289 100644 --- a/macosx/tkMacOSXColor.c +++ b/macosx/tkMacOSXColor.c @@ -266,7 +266,7 @@ GetEntryFromPixelCode( static NSColorSpace* deviceRGB = NULL; static CGFloat blueAccentRGBA[4] = {0, 122.0 / 255, 1.0, 1.0}; -static CGFloat windowBackground[4] = +static CGFloat windowBackground[4] = {236.0 / 255, 236.0 / 255, 236.0 / 255, 1.0}; static OSStatus @@ -279,7 +279,7 @@ SetCGColorComponents( NSColor *bgColor, *color; CGFloat rgba[4] = {0, 0, 0, 1}; #if MAC_OS_X_VERSION_MAX_ALLOWED < 101400 - NSInteger colorVariant; + NSInteger colorVariant; static CGFloat graphiteAccentRGBA[4] = {152.0 / 255, 152.0 / 255, 152.0 / 255, 1.0}; #endif @@ -360,7 +360,7 @@ SetCGColorComponents( } else { color = [[NSColor blackColor] colorUsingColorSpace: deviceRGB]; - } + } break; case 6: color = [[NSColor textBackgroundColor] colorUsingColorSpace: @@ -699,7 +699,7 @@ TkMacOSXSetColorInContext( kHIThemeOrientationNormal); break; case HIBackground: - info.kind = entry.value; + info.kind = entry.value; rect = CGContextGetClipBoundingBox(context); err = ChkErr(HIThemeApplyBackground, &rect, &info, context, kHIThemeOrientationNormal); diff --git a/macosx/tkMacOSXDefault.h b/macosx/tkMacOSXDefault.h index 61fee2d..c6d998c 100644 --- a/macosx/tkMacOSXDefault.h +++ b/macosx/tkMacOSXDefault.h @@ -56,7 +56,6 @@ #define DEF_BUTTON_ACTIVE_FG_COLOR ACTIVE_FG #define DEF_CHKRAD_ACTIVE_FG_COLOR DEF_BUTTON_ACTIVE_FG_COLOR #define DEF_BUTTON_ACTIVE_FG_MONO WHITE -/* #define DEF_BUTTON_BG_COLOR "systemButtonFace"*/ #define DEF_BUTTON_BG_COLOR NORMAL_BG #define DEF_BUTTON_BG_MONO WHITE #define DEF_BUTTON_BITMAP "" @@ -184,20 +183,19 @@ #define DEF_ENTRY_FG NORMAL_FG #define DEF_ENTRY_HIGHLIGHT_BG NORMAL_BG #define DEF_ENTRY_HIGHLIGHT BLACK -/* #define DEF_ENTRY_HIGHLIGHT_WIDTH "3" */ #define DEF_ENTRY_HIGHLIGHT_WIDTH "3" #define DEF_ENTRY_INSERT_BG NORMAL_FG #define DEF_ENTRY_INSERT_BD_COLOR "0" #define DEF_ENTRY_INSERT_BD_MONO "0" #define DEF_ENTRY_INSERT_OFF_TIME "300" #define DEF_ENTRY_INSERT_ON_TIME "600" -/* #define DEF_ENTRY_INSERT_WIDTH "2" */ #define DEF_ENTRY_INSERT_WIDTH "1" #define DEF_ENTRY_JUSTIFY "left" +#define DEF_ENTRY_PLACEHOLDER "" +#define DEF_ENTRY_PLACEHOLDERFG "#b3b3b3" #define DEF_ENTRY_READONLY_BG_COLOR NORMAL_BG #define DEF_ENTRY_READONLY_BG_MONO WHITE #define DEF_ENTRY_RELIEF "sunken" -/* #define DEF_ENTRY_RELIEF "solid" */ #define DEF_ENTRY_SCROLL_COMMAND "" #define DEF_ENTRY_SELECT_COLOR SELECT_BG #define DEF_ENTRY_SELECT_MONO BLACK @@ -315,6 +313,7 @@ #define DEF_MENU_ACTIVE_BORDER_WIDTH "0" #define DEF_MENU_ACTIVE_FG_COLOR "systemMenuActiveText" #define DEF_MENU_ACTIVE_FG_MONO WHITE +#define DEF_MENU_ACTIVE_RELIEF "flat" #define DEF_MENU_BG_COLOR "systemMenu" #define DEF_MENU_BG_MONO WHITE #define DEF_MENU_BORDER_WIDTH "0" diff --git a/macosx/tkMacOSXDialog.c b/macosx/tkMacOSXDialog.c index a7997f2..90d0dc7 100644 --- a/macosx/tkMacOSXDialog.c +++ b/macosx/tkMacOSXDialog.c @@ -42,7 +42,7 @@ typedef struct { NSMutableArray *fileTypeExtensions; /* Array of allowed extensions per * name, e.g. "txt", "doc". */ NSMutableArray *fileTypeLabels; /* Displayed string, e.g. "Text - * document (.txt, .doc)". */ + * document (.txt, .doc)". */ NSMutableArray *fileTypeAllowsAll; /* Boolean if the all pattern (*.*) is * included. */ NSMutableArray *allowedExtensions; /* Set of all allowed extensions. */ diff --git a/macosx/tkMacOSXInit.c b/macosx/tkMacOSXInit.c index 89d6983..e403501 100644 --- a/macosx/tkMacOSXInit.c +++ b/macosx/tkMacOSXInit.c @@ -102,7 +102,6 @@ static char scriptPath[PATH_MAX + 1] = ""; _defaultMainMenu = nil; [self _setupMenus]; - /* * Initialize event processing. */ @@ -128,7 +127,7 @@ static char scriptPath[PATH_MAX + 1] = ""; * Process events to ensure that the root window is fully initialized. See * ticket 56a1823c73. */ - + [NSApp _lockAutoreleasePool]; while (Tcl_DoOneEvent(TCL_WINDOW_EVENTS| TCL_DONT_WAIT)) {} [NSApp _unlockAutoreleasePool]; diff --git a/macosx/tkMacOSXMenu.c b/macosx/tkMacOSXMenu.c index 053b374..790b6ff 100644 --- a/macosx/tkMacOSXMenu.c +++ b/macosx/tkMacOSXMenu.c @@ -690,7 +690,7 @@ TkpConfigureMenuEntry( [submenu setTitle:title]; if ([menuItem isEnabled]) { - + /* * This menuItem might have been previously disabled (XXX: * track this), which would have disabled entries; we must @@ -816,7 +816,7 @@ TkpPostMenu( if (itemIndex >= 0) { item = [menu itemAtIndex:itemIndex]; } - + /* * The post commands could have deleted the menu, which means we are dead * and should go away. @@ -1010,8 +1010,8 @@ TkpSetMainMenubar( Tk_Window menubar = NULL; if (winPtr->wmInfoPtr && - winPtr->wmInfoPtr->menuPtr && - winPtr->wmInfoPtr->menuPtr->masterMenuPtr) { + winPtr->wmInfoPtr->menuPtr && + winPtr->wmInfoPtr->menuPtr->masterMenuPtr) { menubar = winPtr->wmInfoPtr->menuPtr->masterMenuPtr->tkwin; } @@ -1037,7 +1037,7 @@ TkpSetMainMenubar( * If we couldn't find a menu, do nothing unless the window belongs to a * different application. In that case, install the default menubar. */ - + if (menu || interp != currentInterp) { [NSApp tkSetMainMenu:menu]; } @@ -1246,7 +1246,7 @@ TkpComputeStandardMenuGeometry( if (menuPtr->tkwin == NULL || menuPtr->masterMenuPtr != menuPtr) { return; } - + menuSize = [(NSMenu *) menuPtr->platformData size]; Tk_GetPixelsFromObj(NULL, menuPtr->tkwin, menuPtr->borderWidthPtr, &borderWidth); diff --git a/macosx/tkMacOSXMenubutton.c b/macosx/tkMacOSXMenubutton.c index 93300a0..dbad8db 100644 --- a/macosx/tkMacOSXMenubutton.c +++ b/macosx/tkMacOSXMenubutton.c @@ -348,7 +348,7 @@ TkpComputeMenuButtonGeometry(butPtr) } } } - + butPtr->inset = highlightWidth + butPtr->borderWidth; width += LEFT_INSET + RIGHT_INSET + 2*butPtr->inset; height += 2*butPtr->inset; diff --git a/macosx/tkMacOSXMouseEvent.c b/macosx/tkMacOSXMouseEvent.c index 2848a52..adc24b1 100644 --- a/macosx/tkMacOSXMouseEvent.c +++ b/macosx/tkMacOSXMouseEvent.c @@ -244,7 +244,7 @@ enum { /* * For scroll wheel events we need to send the XEvent here. */ - + CGFloat delta; int coarseDelta; XEvent xEvent; @@ -685,7 +685,6 @@ TkMacOSXGetCapture(void) return captureWinPtr; } - /* * Local Variables: * mode: objc diff --git a/macosx/tkMacOSXSubwindows.c b/macosx/tkMacOSXSubwindows.c index 853abc2..21f40ce 100644 --- a/macosx/tkMacOSXSubwindows.c +++ b/macosx/tkMacOSXSubwindows.c @@ -168,7 +168,7 @@ XMapWindow( } else { [win orderFrontRegardless]; } - + /* * In some cases the toplevel will not be drawn unless we process * all pending events now. See ticket 56a1823c73. diff --git a/macosx/tkMacOSXWindowEvent.c b/macosx/tkMacOSXWindowEvent.c index 327132c..3eda4ec 100644 --- a/macosx/tkMacOSXWindowEvent.c +++ b/macosx/tkMacOSXWindowEvent.c @@ -896,7 +896,7 @@ RedisplayView( * Make sure that we are not trying to displaying a view that no longer * exists. */ - + for (NSWindow *w in [NSApp orderedWindows]) { if ([w contentView] == view) { [view setNeedsDisplay:YES]; diff --git a/macosx/tkMacOSXWm.c b/macosx/tkMacOSXWm.c index e68f1d5..e69f9ee 100644 --- a/macosx/tkMacOSXWm.c +++ b/macosx/tkMacOSXWm.c @@ -1745,7 +1745,7 @@ WmCommandCmd( } return TCL_OK; } - if (Tcl_GetString(objv[3])[0] == 0) { + if (*Tcl_GetString(objv[3]) == '\0') { if (wmPtr->commandObj != NULL) { Tcl_DecrRefCount(wmPtr->commandObj); wmPtr->commandObj = NULL; @@ -3608,7 +3608,7 @@ WmTransientCmd( } return TCL_OK; } - if (Tcl_GetString(objv[3])[0] == '\0') { + if (*Tcl_GetString(objv[3]) == '\0') { RemoveTransient(winPtr); } else { if (TkGetWindowFromObj(interp, tkwin, objv[3], &master) != TCL_OK) { diff --git a/macosx/tkMacOSXWm.h b/macosx/tkMacOSXWm.h index 5f07fe6..20bbb6d 100644 --- a/macosx/tkMacOSXWm.h +++ b/macosx/tkMacOSXWm.h @@ -43,7 +43,7 @@ typedef struct ProtocolHandler { typedef struct Transient { TkWindow *winPtr; int flags; - struct Transient *nextPtr; + struct Transient *nextPtr; } Transient; #define WITHDRAWN_BY_MASTER 0x1 diff --git a/macosx/ttkMacOSXTheme.c b/macosx/ttkMacOSXTheme.c index 82b94f3..a1d13de 100644 --- a/macosx/ttkMacOSXTheme.c +++ b/macosx/ttkMacOSXTheme.c @@ -276,7 +276,7 @@ static void GetBackgroundColor( /*---------------------------------------------------------------------- * +++ Single Arrow Buttons -- * - * Used in ListHeaders and Comboboxes. + * Used in ListHeaders and Comboboxes. */ static void DrawDownArrow( @@ -326,7 +326,7 @@ static void DrawUpArrow( /*---------------------------------------------------------------------- * +++ Double Arrow Buttons -- * - * Used in MenuButtons and SpinButtons. + * Used in MenuButtons and SpinButtons. */ static void DrawUpDownArrows( @@ -966,7 +966,7 @@ static void DrawDarkTab( CGContextRestoreGState(context); } } else { - + /* * This is the selected tab; paint it blue. If it is first, cover up * the separator line drawn by the second one. (The selected tab is @@ -1144,7 +1144,7 @@ static Ttk_StateTable ButtonValueTable[] = { {kThemeButtonOn, TTK_STATE_SELECTED, 0}, {kThemeButtonOff, 0, 0} - /* + /* * Others: kThemeDisclosureRight, kThemeDisclosureDown, * kThemeDisclosureLeft */ -- cgit v0.12 From 71c5035aac2580da0a2644e9f047364affbe44eb Mon Sep 17 00:00:00 2001 From: "jan.nijtmans" Date: Thu, 9 May 2019 20:50:33 +0000 Subject: =?UTF-8?q?Fran=C3=A7ois=20Vogel=20review=20(thanks!).=20Streamlin?= =?UTF-8?q?e=20UNIX=20defaults=20with=20MAC/WIN=20defaults.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- macosx/tkMacOSXDefault.h | 3 --- unix/tkUnixDefault.h | 7 +++---- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/macosx/tkMacOSXDefault.h b/macosx/tkMacOSXDefault.h index c6d998c..f965d22 100644 --- a/macosx/tkMacOSXDefault.h +++ b/macosx/tkMacOSXDefault.h @@ -191,8 +191,6 @@ #define DEF_ENTRY_INSERT_ON_TIME "600" #define DEF_ENTRY_INSERT_WIDTH "1" #define DEF_ENTRY_JUSTIFY "left" -#define DEF_ENTRY_PLACEHOLDER "" -#define DEF_ENTRY_PLACEHOLDERFG "#b3b3b3" #define DEF_ENTRY_READONLY_BG_COLOR NORMAL_BG #define DEF_ENTRY_READONLY_BG_MONO WHITE #define DEF_ENTRY_RELIEF "sunken" @@ -313,7 +311,6 @@ #define DEF_MENU_ACTIVE_BORDER_WIDTH "0" #define DEF_MENU_ACTIVE_FG_COLOR "systemMenuActiveText" #define DEF_MENU_ACTIVE_FG_MONO WHITE -#define DEF_MENU_ACTIVE_RELIEF "flat" #define DEF_MENU_BG_COLOR "systemMenu" #define DEF_MENU_BG_MONO WHITE #define DEF_MENU_BORDER_WIDTH "0" diff --git a/unix/tkUnixDefault.h b/unix/tkUnixDefault.h index 21f6276..6ca0b6f 100644 --- a/unix/tkUnixDefault.h +++ b/unix/tkUnixDefault.h @@ -31,8 +31,7 @@ #define ACTIVE_BG "#ececec" #define SELECT_BG "#c3c3c3" #define TROUGH "#b3b3b3" -#define CHECK_INDICATOR WHITE -#define MENU_INDICATOR BLACK +#define INDICATOR WHITE #define DISABLED "#a3a3a3" /* @@ -79,7 +78,7 @@ #define DEF_LABCHKRAD_RELIEF "flat" #define DEF_BUTTON_REPEAT_DELAY "0" #define DEF_BUTTON_REPEAT_INTERVAL "0" -#define DEF_BUTTON_SELECT_COLOR CHECK_INDICATOR +#define DEF_BUTTON_SELECT_COLOR INDICATOR #define DEF_BUTTON_SELECT_MONO BLACK #define DEF_BUTTON_SELECT_IMAGE ((char *) NULL) #define DEF_BUTTON_STATE "normal" @@ -284,7 +283,7 @@ #define DEF_MENU_FG BLACK #define DEF_MENU_POST_COMMAND "" #define DEF_MENU_RELIEF "raised" -#define DEF_MENU_SELECT_COLOR MENU_INDICATOR +#define DEF_MENU_SELECT_COLOR BLACK #define DEF_MENU_SELECT_MONO BLACK #define DEF_MENU_TAKE_FOCUS "0" #define DEF_MENU_TEAROFF "1" -- cgit v0.12 From 50b390e8c37fc97708f980d5cdd9fb5480b64e4c Mon Sep 17 00:00:00 2001 From: "jan.nijtmans" Date: Thu, 9 May 2019 22:10:06 +0000 Subject: While on it: A few more whitespaces --- library/ttk/aquaTheme.tcl | 4 ++-- library/ttk/menubutton.tcl | 4 ++-- tests/ttk/treeview.test | 2 +- unix/tcl.m4 | 6 +++--- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/library/ttk/aquaTheme.tcl b/library/ttk/aquaTheme.tcl index 92689d8..d1b0bff 100644 --- a/library/ttk/aquaTheme.tcl +++ b/library/ttk/aquaTheme.tcl @@ -15,7 +15,7 @@ namespace eval ttk::theme::aqua { -insertwidth 1 ttk::style map . \ - -foreground { + -foreground { disabled systemDisabledControlTextColor background systemLabelColor} \ -selectbackground { @@ -89,7 +89,7 @@ namespace eval ttk::theme::aqua { !focus systemTextBackgroundColor focus systemSelectedTextBackgroundColor } - + # Treeview: ttk::style configure Heading \ -font TkHeadingFont \ diff --git a/library/ttk/menubutton.tcl b/library/ttk/menubutton.tcl index c2c5d54..bb947c2 100644 --- a/library/ttk/menubutton.tcl +++ b/library/ttk/menubutton.tcl @@ -97,7 +97,7 @@ if {[tk windowingsystem] eq "aqua"} { } below { set entry "" - incr y $bh + incr y $bh } left { incr y $menuPad @@ -105,7 +105,7 @@ if {[tk windowingsystem] eq "aqua"} { } right { incr y $menuPad - incr x $bw + incr x $bw } default { incr y $bbh diff --git a/tests/ttk/treeview.test b/tests/ttk/treeview.test index a36e3d1..1863a95 100644 --- a/tests/ttk/treeview.test +++ b/tests/ttk/treeview.test @@ -650,7 +650,7 @@ test treeview-3085489-2 "tag remove, no -tags" -setup { test treeview-368fa4561e "indicators cannot be clicked on leafs" -setup { pack [ttk::treeview .tv] - .tv insert {} end -id foo -text "<-- (1) Click the blank space to my left" + .tv insert {} end -id foo -text "<-- (1) Click the blank space to my left" update } -body { foreach {x y w h} [.tv bbox foo #0] {} diff --git a/unix/tcl.m4 b/unix/tcl.m4 index 99f5d29..e0d4778 100644 --- a/unix/tcl.m4 +++ b/unix/tcl.m4 @@ -494,7 +494,7 @@ AC_DEFUN([SC_TCL_FIND_SOURCES],[ set tclh $candidate/generic/tcl.h if {![file exists $tclh]} { - return {} + return {} } set version [tclhversion [cat $tclh]] @@ -506,7 +506,7 @@ AC_DEFUN([SC_TCL_FIND_SOURCES],[ } } - return {} + return {} } proc tclhversion data { @@ -559,7 +559,7 @@ AC_DEFUN([SC_TCL_LINDEX], EOF ` ]] - + ) #------------------------------------------------------------------------ -- cgit v0.12 From 3a509540d384f5f707a39987642f1f111e4bf657 Mon Sep 17 00:00:00 2001 From: dgp Date: Sat, 11 May 2019 20:36:25 +0000 Subject: Tests for Ticket [5d991b822e]. --- tests/button.test | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tests/button.test b/tests/button.test index d4db317..21ccf8f 100644 --- a/tests/button.test +++ b/tests/button.test @@ -3958,6 +3958,33 @@ test button-14.1 {bug fix: [011706ec42] tk::ButtonInvoke unsafe wrt widget destr destroy .top.b .top } -result {} +test button-15.1 {Bug [5d991b822e]} { + # Want this not to segfault + set var INIT + button .b -textvariable var + trace add variable var unset {apply {args { + .b configure -textvariable {} + }}} + pack .b + bind .b {unset var} + update + destroy .b +} {} +test button-15.2 {Bug [5d991b822e]} { + # Want this not to leak traces + set var INIT + button .b -textvariable var + trace add variable var unset {apply {args { + .b configure -textvariable new + }}} + pack .b + bind .b {unset var} + update + destroy .b + unset new +} {} + + imageFinish cleanupTests return -- cgit v0.12 From 6721be522c279e1343d675072819bd1671b40fe8 Mon Sep 17 00:00:00 2001 From: dgp Date: Sat, 11 May 2019 20:53:22 +0000 Subject: Fix for the [button ... -textvariable] parts of [5d991b822e]. --- generic/tkButton.c | 29 ++++++++++++++++++++++++++++- tests/button.test | 2 +- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/generic/tkButton.c b/generic/tkButton.c index b7e314e..0e1a4e9 100644 --- a/generic/tkButton.c +++ b/generic/tkButton.c @@ -1709,7 +1709,34 @@ ButtonTextVarProc( */ if (flags & TCL_TRACE_UNSETS) { - if ((flags & TCL_TRACE_DESTROYED) && !(flags & TCL_INTERP_DESTROYED)) { + if (!Tcl_InterpDeleted(interp) && butPtr->textVarNamePtr != NULL) { + + /* + * An unset trace on some variable brought us here, but is it + * the variable we have stored in butPtr->textVarNamePtr ? + */ + + ClientData probe = NULL; + + do { + probe = Tcl_VarTraceInfo(interp, + Tcl_GetString(butPtr->textVarNamePtr), + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + ButtonTextVarProc, probe); + if (probe == (ClientData)butPtr) { + break; + } + } while (probe); + if (probe) { + /* + * We were able to fetch the unset trace for our + * textVarNamePtr, which means it is not unset and not + * the cause of this unset trace. Instead some outdated + * former textvariable must be, and we should ignore it. + */ + return NULL; + } + Tcl_ObjSetVar2(interp, butPtr->textVarNamePtr, NULL, butPtr->textPtr, TCL_GLOBAL_ONLY); Tcl_TraceVar2(interp, Tcl_GetString(butPtr->textVarNamePtr), diff --git a/tests/button.test b/tests/button.test index 21ccf8f..edc5a42 100644 --- a/tests/button.test +++ b/tests/button.test @@ -3978,7 +3978,7 @@ test button-15.2 {Bug [5d991b822e]} { .b configure -textvariable new }}} pack .b - bind .b {unset var} + bind .b {unset -nocomplain var} update destroy .b unset new -- cgit v0.12 From 01e6edbdb423d22ea06fb1cfafa3fa0691265d07 Mon Sep 17 00:00:00 2001 From: dgp Date: Sun, 12 May 2019 23:15:19 +0000 Subject: Similar test and fix for [checkbutton ... -variable]. --- generic/tkButton.c | 22 +++++++++++++++++++++- tests/button.test | 12 ++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/generic/tkButton.c b/generic/tkButton.c index 0e1a4e9..f3bdbfb 100644 --- a/generic/tkButton.c +++ b/generic/tkButton.c @@ -1617,7 +1617,27 @@ ButtonVarProc( if (flags & TCL_TRACE_UNSETS) { butPtr->flags &= ~(SELECTED | TRISTATED); - if ((flags & TCL_TRACE_DESTROYED) && !(flags & TCL_INTERP_DESTROYED)) { + if (!Tcl_InterpDeleted(interp)) { + ClientData probe = NULL; + + do { + probe = Tcl_VarTraceInfo(interp, + Tcl_GetString(butPtr->selVarNamePtr), + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + ButtonVarProc, probe); + if (probe == (ClientData)butPtr) { + break; + } + } while (probe); + if (probe) { + /* + * We were able to fetch the unset trace for our + * selVarNamePtr, which means it is not unset and not + * the cause of this unset trace. Instead some outdated + * former variable must be, and we should ignore it. + */ + goto redisplay; + } Tcl_TraceVar2(interp, Tcl_GetString(butPtr->selVarNamePtr), NULL, TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, ButtonVarProc, clientData); diff --git a/tests/button.test b/tests/button.test index edc5a42..b953197 100644 --- a/tests/button.test +++ b/tests/button.test @@ -3983,6 +3983,18 @@ test button-15.2 {Bug [5d991b822e]} { destroy .b unset new } {} +test button-15.3 {Bug [5d991b822e]} { + # Want this not to leak traces + set var INIT + checkbutton .b -variable var + trace add variable var unset {apply {args { + .b configure -variable {} + }}} + pack .b + bind .b {unset var} + update + destroy .b +} {} imageFinish -- cgit v0.12 From 8760f6459a6dc7b1902f830af8bcb4b1bbdca2d5 Mon Sep 17 00:00:00 2001 From: dgp Date: Sun, 12 May 2019 23:56:49 +0000 Subject: Similar tests and fix for [entry .... -textvariable] --- generic/tkEntry.c | 24 ++++++++++++++++++++++-- tests/entry.test | 28 ++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/generic/tkEntry.c b/generic/tkEntry.c index 25774cc..0817952 100644 --- a/generic/tkEntry.c +++ b/generic/tkEntry.c @@ -3155,14 +3155,34 @@ EntryTextVarProc( */ if (flags & TCL_TRACE_UNSETS) { - if ((flags & TCL_TRACE_DESTROYED) && !(flags & TCL_INTERP_DESTROYED)) { + if (!Tcl_InterpDeleted(interp) && entryPtr->textVarName) { + ClientData probe = NULL; + + do { + probe = Tcl_VarTraceInfo(interp, + entryPtr->textVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + EntryTextVarProc, probe); + if (probe == (ClientData)entryPtr) { + break; + } + } while (probe); + if (probe) { + /* + * We were able to fetch the unset trace for our + * textVarName, which means it is not unset and not + * the cause of this unset trace. Instead some outdated + * former variable must be, and we should ignore it. + */ + return NULL; + } Tcl_SetVar2(interp, entryPtr->textVarName, NULL, entryPtr->string, TCL_GLOBAL_ONLY); Tcl_TraceVar2(interp, entryPtr->textVarName, NULL, TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, EntryTextVarProc, clientData); entryPtr->flags |= ENTRY_VAR_TRACED; - } + } return NULL; } diff --git a/tests/entry.test b/tests/entry.test index fbaf6a5..67f8374 100644 --- a/tests/entry.test +++ b/tests/entry.test @@ -3502,6 +3502,34 @@ test entry-24.1 {textvariable lives in a non-existing namespace} -setup { destroy .e } -result {can't trace "thisnsdoesntexist::myvar": parent namespace doesn't exist} +test entry-25.1 {Bug [5d991b822e]} { + # Want this not to segfault, or write to variable with empty name + set var INIT + entry .b -textvariable var + trace add variable var unset {apply {args { + .b configure -textvariable {} + }}} + pack .b + bind .b {unset var} + update + destroy .b + info exists {} +} 0 +test entry-25.2 {Bug [5d991b822e]} { + # Want this not to leak traces + set var INIT + entry .b -textvariable var + trace add variable var unset {apply {args { + .b configure -textvariable new + }}} + pack .b + bind .b {unset -nocomplain var} + update + destroy .b + unset new +} {} + + # Gathered comments about lacks # XXX Still need to write tests for EntryBlinkProc, EntryFocusProc, # and EntryTextVarProc. -- cgit v0.12 From 0be716f0f282bf6e937b7ad2a8beb171b51d1659 Mon Sep 17 00:00:00 2001 From: fvogel Date: Mon, 13 May 2019 09:26:32 +0000 Subject: Fix [caa8cb25a8]: spelling fix in comment of tkMenuDraw.c --- generic/tkMenuDraw.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/generic/tkMenuDraw.c b/generic/tkMenuDraw.c index bd00d38..d91bc11 100644 --- a/generic/tkMenuDraw.c +++ b/generic/tkMenuDraw.c @@ -475,7 +475,7 @@ TkRecomputeMenu( * None. * * Side effects: - * A when-idle hander is scheduled to do the redisplay, if there isn't + * A when-idle handler is scheduled to do the redisplay, if there isn't * one already scheduled. * *---------------------------------------------------------------------- -- cgit v0.12 From ce0292947c3d5a70d1c78251dfdf5f47bc752924 Mon Sep 17 00:00:00 2001 From: "jan.nijtmans" Date: Mon, 13 May 2019 22:19:00 +0000 Subject: Fix gcc-8 warning --- generic/tkText.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/generic/tkText.c b/generic/tkText.c index d4f780c..551ef5e 100644 --- a/generic/tkText.c +++ b/generic/tkText.c @@ -2780,7 +2780,7 @@ TextPushUndoAction( int canUndo, canRedo; char lMarkName[20] = "tk::undoMarkL"; char rMarkName[20] = "tk::undoMarkR"; - char stringUndoMarkId[7] = ""; + char stringUndoMarkId[16] = ""; /* * Create the helpers. -- cgit v0.12 From 8dc126139592299e8d3c5a29e840a9711ca540d1 Mon Sep 17 00:00:00 2001 From: "jan.nijtmans" Date: Wed, 15 May 2019 07:16:46 +0000 Subject: Fix [94eeb111fb]: macos, linux: configuration: unable to build using trunk. For now by reverting [a9c9a75b5ba1f4a6]. --- unix/Makefile.in | 16 ++-- unix/configure | 243 +++++++++++++----------------------------------------- unix/configure.ac | 4 +- unix/tcl.m4 | 134 +----------------------------- win/configure | 14 +++- 5 files changed, 84 insertions(+), 327 deletions(-) diff --git a/unix/Makefile.in b/unix/Makefile.in index 0c331bf..d26ab98 100644 --- a/unix/Makefile.in +++ b/unix/Makefile.in @@ -100,11 +100,11 @@ DEMO_INSTALL_DIR = $(INSTALL_ROOT)@DEMO_DIR@ # The directory containing the Tcl sources and headers appropriate # for this version of Tk ("srcdir" will be replaced or has already # been replaced by the configure script): -TCL_GENERIC_DIR = @TCL_ACTUAL_SRC_DIR@/generic +TCL_GENERIC_DIR = @TCL_SRC_DIR@/generic # The directory containing the platform specific Tcl sources and headers # appropriate for this version of Tk: -TCL_PLATFORM_DIR = @TCL_ACTUAL_SRC_DIR@/unix +TCL_PLATFORM_DIR = @TCL_SRC_DIR@/unix # The directory containing the Tcl library archive file appropriate # for this version of Tk: @@ -310,7 +310,7 @@ GENERIC_DIR = $(TOP_DIR)/generic TTK_DIR = $(GENERIC_DIR)/ttk UNIX_DIR = $(TOP_DIR)/unix BMAP_DIR = $(TOP_DIR)/bitmaps -TOOL_DIR = @TCL_ACTUAL_SRC_DIR@/tools +TOOL_DIR = @TCL_SRC_DIR@/tools TEST_DIR = $(TOP_DIR)/tests MAC_OSX_DIR = $(TOP_DIR)/macosx XLIB_DIR = $(TOP_DIR)/xlib @@ -569,7 +569,7 @@ DEMOPROGS = browse hello ixset rmt rolodex square tcolor timer widget SHELL_ENV = \ @LD_LIBRARY_PATH_VAR@="`pwd`:${TCL_BIN_DIR}:$${@LD_LIBRARY_PATH_VAR@}"; \ export @LD_LIBRARY_PATH_VAR@; \ - TCL_LIBRARY=@TCL_ACTUAL_SRC_DIR@/library; export TCL_LIBRARY; \ + TCL_LIBRARY=@TCL_SRC_DIR@/library; export TCL_LIBRARY; \ TK_LIBRARY=@TK_SRC_DIR@/library; export TK_LIBRARY; all: binaries libraries doc @@ -579,7 +579,7 @@ binaries: ${LIB_FILE} ${WISH_EXE} libraries: $(TOP_DIR)/doc/man.macros: - $(INSTALL_DATA) $(TCLDIR)/doc/man.macros $(TOP_DIR)/doc/man.macros + $(INSTALL_DATA) @TCL_SRC_DIR@/doc/man.macros $(TOP_DIR)/doc/man.macros doc: $(TOP_DIR)/doc/man.macros @@ -685,7 +685,7 @@ demo: # This target can be used to run wish inside either gdb or insight gdb: ${WISH_EXE} @echo "set env @LD_LIBRARY_PATH_VAR@=\"`pwd`:${TCL_BIN_DIR}:$${@LD_LIBRARY_PATH_VAR@}\"" > gdb.run - @echo "set env TCL_LIBRARY=@TCL_ACTUAL_SRC_DIR@/library" >> gdb.run + @echo "set env TCL_LIBRARY=@TCL_SRC_DIR@/library" >> gdb.run @echo "set env TK_LIBRARY=@TK_SRC_DIR@/library" >> gdb.run gdb ./${WISH_EXE} --command=gdb.run rm gdb.run @@ -1566,7 +1566,7 @@ DISTROOT = /tmp/dist DISTNAME = tk${VERSION}${PATCH_LEVEL} ZIPNAME = tk${MAJOR_VERSION}${MINOR_VERSION}${PATCH_LEVEL}-src.zip DISTDIR = $(DISTROOT)/$(DISTNAME) -TCLDIR = @TCL_ACTUAL_SRC_DIR@ +TCLDIR = @TCL_SRC_DIR@ DIST_INSTALL_DATA = CPPROG='cp -p' $(INSTALL) -m 644 DIST_INSTALL_SCRIPT = CPPROG='cp -p' $(INSTALL) -m 755 @@ -1723,7 +1723,7 @@ BUILD_HTML = \ $(SHELL_ENV) TCLSH="$(BUILD_TCLSH)"; else \ TCLSH="$(TCL_EXE)"; fi ;\ "$${TCLSH}" $(TOOL_DIR)/tcltk-man2html.tcl --htmldir="$(HTML_INSTALL_DIR)" \ - --tk --srcdir=$(TOP_DIR) $(BUILD_HTML_FLAGS) + --srcdir=$(TOP_DIR)/.. $(BUILD_HTML_FLAGS) # # The list of all the targets that do not correspond to real files. This stops diff --git a/unix/configure b/unix/configure index 694cde3..0a70642 100755 --- a/unix/configure +++ b/unix/configure @@ -709,6 +709,8 @@ LDFLAGS CFLAGS CC MAN_FLAGS +BUILD_TCLSH +TCLSH_PROG TCL_STUB_LIB_SPEC TCL_STUB_LIB_FLAG TCL_STUB_LIB_FILE @@ -719,11 +721,6 @@ TCL_SRC_DIR TCL_BIN_DIR TCL_PATCH_LEVEL TCL_VERSION -TCL_ACTUAL_SRC_DIR -TCL_SOURCE_MINOR_VERSION -TCL_SOURCE_MAJOR_VERSION -BUILD_TCLSH -TCLSH_PROG target_alias host_alias build_alias @@ -743,6 +740,7 @@ infodir docdir oldincludedir includedir +runstatedir localstatedir sharedstatedir sysconfdir @@ -832,6 +830,7 @@ datadir='${datarootdir}' sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' +runstatedir='${localstatedir}/run' includedir='${prefix}/include' oldincludedir='/usr/include' docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' @@ -1084,6 +1083,15 @@ do | -silent | --silent | --silen | --sile | --sil) silent=yes ;; + -runstatedir | --runstatedir | --runstatedi | --runstated \ + | --runstate | --runstat | --runsta | --runst | --runs \ + | --run | --ru | --r) + ac_prev=runstatedir ;; + -runstatedir=* | --runstatedir=* | --runstatedi=* | --runstated=* \ + | --runstate=* | --runstat=* | --runsta=* | --runst=* | --runs=* \ + | --run=* | --ru=* | --r=*) + runstatedir=$ac_optarg ;; + -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) ac_prev=sbindir ;; -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ @@ -1221,7 +1229,7 @@ fi for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ - libdir localedir mandir + libdir localedir mandir runstatedir do eval ac_val=\$$ac_var # Remove trailing slashes. @@ -1374,6 +1382,7 @@ Fine tuning of the installation directories: --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] + --runstatedir=DIR modifiable per-process data [LOCALSTATEDIR/run] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] @@ -2296,47 +2305,6 @@ LOCALES="cs da de el en en_gb eo es fr hu it nl pl pt ru sv" # Find and load the tclConfig.sh file #-------------------------------------------------------------------- - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for tclsh" >&5 -$as_echo_n "checking for tclsh... " >&6; } - if ${ac_cv_path_tclsh+:} false; then : - $as_echo_n "(cached) " >&6 -else - - search_path=`echo ${PATH} | sed -e 's/:/ /g'` - for dir in $search_path ; do - for j in `ls -r $dir/tclsh[8-9]* 2> /dev/null` \ - `ls -r $dir/tclsh* 2> /dev/null` ; do - if test x"$ac_cv_path_tclsh" = x ; then - if test -f "$j" ; then - ac_cv_path_tclsh=$j - break - fi - fi - done - done - -fi - - - if test -f "$ac_cv_path_tclsh" ; then - TCLSH_PROG="$ac_cv_path_tclsh" - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $TCLSH_PROG" >&5 -$as_echo "$TCLSH_PROG" >&6; } - else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: No tclsh avaliable" >&5 -$as_echo "No tclsh avaliable" >&6; } - fi - - - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for tclsh in Tcl build directory" >&5 -$as_echo_n "checking for tclsh in Tcl build directory... " >&6; } - BUILD_TCLSH="${TCL_BIN_DIR}"/tclsh - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $BUILD_TCLSH" >&5 -$as_echo "$BUILD_TCLSH" >&6; } - - - # # Ok, lets find the tcl configuration @@ -2518,144 +2486,6 @@ $as_echo "could not find ${TCL_BIN_DIR}/tclConfig.sh" >&6; } eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\"" - TCL_ACTUAL_SRC_DIR=` <<-'EOF' "$TCLSH_PROG" - "$srcdir" "$TCL_SRC_DIR" \ - "$TCL_MAJOR_VERSION" "$TCL_MINOR_VERSION" - - proc cat fname { - set chan [open $fname] - try { - read $chan - } finally { - close $chan - } - } - - proc main {argv0 argv} { - try { - lassign $argv -> srcdir tcl_src_dir majortarget minortarget - lappend candidates $tcl_src_dir - set srcdir [file dirname [file normalize $srcdir/...]] - set topsrcdir [file dirname $srcdir] - set sources [file dirname $topsrcdir] - foreach dirname [glob -nocomplain -directory $sources *] { - if {$dirname ni $candidates} { - lappend candidates $dirname - } - } - foreach candidate $candidates { - set res [check $candidate $majortarget $minortarget] - if {$res eq {}} continue else { - puts -nonewline $res - break - } - } - set status 0 - } on error {tres topts} { - puts stderr [dict get $topts -errorinfo] - set status 1 - } - exit $status - } - - proc check {candidate majortarget minortarget} { - set tclh $candidate/generic/tcl.h - - if {![file exists $tclh]} { - return {} - } - - set version [tclhversion [cat $tclh]] - if {[llength $version]} { - lassign $version major minor - if {[package vcompare $major.$minor \ - $majortarget.$minortarget] >= 0} { - return [list $candidate $major $minor] - } - } - - return {} - } - - proc tclhversion data { - if {[regexp -line {^#define\s+_TCL} $data]} { - if {[ - regexp -line {^#define\s+TCL_VERSION\s+\"([^.])+\.([^.\"]+)} \ - $data -> major minor - ]} { - return [list $major $minor] - } - } - return {} - } - main $argv0 $argv - EOF - - ` - - if test "x${TCL_ACTUAL_SRC_DIR}" = x; then - as_fn_error $? "could not find Tcl sources" "$LINENO" 5 - else - TCL_SOURCE_MAJOR_VERSION=` <<-'EOF' "$TCLSH_PROG" - "$TCL_ACTUAL_SRC_DIR " "1" - proc main {argv0 argv} { - try { - lassign $argv -> list index - puts -nonewline [lindex $list $index] - set status 0 - } on error {tres topts} { - puts stderr [dict get $topts -errorinfo] - set status 1 - } - exit $status - } - main $argv0 $argv - EOF - ` - - - - - TCL_SOURCE_MINOR_VERSION=` <<-'EOF' "$TCLSH_PROG" - "$TCL_ACTUAL_SRC_DIR " "2" - proc main {argv0 argv} { - try { - lassign $argv -> list index - puts -nonewline [lindex $list $index] - set status 0 - } on error {tres topts} { - puts stderr [dict get $topts -errorinfo] - set status 1 - } - exit $status - } - main $argv0 $argv - EOF - ` - - - - - TCL_ACTUAL_SRC_DIR=` <<-'EOF' "$TCLSH_PROG" - "$TCL_ACTUAL_SRC_DIR " "0" - proc main {argv0 argv} { - try { - lassign $argv -> list index - puts -nonewline [lindex $list $index] - set status 0 - } on error {tres topts} { - puts stderr [dict get $topts -errorinfo] - set status 1 - } - exit $status - } - main $argv0 $argv - EOF - ` - - - - - fi - - - @@ -2681,6 +2511,49 @@ fi fi + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for tclsh" >&5 +$as_echo_n "checking for tclsh... " >&6; } + if ${ac_cv_path_tclsh+:} false; then : + $as_echo_n "(cached) " >&6 +else + + search_path=`echo ${PATH} | sed -e 's/:/ /g'` + for dir in $search_path ; do + for j in `ls -r $dir/tclsh[8-9]* 2> /dev/null` \ + `ls -r $dir/tclsh* 2> /dev/null` ; do + if test x"$ac_cv_path_tclsh" = x ; then + if test -f "$j" ; then + ac_cv_path_tclsh=$j + break + fi + fi + done + done + +fi + + + if test -f "$ac_cv_path_tclsh" ; then + TCLSH_PROG="$ac_cv_path_tclsh" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $TCLSH_PROG" >&5 +$as_echo "$TCLSH_PROG" >&6; } + else + # It is not an error if an installed version of Tcl can't be located. + TCLSH_PROG="" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: No tclsh found on PATH" >&5 +$as_echo "No tclsh found on PATH" >&6; } + fi + + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for tclsh in Tcl build directory" >&5 +$as_echo_n "checking for tclsh in Tcl build directory... " >&6; } + BUILD_TCLSH="${TCL_BIN_DIR}"/tclsh + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $BUILD_TCLSH" >&5 +$as_echo "$BUILD_TCLSH" >&6; } + + + #------------------------------------------------------------------------ # Handle the --prefix=... option #------------------------------------------------------------------------ diff --git a/unix/configure.ac b/unix/configure.ac index 951eb99..f12d8de 100644 --- a/unix/configure.ac +++ b/unix/configure.ac @@ -32,8 +32,6 @@ LOCALES="cs da de el en en_gb eo es fr hu it nl pl pt ru sv" #-------------------------------------------------------------------- # Find and load the tclConfig.sh file #-------------------------------------------------------------------- -SC_PROG_TCLSH -SC_BUILD_TCLSH SC_PATH_TCLCONFIG SC_LOAD_TCLCONFIG @@ -49,6 +47,8 @@ Found config for Tcl ${TCL_VERSION}]) fi fi +SC_PROG_TCLSH +SC_BUILD_TCLSH #------------------------------------------------------------------------ # Handle the --prefix=... option diff --git a/unix/tcl.m4 b/unix/tcl.m4 index e0d4778..2f114d7 100644 --- a/unix/tcl.m4 +++ b/unix/tcl.m4 @@ -336,8 +336,6 @@ AC_DEFUN([SC_LOAD_TCLCONFIG], [ eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\"" eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\"" - SC_TCL_FIND_SOURCES() - AC_SUBST(TCL_VERSION) AC_SUBST(TCL_PATCH_LEVEL) AC_SUBST(TCL_BIN_DIR) @@ -434,134 +432,6 @@ AC_DEFUN([SC_LOAD_TKCONFIG], [ AC_SUBST(TK_STUB_LIB_SPEC) ]) - -#------------------------------------------------------------------------ -# SC_TCL_FIND_SOURCES -# Find a directory containing Tcl sources that match the version required by -# tclConfig.sh. The sources indicated by tclConfig.sh are preferred. -# -# Arguments: -# none -# -# Results: -# Substitutes the following vars: -# TCL_SOURCE_MAJOR_VERSION -# TCL_SOURCE_MINOR_VERSION -# TCL_ACTUAL_SRC_DIR -#------------------------------------------------------------------------ - -AC_DEFUN([SC_TCL_FIND_SOURCES],[ - [TCL_ACTUAL_SRC_DIR=` <<-'EOF' "$TCLSH_PROG" - "$srcdir" "$TCL_SRC_DIR" \ - "$TCL_MAJOR_VERSION" "$TCL_MINOR_VERSION" - - proc cat fname { - set chan [open $fname] - try { - read $chan - } finally { - close $chan - } - } - - proc main {argv0 argv} { - try { - lassign $argv -> srcdir tcl_src_dir majortarget minortarget - lappend candidates $tcl_src_dir - set srcdir [file dirname [file normalize $srcdir/...]] - set topsrcdir [file dirname $srcdir] - set sources [file dirname $topsrcdir] - foreach dirname [glob -nocomplain -directory $sources *] { - if {$dirname ni $candidates} { - lappend candidates $dirname - } - } - foreach candidate $candidates { - set res [check $candidate $majortarget $minortarget] - if {$res eq {}} continue else { - puts -nonewline $res - break - } - } - set status 0 - } on error {tres topts} { - puts stderr [dict get $topts -errorinfo] - set status 1 - } - exit $status - } - - proc check {candidate majortarget minortarget} { - set tclh $candidate/generic/tcl.h - - if {![file exists $tclh]} { - return {} - } - - set version [tclhversion [cat $tclh]] - if {[llength $version]} { - lassign $version major minor - if {[package vcompare $major.$minor \ - $majortarget.$minortarget] >= 0} { - return [list $candidate $major $minor] - } - } - - return {} - } - - proc tclhversion data { - if {[regexp -line {^#define\s+_TCL} $data]} { - if {[ - regexp -line {^#define\s+TCL_VERSION\s+\"([^.])+\.([^.\"]+)} \ - $data -> major minor - ]} { - return [list $major $minor] - } - } - return {} - } - main $argv0 $argv - EOF - ] - ` - - if test "x${TCL_ACTUAL_SRC_DIR}" = x; then - AC_MSG_ERROR([could not find Tcl sources]) - else - TCL_SOURCE_MAJOR_VERSION=SC_TCL_LINDEX([$TCL_ACTUAL_SRC_DIR] ,1) - AC_SUBST(TCL_SOURCE_MAJOR_VERSION) - TCL_SOURCE_MINOR_VERSION=SC_TCL_LINDEX([$TCL_ACTUAL_SRC_DIR] ,2) - AC_SUBST(TCL_SOURCE_MINOR_VERSION) - TCL_ACTUAL_SRC_DIR=SC_TCL_LINDEX([$TCL_ACTUAL_SRC_DIR] ,0) - AC_SUBST(TCL_ACTUAL_SRC_DIR) - fi -]) - - -#------------------------------------------------------------------------ -# SC_TCL_LINDEX -#------------------------------------------------------------------------ - -AC_DEFUN([SC_TCL_LINDEX], - [[` <<-'EOF' "$TCLSH_PROG" - "$1" "$2" - proc main {argv0 argv} { - try { - lassign $argv -> list index - puts -nonewline [lindex $list $index] - set status 0 - } on error {tres topts} { - puts stderr [dict get $topts -errorinfo] - set status 1 - } - exit $status - } - main $argv0 $argv - EOF - ` - ]] - -) - #------------------------------------------------------------------------ # SC_PROG_TCLSH # Locate a tclsh shell installed on the system path. This macro @@ -603,7 +473,9 @@ AC_DEFUN([SC_PROG_TCLSH], [ TCLSH_PROG="$ac_cv_path_tclsh" AC_MSG_RESULT([$TCLSH_PROG]) else - AC_MSG_RESULT([No tclsh avaliable]) + # It is not an error if an installed version of Tcl can't be located. + TCLSH_PROG="" + AC_MSG_RESULT([No tclsh found on PATH]) fi AC_SUBST(TCLSH_PROG) ]) diff --git a/win/configure b/win/configure index fd50504..87fb43f 100755 --- a/win/configure +++ b/win/configure @@ -740,6 +740,7 @@ infodir docdir oldincludedir includedir +runstatedir localstatedir sharedstatedir sysconfdir @@ -816,6 +817,7 @@ datadir='${datarootdir}' sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' +runstatedir='${localstatedir}/run' includedir='${prefix}/include' oldincludedir='/usr/include' docdir='${datarootdir}/doc/${PACKAGE}' @@ -1068,6 +1070,15 @@ do | -silent | --silent | --silen | --sile | --sil) silent=yes ;; + -runstatedir | --runstatedir | --runstatedi | --runstated \ + | --runstate | --runstat | --runsta | --runst | --runs \ + | --run | --ru | --r) + ac_prev=runstatedir ;; + -runstatedir=* | --runstatedir=* | --runstatedi=* | --runstated=* \ + | --runstate=* | --runstat=* | --runsta=* | --runst=* | --runs=* \ + | --run=* | --ru=* | --r=*) + runstatedir=$ac_optarg ;; + -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) ac_prev=sbindir ;; -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ @@ -1205,7 +1216,7 @@ fi for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ - libdir localedir mandir + libdir localedir mandir runstatedir do eval ac_val=\$$ac_var # Remove trailing slashes. @@ -1358,6 +1369,7 @@ Fine tuning of the installation directories: --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] + --runstatedir=DIR modifiable per-process data [LOCALSTATEDIR/run] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] -- cgit v0.12 From cdb0df2ccb91f62869444148376ce5889bd755b3 Mon Sep 17 00:00:00 2001 From: "jan.nijtmans" Date: Wed, 15 May 2019 07:52:44 +0000 Subject: sync rules.vc and tcl.m4 (both win and unix) with Tcl version --- unix/configure | 6 ------ unix/tcl.m4 | 8 ++------ win/configure | 2 +- win/rules.vc | 54 +++++++++++++++++++++++++++++++++++++++++++++++++----- win/tcl.m4 | 6 +++--- 5 files changed, 55 insertions(+), 21 deletions(-) diff --git a/unix/configure b/unix/configure index 0a70642..66b1581 100755 --- a/unix/configure +++ b/unix/configure @@ -5271,12 +5271,6 @@ fi SHLIB_SUFFIX=".dylib" DL_OBJS="tclLoadDyld.o" DL_LIBS="" - # Don't use -prebind when building for Mac OS X 10.4 or later only: - if test "`echo "${MACOSX_DEPLOYMENT_TARGET}" | awk -F '10\\.' '{print int($2)}'`" -lt 4 -a \ - "`echo "${CPPFLAGS}" | awk -F '-mmacosx-version-min=10\\.' '{print int($2)}'`" -lt 4; then : - - LDFLAGS="$LDFLAGS -prebind" -fi LDFLAGS="$LDFLAGS -headerpad_max_install_names" { $as_echo "$as_me:${as_lineno-$LINENO}: checking if ld accepts -search_paths_first flag" >&5 $as_echo_n "checking if ld accepts -search_paths_first flag... " >&6; } diff --git a/unix/tcl.m4 b/unix/tcl.m4 index 2f114d7..a206f26 100644 --- a/unix/tcl.m4 +++ b/unix/tcl.m4 @@ -1459,10 +1459,6 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [ SHLIB_SUFFIX=".dylib" DL_OBJS="tclLoadDyld.o" DL_LIBS="" - # Don't use -prebind when building for Mac OS X 10.4 or later only: - AS_IF([test "`echo "${MACOSX_DEPLOYMENT_TARGET}" | awk -F '10\\.' '{print int([$]2)}'`" -lt 4 -a \ - "`echo "${CPPFLAGS}" | awk -F '-mmacosx-version-min=10\\.' '{print int([$]2)}'`" -lt 4], [ - LDFLAGS="$LDFLAGS -prebind"]) LDFLAGS="$LDFLAGS -headerpad_max_install_names" AC_CACHE_CHECK([if ld accepts -search_paths_first flag], tcl_cv_ld_search_paths_first, [ @@ -3014,7 +3010,7 @@ AC_DEFUN([SC_ZIPFS_SUPPORT], [ ZIP_PROG="$ac_cv_path_zip" AC_MSG_RESULT([$ZIP_PROG]) ZIP_PROG_OPTIONS="-rq" - ZIP_PROG_VFSSEARCH="." + ZIP_PROG_VFSSEARCH="*" AC_MSG_RESULT([Found INFO Zip in environment]) # Use standard arguments for zip else @@ -3022,7 +3018,7 @@ AC_DEFUN([SC_ZIPFS_SUPPORT], [ # We can use the locally distributed minizip instead ZIP_PROG="./minizip${EXEEXT_FOR_BUILD}" ZIP_PROG_OPTIONS="-o -r" - ZIP_PROG_VFSSEARCH="." + ZIP_PROG_VFSSEARCH="*" ZIP_INSTALL_OBJS="minizip${EXEEXT_FOR_BUILD}" AC_MSG_RESULT([No zip found on PATH. Building minizip]) fi diff --git a/win/configure b/win/configure index 87fb43f..069f4e2 100755 --- a/win/configure +++ b/win/configure @@ -4325,7 +4325,7 @@ $as_echo "using shared flags" >&6; } CFLAGS_DEBUG=-g CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer" - CFLAGS_WARNING="-Wall -Wwrite-strings -Wsign-compare -Wdeclaration-after-statement" + CFLAGS_WARNING="-Wall -Wwrite-strings -Wsign-compare -Wdeclaration-after-statement -Wpointer-arith" LDFLAGS_DEBUG= LDFLAGS_OPTIMIZE= diff --git a/win/rules.vc b/win/rules.vc index fbcb235..1cd0b68 100644 --- a/win/rules.vc +++ b/win/rules.vc @@ -475,6 +475,21 @@ MACHINE = AMD64 MACHINE=$(ARCH) !endif +#--------------------------------------------------------------- +# The PLATFORM_IDENTIFY macro matches the values returned by +# the Tcl platform::identify command +!if "$(MACHINE)" == "AMD64" +PLATFORM_IDENTIFY = win32-x86_64 +!else +PLATFORM_IDENTIFY = win32-ix86 +!endif + +# The MULTIPLATFORM macro controls whether binary extensions are installed +# in platform-specific directories. Intended to be set/used by extensions. +!ifndef MULTIPLATFORM_INSTALL +MULTIPLATFORM_INSTALL = 0 +!endif + #------------------------------------------------------------ # Figure out the *host* architecture by reading the registry @@ -730,6 +745,8 @@ TCL_USE_STATIC_PACKAGES = 1 TCL_USE_STATIC_PACKAGES = 0 !endif +# Yes, it's weird that the "symbols" option controls DEBUG and +# the "pdbs" option controls SYMBOLS. That's historical. !if [nmakehlp -f $(OPTS) "symbols"] !message *** Doing symbols DEBUG = 1 @@ -1205,8 +1222,13 @@ INCLUDE_INSTALL_DIR = $(_INSTALLDIR)\include !else # extension other than Tk PRJ_INSTALL_DIR = $(_INSTALLDIR)\$(PROJECT)$(DOTVERSION) +!if $(MULTIPLATFORM_INSTALL) +LIB_INSTALL_DIR = $(PRJ_INSTALL_DIR)\$(PLATFORM_IDENTIFY) +BIN_INSTALL_DIR = $(PRJ_INSTALL_DIR)\$(PLATFORM_IDENTIFY) +!else LIB_INSTALL_DIR = $(PRJ_INSTALL_DIR) BIN_INSTALL_DIR = $(PRJ_INSTALL_DIR) +!endif DOC_INSTALL_DIR = $(PRJ_INSTALL_DIR) SCRIPT_INSTALL_DIR = $(PRJ_INSTALL_DIR) DEMO_INSTALL_DIR = $(PRJ_INSTALL_DIR)\demos @@ -1480,9 +1502,15 @@ DEFAULT_BUILD_TARGET = $(PROJECT) default-target: $(DEFAULT_BUILD_TARGET) +!if $(MULTIPLATFORM_INSTALL) +default-pkgindex: + @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \ + [list load [file join $$dir $(PLATFORM_IDENTIFY) $(PRJLIBNAME)]] > $(OUT_DIR)\pkgIndex.tcl +!else default-pkgindex: @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \ [list load [file join $$dir $(PRJLIBNAME)]] > $(OUT_DIR)\pkgIndex.tcl +!endif default-pkgindex-tea: @if exist $(ROOT)\pkgIndex.tcl.in nmakehlp -s << $(ROOT)\pkgIndex.tcl.in > $(OUT_DIR)\pkgIndex.tcl @@ -1492,15 +1520,26 @@ default-pkgindex-tea: @PKG_LIB_FILE@ $(PRJLIBNAME) << - default-install: default-install-binaries default-install-libraries +!if $(SYMBOLS) +default-install: default-install-pdbs +!endif +# Again to deal with historical brokenness, there is some confusion +# in terminlogy. For extensions, the "install-binaries" was used to +# locate target directory for *binary shared libraries* and thus +# the appropriate macro is LIB_INSTALL_DIR since BIN_INSTALL_DIR is +# for executables (exes). On the other hand the "install-libraries" +# target is for *scripts* and should have been called "install-scripts". default-install-binaries: $(PRJLIB) - @echo Installing binaries to '$(SCRIPT_INSTALL_DIR)' - @if not exist "$(SCRIPT_INSTALL_DIR)" mkdir "$(SCRIPT_INSTALL_DIR)" - @$(CPY) $(PRJLIB) "$(SCRIPT_INSTALL_DIR)" >NUL + @echo Installing binaries to '$(LIB_INSTALL_DIR)' + @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)" + @$(CPY) $(PRJLIB) "$(LIB_INSTALL_DIR)" >NUL -default-install-libraries: $(OUT_DIR)\pkgIndex.tcl +# Alias for default-install-scripts +default-install-libraries: default-install-scripts + +default-install-scripts: $(OUT_DIR)\pkgIndex.tcl @echo Installing libraries to '$(SCRIPT_INSTALL_DIR)' @if exist $(LIBDIR) $(CPY) $(LIBDIR)\*.tcl "$(SCRIPT_INSTALL_DIR)" @echo Installing package index in '$(SCRIPT_INSTALL_DIR)' @@ -1511,6 +1550,11 @@ default-install-stubs: @if not exist "$(SCRIPT_INSTALL_DIR)" mkdir "$(SCRIPT_INSTALL_DIR)" @$(CPY) $(PRJSTUBLIB) "$(SCRIPT_INSTALL_DIR)" >NUL +default-install-pdbs: + @echo Installing PDBs to '$(LIB_INSTALL_DIR)' + @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)" + @$(CPY) "$(OUT_DIR)\*.pdb" "$(LIB_INSTALL_DIR)\" + default-install-docs-html: @echo Installing documentation files to '$(DOC_INSTALL_DIR)' @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)" diff --git a/win/tcl.m4 b/win/tcl.m4 index a58dc2f..c0dd539 100644 --- a/win/tcl.m4 +++ b/win/tcl.m4 @@ -685,7 +685,7 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [ CFLAGS_DEBUG=-g CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer" - CFLAGS_WARNING="-Wall -Wwrite-strings -Wsign-compare -Wdeclaration-after-statement" + CFLAGS_WARNING="-Wall -Wwrite-strings -Wsign-compare -Wdeclaration-after-statement -Wpointer-arith" LDFLAGS_DEBUG= LDFLAGS_OPTIMIZE= @@ -1270,7 +1270,7 @@ AC_DEFUN([SC_ZIPFS_SUPPORT], [ ZIP_PROG="$ac_cv_path_zip" AC_MSG_RESULT([$ZIP_PROG]) ZIP_PROG_OPTIONS="-rq" - ZIP_PROG_VFSSEARCH="." + ZIP_PROG_VFSSEARCH="*" AC_MSG_RESULT([Found INFO Zip in environment]) # Use standard arguments for zip else @@ -1278,7 +1278,7 @@ AC_DEFUN([SC_ZIPFS_SUPPORT], [ # We can use the locally distributed minizip instead ZIP_PROG="./minizip${EXEEXT_FOR_BUILD}" ZIP_PROG_OPTIONS="-o -r" - ZIP_PROG_VFSSEARCH="." + ZIP_PROG_VFSSEARCH="*" ZIP_INSTALL_OBJS="minizip${EXEEXT_FOR_BUILD}" AC_MSG_RESULT([No zip found on PATH building minizip]) fi -- cgit v0.12 From ada461f65ebad984c9653f530723bd55a847e590 Mon Sep 17 00:00:00 2001 From: culler Date: Wed, 15 May 2019 16:55:50 +0000 Subject: fix bug [d1989fb7cf]: Root window appears before Tk_Mainloop is called. --- macosx/tkMacOSXInit.c | 21 +++++++++++---------- macosx/tkMacOSXSubwindows.c | 9 --------- 2 files changed, 11 insertions(+), 19 deletions(-) diff --git a/macosx/tkMacOSXInit.c b/macosx/tkMacOSXInit.c index e403501..b21e95e 100644 --- a/macosx/tkMacOSXInit.c +++ b/macosx/tkMacOSXInit.c @@ -325,6 +325,17 @@ TkpInit( [pool drain]; [NSApp _setup:interp]; [NSApp finishLaunching]; + Tk_MacOSXSetupTkNotifier(); + + /* + * If the root window is mapped before the App has finished launching + * it will open off screen (see ticket 56a1823c73). To avoid this we + * ask Tk to process an event with no wait. We expect Tcl_DoOneEvent + * to wait until the Mac event loop has been created and then return + * immediately since the queue is empty. + */ + + Tcl_DoOneEvent(TCL_WINDOW_EVENTS| TCL_DONT_WAIT); /* * If we don't have a TTY and stdin is a special character file of @@ -361,8 +372,6 @@ TkpInit( } - Tk_MacOSXSetupTkNotifier(); - if (tkLibPath[0] != '\0') { Tcl_SetVar2(interp, "tk_library", NULL, tkLibPath, TCL_GLOBAL_ONLY); } @@ -377,14 +386,6 @@ TkpInit( Tcl_CreateObjCommand(interp, "::tk::mac::iconBitmap", TkMacOSXIconBitmapObjCmd, NULL, NULL); - /* - * Workaround for 3efbe4a397; console not accepting keyboard input on 10.14 - * if displayed before main window. This places console in background and it - * accepts input after being raised. - */ - - while (Tcl_DoOneEvent(TCL_IDLE_EVENTS)) {} - return TCL_OK; } diff --git a/macosx/tkMacOSXSubwindows.c b/macosx/tkMacOSXSubwindows.c index 21f40ce..2579892 100644 --- a/macosx/tkMacOSXSubwindows.c +++ b/macosx/tkMacOSXSubwindows.c @@ -168,15 +168,6 @@ XMapWindow( } else { [win orderFrontRegardless]; } - - /* - * In some cases the toplevel will not be drawn unless we process - * all pending events now. See ticket 56a1823c73. - */ - - [NSApp _lockAutoreleasePool]; - while (Tcl_DoOneEvent(TCL_WINDOW_EVENTS| TCL_DONT_WAIT)) {} - [NSApp _unlockAutoreleasePool]; } else { TkWindow *contWinPtr = TkpGetOtherWindow(winPtr); -- cgit v0.12 From 7f33552ef446220a57674a0350a829fbf08451de Mon Sep 17 00:00:00 2001 From: dgp Date: Wed, 15 May 2019 17:01:05 +0000 Subject: Tests for same issues with [listbox ... -listvariable]. --- tests/listbox.test | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tests/listbox.test b/tests/listbox.test index 99c84a7..2c07633 100644 --- a/tests/listbox.test +++ b/tests/listbox.test @@ -3177,6 +3177,33 @@ test listbox-31.2 {<> event on lost selection} -setup { destroy .l } -result {{.l 0} {{} {}}} +test listbox-32.1 {Bug [5d991b822e]} { + # Want this not to segfault, or write to variable with empty name + set var INIT + listbox .b -listvariable var + trace add variable var unset {apply {args { + .b configure -listvariable {} + }}} + pack .b + bind .b {unset var} + update + destroy .b + info exists {} +} 0 +test listbox-32.2 {Bug [5d991b822e]} { + # Want this not to leak traces + set var INIT + listbox .b -listvariable var + trace add variable var unset {apply {args { + .b configure -listvariable new + }}} + pack .b + bind .b {unset -nocomplain var} + update + destroy .b + unset new +} {} + resetGridInfo deleteWindows option clear -- cgit v0.12 From 9c596d150ad96b9e928fb86d4dad82ebfcefa2d2 Mon Sep 17 00:00:00 2001 From: dgp Date: Wed, 15 May 2019 17:08:01 +0000 Subject: Fix for the failing/crashing listbox tests. --- generic/tkListbox.c | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/generic/tkListbox.c b/generic/tkListbox.c index b18a7f4..de85d51 100644 --- a/generic/tkListbox.c +++ b/generic/tkListbox.c @@ -3445,7 +3445,28 @@ ListboxListVarProc( */ if (flags & TCL_TRACE_UNSETS) { - if ((flags & TCL_TRACE_DESTROYED) && !(flags & TCL_INTERP_DESTROYED)) { + + if (!Tcl_InterpDeleted(interp) && listPtr->listVarName) { + ClientData probe = NULL; + + do { + probe = Tcl_VarTraceInfo(interp, + listPtr->listVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + ListboxListVarProc, probe); + if (probe == (ClientData)listPtr) { + break; + } + } while (probe); + if (probe) { + /* + * We were able to fetch the unset trace for our + * listVarName, which means it is not unset and not + * the cause of this unset trace. Instead some outdated + * former variable must be, and we should ignore it. + */ + return NULL; + } Tcl_SetVar2Ex(interp, listPtr->listVarName, NULL, listPtr->listObj, TCL_GLOBAL_ONLY); Tcl_TraceVar2(interp, listPtr->listVarName, -- cgit v0.12 From 1673645f691d6a028123a612d5476541b8305d91 Mon Sep 17 00:00:00 2001 From: dgp Date: Wed, 15 May 2019 17:16:15 +0000 Subject: Tests and fix for [menubutton ... -textvariable]. --- generic/tkMenubutton.c | 22 +++++++++++++++++++++- tests/menubut.test | 28 ++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/generic/tkMenubutton.c b/generic/tkMenubutton.c index 1a4d5ae..9faa263 100644 --- a/generic/tkMenubutton.c +++ b/generic/tkMenubutton.c @@ -887,7 +887,27 @@ MenuButtonTextVarProc( */ if (flags & TCL_TRACE_UNSETS) { - if ((flags & TCL_TRACE_DESTROYED) && !(flags & TCL_INTERP_DESTROYED)) { + if (!Tcl_InterpDeleted(interp) && mbPtr->textVarName) { + ClientData probe = NULL; + + do { + probe = Tcl_VarTraceInfo(interp, + mbPtr->textVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + MenuButtonTextVarProc, probe); + if (probe == (ClientData)mbPtr) { + break; + } + } while (probe); + if (probe) { + /* + * We were able to fetch the unset trace for our + * textVarName, which means it is not unset and not + * the cause of this unset trace. Instead some outdated + * former variable must be, and we should ignore it. + */ + return NULL; + } Tcl_SetVar2(interp, mbPtr->textVarName, NULL, mbPtr->text, TCL_GLOBAL_ONLY); Tcl_TraceVar2(interp, mbPtr->textVarName, NULL, diff --git a/tests/menubut.test b/tests/menubut.test index 6efdb0f..93b2482 100644 --- a/tests/menubut.test +++ b/tests/menubut.test @@ -747,6 +747,34 @@ test menubutton-8.1 {menubutton vs hidden commands} -body { expr {$res1 eq $res2} } -result 1 +test menubutton-9.1 {Bug [5d991b822e]} { + # Want this not to segfault, or write to variable with empty name + set var INIT + menubutton .b -textvariable var + trace add variable var unset {apply {args { + .b configure -textvariable {} + }}} + pack .b + bind .b {unset var} + update + destroy .b + info exists {} +} 0 +test menubutton-9.2 {Bug [5d991b822e]} { + # Want this not to leak traces + set var INIT + menubutton .b -textvariable var + trace add variable var unset {apply {args { + .b configure -textvariable new + }}} + pack .b + bind .b {unset -nocomplain var} + update + destroy .b + unset new +} {} + + deleteWindows -- cgit v0.12 From 53669ac6b8743ed34a13bcb8d68521966b4d479a Mon Sep 17 00:00:00 2001 From: dgp Date: Wed, 15 May 2019 17:20:54 +0000 Subject: Tests and fix for [message ... -textvariable]. --- generic/tkMessage.c | 22 +++++++++++++++++++++- tests/message.test | 27 +++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/generic/tkMessage.c b/generic/tkMessage.c index 2b71998..1508beb 100644 --- a/generic/tkMessage.c +++ b/generic/tkMessage.c @@ -844,7 +844,27 @@ MessageTextVarProc( */ if (flags & TCL_TRACE_UNSETS) { - if ((flags & TCL_TRACE_DESTROYED) && !(flags & TCL_INTERP_DESTROYED)) { + if (!Tcl_InterpDeleted(interp) && msgPtr->textVarName) { + ClientData probe = NULL; + + do { + probe = Tcl_VarTraceInfo(interp, + msgPtr->textVarName, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + MessageTextVarProc, probe); + if (probe == (ClientData)msgPtr) { + break; + } + } while (probe); + if (probe) { + /* + * We were able to fetch the unset trace for our + * textVarName, which means it is not unset and not + * the cause of this unset trace. Instead some outdated + * former variable must be, and we should ignore it. + */ + return NULL; + } Tcl_SetVar2(interp, msgPtr->textVarName, NULL, msgPtr->string, TCL_GLOBAL_ONLY); Tcl_TraceVar2(interp, msgPtr->textVarName, NULL, diff --git a/tests/message.test b/tests/message.test index dcffc72..cc2e0d0 100644 --- a/tests/message.test +++ b/tests/message.test @@ -470,5 +470,32 @@ test message-3.7 {MessageWidgetObjCmd procedure, "configure"} -setup { destroy .m } -result {4} +test message-4.1 {Bug [5d991b822e]} { + # Want this not to segfault, or write to variable with empty name + set var INIT + message .b -textvariable var + trace add variable var unset {apply {args { + .b configure -textvariable {} + }}} + pack .b + bind .b {unset var} + update + destroy .b + info exists {} +} 0 +test message-4.2 {Bug [5d991b822e]} { + # Want this not to leak traces + set var INIT + message .b -textvariable var + trace add variable var unset {apply {args { + .b configure -textvariable new + }}} + pack .b + bind .b {unset -nocomplain var} + update + destroy .b + unset new +} {} + cleanupTests return -- cgit v0.12 From aefe754799655f3fa04cc84f4ea5d110d0289c46 Mon Sep 17 00:00:00 2001 From: dgp Date: Wed, 15 May 2019 17:30:35 +0000 Subject: Tests and fix for [scale ... -variable]. --- generic/tkScale.c | 23 ++++++++++++++++++++++- tests/scale.test | 26 ++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/generic/tkScale.c b/generic/tkScale.c index ef67630..3920aea 100644 --- a/generic/tkScale.c +++ b/generic/tkScale.c @@ -1198,7 +1198,28 @@ ScaleVarProc( */ if (flags & TCL_TRACE_UNSETS) { - if ((flags & TCL_TRACE_DESTROYED) && !(flags & TCL_INTERP_DESTROYED)) { + + if (!Tcl_InterpDeleted(interp) && scalePtr->varNamePtr) { + ClientData probe = NULL; + + do { + probe = Tcl_VarTraceInfo(interp, + Tcl_GetString(scalePtr->varNamePtr), + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + ScaleVarProc, probe); + if (probe == (ClientData)scalePtr) { + break; + } + } while (probe); + if (probe) { + /* + * We were able to fetch the unset trace for our + * varNamePtr, which means it is not unset and not + * the cause of this unset trace. Instead some outdated + * former variable must be, and we should ignore it. + */ + return NULL; + } Tcl_TraceVar2(interp, Tcl_GetString(scalePtr->varNamePtr), NULL, TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, ScaleVarProc, clientData); diff --git a/tests/scale.test b/tests/scale.test index 79524eb..ba70285 100644 --- a/tests/scale.test +++ b/tests/scale.test @@ -1524,6 +1524,32 @@ test scale-21.2 {Bug [55b95f578a] again - Bignum value for -from/-to with scale destroy .s } -result {} +test scale-22.1 {Bug [5d991b822e]} { + # Want this not to crash + set var INIT + scale .b -variable var + trace add variable var unset {apply {args { + .b configure -variable {} + }}} + pack .b + bind .b {unset var} + update + destroy .b +} {} +test scale-22.2 {Bug [5d991b822e]} { + # Want this not to leak traces + set var INIT + scale .b -variable var + trace add variable var unset {apply {args { + .b configure -variable new + }}} + pack .b + bind .b {unset -nocomplain var} + update + destroy .b + unset new +} {} + option clear # cleanup -- cgit v0.12 From 273f03adcc49bca49f4941c8adb241b5ccc26c25 Mon Sep 17 00:00:00 2001 From: dgp Date: Wed, 15 May 2019 18:05:47 +0000 Subject: Tests and fix for similar issues in [menu]. --- generic/tkMenu.c | 32 +++++++++++++++++++++++++------- generic/tkScale.c | 1 - tests/menu.test | 28 ++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 8 deletions(-) diff --git a/generic/tkMenu.c b/generic/tkMenu.c index 42ddbd5..d7f5858 100644 --- a/generic/tkMenu.c +++ b/generic/tkMenu.c @@ -2486,9 +2486,10 @@ MenuVarProc( const char *value; const char *name, *onValue; - if (flags & TCL_INTERP_DESTROYED) { + if (Tcl_InterpDeleted(interp) || (mePtr->namePtr == NULL)) { /* - * Do nothing if the interpreter is going away. + * Do nothing if the interpreter is going away or we have + * no variable name. */ return NULL; @@ -2507,12 +2508,29 @@ MenuVarProc( */ if (flags & TCL_TRACE_UNSETS) { + ClientData probe = NULL; mePtr->entryFlags &= ~ENTRY_SELECTED; - if (flags & TCL_TRACE_DESTROYED) { - Tcl_TraceVar2(interp, name, NULL, - TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, - MenuVarProc, clientData); - } + + do { + probe = Tcl_VarTraceInfo(interp, name, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + MenuVarProc, probe); + if (probe == (ClientData)mePtr) { + break; + } + } while (probe); + if (probe) { + /* + * We were able to fetch the unset trace for our + * namePtr, which means it is not unset and not + * the cause of this unset trace. Instead some outdated + * former variable must be, and we should ignore it. + */ + return NULL; + } + Tcl_TraceVar2(interp, name, NULL, + TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, + MenuVarProc, clientData); TkpConfigureMenuEntry(mePtr); TkEventuallyRedrawMenu(menuPtr, NULL); return NULL; diff --git a/generic/tkScale.c b/generic/tkScale.c index 3920aea..4630170 100644 --- a/generic/tkScale.c +++ b/generic/tkScale.c @@ -1198,7 +1198,6 @@ ScaleVarProc( */ if (flags & TCL_TRACE_UNSETS) { - if (!Tcl_InterpDeleted(interp) && scalePtr->varNamePtr) { ClientData probe = NULL; diff --git a/tests/menu.test b/tests/menu.test index 95699ff..9378686 100644 --- a/tests/menu.test +++ b/tests/menu.test @@ -3162,6 +3162,34 @@ test menu-17.5 {MenuVarProc} -setup { } -cleanup { deleteWindows } -result {{} goodbye {}} +test menu-17.6 {MenuVarProc [5d991b822e]} -setup { + deleteWindows +} -body { + # Want this not to crash + menu .b + set var INIT + .b add checkbutton -variable var + trace add variable var unset {apply {args { + .b entryconfigure 1 -variable {} + }}} + unset var +} -cleanup { + deleteWindows +} -result {} +test menu-17.7 {MenuVarProc [5d991b822e]} -setup { + deleteWindows +} -body { + # Want this not to duplicate traces + menu .b + set var INIT + .b add checkbutton -variable var + trace add variable var unset {apply {args { + .b entryconfigure 1 -variable new + }}} + unset var +} -cleanup { + deleteWindows +} -result {} test menu-18.1 {TkActivateMenuEntry} -setup { -- cgit v0.12 From cdf0d2aad93208954b01d2446181854ba1221482 Mon Sep 17 00:00:00 2001 From: dgp Date: Wed, 15 May 2019 20:02:09 +0000 Subject: Make new tests more robust against context. --- tests/menubut.test | 1 + tests/message.test | 1 + 2 files changed, 2 insertions(+) diff --git a/tests/menubut.test b/tests/menubut.test index 9615fa8..4ac5d92 100644 --- a/tests/menubut.test +++ b/tests/menubut.test @@ -753,6 +753,7 @@ test menubutton-8.1 {menubutton vs hidden commands} -body { test menubutton-9.1 {Bug [5d991b822e]} { # Want this not to segfault, or write to variable with empty name + unset -nocomplain {} set var INIT menubutton .b -textvariable var trace add variable var unset {apply {args { diff --git a/tests/message.test b/tests/message.test index cc2e0d0..b90e89c 100644 --- a/tests/message.test +++ b/tests/message.test @@ -472,6 +472,7 @@ test message-3.7 {MessageWidgetObjCmd procedure, "configure"} -setup { test message-4.1 {Bug [5d991b822e]} { # Want this not to segfault, or write to variable with empty name + unset -nocomplain {} set var INIT message .b -textvariable var trace add variable var unset {apply {args { -- cgit v0.12 From 8175c0e93450e5523767039b7f4be7d89e7a63c9 Mon Sep 17 00:00:00 2001 From: culler Date: Thu, 16 May 2019 13:03:28 +0000 Subject: In Aqua, draw dark mode menubuttons as inactive, as is done for buttons. This makes them imperfect, but usable. This is the best we can do as long as HITheme is used for drawing. For correct appearance use ttk::menubutton. --- macosx/tkMacOSXDefault.h | 4 ++-- macosx/tkMacOSXMenubutton.c | 11 +++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/macosx/tkMacOSXDefault.h b/macosx/tkMacOSXDefault.h index f965d22..660b240 100644 --- a/macosx/tkMacOSXDefault.h +++ b/macosx/tkMacOSXDefault.h @@ -335,9 +335,9 @@ #define DEF_MENUBUTTON_ANCHOR "w" #define DEF_MENUBUTTON_ACTIVE_BG_COLOR ACTIVE_BG -#define DEF_MENUBUTTON_ACTIVE_BG_MONO BLACK +#define DEF_MENUBUTTON_ACTIVE_BG_MONO WHITE #define DEF_MENUBUTTON_ACTIVE_FG_COLOR ACTIVE_FG -#define DEF_MENUBUTTON_ACTIVE_FG_MONO WHITE +#define DEF_MENUBUTTON_ACTIVE_FG_MONO BLACK #define DEF_MENUBUTTON_BG_COLOR NORMAL_BG #define DEF_MENUBUTTON_BG_MONO WHITE #define DEF_MENUBUTTON_BITMAP "" diff --git a/macosx/tkMacOSXMenubutton.c b/macosx/tkMacOSXMenubutton.c index dbad8db..53adb01 100644 --- a/macosx/tkMacOSXMenubutton.c +++ b/macosx/tkMacOSXMenubutton.c @@ -580,6 +580,17 @@ TkMacOSXDrawMenuButton( hiinfo.animation.time.start = hiinfo.animation.time.current; } + /* + * To avoid menubuttons with white text on a white background, we + * always set the state to inactive in Dark Mode. It isn't perfect but + * it is usable. Using a ttk::menubutton would be a better choice, + * however. + */ + + if (TkMacOSXInDarkMode(butPtr->tkwin)) { + hiinfo.state = kThemeStateInactive; + } + HIThemeDrawButton(&cntrRect, &hiinfo, dc.context, kHIThemeOrientationNormal, &contHIRec); TkMacOSXRestoreDrawingContext(&dc); -- cgit v0.12