OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Blame | Last modification | View Log | RSS feed

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
 * 
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each file.
 */
 
 package org.openconcerto.ui;

import org.openconcerto.utils.Platform;

import java.awt.Toolkit;
import java.lang.reflect.Field;
import java.util.Objects;
import java.util.function.Supplier;

public class WindowUtils {
    private WindowUtils() {
    }

    /**
     * Allow to set WM_CLASS for X11 windows.
     * 
     * @param nameSupplier which name to use.
     * @param pidSuffix <code>true</code> if the name should be suffixed by the PID of the VM. That
     *        way, there is one group of windows per launch.
     */
    static public void setWMClass(final Supplier<String> nameSupplier, final boolean pidSuffix) {
        // Set WM_CLASS to have a meaningful name and avoid grouping together all windows of all VMs
        final Class<?> xtoolkit = Toolkit.getDefaultToolkit().getClass();
        // https://bugs.openjdk.java.net/browse/JDK-6528430
        // need system property to override default WM_CLASS
        // #183739 - provide proper app name on Linux
        // org/netbeans/core/windows/view/ui/MainWindow.java
        if (xtoolkit.getName().equals("sun.awt.X11.XToolkit")) {
            try {
                final Field awtAppClassName = xtoolkit.getDeclaredField("awtAppClassName");
                awtAppClassName.setAccessible(true);

                String pid = null;
                // use PID to have one group of windows per launch
                if (pidSuffix) {
                    try {
                        final Platform p = Platform.getInstance();
                        if (p.supportsPID())
                            pid = p.getPID();
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
                final String suppliedName = Objects.requireNonNull(nameSupplier.get(), "Null name").trim();
                if (suppliedName.isEmpty())
                    throw new IllegalArgumentException("Empty name");
                final String name = suppliedName + (pid == null ? "" : " [" + pid + "]");

                awtAppClassName.set(null, name);
            } catch (Exception x) {
                x.printStackTrace();
            }
        }
    }
}