Learn more  » Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Bower components Debian packages RPM packages NuGet packages

beebox / crossover   deb

Repository URL to install this package:

/ opt / cxoffice / bin / cxmessage

#! /usr/bin/env python
# (c) Copyright 2009-2013. 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=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


# pylint: disable=W0611
import checkpython
import cxopt

# for localization
from cxutils import cxgettext as _


def callshow(w):
    w.show_all()

#----------------------------------------------------------------------------
#  Parse Arguments
#----------------------------------------------------------------------------

opt_parser = cxopt.Parser(usage=_("%prog [-options] MESSAGE [ARGUMENTS...]"),
                          description=_("Displays a message or question in a window."),
                          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("--buttons", dest="buttons", help=_("A comma-separated list of label:exitcode specifying the buttons to display and their exit codes"))
opt_parser.add_option("--default", dest="default", help=_("Button to activate if Return is pressed"))
opt_parser.add_option("--print", dest="printresult", help=_("Print the button label on exit"), action="store_true", default=False)
opt_parser.add_option("--named-args", dest="named", help=_("The format string takes named arguments"), action="store_true", default=False)
opt_parser.add_option("--no-focus", action="store_true", dest="nofocus", default=False, help=_("Do not steal focus"))
opt_parser.add_option("--wm-class", dest="wm_class", help=_("The window's WM_CLASS property"))

# Old xmessage-style arguments use single dashes. OptionParser doesn't like
# those and, anyway, we also want to support the modern form. So, convert all
# single-dash arguments to double-dashes.
# Also 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:
        if len(arg) > 1 and arg[0] == "-" and arg[1] != "-":
            argvw.append("-" + arg)
        else:
            argvw.append(arg)
(options, args) = opt_parser.parse_args(argvw)
if not args:
    opt_parser.error(_("you must specify the message or question to display"))

#----------------------------------------------------------------------------
#  Check gtk and $DISPLAY
#----------------------------------------------------------------------------
# It's not worth bringing up a GUI error message explaining that cxmessage
# failed. However we should at least issue an error on stderr explaining what
# happened. Then it's up to the calling script to deal with the error.
import checkgtk
if checkgtk.check_gtk(warn_gtk=False) != checkgtk.OK:
    sys.exit(1)

#----------------------------------------------------------------------------
#  Set Text and Title
#----------------------------------------------------------------------------
message_format = cxutils.cxgettext(args[0])
try:
    if options.named:
        named_args = {}
        for i in xrange(1, len(args), 2):
            # If arg[1:] does not contain an even number of elements,
            # then we will just print the message format
            named_args[args[i]] = args[i + 1]
        messageString = message_format % named_args
    else:
        messageString = message_format % tuple(args[1:])
except (TypeError, IndexError):
    messageString = message_format

import gtk
if options.title:
    options.title = cxutils.cxgettext(options.title)
    dialog = gtk.MessageDialog(parent=None, message_format=options.title, flags=gtk.DIALOG_MODAL, buttons=gtk.BUTTONS_NONE)
elif len(messageString) > 1000 or messageString.count('\n') > 9:
    dialog = gtk.MessageDialog(parent=None, flags=gtk.DIALOG_MODAL, buttons=gtk.BUTTONS_NONE)
else:
    dialog = gtk.MessageDialog(parent=None, message_format=messageString, flags=gtk.DIALOG_MODAL, buttons=gtk.BUTTONS_NONE)

if options.wm_class:
    dialog.set_wmclass(options.wm_class, options.wm_class)

if len(messageString) > 1000 or messageString.count('\n') > 9:
    tb = gtk.TextBuffer()
    tb.set_text(messageString)
    tv = gtk.TextView(tb)
    tv.set_property("height-request", 300)
    tv.set_property("width-request", 350)
    sw = gtk.ScrolledWindow()
    sw.add(tv)
    ca = dialog.get_content_area()
    ca.add(sw)
    ca.foreach(callshow)
else:
    if options.title:
        dialog.format_secondary_text(messageString)

#----------------------------------------------------------------------------
#  Add Buttons
#----------------------------------------------------------------------------
if options.buttons:
    rawButtonList = options.buttons.split(",")
    for index, button in enumerate(rawButtonList):
        buttonPair = button.split(":")
        try:
            if len(buttonPair) == 2:
                response = int(buttonPair[1])
            elif len(buttonPair) == 1:
                response = 101 + index
            else:
                raise Exception()
        except: # pylint: disable=W0702
            opt_parser.error("invalid button description '%s'" % button)

        if buttonPair[0].lower() == "ok":
            dialog.add_button(gtk.STOCK_OK, response)
        elif buttonPair[0].lower() == "cancel":
            dialog.add_button(gtk.STOCK_CANCEL, response)
        elif buttonPair[0].lower() == "open":
            dialog.add_button(gtk.STOCK_OPEN, response)
        elif buttonPair[0].lower() == "yes":
            dialog.add_button(gtk.STOCK_YES, response)
        elif buttonPair[0].lower() == "quit":
            dialog.add_button(gtk.STOCK_QUIT, response)
        elif buttonPair[0].lower() == "no":
            dialog.add_button(gtk.STOCK_NO, response)
        else:
            dialog.add_button(cxutils.cxgettext(buttonPair[0]), response)

        if options.default and (options.default.lower() == buttonPair[0].lower()):
            dialog.set_default_response(response)

else:
    dialog.add_button(gtk.STOCK_OK, 0)


#----------------------------------------------------------------------------
#  Set Image
#----------------------------------------------------------------------------
import cxguitools
if options.image and hasattr(dialog, 'set_image'):
    # GTK+ >= 2.10
    image = gtk.Image()
    if '/' in options.image:
        image.set_from_file(options.image)
    else:
        image.set_from_pixbuf(cxguitools.get_std_icon(options.image))
    image.show()
    dialog.set_image(image)

#----------------------------------------------------------------------------
#  Bring up the dialog
#----------------------------------------------------------------------------
if options.nofocus:
    dialog.set_property('focus-on-map', False)

cxguitools.set_default_icon()
rval = dialog.run()

if options.printresult:
    if options.buttons:
        rawButtonList = options.buttons.split(",")
        for button in rawButtonList:
            buttonPair = button.split(":")
            if rval == int(buttonPair[1]):
                # We need the parentheses for Python 3
                # pylint: disable=C0325
                print(buttonPair[0])
                break
    else:
        # We need the parentheses for Python 3
        # pylint: disable=C0325
        print("OK")

sys.exit(rval)