#! /usr/bin/env python
import pygtk; pygtk.require("2.0")

import sys
import os.path

debug_mode = False
if os.path.isfile("../../gnumexp.desktop.in"):
    debug_mode = True
if debug_mode:
    import profile
    import pstats
    print >> sys.stderr, "warning: importing gnumexp modules from source dir\n\n"
    sys.path.insert(0, "../xygraph")
    sys.path.insert(0, "../console")
    sys.path.insert(0, "../common")
    sys.path.insert(0, "../..")


import bonobo
import CORBA
import gobject
import gtk
import gnome
import gnome.ui

import gnumexp_conf


import Numexp_Console.control
import Numexp_XYGraph.control
from GNumexp_Shell.main import MainWindow

CONSOLE_IID = "OAFIID:Numexp_ConsoleView"
XYGRAPH_IID = "OAFIID:Numexp_XYGraph"

# ---------------------------------------
# (longName, shortName, type , default, flags, descrip , argDescrip)
popt_table = [
       ('plot-window', 'p', None, None, 0,
        'Start a Plot window instead of a Console', ''),
       ]
prog = gnome.program_init("gnumexp", gnumexp_conf.VERSION,
                          gnome.libgnome_module_info_get(),
                          sys.argv, popt_table)
icon = gtk.gdk.pixbuf_new_from_file(os.path.join(gnumexp_conf.ICONDIR, "gnumexp_icon.png"))
gtk.window_set_default_icon_list(icon); del icon
gnome.ui.authentication_manager_init()


def new_instance_cb(app, argc, argv):
    num_toplevels = len(MainWindow.toplevels)
    leftover_args, argdict = gnome.popt_parse(argv, popt_table)
    if argdict['plot-window']:
        default_component = XYGRAPH_IID
    else:
        default_component = CONSOLE_IID    
    for arg in leftover_args:
        # Only XYGraph can load files..
        mainwin = MainWindow(XYGRAPH_IID)
        mainwin.load_from(arg)
    # If no documents were loaded, create a default main window
    if len(MainWindow.toplevels) == num_toplevels:
	MainWindow(default_component)
    return False

def factory_callback(factory, iid):
    print " ==> factory_callback: iid=" + iid
    if iid == CONSOLE_IID:
	print "creating console view"
	console = Numexp_Console.control.ConsoleControl()
	return console
    elif iid == XYGRAPH_IID:
	xy = Numexp_XYGraph.control.XYGraphControl()
	return xy
    print "not returning anything!"

def create_initial_window(app):
    app.new_instance(sys.argv)

CORBA.ORB_init(sys.argv)
bonobo.activate()

factory_activation = ("--oaf-activate-iid=OAFIID:GNumexp_ControlsFactory"
                      in sys.argv[1:])
app = bonobo.Application("GNumexp")

def mainloop():
    while True:
        bonobo.generic_factory_main("OAFIID:GNumexp_ControlsFactory",
                                    factory_callback, timeout=500)
        if not MainWindow.toplevels:
            break


client = app.register_unique("")
if client is not None:
    assert not factory_activation
    app.unref()
    i = client.new_instance(sys.argv)
    try:
        gtk.gdk.notify_startup_complete()
    except AttributeError:
        pass
else:
    app.connect("new-instance", new_instance_cb)
    # the factory determines our lifecycle, not the app
    bonobo.context_running_get().corba_objref().removeObject(app.corba_objref())
    if not factory_activation:
        gobject.idle_add(create_initial_window, app)
    if False:#debug_mode:
        profile.run("mainloop()", "gnumexp-profile.log")
        stats = pstats.Stats("gnumexp-profile.log")
        stats.sort_stats('time')
        stats.print_stats(.25)
    else:
        mainloop()
    app.unref()

