/*
 * The contents of this file are subject to the terms of the Common Development
 * and Distribution License (the License). You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
 * or http://www.netbeans.org/cddl.txt.
 * 
 * When distributing Covered Code, include this CDDL Header Notice in each file
 * and include the License file at http://www.netbeans.org/cddl.txt.
 * If applicable, add the following below the CDDL Header, with the fields
 * enclosed by brackets [] replaced by your own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * The Original Software is NetBeans. The Initial Developer of the Original
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
 * Microsystems, Inc. All Rights Reserved.
 */

package org.netbeans.core.output;

import java.awt.Rectangle;
import javax.swing.JTabbedPane;

/**
 * This class provides a few helper methods to work around JDK bug 4620540
 * which happens in Sun JDK 1.4.0.
 * This bug was fixed in Sun JDK 1.4.1 but this class is still necessary
 * for Sun JDK 1.4.0.
 * Taken from org.netbeans.core.windows to support popup menu on OutputView
 * inner tabs.
 * 
 * @author Tran Duc Trung
 */

public class JdkBug4620540Hack
{
    private JdkBug4620540Hack() {}

    // XXX(-ttran) on JDK 1.4.0 if tabLayoutPolicy == SCROLL_TAB_LAYOUT &&
    // tabPlacement == BOTTOM then JTabbedPane.getBoundsAt() returns incorrect
    // value.

    public static void fixGetBoundsAt(Rectangle b) {
        if (b.y < 0)
            b.y = -b.y;
        if (b.x < 0)
            b.x = -b.x;
    }

    // XXX(-ttran) We would like to be able to write
    // 
    //      TabbedPaneUI tabUI = tab.getUI();
    //      int click = tabUI.tabForCoordinate(tab, p.x, p.y);
    //
    // but this piece of code doesn't work correctly for tabLayoutPolicy ==
    // SCROLL_TAB_LAYOUT && tabPlacement == BOTTOM.  tabForCoordinate() never
    // finds any tab, the method always returns -1.
    
    public static int findTabForCoordinate(JTabbedPane tab, int x, int y) {
        for (int i = 0; i < tab.getTabCount(); i++) {
            Rectangle b = tab.getBoundsAt(i);
            if (b != null) {
                b = new Rectangle(b);
                fixGetBoundsAt(b);
                
                if (b.contains(x, y)) {
                    return i;
                }
            }
        }
        return -1;
    }
}
