
package uk.co.wingpath.util;

import java.io.*;
import java.awt.*;
import java.net.*;
import java.lang.reflect.*;

/**
* This class provides a method for launching the default browser to view
* a specified URI.
* <p>It uses the Java 6 java.awt.Desktop class if it is available.
* Otherwise, it uses platform-specific methods to find the browser.
* <p>The implementation is based on code and ideas from 
* <a href="http://www.centerkey.com/java/browser/">http://www.centerkey.com/java/browser/</a> and
* <a href="http://stackoverflow.com/questions/879938/workaround-for-no-default-browser-on-linux">http://stackoverflow.com/questions/879938/workaround-for-no-default-browser-on-linux</a>.
*/
public class Browser
{
    static final String [] browsers =
    {
        "xdg-open",
        "firefox",
        "konqueror",
        "google-chrome",
        "opera",
        "epiphany",
        "seamonkey",
        "galeon",
        "mozilla"
    };

   /**
    * Opens the specified URI in the user's default browser.
    * @param uri the URI to be opened.
    * @return {@code true} if the default browser was successfully launched,
    * {@code false} otherwise.
    */
    public static boolean browse (URI uri)
    {
        if (Desktop.isDesktopSupported ())
        {
            try
            {
                Desktop desktop = Desktop.getDesktop ();
                desktop.browse (uri);
                return true;
            }
            catch (Exception e)
            {
            }
        }

        // Desktop class not available or failed.

        Runtime rt = Runtime.getRuntime ();
        String osName = System.getProperty ("os.name");
        if (osName.startsWith ("Mac OS"))
        {
            try
            {
                rt.exec ("open " + uri);
                return true;
            }
            catch (Exception e)
            {
            }
        }
        else if (osName.startsWith ("Windows"))
        {
            try
            {
                rt.exec ("rundll32 url.dll,FileProtocolHandler " + uri);
                return true;
            }
            catch (Exception e)
            {
            }
        }
        else
        {
            // Assume Unix or Linux

            for (String browser : browsers)
            {
                try
                {
                    rt.exec (new String [] { browser, uri.toString () });
                    return true;
                }
                catch (Exception e)
                {
                }
            }
        }

        return false;
    }
}


