/***************************************************************************
                            KMainWindow.java -  description
                             -------------------
    begin                : Sun Jan 27 16:22:17 2002
    copyright            : (C) 2000-2001 Lost Highway Ltd.
    email                : Richard_Dale@tipitina.demon.co.uk
    generated by         : duke@tipitina on Sun Jan 27 16:22:17 2002, using kalyptus 0.9.
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
***************************************************************************/

package org.kde.koala;

import org.kde.qt.*;
import java.util.*;
import java.lang.Error;

/**

 Top level widget that provides toolbars, a status line and a frame.

 It should be used as a top level (parent-less) widget.
 It manages the geometry for all its children, including your
 main widget.

 Normally, you will inherit from KMainWindow,
 then construct (or use some existing) widget as
 your main view. You can set only one main view.

 You can add as many toolbars as you like. There can be only one menubar
 and only one statusbar.

 The toolbars, menubar, and statusbar can be created by the
 KMainWindow and - unlike the old KMainWindow - may, but do not
 have to, be deleted by you. KMainWindow will handle that internally.

 Height and width can be operated independently from each other. Simply
 define the minimum/maximum height/width of your main widget and
 KMainWindow will take this into account. For fixed size windows set
 your main widget to a fixed size.

 Fixed aspect ratios (heightForWidth()) and fixed width widgets are
 not supported.

 KMainWindow will set icon, mini icon and caption, which it gets
 from {@link KApplication}. It provides full session management, and
 will save its position, geometry and positions of toolbars and
 menubar on logout. If you want to save additional data, reimplement
 {@link #saveProperties} and (to read them again on next login) {@link #readProperties}. To save special data about your data, reimplement
 {@link #saveGlobalProperties}. To warn user that application or
 windows have unsaved data on close or logout, reimplement {@link #queryClose} and/or {@link #queryExit}.

 There is also a macro RESTORE which can restore all your windows
 on next login.

  Note that a KMainWindow per-default is created with the
  WDestructiveClose flag, i.e. it is automatically destroyed when the
  window is closed. If you do not want this behavior, specify 0 as
  widget flag in the constructor.

 
 See {@link KMainWindowSignals} for signals emitted by KMainWindow.

 See {@link KMainWindowEventHandling} for event handlers to override in subclasses of KMainWindow.

 @author Reginald Stadlbauer (reggie@kde.org) Stephan Kulow (coolo@kde.org), Matthias Ettrich (ettrich@kde.org), Chris Schlaeger (cs@kde.org), Sven Radej (radej@kde.org). Maintained by Sven Radej (radej@kde.org)

 @short KDE top level main window.
*/
public class KMainWindow extends QMainWindow implements  KXMLGUIBuilderInterface, KXMLGUIClientInterface {
	protected KMainWindow(Class dummy){super((Class) null);}

	private native void newKMainWindow( QWidget parent, String name, int f);

/** 
 Construct a main window.

 KMainWindows must be created on the heap with 'new', like:
  <pre> KMainWindow kmw = new KMainWindow (...</pre>

*/
	public KMainWindow( QWidget parent, String name, int f) {
		super((Class) null);
		newKMainWindow( parent, name, f);
	}
	public KMainWindow( QWidget parent, String name) {
		this( parent, name, 0);
	}
	public KMainWindow( QWidget parent) {
		this( parent, null, 0);
	}
	private native void newKMainWindow();
	public KMainWindow() {
		super((Class) null);
		newKMainWindow();
	}

/** 
 Destructor.

 Will also destroy the toolbars, and menubar if
 needed.
     
*/
	protected native void finalize() throws InternalError;
	public native void dispose();
	public native boolean isDisposed();

/** 
 Retrieve the standard help menu.

 It contains entires for the
 help system (activated by F1), an optional "What's This?" entry
 (activated by Shift F1), an application specific dialog box,
 and an "About KDE" dialog box.

 Example (adding a standard help menu to your application):
 <pre>
 KPopupMenu help = helpMenu( <myTextString> );
 menuBar().insertItem( i18n("&Help"), help );
 </pre>

*/
	public native KPopupMenu helpMenu( String aboutAppText, boolean showWhatsThis);
	public KPopupMenu helpMenu(String aboutAppText) {
		return this.helpMenu(aboutAppText,true);
	}
	public native KPopupMenu helpMenu();

/** 
 Returns the help menu. Creates a standard help menu if none exists yet.

 It contains entries for the
 help system (activated by F1), an optional "What's This?" entry
 (activated by Shift F1), an application specific dialog box,
 and an "About KDE" dialog box. You must create the application
 specific dialog box yourself. When the "About application"
 menu entry is activated, a signal will trigger the
 {@link showAboutApplication} slot. See {@link showAboutApplication} for more
 information.

 Example (adding a help menu to your application):
 <pre>
 menuBar().insertItem( i18n("&Help"), customHelpMenu() );
 </pre>

*/
	public native KPopupMenu customHelpMenu( boolean showWhatsThis);
	public native KPopupMenu customHelpMenu();

/** 
 Restore the session specified by <code>number.</code>

 Returns <code>false</code> if this
 fails, otherwise returns <code>true</code> and shows the window.
 You should call {@link #canBeRestored} first.
 If <code>show</code> is true (default), this widget will be shown automatically.
     
*/
	public native boolean restore( int number, boolean show);
	public native boolean restore( int number);
	public native KXMLGUIFactory guiFactory();

/** 
 Create a GUI given a local XML file.

 If <code>xmlfile</code> is NULL,
 then it will try to construct a local XML filename like
 appnameui.rc where 'appname' is your app's name.  If that file
 does not exist, then the XML UI code will only use the global
 (standard) XML file for the layout purposes.

*/
	public native void createGUI( String xmlfile, boolean _conserveMemory);
	public void createGUI( String xmlfile) {
		createGUI(xmlfile, true);
		return;
	}
	public native void createGUI();

/** 
 Enables the build of a standard help menu when calling createGUI().

 The default behavior is to build one, you must call this function
 to disable it
     
*/
	public native void setHelpMenuEnabled( boolean showHelpMenu);
	public native void setHelpMenuEnabled();

/** 
 Return <code>true</code> when the help menu is enabled
     
*/
	public native boolean isHelpMenuEnabled();

/** 
 Returns a pointer to the menu bar.

 If there is no menu bar yet one will be created.

*/
	public native QMenuBar menuBar();

/** 
 Returns a pointer to the status bar.

  If there is no
 status bar yet one will be created.
     
*/
	public native QStatusBar statusBar();
	
/**
 List of members of KMainWindow class.
*/
	public native ArrayList memberList();

/** 
 Returns a pointer to the toolbar with the specified name.
 This refers to toolbars created dynamically from the XML UI
 framework.  If the toolbar does not exist one will be created.

*/
	public native KToolBar toolBar( String name);
	public native KToolBar toolBar();

/** 

*/
//	public native QPtrListIterator<KToolBar> toolBarIterator();

/** 

*/
	public native KAccel accel();
	public native void setFrameBorderWidth( int arg1);

/** 
 Call this to enable "auto-save" of toolbar/menubar/statusbar settings
 (and optionally window size).
 If the bars were moved around/shown/hidden when the window is closed,
 saveMainWindowSettings( KGlobal.config(), groupName ) will be called.

 Typically, you will call setAutoSaveSettings() in your
 KMainWindow-inherited class constructor, and it will take care
 of restoring and saving automatically. Make sure you call this
 _after all_ your bars have been created.
     
*/
	public native void setAutoSaveSettings( String arg1, boolean saveWindowSize);
	public native void setAutoSaveSettings();

/** 
 Disable the auto-save-settings feature.
 You don't normally need to call this, ever.
     
*/
	public native void resetAutoSaveSettings();

/** 
 Read settings for statusbar, menubar and toolbar from their respective
 groups in the config file and apply them.

*/
	public native void applyMainWindowSettings( KConfig config, String groupName);
	public native void applyMainWindowSettings( KConfig config);

/** 
 Save settings for statusbar, menubar and toolbar to their respective
 groups in the config file <code>config.</code>

*/
	public native void saveMainWindowSettings( KConfig config, String groupName);
	public native void saveMainWindowSettings( KConfig config);

/** 

     
*/
	public native void finalizeGUI( boolean force);

/** 

*/
	public native boolean initialGeometrySet();

/** 

*/
	public native QSize sizeForCentralWidgetSize( QSize size);

/** 
 Makes a KDE compliant caption.

*/
	public native void setCaption( String caption);

/** 
 Makes a KDE compliant caption.

*/
	public native void setCaption( String caption, boolean modified);

/** 
 Make a plain caption without any modifications.

*/
	public native void setPlainCaption( String caption);

/** 
 Open the help page for the application.

  The application name is
 used as a key to determine what to display and the system will attempt
 to open <appName>/index.html.

 This method is intended for use by a help button in the toolbar or
 components outside the regular help menu. Use {@link #helpMenu} when you
 want to provide access to the help system from the help menu.

 Example (adding a help button to the first toolbar):

 <pre>
 KIconLoader &loader = KGlobal.iconLoader();
 QPixmap pixmap = loader.loadIcon( "help" );
 toolBar(0).insertButton( pixmap, 0, SIGNAL("clicked()"),
   this, SLOT("appHelpActivated()"), true, i18n("Help") );
 </pre>

     
*/
	public native void appHelpActivated();

/** 
 Apply a state change

 Enable and disable actions as defined in the XML rc file
     
*/
	public native void slotStateChanged( String newstate);

/** 

     
*/
	public native void setSettingsDirty();

/** 

 Try to restore the toplevel widget as defined by the number (1..X).

 If the session did not contain so high a number, the configuration
 is not changed and <code>false</code> returned.

 That means clients could simply do the following:
 <pre>
 if (kapp.isRestored()){
   int n = 1;
   while (KMainWindow.canBeRestored(n)){
     (new childMW).restore(n);
     n++;
   }
 } else {
 // create default application as usual
 }
 </pre>
 Note that {@link QWidget#show} is called implicitly in restore.

 With this you can easily restore all toplevel windows of your
 application.

 If your application uses different kinds of toplevel
 windows, then you can use {@link KMainWindow#classNameOfToplevel}
 to determine the exact type before calling the childMW
 constructor in the example from above.

 If your client has only one kind of toplevel widgets (which should
 be pretty usual) then you should use the RESTORE-macro:

 <pre>
 if (kapp.isRestored())
   RESTORE(childMW)
 else {
 // create default application as usual
 }
 </pre>

 The macro expands to the term above but is easier to use and
 less code to write.

     
*/
	public static native boolean canBeRestored( int number);

/** 
 Returns the {@link #className} of the <code>number</code> of the toplevel window which
 should be restored.

  This is only useful if your application uses
 different kinds of toplevel windows.
     
*/
	public static native String classNameOfToplevel( int number);
	protected native void paintEvent( QPaintEvent e);
	protected native void childEvent( QChildEvent e);
	protected native void resizeEvent( QResizeEvent e);

/** 
 Reimplemented to call the queryClose() and queryExit() handlers.

 We recommend that you reimplement the handlers rather than {@link #closeEvent}.
 If you do it anyway, ensure to call the base implementation to keep
 {@link #queryExit} running.
     
*/
	protected native void closeEvent( QCloseEvent arg1);

/** 
       Called before the very last window is closed, either by the
       user or indirectly by the session manager.

       It is not recommended to do any user interaction in this
       function other than indicating severe errors. Better ask the
       user on {@link #queryClose} (see below).

       However, {@link #queryExit} is useful to do some final cleanups. A
       typical example would be to write configuration data back.

       Note that the application may continue to run after {@link #queryExit}
       (the user may have cancelled a shutdown). The purpose of
       {@link #queryExit} is purely to prepare the application (with possible
       user interaction) so it can safely be closed later (without
       user interaction).

       If you need to do serious things on exit (like shutting a
       dial-up connection down), connect to the signal
       {@link KApplication#shutDown}.

       Default implementation returns <code>true.</code> Returning <code>false</code> will
       cancel the exiting. In the latter case, the last window will
       remain visible.

*/
	protected native boolean queryExit();

/** 
       Called before the window is closed, either by the user or indirectly by
       the session manager.

       The purpose of this function is to prepare the window in a way that it is
       safe to close it, i.e. without the user losing some data.

       Default implementation returns true. Returning <code>false</code> will cancel
       the closing.

       Reimplement this function to prevent the user from losing data.
       Example:
       <pre>

           switch ( KMessageBox.warningYesNoCancel( this,
				   i18n("Save changes to Document Foo?")) ) {
           case KMessageBox.Yes :
             // save document here. If saving fails, return FALSE;
             return TRUE;
           case KMessageBox.No :
             return TRUE;
           default: // cancel
             return FALSE;

    </pre>

    
*/
	protected native boolean queryClose();

/** 
 Save your instance-specific properties. The function is
 invoked when the session manager requests your application
 to save its state.

 You <em>must</em> <em>not</em> change the group of the <code>kconfig</code> object, since
 KMainWindow uses one group for each window.  Please
 reimplement these function in childclasses.

 Note: No user interaction is allowed
 in this function!

     
*/
	protected native void saveProperties( KConfig arg1);

/** 
 Read your instance-specific properties.
    
*/
	protected native void readProperties( KConfig arg1);

/** 
 Save your application-wide properties. The function is
 invoked when the session manager requests your application
 to save its state.

 This function is similar to {@link #saveProperties} but is only called for
 the very first main window, regardless how many main window are open.

 Override it if you need to save other data about your documents on
 session end. sessionConfig is a config to which that data should be
 saved. Normally, you don't need this function. But if you want to save
 data about your documents that are not in opened windows you might need
 it.

 Default implementation does nothing.
     
*/
	protected native void saveGlobalProperties( KConfig sessionConfig);

/** 
 The counterpart of {@link #saveGlobalProperties}.

 Read the application-specific properties in again.
     
*/
	protected native void readGlobalProperties( KConfig sessionConfig);
	protected native void savePropertiesInternal( KConfig arg1, int arg2);
	protected native boolean readPropertiesInternal( KConfig arg1, int arg2);

/** 
 For inherited classes
     
*/
	protected native boolean settingsDirty();

/** 
 For inherited classes
     
*/
	protected native String settingsGroup();

/** 
 For inherited classes
 Note that the group must be set before calling
     
*/
	protected native void saveWindowSize( KConfig config);

/** 
 For inherited classes
 Note that the group must be set before calling, and that
 a -geometry on the command line has priority.
     
*/
	protected native void restoreWindowSize( KConfig config);
	protected native void parseGeometry( boolean parsewidth);

/** 
 This slot does nothing.

 It must be reimplemented if you want
 to use a custom About Application dialog box. This slot is
 connected to the About Application entry in the menu returned
 by {@link customHelpMenu}.

 Example:
 <pre>

 void MyMainLevel.setupInterface()
 {
   ..
   menuBar().insertItem( i18n("&Help"), customHelpMenu() );
   ..
 }

 void MyMainLevel.showAboutApplication( void )
 {
   <activate your custom dialog>
 }
 </pre>
    
*/
	protected native void showAboutApplication();
        // From KXMLGUIBuilderInterface

        public native KXMLGUIClientInterface builderClient();
        public native void setBuilderClient( KXMLGUIClientInterface client);
        public native KInstanceInterface builderInstance();
        public native void setBuilderInstance( KInstanceInterface instance);
        public native ArrayList containerTags();

/**
 Create a container (menubar/menu/toolbar/statusbar/separator/...)
 from an element in the XML file

*/
        public native QWidget createContainer( QWidget parent, int index, QDomElement element, int identifier);

/**
 Remove the given (and previously via {@link createContainer} )
 created container.

*/
        public native void removeContainer( QWidget container, QWidget parent, QDomElement element, int identifier);
        public native ArrayList customTags();
        public native int createCustomElement( QWidget parent, int index, QDomElement element);
        public native void removeCustomElement( QWidget parent, int identifier);
        public native void finalizeGUI( KXMLGUIClientInterface client);

        /**
 Retrieve an action of the client by name.
 This method is provided for convenience, as it uses {@link #actionCollection}
 to get the action object.

*/
	public native KAction action( String name);

        // From KXMLGUIClientInterface


/**
 Retrieves an action for a given {@link QDomElement}. The default
 implementation uses the "name" attribute to query the action
 object via the other action() method.

*/
	public native KAction action( QDomElement element);

/**
 Retrieves the entire action collection for the GUI client

*/
	public native KActionCollection actionCollection();

/**

*/
	public native KInstanceInterface instance();

/**

*/
	public native QDomDocument domDocument();

/**
 This will return the name of the XML file as set by {@link #setXMLFile}.
 If {@link #setXML} is used directly, then this will return NULL.

 The filename that this returns is obvious for components as each
 component has exactly one XML file.  In non-components, however,
 there are usually two: the global file and the local file.  This
 function doesn't really care about that, though.  It will always
 return the last XML file set.  This, in almost all cases, will
 be the local XML file.

*/
	public native String xmlFile();
	public native String localXMLFile();

/**


*/
	public native void setXMLGUIBuildDocument( QDomDocument doc);

/**


*/
	public native QDomDocument xmlguiBuildDocument();

/**
 This method is called by the {@link KXMLGUIFactory} as soon as the client
 is added to the KXMLGUIFactory's GUI.

*/
	public native void setFactory( KXMLGUIFactory factory);

/**
 Retrieves a pointer to the {@link KXMLGUIFactory} this client is
 associated with (will return null if the client's GUI has not been built
 by a KXMLGUIFactory.

*/
	public native KXMLGUIFactory factory();

/**
 KXMLGUIClients can form a simple child/parent object tree. This
 method returns a pointer to the parent client or null if it has no
 parent client assigned.

*/
	public native KXMLGUIClientInterface parentClient();

/**
 Use this method to make a client a child client of another client.
 Usually you don't need to call this method, as it is called
 automatically when using the second constructor, which takes a
 arent argument.

*/
	public native void insertChildClient( KXMLGUIClientInterface child);

/**
 Removes the given <code>child</code> from the client's children list.

*/
	public native void removeChildClient( KXMLGUIClientInterface child);

/**
 A client can have an own {@link KXMLGUIBuilder}.
 Use this method to assign your builder instance to the client (so that the
 {@link KXMLGUIFactory} can use it when building the client's GUI)

 Client specific guibuilders are useful if you want to create
 custom container widgets for your GUI.

*/
	public native void setClientBuilder( KXMLGUIBuilderInterface builder);

/**
 Retrieves the client's GUI builder or null if no client specific
 uilder has been assigned via {@link #setClientBuilder}

*/
	public native KXMLGUIBuilderInterface clientBuilder();

/**
 Forces this client to re-read its XML resource file.  This is
 intended to be used when you know that the resource file has
 changed and you will soon be rebuilding the GUI.  It has no
 useful effect with non-KParts GUIs, so don't bother using it
 unless your app is component based.

*/
	public native void reloadXML();
	public native void unplugActionList( String name);
	public native void addStateActionEnabled( String state, String action);
	public native void addStateActionDisabled( String state, String action);
//	public native StateChange getActionsToChangeForState( String state);
	public static native String findMostRecentXMLFile( String[] files, String doc);

/**
 Sets the instance ({@link KInstance}) for this part.

 Call this first in the inherited class constructor.
 (At least before {@link #setXMLFile}.)

*/
	public native void setInstance( KInstanceInterface instance);

/**
 Sets the name of the rc file containing the XML for the part.

 Call this in the Part-inherited class constructor.

*/
	protected native void setXMLFile( String file, boolean merge, boolean setXMLDoc);
	protected native void setXMLFile( String file);
	protected native void setLocalXMLFile( String file);

/**
 Sets the XML for the part.

 Call this in the Part-inherited class constructor if you
  don't call {@link #setXMLFile}.

*/
	protected native void setXML( String document, boolean merge);
	protected native void setXML( String document);

/**
 Sets the Document for the part, describing the layout of the GUI.

 Call this in the Part-inherited class constructor if you don't call
 {@link setXMLFile} or {@link setXML} .

*/
	protected native void setDOMDocument( QDomDocument document, boolean merge);
	protected native void setDOMDocument( QDomDocument document);

/**
 This function will attempt to give up some memory after the GUI
 is built.  It should never be used in apps where the GUI may be
 rebuilt at some later time (components, for instance).

*/
	protected native void conserveMemory();
	protected native void stateChanged( String newstate);
	
	public static void RESTORE(String typeName)
	{
		Class	savedClass;
		
		try {
			savedClass = Class.forName(typeName);
			int n = 1;
			while (KMainWindow.canBeRestored(n)){
				((KMainWindow) savedClass.newInstance()).restore(n);
				n++;
			}
		} catch(Exception e) {
			return;
		}
		
		return;
	}
}
