#! /usr/bin/env python
# (c) Copyright 2009-2012. CodeWeavers, Inc.

import os

# Portable which(1) implementation
def which(path, app):
    """Looks for an executable in the specified directory list.

    path is an os.pathsep-separated list of directories and app is the
    executable name. If app contains a path separator then path is ignored.
    If the file is not found, then None is returned.
    """
    if os.path.isabs(app):
        if os.path.isfile(app) and os.access(app, os.X_OK):
            return app
    elif os.sep in app or (os.altsep and os.altsep in app):
        app_path = os.path.join(os.getcwd(), app)
        if os.path.isfile(app_path) and os.access(app_path, os.X_OK):
            return app_path
    else:
        for directory in path.split(os.pathsep):
            if directory == "":
                continue
            app_path = os.path.join(directory, app)
            if os.path.isfile(app_path) and os.access(app_path, os.X_OK):
                return app_path
    return None

import sys
def locate_cx_root():
    """Locate where CrossOver is installed.

    We start by locating our own python script file and walking back up the
    path, traversing symbolic links on the way. Then we verify what we have
    found the right directory by checking for the presence of the cxmenu
    script.
    """
    # pylint: disable-msg=I0011,W0601,W0603
    global CX_ROOT
    if "CX_DEVELOP_ROOT" in os.environ:
        CX_ROOT = os.environ["CX_DEVELOP_ROOT"]
        return

    # figure out argv0
    argv0 = which(os.environ["PATH"], sys.argv[0])
    if not argv0:
        argv0 = sys.argv[0]
        if not os.path.isabs(argv0):
            argv0 = os.path.join(os.getcwd(), argv0)

    # traverse the symbolic links
    dir0 = os.path.dirname(argv0)
    while True:
        if dir0.endswith("/lib"):
            bindir = dir0[0:-3] + "bin"
        else:
            bindir = dir0
        landmark = os.path.join(bindir, "cxmenu")
        if os.path.isfile(landmark):
            break
        if not os.path.islink(argv0):
            break
        argv0 = os.readlink(argv0)
        if not os.path.isabs(argv0):
            argv0 = os.path.join(dir0, argv0)
        dir0 = os.path.dirname(argv0)

    # compute CX_ROOT
    CX_ROOT = os.path.dirname(os.path.normpath(bindir))

    # check CX_ROOT
    landmark = os.path.join(CX_ROOT, "bin", "cxmenu")
    if not os.path.isfile(landmark) or not os.access(landmark, os.X_OK):
        sys.stderr.write("%s:error: could not find CrossOver in '%s'\n" % (os.path.dirname(sys.argv[0]), CX_ROOT))
        sys.exit(1)

    sys.path.append(os.path.join(CX_ROOT, "lib", "python"))

locate_cx_root()
import cxutils
cxutils.CX_ROOT = CX_ROOT


import checkgtk
if checkgtk.check_gtk(warn_gtk=False, warn_display=False) != checkgtk.OK:
    # Displaying the wait message is not essential so just exit if we cannot
    # bring up the GUI.
    sys.exit(1)

import gobject
import gtk
import gtk.glade
gtk.gdk.threads_init()

import cxopt

import cxguitools

# for localization
from cxutils import cxgettext as _


class WaitDialogController(object):

    mainWindow = None
    xml = None

    modeldialogxml = None

    def __init__(self):
        # Parse Arguments
        opt_parser = cxopt.Parser(usage="%prog MESSAGE [ARGS...]",
                                  description=_("Displays a message asking the user to be patient."),
                                  epilog=_("MESSAGE can be a simple string or a printf-style format string followed by arguments."))
        opt_parser.add_option("--title", dest="title", help=_("Title of the window"))
        opt_parser.add_option("--image", dest="image", help=_("Display the specified image"))
        opt_parser.add_option("--no-focus", action="store_true", dest="nofocus", default=False, help=_("Do not steal focus"))
        # We want all these arguments in Unicode for Gtk.
        argvw = []
        arg_encoding = sys.getfilesystemencoding()
        for arg in sys.argv[1:]:
            try:
                arg = unicode(arg, arg_encoding)
            finally:
                argvw.append(arg)
        (options, args) = opt_parser.parse_args(argvw)
        if not args:
            # No message was given so show the usage
            opt_parser.print_help()
            sys.exit(0)

        try:
            glade_path = os.environ["CX_GLADEPATH"]
        except KeyError:
            glade_path = os.path.join(cxutils.CX_ROOT, "lib", "python", "glade")

        self.glade_file = os.path.join(glade_path, "waitdlg.glade")
        if not gtk.glade.textdomain() == "crossover":
            locale_path = os.path.join(CX_ROOT, "share", "locale")
            gtk.glade.bindtextdomain("crossover", locale_path)
            gtk.glade.textdomain("crossover")
        self.xml = gtk.glade.XML(self.glade_file)
        self.xml.signal_autoconnect(self)

        # We have a c-style string format, and need to convert it.
        message_format = cxutils.cxgettext(args[0])
        try:
            message = message_format % tuple(args[1:])
        except TypeError:
            message = message_format

        window = self.xml.get_widget("WaitDlg")
        window.set_property('focus-on-map', not options.nofocus)

        # Set up title
        if options.title:
            window.set_title(cxutils.cxgettext(options.title))

        # Set up image
        if options.image:
            image = self.xml.get_widget("WaitImage")
            if '/' in options.image:
                image.set_from_file(options.image)
            else:
                image.set_from_pixbuf(cxguitools.get_std_icon(options.image))

        # Set up progress bar
        prog_bar = self.xml.get_widget("ProgBar")
        prog_bar.set_pulse_step(.05)
        gobject.timeout_add(100, self.prog_bar_pulse)
        prog_bar.show()

        # Fill Message Text
        msg_widget = self.xml.get_widget("WaitMessage")
        msg_widget.set_text(message)

        cxguitools.set_default_icon()
        window.show()


    def quit_requested(self, caller):
        # pylint: disable-msg=R0201,W0613
        gtk.main_quit()

    def prog_bar_pulse(self):
        prog_bar = self.xml.get_widget("ProgBar")
        prog_bar.pulse()
        return True


if __name__ == "__main__":
    WaitDialogController()
    gtk.main()
    sys.exit()


