Compare commits

...

29 Commits

Author SHA1 Message Date
Vitaly Provodin
c86c32c8b5 Revert "JBR-4363 Changes in fonts rendering between JBR11 and JBR17"
This reverts commit bfa7a36237.
2022-04-17 07:05:41 +07:00
Vladimir Dvorak
d13b075e7e JBR-4392 - use only loaded classes when collecting affected classes 2022-04-17 03:44:06 +07:00
Vladimir Dvorak
86b7feb77a JBR-4386 - disable AllowEnhancedClassRedefinition in jfr 2022-04-17 03:42:12 +07:00
Vitaly Provodin
9b5ebaaa5a exclude java/awt/Focus/NonFocusableWindowTest/NonfocusableOwnerTest.java due to 8280392 2022-04-16 05:55:55 +07:00
Konstantin Bulenkov
a37db66560 Update JetBrains Mono font to 2.225 2022-04-15 22:32:25 +02:00
Dmitry Batrak
39dd2f608c JBR-4382 [i3] All dialogs are tiled
(cherry picked from commit 800220af16)
2022-04-15 22:27:51 +03:00
Konstantin Bulenkov
890efa0ea8 bundle Inter font 2022-04-14 19:04:47 +02:00
Anton Tarasov
7efb0075bc JBR-4362 [mac] system menu opens with duplicated items
(cherry picked from commit e32defe49d)
2022-04-12 15:50:50 +03:00
Alexey Ushakov
413ff95d63 Removed comma from tag parsing result 2022-04-11 19:41:28 +02:00
Alexey Ushakov
bfa7a36237 JBR-4363 Changes in fonts rendering between JBR11 and JBR17
Resolved merge artifact after applying IDEA-57233 fix
2022-04-11 19:34:30 +02:00
Andrew Leonard
138596467d JBR-4062 8284437: Building from different users/workspace is not always deterministic
Reviewed-by: erikj
(cherry picked from commit 4451257b14)
2022-04-08 10:41:39 +03:00
Dmitry Batrak
f7a0716ccd JBR-4346 [Xfce] Windows are moved unexpectedly between workspaces when modal dialog is shown
(cherry picked from commit ad299f1e74)
2022-04-06 22:41:56 +03:00
Zhengyu Gu
bdb9d3f12f JBR-4360 284023: java.sun.awt.X11GraphicsDevice.getDoubleBufferVisuals() leaks XdbeScreenVisualInfo
Reviewed-by: prr, serb
2022-04-06 16:07:42 +03:00
Maxim Kartashev
1e8d2c0873 JBR-4357 8284033: Leak XVisualInfo in getAllConfigs in awt_GraphicsEnv.c
Reviewed-by: serb, prr
2022-04-04 23:03:35 -07:00
Vladimir Dvorak
360f8f332c Remove version-numbers left over from the merge of dcevm17 2022-04-05 04:38:32 +07:00
Vladimir Dvorak
13512decff JBR-4352 - fix AARCH64 compilation issues
- use correct INCLUDE_JFR condition for jfr code
- exclude jvmtiEnhancedRedefineClasses.cpp if INCLUDE_JVMTI=0
2022-04-02 16:33:54 +01:00
Vitaly Provodin
28ebc0c2e0 excludejava/awt/Mouse/GetMousePositionTest/GetMousePositionWithPopup.java on windows
and java/io/File/createTempFile/SpecialTempFile.java on windows11
2022-04-02 06:29:47 +07:00
Anton Tarasov
9a35ca0b25 JBR-4349 jb/java/awt/Toolkit/LWCToolkitInvokeAndWaitTest.java: Test FAILED! (not found in the log: “lost”) 2022-04-01 21:34:03 +03:00
Anton Tarasov
e424a5bf19 JBR-4347 jb/java/awt/Toolkit/AWTThreadingCMenuTest.java fails by ClassNotFoundException 2022-04-01 21:32:14 +03:00
Alexey Ushakov
ca4d838caf 8273355: Flickering on tooltip appearance IntelliJ IDEA 2021.2.1
Reviewed-by: serb, aghaisas
2022-03-30 20:42:06 +02:00
Alexey Ushakov
6ed5106466 Revert "JBR-3727 JBR17-Metal: Flickering on tooltip appearance"
This reverts commit eaa9c1618e.
2022-03-30 20:27:45 +02:00
Dmitry Batrak
098a50d91a JBR-4334 java/awt/Mouse/MouseModifiersUnitTest/MouseModifiersUnitTest_Extra.java fails
re-fix JBR-4306 in a different way

(cherry picked from commit 3b5ded0d02)
2022-03-30 12:16:24 +03:00
Dmitry Batrak
050990303b JBR-4334 java/awt/Mouse/MouseModifiersUnitTest/MouseModifiersUnitTest_Extra.java fails
revert original fix for JBR-4306

(cherry picked from commit 0f33031484)
2022-03-30 12:16:24 +03:00
Anton Tarasov
9f9416a12e JBR-4328 remove LWCToolkit.unsafeNonblockingExecute
(cherry picked from commit 9a3f31a6c4)
2022-03-28 22:00:59 +03:00
Anton Tarasov
b6cb489fee JBR-4134 PyCharm is slow and unusable on MacBook Pro with M1
(cherry picked from commit 36190505f5)
2022-03-28 22:00:52 +03:00
Anton Tarasov
446535b706 JBR-4284 Sub items of main menu options are not displayed
A regression of JBR-4208 LWCToolkit.invokeAndWait should not stuck on invocation loss

(cherry picked from commit c464e4748e)
2022-03-28 21:59:41 +03:00
Anton Tarasov
c18934bb98 JBR-4119 UI freezes at sun.lwawt.macosx.CAccessibility.getChildrenAndRoles
(cherry picked from commit 6ba79774d8)
2022-03-28 21:59:36 +03:00
Anton Tarasov
e8a6e8bd6e JBR-4106 PyCharm hangs with 100% CPU usage on one core 2022-03-28 21:59:28 +03:00
Mikhail Grishchenko
4a7241931f JBR-3975 print Teamcity messages 2022-03-26 05:32:40 +07:00
54 changed files with 1127 additions and 417 deletions

View File

@@ -31,7 +31,7 @@ architecture=$3 # aarch64 or x64
bundle_type=$(do_maketest)
do_maketest=$?
tag_prefix="jbr-"
OPENJDK_TAG=$(git log --simplify-by-decoration --decorate=short --pretty=short | grep "$tag_prefix" | cut -d "(" -f2 | cut -d ")" -f1 | awk '{print $2}' | sort -t "-" -k 2 -g | tail -n 1)
OPENJDK_TAG=$(git log --simplify-by-decoration --decorate=short --pretty=short | grep "$tag_prefix" | cut -d "(" -f2 | cut -d ")" -f1 | awk '{print $2}' | sort -t "-" -k 2 -g | tail -n 1 | tr -d ",")
VERSION_FEATURE=$(getVersionProp "DEFAULT_VERSION_FEATURE")
VERSION_INTERIM=$(getVersionProp "DEFAULT_VERSION_INTERIM")
VERSION_UPDATE=$(getVersionProp "DEFAULT_VERSION_UPDATE")

View File

@@ -1,5 +1,16 @@
#!/bin/bash
while getopts ":t" o; do
case "${o}" in
t)
t="With Teamcity tests info"
TC_PRINT=1
;;
esac
done
shift $((OPTIND-1))
NEWFILEPATH=$1
CONFIGID=$2
BUILDID=$3
@@ -7,6 +18,7 @@ TOKEN=$4
#
# Get the size of new artifact
#
unameOut="$(uname -s)"
case "${unameOut}" in
Linux*)
@@ -16,7 +28,11 @@ case "${unameOut}" in
NEWFILESIZE=$(stat -f%z "$NEWFILEPATH")
;;
CYGWIN*)
NEWFILESIZE=$(stat -c%s "$NEWFILEPATH")
NEWFILESIZE=$(stat -c%s$4
#
# Get the size of new artifact
#
"$NEWFILEPATH")
;;
MINGW*)
NEWFILESIZE=$(stat -c%s "$NEWFILEPATH")
@@ -26,6 +42,7 @@ case "${unameOut}" in
exit 1
esac
FILENAME=$(basename ${NEWFILEPATH})
#
# Get pattern of artifact name
# Base filename pattern: <BUNDLE_TYPE>-<JDK_VERSION>-<OS>-<ARCH>-b<BUILD>.tar.gz: jbr_dcevm-17.0.2-osx-x64-b1234.tar.gz
@@ -34,16 +51,40 @@ FILENAME=$(basename ${NEWFILEPATH})
BUNDLE_TYPE=jbrsdk
OS_ARCH_PATTERN=""
re='(jbr[a-z_]*).+[0-9_\.]+-(.+)-b.+\.tar\.gz'
FILE_EXTENSION=tar.gz
re='(jbr[a-z_]*).*-[0-9_\.]+-(.+)-b[0-9]+(.+)'
if [[ $FILENAME =~ $re ]]; then
BUNDLE_TYPE=${BASH_REMATCH[1]}
OS_ARCH_PATTERN=${BASH_REMATCH[2]}
FILE_EXTENSION=${BASH_REMATCH[3]}
fi
if [ $TC_PRINT -eq 1 ]; then
testname_file_ext=`echo $FILE_EXTENSION | sed 's/\./_/g'`
testname=$BUNDLE_TYPE"_"$OS_ARCH_PATTERN$testname_file_ext
echo \#\#teamcity[testStarted name=\'$testname\']
fi
echo "BUNDLE_TYPE: " $BUNDLE_TYPE
echo "OS_ARCH_PATTERN: " $OS_ARCH_PATTERN
echo "FILE_EXTENSION: " $FILE_EXTENSION
echo "New size of $FILENAME = $NEWFILESIZE bytes."
function test_failed_msg() {
if [ $3 -eq 1 ]; then
echo \#\#teamcity[testFailed name=\'$1\' message=\'$2\']
fi
}
function test_finished_msg() {
if [ $2 -eq 1 ]; then
echo \#\#teamcity[testFinished name=\'$1\']
fi
}
#
# Get previous successful build ID
# Example:
@@ -62,8 +103,11 @@ if [[ $CURL_RESPONSE =~ $re ]]; then
ID=${BASH_REMATCH[1]}
echo "BUILD Number: ${BASH_REMATCH[2]}"
else
echo "ERROR: can't find previous build"
msg="ERROR: can't find previous build"
echo $msg
echo $CURL_RESPONSE
test_failed_msg $testname $msg $TC_PRINT
test_finished_msg $testname $TC_PRINT
exit 1
fi
@@ -78,7 +122,7 @@ echo "Atrifacts of previous build of $CONFIGID :"
echo $CURL_RESPONSE
# Find binary size (in response) with reg exp
re='name=\"('$BUNDLE_TYPE'[^\"]+'${OS_ARCH_PATTERN}'[^\"]+\.tar\.gz)\" size=\"([0-9]+)\"'
re='name=\"('$BUNDLE_TYPE'[^\"]+'${OS_ARCH_PATTERN}'[^\"]+'${FILE_EXTENSION}')\" size=\"([0-9]+)\"'
if [[ $CURL_RESPONSE =~ $re ]]; then
OLDFILENAME=${BASH_REMATCH[1]}
@@ -89,14 +133,20 @@ if [[ $CURL_RESPONSE =~ $re ]]; then
let allowedSize=OLDFILESIZE+OLDFILESIZE/20 # use 5% threshold
echo "Allowed size = $allowedSize"
if [[ "$NEWFILESIZE" -gt "$allowedSize" ]]; then
echo "ERROR: new size is significally greater than prev size (need to investigate)"
msg="ERROR: new size is significally greater than prev size (need to investigate)"
echo $msg
test_failed_msg $testname $msg $TC_PRINT
test_finished_msg $testname $TC_PRINT
exit 1
else
echo "PASSED"
test_finished_msg $testname $TC_PRINT
fi
else
echo "ERROR: can't find string with size in xml response:"
msg="ERROR: can't find string with size in xml response:"
echo $msg
echo $CURL_RESPONSE
test_failed_msg $testname $msg $TC_PRINT
test_finished_msg $testname $TC_PRINT
exit 1
fi

View File

@@ -95,8 +95,24 @@ AC_DEFUN([FLAGS_SETUP_DEBUG_SYMBOLS],
# info flags for toolchains unless we know they work.
# See JDK-8207057.
ASFLAGS_DEBUG_SYMBOLS=""
# Debug prefix mapping if supported by compiler
DEBUG_PREFIX_CFLAGS=
# Debug symbols
if test "x$TOOLCHAIN_TYPE" = xgcc; then
if test "x$ALLOW_ABSOLUTE_PATHS_IN_OUTPUT" = "xfalse"; then
# Check if compiler supports -fdebug-prefix-map. If so, use that to make
# the debug symbol paths resolve to paths relative to the workspace root.
workspace_root_trailing_slash="${WORKSPACE_ROOT%/}/"
DEBUG_PREFIX_CFLAGS="-fdebug-prefix-map=${workspace_root_trailing_slash}="
FLAGS_COMPILER_CHECK_ARGUMENTS(ARGUMENT: [${DEBUG_PREFIX_CFLAGS}],
IF_FALSE: [
DEBUG_PREFIX_CFLAGS=
]
)
fi
CFLAGS_DEBUG_SYMBOLS="-g"
ASFLAGS_DEBUG_SYMBOLS="-g"
elif test "x$TOOLCHAIN_TYPE" = xclang; then
@@ -108,6 +124,11 @@ AC_DEFUN([FLAGS_SETUP_DEBUG_SYMBOLS],
CFLAGS_DEBUG_SYMBOLS="-Z7"
fi
if test "x$DEBUG_PREFIX_CFLAGS" != x; then
CFLAGS_DEBUG_SYMBOLS="$CFLAGS_DEBUG_SYMBOLS $DEBUG_PREFIX_CFLAGS"
ASFLAGS_DEBUG_SYMBOLS="$ASFLAGS_DEBUG_SYMBOLS $DEBUG_PREFIX_CFLAGS"
fi
AC_SUBST(CFLAGS_DEBUG_SYMBOLS)
AC_SUBST(ASFLAGS_DEBUG_SYMBOLS)
])

View File

@@ -1,55 +0,0 @@
#
# Copyright (c) 2011, 2019, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle in the LICENSE file that accompanied this code.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
# Default version, product, and vendor information to use,
# unless overridden by configure
DEFAULT_VERSION_FEATURE=15
DEFAULT_VERSION_INTERIM=0
DEFAULT_VERSION_UPDATE=0
DEFAULT_VERSION_PATCH=0
DEFAULT_VERSION_EXTRA1=0
DEFAULT_VERSION_EXTRA2=0
DEFAULT_VERSION_EXTRA3=0
DEFAULT_VERSION_DATE=2020-09-15
DEFAULT_VERSION_CLASSFILE_MAJOR=59 # "`$EXPR $DEFAULT_VERSION_FEATURE + 44`"
DEFAULT_VERSION_CLASSFILE_MINOR=0
DEFAULT_ACCEPTABLE_BOOT_VERSIONS="14 15"
DEFAULT_JDK_SOURCE_TARGET_VERSION=15
DEFAULT_PROMOTED_VERSION_PRE=
LAUNCHER_NAME=openjdk
PRODUCT_NAME=OpenJDK
PRODUCT_SUFFIX="Runtime Environment"
JDK_RC_PLATFORM_NAME=Platform
COMPANY_NAME=N/A
HOTSPOT_VM_DISTRO="Dynamic Code Evolution"
VENDOR_URL=https://openjdk.java.net/
VENDOR_URL_BUG=https://bugreport.java.com/bugreport/
VENDOR_URL_VM_BUG=https://bugreport.java.com/bugreport/crash.jsp
# Might need better names for these
MACOSX_BUNDLE_NAME_BASE="OpenJDK"
MACOSX_BUNDLE_ID_BASE="net.java.openjdk"

View File

@@ -1,5 +1,5 @@
#
# Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2011, 2022, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -389,6 +389,12 @@ define SetupCompileNativeFileBody
$1_OBJ_DEPS := $$($1_SRC_FILE) $$($$($1_BASE)_COMPILE_VARDEPS_FILE) \
$$($$($1_BASE)_EXTRA_DEPS) $$($1_VARDEPS_FILE)
$1_COMPILE_OPTIONS := $$($1_FLAGS) $(CC_OUT_OPTION)$$($1_OBJ) $$($1_SRC_FILE)
# For reproducible builds with gcc ensure random symbol generation is seeded deterministically
ifeq ($(TOOLCHAIN_TYPE), gcc)
ifeq ($$(ENABLE_REPRODUCIBLE_BUILD), true)
$1_COMPILE_OPTIONS += -frandom-seed="$$($1_FILENAME)"
endif
endif
$$($1_OBJ_JSON): $$($1_OBJ_DEPS)
$$(call WriteCompileCommandsFragment, $$@, $$(PWD), $$($1_SRC_FILE), \
@@ -1143,6 +1149,19 @@ define SetupNativeCompilationBody
endif
endif
# Debuginfo of ASM objects always embeds the absolute object path,
# as ASM debuginfo paths do not get prefix mapped.
# So for reproducible builds use relative paths to ensure a reproducible
# debuginfo and libs, when creating debug symbols.
ifeq ($$(ENABLE_REPRODUCIBLE_BUILD), true)
ifeq ($(call isTargetOs, linux), true)
ifeq ($$($1_COMPILE_WITH_DEBUG_SYMBOLS), true)
$1_LINK_OBJS_RELATIVE := true
$1_ALL_OBJS_RELATIVE := $$(patsubst $$(OUTPUTDIR)/%, %, $$($1_ALL_OBJS))
endif
endif
endif
$1_TARGET_DEPS := $$($1_ALL_OBJS) $$($1_RES) $$($1_MANIFEST) \
$$($1_REAL_MAPFILE) $$($1_VARDEPS_FILE)

View File

@@ -58,6 +58,9 @@ ifeq ($(call check-jvm-feature, compiler2), true)
ADLC_CFLAGS += -I$(TOPDIR)/src/hotspot/share
# Add file macro mappings
ADLC_CFLAGS += $(FILE_MACRO_CFLAGS)
$(eval $(call SetupNativeCompilation, BUILD_ADLC, \
NAME := adlc, \
TYPE := EXECUTABLE, \

View File

@@ -84,7 +84,7 @@ ifneq ($(call check-jvm-feature, jvmti), true)
jvmtiImpl.cpp jvmtiManageCapabilities.cpp jvmtiRawMonitor.cpp jvmtiUtil.cpp jvmtiTrace.cpp \
jvmtiCodeBlobEvents.cpp jvmtiEnv.cpp jvmtiRedefineClasses.cpp jvmtiEnvBase.cpp jvmtiEnvThreadState.cpp \
jvmtiTagMap.cpp jvmtiEventController.cpp evmCompat.cpp jvmtiEnter.xsl jvmtiExport.cpp \
jvmtiClassFileReconstituter.cpp jvmtiTagMapTable.cpp
jvmtiClassFileReconstituter.cpp jvmtiTagMapTable.cpp jvmtiEnhancedRedefineClasses.cpp
endif
ifneq ($(call check-jvm-feature, jvmci), true)

View File

@@ -1,5 +1,5 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -204,6 +204,10 @@ public class MakeZipReproducible {
entry.setTimeLocal(timestamp);
}
// Ensure "extra" field is not set from original ZipEntry info that may be not deterministic
// eg.may contain specific UID/GID
entry.setExtra(null);
zos.putNextEntry(entry);
if (entry.getSize() > 0 && entryInputStream != null) {
entryInputStream.transferTo(zos);

View File

@@ -335,16 +335,6 @@ void ClassLoaderData::classes_do(KlassClosure* klass_closure) {
}
}
void ClassLoaderData::initialized_classes_do(KlassClosure* klass_closure) {
// Lock-free access requires load_acquire
for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
if (k->is_instance_klass() && InstanceKlass::cast(k)->is_initialized()) {
klass_closure->do_klass(k);
}
assert(k != k->next_link(), "no loops!");
}
}
void ClassLoaderData::classes_do(void f(Klass * const)) {
// Lock-free access requires load_acquire
for (Klass* k = Atomic::load_acquire(&_klasses); k != NULL; k = k->next_link()) {

View File

@@ -272,7 +272,6 @@ class ClassLoaderData : public CHeapObj<mtClass> {
void oops_do(OopClosure* f, int claim_value, bool clear_modified_oops = false);
void classes_do(KlassClosure* klass_closure);
void initialized_classes_do(KlassClosure* klass_closure);
Klass* klasses() { return _klasses; }
JNIMethodBlock* jmethod_ids() const { return _jmethod_ids; }

View File

@@ -361,13 +361,6 @@ void ClassLoaderDataGraph::classes_do(KlassClosure* klass_closure) {
}
}
void ClassLoaderDataGraph::initialized_classes_do(KlassClosure* klass_closure) {
ClassLoaderDataGraphIterator iter;
while (ClassLoaderData* cld = iter.get_next()) {
cld->initialized_classes_do(klass_closure);
}
}
void ClassLoaderDataGraph::classes_do(void f(Klass* const)) {
ClassLoaderDataGraphIterator iter;
while (ClassLoaderData* cld = iter.get_next()) {

View File

@@ -79,9 +79,6 @@ class ClassLoaderDataGraph : public AllStatic {
// Walking the ClassLoaderDataGraph also includes hidden classes.
static void classes_do(KlassClosure* klass_closure);
// Enhanced class redefinition
static void initialized_classes_do(KlassClosure* klass_closure);
static void classes_do(void f(Klass* const));
static void methods_do(void f(Method*));
static void modules_do(void f(ModuleEntry*));

View File

@@ -68,6 +68,7 @@ static bool enable() {
}
_enabled = FlightRecorder;
assert(_enabled, "invariant");
AllowEnhancedClassRedefinition = false;
return _enabled;
}

View File

@@ -2129,6 +2129,11 @@ class AffectedKlassClosure : public KlassClosure {
void do_klass(Klass* klass) {
assert(!_affected_klasses->contains(klass), "must not occur more than once!");
// allow only loaded classes
if (!klass->is_instance_klass() || !InstanceKlass::cast(klass)->is_loaded()) {
return;
}
if (klass->new_version() != NULL) {
return;
}
@@ -2185,12 +2190,8 @@ jvmtiError VM_EnhancedRedefineClasses::find_sorted_affected_classes(TRAPS) {
{
MutexLocker mcld(ClassLoaderDataGraph_lock);
// We can't use ClassLoaderDataGraph::classes_do since classes can be uninitialized in cld,
// fully initialized class is in system dictionary, but hidden classes are excluded. Therefore
// we use special method iterating over initialized classes only
// ClassLoaderDataGraph::classes_do(&closure);
ClassLoaderDataGraph::initialized_classes_do(&closure);
// Hidden classes are not in SystemDictionary, so we have to iterate ClassLoaderDataGraph
ClassLoaderDataGraph::classes_do(&closure);
}
log_trace(redefine, class, load)("%d classes affected", _affected_klasses->length());

View File

@@ -4034,9 +4034,9 @@ jint Arguments::parse(const JavaVMInitArgs* initial_cmd_args) {
// Set object alignment values.
set_object_alignment();
#ifndef ZERO
#if INCLUDE_JFR
if (FlightRecorder) {
if (AllowEnhancedClassRedefinition) {
if (AllowEnhancedClassRedefinition || StartFlightRecording != NULL) {
warning("EnhancedClassRedefinition was disabled, it is not allowed in FlightRecorder.");
AllowEnhancedClassRedefinition = false;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright (c) 2011, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -59,6 +59,7 @@ import java.awt.peer.KeyboardFocusManagerPeer;
import java.awt.peer.WindowPeer;
import java.util.List;
import java.util.Objects;
import javax.swing.JComponent;
import sun.awt.AWTAccessor;
@@ -283,6 +284,16 @@ public class LWWindowPeer
super.disposeImpl();
}
@Override
public void setBackground(final Color c) {
Color oldBg = getBackground();
if (Objects.equals(oldBg, c)) {
return;
}
super.setBackground(c);
updateOpaque();
}
@Override
protected void setVisibleImpl(final boolean visible) {
if (!visible && warningWindow != null) {
@@ -291,10 +302,6 @@ public class LWWindowPeer
updateFocusableWindowState();
super.setVisibleImpl(visible);
// TODO: update graphicsConfig, see 4868278
if (visible) {
// Set correct background for a window before making it visible
platformWindow.setOpaque(!isTranslucent());
}
platformWindow.setVisible(visible);
}

View File

@@ -25,6 +25,7 @@
package sun.lwawt.macosx;
import sun.awt.AWTThreading;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
@@ -64,14 +65,14 @@ public class CMenu extends CMenuItem implements MenuPeer {
LWCToolkit.targetToPeer(getTarget().getParent());
if (parent instanceof CMenu) {
return parent.executeGet(this::nativeCreateSubMenu);
return AWTThreading.executeWaitToolkit(() -> parent.executeGet(this::nativeCreateSubMenu));
}
if (parent instanceof CMenuBar) {
MenuBar parentContainer = (MenuBar)getTarget().getParent();
boolean isHelpMenu = parentContainer.getHelpMenu() == getTarget();
int insertionLocation = ((CMenuBar)parent).getNextInsertionIndex();
return parent.executeGet(ptr -> nativeCreateMenu(ptr, isHelpMenu,
insertionLocation));
return AWTThreading.executeWaitToolkit(() -> parent.executeGet(ptr -> nativeCreateMenu(ptr, isHelpMenu,
insertionLocation)));
}
throw new InternalError("Parent must be CMenu or CMenuBar");
}
@@ -84,7 +85,7 @@ public class CMenu extends CMenuItem implements MenuPeer {
@Override
public final void delItem(final int index) {
execute(ptr -> nativeDeleteItem(ptr, index));
AWTThreading.executeWaitToolkit(() -> execute(ptr -> nativeDeleteItem(ptr, index)));
}
@Override

View File

@@ -33,6 +33,7 @@ import java.awt.event.KeyEvent;
import java.awt.peer.MenuItemPeer;
import java.util.concurrent.atomic.AtomicBoolean;
import sun.awt.AWTThreading;
import sun.awt.SunToolkit;
import sun.lwawt.LWToolkit;
@@ -61,7 +62,7 @@ public class CMenuItem extends CMenuComponent implements MenuItemPeer {
@Override
long createModel() {
CMenuComponent parent = (CMenuComponent)LWToolkit.targetToPeer(getTarget().getParent());
return parent.executeGet(ptr->nativeCreate(ptr, isSeparator()));
return AWTThreading.executeWaitToolkit(() -> parent.executeGet(ptr->nativeCreate(ptr, isSeparator())));
}
@SuppressWarnings("deprecation")
public void setLabel(String label, char keyChar, int keyCode, int modifiers) {

View File

@@ -112,6 +112,7 @@ import sun.lwawt.PlatformComponent;
import sun.lwawt.PlatformDropTarget;
import sun.lwawt.PlatformWindow;
import sun.lwawt.SecurityWarningWindow;
import sun.security.action.GetBooleanAction;
import sun.util.logging.PlatformLogger;
@SuppressWarnings("serial") // JDK implementation class
@@ -141,6 +142,13 @@ public final class LWCToolkit extends LWToolkit {
private static CInputMethodDescriptor sInputMethodDescriptor;
// Listens to EDT state in invokeAndWait() and disposes the invocation event
// when EDT becomes free but the invocation event is not yet dispatched (considered lost).
// This prevents a deadlock and makes the invocation return some default result.
@SuppressWarnings("removal")
private static final boolean DISPOSE_INVOCATION_ON_EDT_FREE =
AccessController.doPrivileged(new GetBooleanAction("sun.lwawt.macosx.LWCToolkit.invokeAndWait.disposeOnEDTFree"));
static {
System.err.flush();
@@ -187,7 +195,7 @@ public final class LWCToolkit extends LWToolkit {
*/
private static final boolean inAWT;
private static final PlatformLogger log = PlatformLogger.getLogger("sun.lwawt.macosx.LWCToolkit");
private static final PlatformLogger log = PlatformLogger.getLogger(LWCToolkit.class.getName());
public LWCToolkit() {
final String extraButtons = "sun.awt.enableExtraMouseButtons";
@@ -496,7 +504,8 @@ public final class LWCToolkit extends LWToolkit {
if (!(gd instanceof CGraphicsDevice)) {
return AWTThreading.executeWaitToolkit(() -> super.getScreenInsets(gc));
}
return AWTThreading.executeWaitToolkit(() -> ((CGraphicsDevice)gd).getScreenInsets());
CGraphicsDevice cgd = (CGraphicsDevice) gd;
return cgd.getScreenInsets();
}
@Override
@@ -711,30 +720,6 @@ public final class LWCToolkit extends LWToolkit {
}
}
private static final AtomicInteger blockingRunLoopCounter = new AtomicInteger(0);
private static final AtomicBoolean priorityInvocationPending = new AtomicBoolean(false);
@Override
public void unsafeNonblockingExecute(Runnable runnable) {
if (!EventQueue.isDispatchThread()) {
throw new Error("the method must be called on the Event Dispatching thread");
}
if (runnable == null) return;
synchronized (priorityInvocationPending) {
priorityInvocationPending.set(true);
}
AWTAccessor.getEventQueueAccessor().createSecondaryLoop(
getSystemEventQueue(),
() -> blockingRunLoopCounter.get() > 0).enter();
try {
runnable.run();
} finally {
priorityInvocationPending.set(false);
}
}
/**
* Kicks an event over to the appropriate eventqueue and waits for it to
* finish To avoid deadlocking, we manually run the NSRunLoop while waiting
@@ -766,11 +751,18 @@ public final class LWCToolkit extends LWToolkit {
log.fine("invokeAndWait started: " + runnable);
}
boolean nonBlockingRunLoop;
synchronized (priorityInvocationPending) {
nonBlockingRunLoop = priorityInvocationPending.get();
if (!nonBlockingRunLoop) blockingRunLoopCounter.incrementAndGet();
if (isBlockingEventDispatchThread()) {
String msg = "invokeAndWait is discarded as the EventDispatch thread is currently blocked";
if (log.isLoggable(PlatformLogger.Level.FINE)) {
log.fine(msg, new Throwable());
log.fine(AWTThreading.getInstance(component).printEventDispatchThreadStackTrace().toString());
} else if (log.isLoggable(PlatformLogger.Level.INFO)) {
StackTraceElement[] stack = new Throwable().getStackTrace();
log.info(msg + ". Originated at " + stack[stack.length - 1]);
Thread dispatchThread = AWTThreading.getInstance(component).getEventDispatchThread();
log.info(dispatchThread.getName() + " at: " + dispatchThread.getStackTrace()[0].toString());
}
return;
}
AWTThreading.TrackedInvocationEvent invocationEvent =
@@ -791,22 +783,21 @@ public final class LWCToolkit extends LWToolkit {
((LWCToolkit)Toolkit.getDefaultToolkit()).getSystemEventQueueForInvokeAndWait().postEvent(invocationEvent);
}
CompletableFuture<Void> eventDispatchThreadFreeFuture =
AWTThreading.getInstance(component).onEventDispatchThreadFree(() -> {
if (!invocationEvent.isDone()) {
// EventQueue is now empty but the posted InvocationEvent is still not dispatched,
// consider it lost then.
invocationEvent.dispose("InvocationEvent was lost");
}
});
invocationEvent.onDone(() -> eventDispatchThreadFreeFuture.cancel(false));
if (!doAWTRunLoop(mediator, nonBlockingRunLoop, timeoutSeconds)) {
invocationEvent.dispose("InvocationEvent has timed out");
if (DISPOSE_INVOCATION_ON_EDT_FREE) {
CompletableFuture<Void> eventDispatchThreadFreeFuture =
AWTThreading.getInstance(component).onEventDispatchThreadFree(() -> {
if (!invocationEvent.isCompleted(true)) {
// EventQueue is now empty but the posted InvocationEvent is still not dispatched,
// consider it lost then.
invocationEvent.dispose("InvocationEvent was lost");
}
});
invocationEvent.onDone(() -> eventDispatchThreadFreeFuture.cancel(false));
}
if (!nonBlockingRunLoop) blockingRunLoopCounter.decrementAndGet();
if (!doAWTRunLoop(mediator, false, timeoutSeconds)) {
invocationEvent.dispose("InvocationEvent has timed out");
}
if (log.isLoggable(PlatformLogger.Level.FINE)) {
log.fine("invokeAndWait finished: " + runnable);
@@ -815,6 +806,8 @@ public final class LWCToolkit extends LWToolkit {
checkException(invocationEvent);
}
private static native boolean isBlockingEventDispatchThread();
public static void invokeLater(Runnable event, Component component)
throws InvocationTargetException {
Objects.requireNonNull(component, "Null component provided to invokeLater");
@@ -857,6 +850,11 @@ public final class LWCToolkit extends LWToolkit {
*/
static native void performOnMainThreadAfterDelay(Runnable r, long delay);
/**
* Schedules a {@code Runnable} execution on the Appkit thread and waits for completion.
*/
public static native void performOnMainThreadAndWait(Runnable r);
// DnD support
@Override

View File

@@ -69,6 +69,9 @@ static int* gsButtonEventNumber;
static NSTimeInterval gNextKeyEventTime;
static NSTimeInterval safeDelay;
#define KEY_CODE_COUNT 128
static CGEventFlags keyOwnFlags[KEY_CODE_COUNT];
static inline CGKeyCode GetCGKeyCode(jint javaKeyCode);
static void PostMouseEvent(const CGPoint point, CGMouseButton button,
@@ -107,6 +110,20 @@ static inline void autoDelay(BOOL isMove) {
gNextKeyEventTime = [[NSDate date] timeIntervalSinceReferenceDate] + safeDelay;
}
static void initKeyFlags() {
CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStatePrivate);
for (CGKeyCode keyCode = 0; keyCode < KEY_CODE_COUNT; keyCode++) {
CGEventRef event = CGEventCreateKeyboardEvent(source, keyCode, true);
if (event != NULL) {
keyOwnFlags[keyCode] = CGEventGetFlags(event);
CFRelease(event);
}
}
if (source != NULL) {
CFRelease(source);
}
}
/*
* Class: sun_lwawt_macosx_CRobot
* Method: initRobot
@@ -155,6 +172,8 @@ Java_sun_lwawt_macosx_CRobot_initRobot
for (i = 0; i < gNumberOfButtons; ++i) {
gsButtonEventNumber[i] = ROBOT_EVENT_NUMBER_START;
}
initKeyFlags();
}];
}
}
@@ -283,6 +302,20 @@ Java_sun_lwawt_macosx_CRobot_mouseWheel
}];
}
// CGEventCreateKeyboardEvent incorrectly handles flags pertinent to non-modifier keys
// (e.g. F1-F12 keys always Fn flag set, while arrow keys always have Fn and NumPad flags set).
// Those flags are not cleared for following key presses automatically, so we need to do it ourselves.
// See JBR-4306 for details.
static void clearStickyFlags(CGEventRef event, CGKeyCode keyCode, CGEventFlags flagToCheck) {
if (keyCode < KEY_CODE_COUNT && (keyOwnFlags[keyCode] & flagToCheck) == 0) {
CGEventFlags flags = CGEventGetFlags(event);
CGEventFlags updatedFlags = flags & ~flagToCheck;
if (updatedFlags != flags) {
CGEventSetFlags(event, updatedFlags);
}
}
}
/*
* Class: sun_lwawt_macosx_CRobot
* Method: keyEvent
@@ -294,8 +327,20 @@ Java_sun_lwawt_macosx_CRobot_keyEvent
{
autoDelay(NO);
[ThreadUtilities performOnMainThreadWaiting:YES block:^(){
CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
CGKeyCode keyCode = GetCGKeyCode(javaKeyCode);
CGPostKeyboardEvent(0, keyCode, keyPressed);
CGEventRef event = CGEventCreateKeyboardEvent(source, keyCode, keyPressed);
if (event != NULL) {
// this assumes Robot isn't used to generate Fn key presses
clearStickyFlags(event, keyCode, kCGEventFlagMaskSecondaryFn);
// there is no NumPad key, so this won't hurt in any case
clearStickyFlags(event, keyCode, kCGEventFlagMaskNumericPad);
CGEventPost(kCGHIDEventTap, event);
CFRelease(event);
}
if (source != NULL) {
CFRelease(source);
}
}];
}

View File

@@ -620,6 +620,17 @@ JNI_COCOA_EXIT(env);
return result;
}
/*
* Class: sun_lwawt_macosx_LWCToolkit
* Method: isBlockingEventDispatchThread
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_sun_lwawt_macosx_LWCToolkit_isBlockingEventDispatchThread
(JNIEnv *env, jclass clz)
{
return ThreadUtilities.blockingEventDispatchThread;
}
/*
* Class: sun_lwawt_macosx_LWCToolkit
* Method: stopAWTRunLoop
@@ -659,6 +670,23 @@ JNI_COCOA_ENTER(env);
JNI_COCOA_EXIT(env);
}
/*
* Class: sun_lwawt_macosx_LWCToolkit
* Method: performOnMainThreadAndWait
* Signature: (Ljava/lang/Runnable)V
*/
JNIEXPORT void JNICALL Java_sun_lwawt_macosx_LWCToolkit_performOnMainThreadAndWait
(JNIEnv *env, jclass clz, jobject runnable)
{
JNI_COCOA_ENTER(env);
jobject gRunnable = (*env)->NewGlobalRef(env, runnable);
CHECK_NULL(gRunnable);
[ThreadUtilities performOnMainThreadWaiting:YES block:^() {
JavaRunnable* performer = [[JavaRunnable alloc] initWithRunnable:gRunnable];
[performer perform];
}];
JNI_COCOA_EXIT(env);
}
/*
* Class: sun_lwawt_macosx_LWCToolkit

View File

@@ -127,6 +127,13 @@ do { \
__attribute__((visibility("default")))
@interface ThreadUtilities : NSObject { } /* Extend NSObject so can call performSelectorOnMainThread */
/*
* When a blocking performSelectorOnMainThread is executed from the EventDispatch thread,
* and the executed code triggers an opposite blocking a11y call (via LWCToolkit.invokeAndWait)
* this is a deadlock case, and then this property is used to discard LWCToolkit.invokeAndWait.
*/
@property (class, nonatomic, readonly) BOOL blockingEventDispatchThread;
+ (JNIEnv*)getJNIEnv;
+ (JNIEnv*)getJNIEnvUncached;
+ (void)detachCurrentThread;

View File

@@ -50,6 +50,24 @@ static inline void attachCurrentThread(void** env) {
@implementation ThreadUtilities
static BOOL _blockingEventDispatchThread = NO;
static long eventDispatchThreadPtr = (long)nil;
static BOOL isEventDispatchThread() {
return (long)[NSThread currentThread] == eventDispatchThreadPtr;
}
// The [blockingEventDispatchThread] property is readonly, so we implement a private setter
static void setBlockingEventDispatchThread(BOOL value) {
assert([NSThread isMainThread]);
_blockingEventDispatchThread = value;
}
+ (BOOL) blockingEventDispatchThread {
assert([NSThread isMainThread]);
return _blockingEventDispatchThread;
}
+ (void)initialize {
/* All the standard modes plus ours */
javaModes = [[NSArray alloc] initWithObjects:NSDefaultRunLoopMode,
@@ -82,10 +100,10 @@ AWT_ASSERT_APPKIT_THREAD;
}
/* This is needed because we can't directly pass a block to
* performSelectorOnMainThreadWaiting .. since it expects a selector
* performSelectorOnMainThreadWaiting:..waitUntilDone:YES.. since it expects a selector
*/
+ (void)invokeBlock:(void (^)())block {
block();
block();
}
/*
@@ -116,7 +134,19 @@ AWT_ASSERT_APPKIT_THREAD;
if ([NSThread isMainThread] && wait == YES) {
[target performSelector:aSelector withObject:arg];
} else {
[target performSelectorOnMainThread:aSelector withObject:arg waitUntilDone:wait modes:javaModes];
if (wait && isEventDispatchThread()) {
void (^block)(void) = ^{
setBlockingEventDispatchThread(YES);
@try {
[target performSelector:aSelector withObject:arg];
} @finally {
setBlockingEventDispatchThread(NO);
}
};
[self performSelectorOnMainThread:@selector(invokeBlock:) withObject:block waitUntilDone:YES modes:javaModes];
} else {
[target performSelectorOnMainThread:aSelector withObject:arg waitUntilDone:wait modes:javaModes];
}
}
}
@@ -143,3 +173,16 @@ JNIEXPORT jboolean JNICALL Java_sun_lwawt_macosx_CThreading_isMainThread
return [NSThread isMainThread];
}
/*
* Class: sun_awt_AWTThreading
* Method: notifyEventDispatchThreadStartedNative
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_sun_awt_AWTThreading_notifyEventDispatchThreadStartedNative
(JNIEnv *env, jclass c)
{
@synchronized([ThreadUtilities class]) {
eventDispatchThreadPtr = (long)[NSThread currentThread];
}
}

View File

@@ -31,6 +31,7 @@ import java.awt.event.WindowEvent;
import java.util.ArrayList;
import sun.awt.AWTThreading;
import sun.util.logging.PlatformLogger;
import sun.awt.dnd.SunDragSourceContextPeer;
@@ -86,6 +87,7 @@ class EventDispatchThread extends Thread {
}
public void run() {
AWTThreading.getInstance(Thread.currentThread()).notifyEventDispatchThreadStarted();
try {
pumpEvents(new Conditional() {
public boolean evaluate() {
@@ -97,6 +99,8 @@ class EventDispatchThread extends Thread {
}
}
private static native void registerEventDispatchThread();
void pumpEvents(Conditional cond) {
pumpEvents(ANY_EVENT, cond);
}

View File

@@ -5,6 +5,8 @@ import sun.util.logging.PlatformLogger;
import java.awt.*;
import java.awt.event.InvocationEvent;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.ref.WeakReference;
import java.security.AccessController;
import java.security.PrivilegedAction;
@@ -14,6 +16,7 @@ import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.function.Consumer;
/**
* Used to perform a cross threads (EventDispatch, Toolkit) execution so that the execution does not cause a deadlock.
@@ -75,14 +78,25 @@ public class AWTThreading {
}
/**
* Same as {@link #executeWaitToolkit(Callable)}, but without returning a value. If requested (as indicated by
* the passed parameter), the invoked native method is supposed to wait for the result of invocation on AppKit
* thread, and vice versa.
* A boolean value passed to the consumer indicates whether the consumer should perform
* a synchronous invocation on the Toolkit thread and wait, or return immediately.
*
* @see #executeWaitToolkit(Callable).
*/
public static void executeWaitToolkit(Task runnable) {
public static void executeWaitToolkit(Consumer<Boolean> consumer) {
boolean wait = EventQueue.isDispatchThread();
executeWaitToolkit(() -> {
runnable.run(wait);
consumer.accept(wait);
return null;
});
}
/**
* @see #executeWaitToolkit(Callable).
*/
public static void executeWaitToolkit(Runnable runnable) {
executeWaitToolkit(() -> {
runnable.run();
return null;
});
}
@@ -102,12 +116,6 @@ public class AWTThreading {
}
}
if (!isEDT && logger.isLoggable(PlatformLogger.Level.FINE)) {
// this can cause deadlock if calling thread is holding a lock which EDT might require (e.g. AWT tree lock)
logger.fine("AWTThreading.executeWaitToolkit invoked from non-EDT thread", new Throwable());
}
// fallback to default
try {
return callable.call();
} catch (Exception e) {
@@ -246,8 +254,8 @@ public class AWTThreading {
private final Throwable throwable = new Throwable();
private final CompletableFuture<Void> futureResult = new CompletableFuture<>();
// dispatched or disposed
private final AtomicBoolean isFinished = new AtomicBoolean(false);
// dispatch or dispose has been started or already completed
private final AtomicBoolean isCompletionStarted = new AtomicBoolean(false);
static TrackedInvocationEvent create(Object source,
Runnable onDispatch,
@@ -265,7 +273,7 @@ public class AWTThreading {
TrackedInvocationEvent thisEvent = eventRef.get();
if (!thisEvent.isDispatched()) {
// If we're here - this {onDone} is being disposed.
thisEvent.finishIfNotYet(() ->
thisEvent.completeIfNotYet(() ->
// If we're here - this {onDone} is called by the outer AWTAccessor.getInvocationEventAccessor().dispose()
// which we do not control, so complete here.
thisEvent.futureResult.completeExceptionally(new Throwable("InvocationEvent was disposed"))
@@ -298,28 +306,42 @@ public class AWTThreading {
@Override
public void dispatch() {
finishIfNotYet(super::dispatch);
futureResult.complete(null);
// Should not complete if competion has already started.
if (completeIfNotYet(super::dispatch)) {
futureResult.complete(null);
}
}
public void dispose(String reason) {
finishIfNotYet(() -> AWTAccessor.getInvocationEventAccessor().dispose(this));
completeIfNotYet(() -> AWTAccessor.getInvocationEventAccessor().dispose(this));
// Should complete exceptionally regardless of whether completetion has alredy started or hasn't.
futureResult.completeExceptionally(new Throwable(reason));
}
private void finishIfNotYet(Runnable finish) {
if (!isFinished.getAndSet(true)) {
finish.run();
private boolean completeIfNotYet(Runnable competeRunnable) {
if (!isCompletionStarted.getAndSet(true)) {
competeRunnable.run();
return true;
}
return false;
}
/**
* Returns whether the event is dispatched or disposed.
*/
public boolean isDone() {
public boolean isCompleted() {
return futureResult.isDone();
}
/**
* Returns whether the event is dispatched or disposed.
* If {@code isCompletionInProgress} is true then also checks whether the event
* dispatching or disposal is in progress and if so returns true.
*/
public boolean isCompleted(boolean isCompletionInProgress) {
return isCompleted() || (isCompletionInProgress && isCompletionStarted.get());
}
/**
* Calls the runnable when it's done (immediately if it's done).
*/
@@ -357,6 +379,19 @@ public class AWTThreading {
return eventDispatchThread;
}
public StringWriter printEventDispatchThreadStackTrace() {
return printEventDispatchThreadStackTrace(new StringWriter());
}
public StringWriter printEventDispatchThreadStackTrace(StringWriter writer) {
assert writer != null;
var printer = new PrintWriter(writer);
Thread dispatchThread = getEventDispatchThread();
printer.println(dispatchThread.getName());
Arrays.asList(dispatchThread.getStackTrace()).forEach(frame -> printer.append("\tat ").println(frame));
return writer;
}
/**
* Sets {@code AWTThreading} instance factory.
* WARNING: for testing purpose.
@@ -365,6 +400,15 @@ public class AWTThreading {
theAWTThreadingFactory.set(factory);
}
/**
* Must be called on the EventDispatch thread.
*/
public void notifyEventDispatchThreadStarted() {
if (FontUtilities.isMacOSX) notifyEventDispatchThreadStartedNative();
}
private static native void notifyEventDispatchThreadStartedNative();
public void notifyEventDispatchThreadFree() {
List<CompletableFuture<Void>> notifiers = Collections.emptyList();
synchronized (eventDispatchThreadStateNotifiers) {
@@ -413,8 +457,4 @@ public class AWTThreading {
future.complete(null);
return future;
}
public interface Task {
void run(boolean wait);
}
}

View File

@@ -351,10 +351,26 @@ public abstract class SunFontManager implements FontSupport, FontManagerForSGE {
jreFamilyMap.put("Roboto-Light", "Roboto Light");
jreFamilyMap.put("Roboto-Thin", "Roboto Thin");
jreFontMap.put("JetBrainsMono-Bold.ttf", new BundledFontInfo("JetBrainsMono-Bold", 1, 0, 2));
jreFontMap.put("JetBrainsMono-Regular.ttf", new BundledFontInfo("JetBrainsMono-Regular", 1, 0, 2));
jreFontMap.put("JetBrainsMono-Italic.ttf", new BundledFontInfo("JetBrainsMono-Italic", 1, 0, 2));
jreFontMap.put("JetBrainsMono-Bold-Italic.ttf", new BundledFontInfo("JetBrainsMono-BoldItalic", 1, 0, 2));
jreFontMap.put("JetBrainsMono-Bold.ttf", new BundledFontInfo("JetBrainsMono-Bold", 2, 225, 0));
jreFontMap.put("JetBrainsMono-Bold-Italic.ttf", new BundledFontInfo("JetBrainsMono-Bold-Italic", 2, 225, 0));
jreFontMap.put("JetBrainsMono-BoldItalic.ttf", new BundledFontInfo("JetBrainsMono-BoldItalic", 2, 225, 0));
jreFontMap.put("JetBrainsMono-ExtraBold.ttf", new BundledFontInfo("JetBrainsMono-ExtraBold", 2, 225, 0));
jreFontMap.put("JetBrainsMono-ExtraBoldItalic.ttf", new BundledFontInfo("JetBrainsMono-ExtraBoldItalic", 2, 225, 0));
jreFontMap.put("JetBrainsMono-ExtraLight.ttf", new BundledFontInfo("JetBrainsMono-ExtraLight", 2, 225, 0));
jreFontMap.put("JetBrainsMono-ExtraLightItalic.ttf", new BundledFontInfo("JetBrainsMono-ExtraLightItalic", 2, 225, 0));
jreFontMap.put("JetBrainsMono-Italic.ttf", new BundledFontInfo("JetBrainsMono-Italic", 2, 225, 0));
jreFontMap.put("JetBrainsMono-Light.ttf", new BundledFontInfo("JetBrainsMono-Light", 2, 225, 0));
jreFontMap.put("JetBrainsMono-LightItalic.ttf", new BundledFontInfo("JetBrainsMono-LightItalic", 2, 225, 0));
jreFontMap.put("JetBrainsMono-Medium.ttf", new BundledFontInfo("JetBrainsMono-Medium", 2, 225, 0));
jreFontMap.put("JetBrainsMono-MediumItalic.ttf", new BundledFontInfo("JetBrainsMono-MediumItalic", 2, 225, 0));
jreFontMap.put("JetBrainsMono-Regular.ttf", new BundledFontInfo("JetBrainsMono-Regular", 2, 225, 0));
jreFontMap.put("JetBrainsMono-Thin.ttf", new BundledFontInfo("JetBrainsMono-Thin", 2, 225, 0));
jreFontMap.put("JetBrainsMono-ThinItalic.ttf", new BundledFontInfo("JetBrainsMono-ThinItalic", 2, 225, 0));
jreFontMap.put("Inter-Bold.otf", new BundledFontInfo("Inter-Bold", 3, 19, 0));
jreFontMap.put("Inter-Regular.otf", new BundledFontInfo("Inter-Regular", 3, 19, 0));
jreFontMap.put("Inter-Italic.otf", new BundledFontInfo("Inter-Italic", 3, 19, 0));
jreFontMap.put("Inter-BoldItalic.otf", new BundledFontInfo("Inter-BoldItalic", 3, 19, 0));
jreBundledFontFiles.addAll(jreFontMap.keySet());
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,94 @@
Copyright (c) 2016-2020 The Inter Project Authors.
"Inter" is trademark of Rasmus Andersson.
https://github.com/rsms/inter
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION AND CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

Binary file not shown.

Binary file not shown.

View File

@@ -65,6 +65,8 @@ class XWindowPeer extends XPanelPeer implements WindowPeer,
static final boolean ENABLE_REPARENTING_CHECK
= "true".equals(GetPropertyAction.privilegedGetProperty("reparenting.check"));
private static final boolean ENABLE_DESKTOP_CHECK
= "true".equals(GetPropertyAction.privilegedGetProperty("transients.desktop.check", "true"));
// should be synchronized on awtLock
private static Set<XWindowPeer> windows = new HashSet<XWindowPeer>();
@@ -95,6 +97,9 @@ class XWindowPeer extends XPanelPeer implements WindowPeer,
private static final AtomicBoolean isStartupNotificationRemoved = new AtomicBoolean();
private Long desktopId; // guarded by AWT lock
private boolean desktopIdInvalid; // guarded by AWT lock
/*
* Focus related flags
*/
@@ -159,6 +164,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer,
params.put(EVENT_MASK, eventMask);
XA_NET_WM_STATE = XAtom.get("_NET_WM_STATE");
XA_NET_WM_DESKTOP = XAtom.get("_NET_WM_DESKTOP");
params.put(OVERRIDE_REDIRECT, Boolean.valueOf(isOverrideRedirect()));
@@ -1730,7 +1736,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer,
if (!allStates && (window.getWMState() != transientForWindow.getWMState())) {
return;
}
if (window.getScreenNumber() != transientForWindow.getScreenNumber()) {
if (screenOrDesktopDiffers(window, transientForWindow)) {
return;
}
long bpw = window.getWindow();
@@ -1767,7 +1773,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer,
void updateTransientFor() {
int state = getWMState();
XWindowPeer p = prevTransientFor;
while ((p != null) && ((p.getWMState() != state) || (p.getScreenNumber() != getScreenNumber()))) {
while ((p != null) && ((p.getWMState() != state) || screenOrDesktopDiffers(p, this))) {
p = p.prevTransientFor;
}
if (p != null) {
@@ -1776,7 +1782,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer,
restoreTransientFor(this);
}
XWindowPeer n = nextTransientFor;
while ((n != null) && ((n.getWMState() != state) || (n.getScreenNumber() != getScreenNumber()))) {
while ((n != null) && ((n.getWMState() != state) || screenOrDesktopDiffers(n, this))) {
n = n.nextTransientFor;
}
if (n != null) {
@@ -1784,6 +1790,43 @@ class XWindowPeer extends XPanelPeer implements WindowPeer,
}
}
private Long getDesktopId() {
XToolkit.awtLock();
try {
if (desktopIdInvalid) {
desktopIdInvalid = false;
desktopId = null;
WindowPropertyGetter getter =
new WindowPropertyGetter(window, XA_NET_WM_DESKTOP, 0, 1, false, XAtom.XA_CARDINAL);
try {
if (getter.execute() == XConstants.Success &&
getter.getActualType() == XAtom.XA_CARDINAL &&
getter.getActualFormat() == 32) {
long ptr = getter.getData();
if (ptr != 0) {
desktopId = Native.getCard32(ptr);
}
}
} finally {
getter.dispose();
}
}
return desktopId;
} finally {
XToolkit.awtUnlock();
}
}
private static boolean screenOrDesktopDiffers(XWindowPeer p1, XWindowPeer p2) {
if (p1.getScreenNumber() != p2.getScreenNumber()) return true;
if (!ENABLE_DESKTOP_CHECK) return false;
Long d1 = p1.getDesktopId();
if (d1 == null) return false;
Long d2 = p2.getDesktopId();
if (d2 == null) return false;
return !d1.equals(d2);
}
/*
* Removes the TRANSIENT_FOR hint from the given top-level window.
* If window or transientForWindow are embedded frames, the containing
@@ -2163,6 +2206,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer,
cachedFocusableWindow = isFocusableWindow();
}
XAtom XA_NET_WM_DESKTOP;
XAtom XA_NET_WM_STATE;
XAtomList net_wm_state;
public XAtomList getNETWMState() {
@@ -2179,6 +2223,18 @@ class XWindowPeer extends XPanelPeer implements WindowPeer,
}
}
@Override
public void handlePropertyNotify(XEvent xev) {
super.handlePropertyNotify(xev);
XPropertyEvent ev = xev.get_xproperty();
if (ev.get_atom() == XA_NET_WM_DESKTOP.getAtom()) {
desktopIdInvalid = true;
if (ENABLE_DESKTOP_CHECK) {
updateTransientFor();
}
}
}
public PropMwmHints getMWMHints() {
if (mwm_hints == null) {
mwm_hints = new PropMwmHints();

View File

@@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -583,6 +583,8 @@ cleanup:
XFree (pVI8sg);
if (n1sg != 0)
XFree (pVI1sg);
if (nTrue != 0)
XFree (pVITrue);
}
/*
@@ -1430,6 +1432,9 @@ Java_sun_awt_X11GraphicsDevice_getDoubleBufferVisuals(JNIEnv *env,
break;
}
}
AWT_LOCK();
XdbeFreeVisualInfo(visScreenInfo);
AWT_UNLOCK();
}
/*

View File

@@ -0,0 +1,71 @@
// Copyright 2000-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
import javax.swing.*;
import java.util.function.Consumer;
import static helper.ToolkitTestHelper.*;
import static helper.ToolkitTestHelper.TestCase.*;
/*
* @test
* @summary tests that CMenu/CMenuItem methods wrapped with {AWTThreading.executeWaitToolkit} are normally callable
* @requires (os.family == "mac")
* @modules java.desktop/sun.lwawt.macosx java.desktop/sun.awt
* @run main/othervm -Dapple.laf.useScreenMenuBar=true AWTThreadingCMenuTest
* @author Anton Tarasov
*/
public class AWTThreadingCMenuTest {
public static void main(String[] args) {
initTest(AWTThreadingCMenuTest.class);
testCase().
withCaption("populate Menu").
withRunnable(AWTThreadingCMenuTest::test1, true).
withExpectedInLog("discarded", false).
withCompletionTimeout(1).
run();
testCase().
withCaption("de-populate Menu").
withRunnable(AWTThreadingCMenuTest::test2, true).
withExpectedInLog("discarded", false).
withCompletionTimeout(1).
run();
System.out.println("Test PASSED");
}
@SuppressWarnings("deprecation")
private static void test1() {
var bar = new JMenuBar();
FRAME.setJMenuBar(bar);
var menu = new JMenu("Menu");
Consumer<String> addItem = text -> {
var item = new JMenuItem(text);
item.setLabel("label " + text);
menu.add(item);
menu.addSeparator();
};
addItem.accept("one");
addItem.accept("two");
addItem.accept("three");
bar.add(menu);
TEST_CASE_RESULT.complete(true);
}
private static void test2() {
var bar = FRAME.getJMenuBar();
var menu = bar.getMenu(0);
for (int i = 0; i < FRAME.getJMenuBar().getMenuCount(); i++) {
menu.remove(i);
}
TEST_CASE_RESULT.complete(true);
}
}

View File

@@ -1,139 +1,188 @@
// Copyright 2000-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
import java.awt.*;
import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.Arrays;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Supplier;
import sun.lwawt.macosx.CThreading;
import sun.lwawt.macosx.LWCToolkit;
import sun.awt.AWTThreading;
import static helper.ToolkitTestHelper.*;
import static helper.ToolkitTestHelper.TestCase.*;
/*
* @test
* @summary tests that AWTThreading can manage a stream of cross EDT/AppKit invocation requests
* @summary tests that AWTThreading can manage cross EDT/AppKit blocking invocation requests
* @requires (os.family == "mac")
* @compile --add-exports=java.desktop/sun.lwawt.macosx=ALL-UNNAMED --add-exports=java.desktop/sun.awt=ALL-UNNAMED AWTThreadingTest.java
* @run main/othervm --add-exports=java.desktop/sun.lwawt.macosx=ALL-UNNAMED --add-exports=java.desktop/sun.awt=ALL-UNNAMED AWTThreadingTest
* @modules java.desktop/sun.lwawt.macosx java.desktop/sun.awt
* @run main AWTThreadingTest
* @author Anton Tarasov
*/
@SuppressWarnings("ConstantConditions")
public class AWTThreadingTest {
static final ReentrantLock LOCK = new ReentrantLock();
static final Condition COND = LOCK.newCondition();
static final CountDownLatch LATCH = new CountDownLatch(1);
static final int TIMEOUT_SECONDS = 1;
static JFrame frame;
static Thread thread;
static final AtomicInteger ITER_COUNTER = new AtomicInteger();
static final AtomicBoolean DUMP_STACK = new AtomicBoolean(false);
final static AtomicBoolean passed = new AtomicBoolean(true);
final static AtomicInteger counter = new AtomicInteger(0);
static volatile Thread THREAD;
public static void main(String[] args) throws InterruptedException {
EventQueue.invokeLater(AWTThreadingTest::runGui);
public static void main(String[] args) {
DUMP_STACK.set(args.length > 0 && "dumpStack".equals(args[0]));
LATCH.await(5, TimeUnit.SECONDS);
initTest(AWTThreadingTest.class);
frame.dispose();
thread.interrupt();
testCase().
withCaption("certain threads superposition").
withRunnable(AWTThreadingTest::test1, false).
run();
testCase().
withCaption("random threads superposition").
withRunnable(AWTThreadingTest::test1, false).
run();
testCase().
withCaption("JBR-4362").
withRunnable(AWTThreadingTest::test2, false).
withCompletionTimeout(3).
run();
if (!passed.get()) {
throw new RuntimeException("Test FAILED!");
}
System.out.println("Test PASSED");
}
static void runGui() {
frame = new JFrame("frame");
frame.getContentPane().setBackground(Color.green);
frame.setLocationRelativeTo(null);
frame.setSize(200, 200);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
startThread();
}
});
frame.setVisible(true);
static void test1() {
ITER_COUNTER.set(0);
var timer = new TestTimer(TIMEOUT_SECONDS * 3, TimeUnit.SECONDS);
EventQueue.invokeLater(() -> startThread(() ->
TEST_CASE_RESULT.isDone() ||
timer.hasFinished()));
waitTestCaseCompletion(TIMEOUT_SECONDS * 4);
tryRun(THREAD::join);
System.out.println(ITER_COUNTER + " iterations passed");
}
static void startThread() {
thread = new Thread(() -> {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
break;
}
static void startThread(Supplier<Boolean> shouldExitLoop) {
THREAD = new Thread(() -> {
while (!shouldExitLoop.get()) {
ITER_COUNTER.incrementAndGet();
var point_1 = new CountDownLatch(1);
var point_2 = new CountDownLatch(1);
var point_3 = new CountDownLatch(1);
var invocations = new CountDownLatch(2);
//
// 1. Execute invokeAndWait() from AppKit to EDT
// 1. Blocking invocation from AppKit to EDT
//
CThreading.executeOnAppKit(() -> {
try {
LWCToolkit.invokeAndWait(counter::incrementAndGet, Window.getWindows()[0]);
} catch (Exception e) {
fail(e);
}
// We're on AppKit, wait for the 2nd invocation to be on the AWTThreading-pool thread.
if (TEST_CASE_NUM == 1) await(point_1, TIMEOUT_SECONDS);
tryRun(() -> LWCToolkit.invokeAndWait(() -> {
// We're being dispatched on EDT.
if (TEST_CASE_NUM == 1) point_2.countDown();
// Wait for the 2nd invocation to be executed on AppKit.
if (TEST_CASE_NUM == 1) await(point_3, TIMEOUT_SECONDS);
}, FRAME));
invocations.countDown();
});
//
// 2. Execute invokeAndBlock() from EDT to AppKit
// 2. Blocking invocation from EDT to AppKit
//
EventQueue.invokeLater(() -> {
passed.set(false);
EventQueue.invokeLater(() -> AWTThreading.executeWaitToolkit(() -> {
// We're on the AWTThreading-pool thread.
if (TEST_CASE_NUM == 1) point_1.countDown();
Boolean success = AWTThreading.executeWaitToolkit(() -> {
try {
return CThreading.executeOnAppKit(() -> Boolean.TRUE);
} catch (Throwable e) {
fail(e);
// Wait for the 1st invocation to start NSRunLoop and be dispatched
if (TEST_CASE_NUM == 1) await(point_2, TIMEOUT_SECONDS);
// Perform in JavaRunLoopMode to be accepted by NSRunLoop started by LWCToolkit.invokeAndWait.
LWCToolkit.performOnMainThreadAndWait(() -> {
if (DUMP_STACK.get()) {
dumpAllThreads();
}
return null;
// We're being executed on AppKit.
if (TEST_CASE_NUM == 1) point_3.countDown();
});
System.out.println("Success: " + counter.get() + ": " + success);
passed.set(Boolean.TRUE.equals(success));
invocations.countDown();
}));
if (passed.get()) {
lock(COND::signal);
}
else {
fail(null);
}
await(invocations, TIMEOUT_SECONDS * 2);
} // while
TEST_CASE_RESULT.complete(true);
});
THREAD.setDaemon(true);
THREAD.start();
}
static void test2() {
var invocations = new CountDownLatch(1);
var invokeAndWaitCompleted = new AtomicBoolean(false);
var log = new Consumer<String>() {
public void accept(String msg) {
System.out.println(msg);
System.out.flush();
}
};
CThreading.executeOnAppKit(() -> {
log.accept("executeOnAppKit - entered");
//
// It's expected that LWCToolkit.invokeAndWait() does not exit before its invocation completes.
//
tryRun(() -> LWCToolkit.invokeAndWait(() -> {
log.accept("\tinvokeAndWait - entered");
AWTThreading.executeWaitToolkit(() -> {
log.accept("\t\texecuteWaitToolkit - entered");
LWCToolkit.performOnMainThreadAndWait(() -> log.accept("\t\t\tperformOnMainThreadAndWait - entered"));
log.accept("\t\t\tperformOnMainThreadAndWait - exited");
});
lock(COND::await);
invokeAndWaitCompleted.set(true);
log.accept("\t\texecuteWaitToolkit - exited");
}, FRAME));
log.accept("\tinvokeAndWait - exited");
if (!invokeAndWaitCompleted.get()) {
TEST_CASE_RESULT.completeExceptionally(new Throwable("Premature exit from invokeAndWait"));
}
invocations.countDown();
});
thread.setDaemon(true);
thread.start();
await(invocations, TIMEOUT_SECONDS * 2);
log.accept("executeOnAppKit + await - exited");
TEST_CASE_RESULT.complete(true);
}
static void lock(MyRunnable runnable) {
LOCK.lock();
try {
try {
runnable.run();
} catch (Exception e) {
e.printStackTrace();
}
} finally {
LOCK.unlock();
}
}
interface MyRunnable {
void run() throws Exception;
}
static void fail(Throwable e) {
if (e != null) e.printStackTrace();
passed.set(false);
LATCH.countDown();
static void dumpAllThreads() {
Thread.getAllStackTraces().keySet().forEach(t -> {
System.out.printf("%s\t%s\t%d\t%s\n", t.getName(), t.getState(), t.getPriority(), t.isDaemon() ? "Daemon" : "Normal");
Arrays.asList(t.getStackTrace()).forEach(frame -> System.out.println("\tat " + frame));
});
System.out.println("\n\n");
}
}

View File

@@ -1,47 +1,46 @@
// Copyright 2000-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
import java.awt.*;
import javax.swing.*;
import java.awt.event.InvocationEvent;
import java.util.Optional;
import java.util.concurrent.*;
import java.util.function.Consumer;
import java.util.logging.*;
import sun.awt.AWTAccessor;
import sun.awt.AWTThreading;
import sun.lwawt.macosx.CThreading;
import sun.lwawt.macosx.LWCToolkit;
import static helper.ToolkitTestHelper.*;
import static helper.ToolkitTestHelper.TestCase.*;
/*
* @test
* @summary Tests different scenarios for LWCToolkit.invokeAndWait().
* @requires (os.family == "mac")
* @modules java.desktop/sun.lwawt.macosx java.desktop/sun.awt
* @run main LWCToolkitInvokeAndWaitTest
* @run main/othervm -DAWTThreading.level.FINER=true LWCToolkitInvokeAndWaitTest
* @run main/othervm -Dlog.level.FINER=true LWCToolkitInvokeAndWaitTest
* @author Anton Tarasov
*/
@SuppressWarnings("ConstantConditions")
public class LWCToolkitInvokeAndWaitTest {
// This property is used in {CAccessibility}
private static final int INVOKE_TIMEOUT_SECONDS = Integer.getInteger("sun.lwawt.macosx.CAccessibility.invokeTimeoutSeconds", 1);
static final int INVOKE_TIMEOUT_SECONDS = Integer.getInteger("sun.lwawt.macosx.CAccessibility.invokeTimeoutSeconds", 1);
static final Runnable CONSUME_DISPATCHING = () -> TEST_CASE_RESULT.completeExceptionally(new Throwable("Unexpected dispatching!"));
static TestLogHandler LOG_HANDLER = new TestLogHandler();
static volatile CompletableFuture<Boolean> FUTURE;
static volatile CountDownLatch EDT_FAST_FREE_LATCH;
static volatile JFrame FRAME;
static volatile Thread MAIN_THREAD;
static int TEST_COUNTER;
static final Runnable CONSUME_DISPATCHING = () -> FUTURE.completeExceptionally(new Throwable("Unexpected dispatching!"));
static {
System.setProperty("sun.lwawt.macosx.LWCToolkit.invokeAndWait.disposeOnEDTFree", "true");
AWTThreading.setAWTThreadingFactory(edt -> new AWTThreading(edt) {
@Override
public CompletableFuture<Void> onEventDispatchThreadFree(Runnable runnable) {
if (EDT_FAST_FREE_LATCH != null) {
// 1. wait for the invocation event to be dispatched
// 2. wait for EDT to become free
trycatch(() -> EDT_FAST_FREE_LATCH.await());
tryRun(EDT_FAST_FREE_LATCH::await);
EDT_FAST_FREE_LATCH = null;
}
@@ -62,101 +61,69 @@ public class LWCToolkitInvokeAndWaitTest {
}
public static void main(String[] args) {
MAIN_THREAD = Thread.currentThread();
trycatch(() -> {
Logger log = LogManager.getLogManager().getLogger(AWTThreading.class.getName());
log.setUseParentHandlers(false);
log.addHandler(LOG_HANDLER);
if (Boolean.getBoolean("AWTThreading.level.FINER")) {
log.setLevel(Level.FINER);
}
});
initTest(LWCToolkitInvokeAndWaitTest.class);
Consumer<InvocationEvent> noop = e -> {};
try {
trycatch(() -> EventQueue.invokeAndWait(LWCToolkitInvokeAndWaitTest::runGui));
testCase().
withCaption("InvocationEvent is normally dispatched").
withRunnable(() -> test1(noop, () -> System.out.println("I'm dispatched")), true).
withCompletionTimeout(INVOKE_TIMEOUT_SECONDS * 2).
run();
test("InvocationEvent is normally dispatched",
"",
noop,
() -> System.out.println("I'm dispatched"));
testCase().
withCaption("InvocationEvent is lost").
withRunnable(() -> test1(noop, CONSUME_DISPATCHING), true).
withCompletionTimeout(INVOKE_TIMEOUT_SECONDS * 2).
withExpectedInLog("lost", true).
run();
test("InvocationEvent is lost",
"lost",
noop,
CONSUME_DISPATCHING);
EDT_FAST_FREE_LATCH = new CountDownLatch(2);
testCase().
withCaption("InvocationEvent is lost (EDT becomes fast free)").
withRunnable(() -> test1(invocationEvent -> EDT_FAST_FREE_LATCH.countDown(), CONSUME_DISPATCHING), true).
withCompletionTimeout(INVOKE_TIMEOUT_SECONDS * 2).
withExpectedInLog("lost", true).
run();
EDT_FAST_FREE_LATCH = new CountDownLatch(2);
test("InvocationEvent is lost (EDT becomes fast free)",
"lost",
// notify the invocationEvent has been dispatched
invocationEvent -> EDT_FAST_FREE_LATCH.countDown(),
CONSUME_DISPATCHING);
testCase().
withCaption("InvocationEvent is disposed").
withRunnable(() -> test1(invocationEvent -> AWTAccessor.getInvocationEventAccessor().dispose(invocationEvent), CONSUME_DISPATCHING), true).
withCompletionTimeout(INVOKE_TIMEOUT_SECONDS * 2).
withExpectedInLog("disposed", true).
run();
test("InvocationEvent is disposed",
"disposed",
invocationEvent -> AWTAccessor.getInvocationEventAccessor().dispose(invocationEvent),
CONSUME_DISPATCHING);
testCase().
withCaption("InvocationEvent is timed out (delayed before dispatching)").
withRunnable(() -> test1(invocationEvent -> sleep(INVOKE_TIMEOUT_SECONDS * 4), CONSUME_DISPATCHING), true).
withCompletionTimeout(INVOKE_TIMEOUT_SECONDS * 2).
withExpectedInLog("timed out", true).
run();
test("InvocationEvent is timed out (delayed before dispatching)",
"timed out",
invocationEvent -> sleep(INVOKE_TIMEOUT_SECONDS * 4),
CONSUME_DISPATCHING);
testCase().
withCaption("InvocationEvent is timed out (delayed during dispatching)").
withRunnable(() -> test1(noop, () -> sleep(INVOKE_TIMEOUT_SECONDS * 4)), true).
withCompletionTimeout(INVOKE_TIMEOUT_SECONDS * 2).
withExpectedInLog("timed out", true).
run();
test("InvocationEvent is timed out (delayed during dispatching)",
"timed out",
noop,
() -> sleep(INVOKE_TIMEOUT_SECONDS * 4));
testCase().
withCaption("invokeAndWait is discarded").
withRunnable(LWCToolkitInvokeAndWaitTest::test2, true).
withCompletionTimeout(INVOKE_TIMEOUT_SECONDS * 2).
withExpectedInLog("discarded", true).
run();
testCase().
withCaption("invokeAndWait is passed").
withRunnable(LWCToolkitInvokeAndWaitTest::test3, true).
withCompletionTimeout(INVOKE_TIMEOUT_SECONDS * 2).
run();
} finally {
FRAME.dispose();
}
System.out.println("Test PASSED");
}
static void runGui() {
FRAME = new JFrame(LWCToolkitInvokeAndWaitTest.class.getSimpleName());
FRAME.getContentPane().setBackground(Color.green);
FRAME.setLocationRelativeTo(null);
FRAME.setSize(200, 200);
FRAME.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
FRAME.setVisible(true);
}
static void test(String testCaption,
String expectedInLog,
Consumer<InvocationEvent> onBeforeDispatching,
Runnable onDispatching)
{
System.out.println("\n(" + (++TEST_COUNTER) + ") TEST: " + testCaption);
FUTURE = new CompletableFuture<>();
FUTURE.whenComplete((r, ex) -> Optional.of(ex).ifPresent(Throwable::printStackTrace));
EventQueue.invokeLater(() -> subTest(onBeforeDispatching, onDispatching));
trycatch(() -> {
if (!FUTURE.get(INVOKE_TIMEOUT_SECONDS * 2L, TimeUnit.SECONDS)) {
throw new RuntimeException("Test FAILED! (negative result)");
}
});
// let AppKit and EDT print all the logging
var latch = new CountDownLatch(1);
CThreading.executeOnAppKit(latch::countDown);
trycatch(latch::await);
trycatch(() -> EventQueue.invokeAndWait(() -> {}));
if (!LOG_HANDLER.testContains(expectedInLog)) {
throw new RuntimeException("Test FAILED! (not found in the log: \"" + expectedInLog + "\")");
}
System.out.println("(" + TEST_COUNTER + ") SUCCEEDED\n");
}
static void subTest(Consumer<InvocationEvent> onBeforeDispatching, Runnable onDispatching) {
static void test1(Consumer<InvocationEvent> onBeforeDispatching, Runnable onDispatching) {
Toolkit.getDefaultToolkit().getSystemEventQueue().push(new EventQueue() {
@Override
protected void dispatchEvent(AWTEvent event) {
@@ -175,55 +142,54 @@ public class LWCToolkitInvokeAndWaitTest {
super.dispatchEvent(event);
}
});
CThreading.executeOnAppKit(() -> trycatch(() -> {
CThreading.executeOnAppKit(() -> tryRun(() -> {
//
// Post an invocation from AppKit.
//
LWCToolkit.invokeAndWait(onDispatching, FRAME, false, INVOKE_TIMEOUT_SECONDS);
FUTURE.complete(true);
TEST_CASE_RESULT.complete(true);
}));
}
static void sleep(int seconds) {
trycatch(() -> Thread.sleep(seconds * 1000L));
static void test2() {
EventQueue.invokeLater(() ->
//
// Blocking EDT.
//
LWCToolkit.performOnMainThreadAndWait(() -> {
//
// The invocation from AppKit should be discarded.
//
tryRun(() -> LWCToolkit.invokeAndWait(EMPTY_RUNNABLE, FRAME, false, INVOKE_TIMEOUT_SECONDS * 4));
TEST_CASE_RESULT.complete(true);
}));
}
static void trycatch(ThrowableRunnable runnable) {
try {
runnable.run();
} catch (Exception e) {
if (Thread.currentThread() == MAIN_THREAD) {
throw new RuntimeException("Test FAILED!", e);
} else {
FUTURE.completeExceptionally(e);
static void test3() {
var point = new CountDownLatch(1);
EventQueue.invokeLater(() -> {
// We're on EDT, wait for the second invocation to perform on AppKit.
await(point, INVOKE_TIMEOUT_SECONDS * 2);
// This should be dispatched in the RunLoop started by LWCToolkit.invokeAndWait from the second invocation.
LWCToolkit.performOnMainThreadAndWait(() -> TEST_CASE_RESULT.complete(true));
});
LWCToolkit.performOnMainThreadAndWait(() -> {
// Notify we're on AppKit.
point.countDown();
// The LWCToolkit.invokeAndWait call starts a native RunLoop.
tryRun(() -> LWCToolkit.invokeAndWait(EMPTY_RUNNABLE, FRAME));
});
}
static void check(String expectedInLog) {
tryRun(() -> {
if (!TEST_CASE_RESULT.get(INVOKE_TIMEOUT_SECONDS * 2L, TimeUnit.SECONDS)) {
throw new RuntimeException("Test FAILED! (negative result)");
}
}
}
interface ThrowableRunnable {
void run() throws Exception;
}
static class TestLogHandler extends StreamHandler {
public StringBuilder buffer = new StringBuilder();
public TestLogHandler() {
// Use System.out to merge with the test printing.
super(System.out, new SimpleFormatter());
setLevel(Level.ALL);
}
@Override
public void publish(LogRecord record) {
buffer.append(record.getMessage());
super.publish(record);
flush();
}
public boolean testContains(String str) {
boolean contains = buffer.toString().contains(str);
buffer.setLength(0);
return contains;
}
});
}
}

View File

@@ -0,0 +1,250 @@
// Copyright 2000-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package helper;
import sun.awt.AWTThreading;
import sun.lwawt.macosx.CThreading;
import sun.lwawt.macosx.LWCToolkit;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.*;
@SuppressWarnings("ConstantConditions")
public class ToolkitTestHelper {
public static final Runnable EMPTY_RUNNABLE = () -> {};
public static final TestLogHandler LOG_HANDLER = new TestLogHandler();
public static volatile CompletableFuture<Boolean> TEST_CASE_RESULT;
public static volatile int TEST_CASE_NUM;
public static volatile JFrame FRAME;
private static volatile JLabel LABEL;
private static volatile Thread MAIN_THREAD;
private static final Runnable UPDATE_LABEL = new Runnable() {
final Random rand = new Random();
@Override
public void run() {
LABEL.setForeground(new Color(rand.nextFloat(), 0, rand.nextFloat()));
LABEL.setText("(" + TEST_CASE_NUM + ")");
}
};
public static void initTest(Class<?> testClass) {
MAIN_THREAD = Thread.currentThread();
assert MAIN_THREAD.getName().toLowerCase().contains("main");
loop(); // init the event threads
tryRun(() -> {
Consumer<Class<?>> setLog = cls -> {
Logger log = LogManager.getLogManager().getLogger(cls.getName());
log.setUseParentHandlers(false);
log.addHandler(LOG_HANDLER);
if (Boolean.getBoolean("log.level.FINER")) {
log.setLevel(Level.FINER);
}
};
setLog.accept(AWTThreading.class);
setLog.accept(LWCToolkit.class);
});
Thread.UncaughtExceptionHandler handler = MAIN_THREAD.getUncaughtExceptionHandler();
MAIN_THREAD.setUncaughtExceptionHandler((t, e) -> {
if (FRAME != null) FRAME.dispose();
handler.uncaughtException(t, e);
});
CountDownLatch showLatch = new CountDownLatch(1);
tryRun(() -> EventQueue.invokeAndWait(() -> {
FRAME = new JFrame(testClass.getSimpleName());
LABEL = new JLabel("0");
LABEL.setFont(LABEL.getFont().deriveFont((float)30));
LABEL.setHorizontalAlignment(SwingConstants.CENTER);
FRAME.add(LABEL, BorderLayout.CENTER);
FRAME.getContentPane().setBackground(Color.green);
FRAME.setLocationRelativeTo(null);
FRAME.setSize(200, 200);
FRAME.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
FRAME.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
showLatch.countDown();
}
});
FRAME.setVisible(true);
}));
//noinspection ResultOfMethodCallIgnored
tryRun(() -> showLatch.await(1, TimeUnit.SECONDS));
Timer timer = new Timer(100, e -> UPDATE_LABEL.run());
timer.setRepeats(true);
timer.start();
new Thread(() -> {
try {
MAIN_THREAD.join();
} catch (InterruptedException ignored) {
}
if (FRAME != null) FRAME.dispose();
timer.stop();
}).start();
}
public static void waitTestCaseCompletion(int seconds) {
tryRun(() -> {
if (!TEST_CASE_RESULT.get(seconds, TimeUnit.SECONDS)) {
throw new RuntimeException("Test FAILED! (negative result)");
}
});
loop(); // wait for the logging to be printed
}
public static class TestCase {
volatile String caption = "";
volatile Runnable testRunnable = EMPTY_RUNNABLE;
volatile int completionTimeoutSeconds = -1;
volatile String expectedInLog = "";
volatile boolean expectedIncludedInLog = true;
public static TestCase testCase() {
return new TestCase();
}
public TestCase withCaption(String caption) {
this.caption = caption;
return this;
}
public TestCase withRunnable(Runnable testRunnable, boolean invokeOnEdt) {
this.testRunnable = invokeOnEdt ? () -> EventQueue.invokeLater(testRunnable) : testRunnable;
return this;
}
public TestCase withCompletionTimeout(int seconds) {
this.completionTimeoutSeconds = seconds;
return this;
}
public TestCase withExpectedInLog(String expectedInLog, boolean included) {
this.expectedInLog = expectedInLog;
this.expectedIncludedInLog = included;
return this;
}
public void run() {
TEST_CASE_RESULT = new CompletableFuture<>();
TEST_CASE_RESULT.whenComplete((r, e) -> Optional.of(e).ifPresent(Throwable::printStackTrace));
//noinspection NonAtomicOperationOnVolatileField
String prefix = "(" + (++TEST_CASE_NUM) + ")";
System.out.println("\n" + prefix + " TEST: " + caption);
UPDATE_LABEL.run();
testRunnable.run();
if (completionTimeoutSeconds >= 0) {
waitTestCaseCompletion(completionTimeoutSeconds);
if (expectedIncludedInLog && !LOG_HANDLER.testContains(expectedInLog)) {
throw new RuntimeException("Test FAILED! (not found in the log: \"" + expectedInLog + "\")");
} else if (!expectedIncludedInLog && LOG_HANDLER.testContains(expectedInLog)) {
throw new RuntimeException("Test FAILED! (found in the log: \"" + expectedInLog + "\")");
}
}
System.out.println(prefix + " SUCCEEDED\n");
}
}
public static void tryRun(ThrowableRunnable runnable) {
tryCall(() -> {
runnable.run();
return null;
}, null);
}
public static <T> T tryCall(Callable<T> callable, T defValue) {
try {
return callable.call();
} catch (Exception e) {
if (Thread.currentThread() == MAIN_THREAD) {
throw new RuntimeException("Test FAILED!", e);
} else {
TEST_CASE_RESULT.completeExceptionally(e);
}
}
return defValue;
}
public static void await(CountDownLatch latch, int seconds) {
if (!tryCall(() -> latch.await(seconds, TimeUnit.SECONDS), false)) {
TEST_CASE_RESULT.completeExceptionally(new Throwable("Awaiting has timed out"));
}
}
public static void sleep(int seconds) {
tryRun(() -> Thread.sleep(seconds * 1000L));
}
private static void loop() {
tryRun(() -> EventQueue.invokeAndWait(EMPTY_RUNNABLE));
var latch = new CountDownLatch(1);
CThreading.executeOnAppKit(latch::countDown);
tryRun(latch::await);
}
public interface ThrowableRunnable {
void run() throws Exception;
}
public static class TestTimer {
private final long finishTime;
public TestTimer(long timeFromNow, TimeUnit unit) {
finishTime = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(timeFromNow, unit);
}
public boolean hasFinished() {
return System.currentTimeMillis() >= finishTime;
}
}
public static class TestLogHandler extends StreamHandler {
public StringBuilder buffer = new StringBuilder();
public TestLogHandler() {
// Use System.out to merge with the test printing.
super(System.out, new SimpleFormatter());
setLevel(Level.ALL);
}
@Override
public void publish(LogRecord record) {
buffer.append(record.getMessage());
super.publish(record);
flush();
}
public boolean testContains(String str) {
boolean contains = buffer.toString().contains(str);
buffer.setLength(0);
return contains;
}
}
}

View File

@@ -1 +1,4 @@
sanity/client/SwingSet/src/TreeDemoTest.java JBR-3389 macosx-all
java/awt/Toolkit/LWCToolkitInvokeAndWaitTest.java nobug macosx-all,linux-all,windows-all
java/awt/Toolkit/AWTThreadingTest.java nobug macosx-all,linux-all,windows-all
java/awt/Toolkit/AWTThreadingCMenuTest.java nobug macosx-all,linux-all,windows-all
sanity/client/SwingSet/src/TreeDemoTest.java JBR-3389 macosx-all

View File

@@ -518,12 +518,14 @@ java/awt/dnd/DisposeFrameOnDragCrash/DisposeFrameOnDragTest.java 8202790 macosx-
java/awt/dnd/MissingDragExitEventTest/MissingDragExitEventTest.java 8030121 macosx-all,linux-all
java/awt/Choice/ChoicePopupLocation/ChoicePopupLocation.java 8202931 macosx-all,linux-all
java/awt/Focus/NonFocusableBlockedOwnerTest/NonFocusableBlockedOwnerTest.java 7124275 macosx-all
java/awt/Focus/NonFocusableWindowTest/NonfocusableOwnerTest.java 8280392
java/awt/Focus/TranserFocusToWindow/TranserFocusToWindow.java 6848810 macosx-all,linux-all
java/awt/FileDialog/ModalFocus/FileDialogModalFocusTest.java 8194751 linux-all
java/awt/image/VolatileImage/BitmaskVolatileImage.java 8133102 linux-all
java/awt/SplashScreen/MultiResolutionSplash/MultiResolutionSplashTest.java 8134231 windows-all,linux-all,macosx-all
java/awt/SplashScreen/MultiResolutionSplash/unix/UnixMultiResolutionSplashTest.java 8203004 linux-all
java/awt/Robot/AcceptExtraMouseButtons/AcceptExtraMouseButtons.java 7107528 linux-all,macosx-all
java/awt/Mouse/GetMousePositionTest/GetMousePositionWithPopup.java 8282232 windows-all
java/awt/Mouse/MouseDragEvent/MouseDraggedTest.java 8080676 linux-all
java/awt/Mouse/MouseModifiersUnitTest/MouseModifiersInKeyEvent.java 8157147 linux-all,windows-all,macosx-all
java/awt/Mouse/TitleBarDoubleClick/TitleBarDoubleClick.java 8148041 linux-all
@@ -592,6 +594,7 @@ javax/management/monitor/DerivedGaugeMonitorTest.java 8042211 generic-al
# jdk_io
java/io/pathNames/GeneralWin32.java 8180264 windows-all
java/io/File/createTempFile/SpecialTempFile.java 8274122 windows11
############################################################################