[Java, BSH and JS Script examples] Display a message box

Creating a macro - Writing a Script - Using the API (OpenOffice Basic, Python, BeanShell, JavaScript)
Post Reply
hol.sten
Volunteer
Posts: 495
Joined: Mon Oct 08, 2007 1:31 am
Location: Hamburg, Germany

[Java, BSH and JS Script examples] Display a message box

Post by hol.sten »

Question: Display a messageBox in JavaScript Code
In the OpenOffice.org Forum andreasbe raised the question, how to display a messageBox in JavaScript Code? Villeroy answered with a Python example for showing a simple message box.

Java and Java script solution
After several failures converting Villeroy's example directly to a BeanShell script I got the following Java code working first:

Code: Select all

import com.sun.star.awt.ActionEvent;
import com.sun.star.awt.KeyEvent;
import com.sun.star.awt.MessageBoxButtons;
import com.sun.star.awt.MouseEvent;
import com.sun.star.awt.Rectangle;
import com.sun.star.awt.XMessageBox;
import com.sun.star.awt.XMessageBoxFactory;
import com.sun.star.awt.XWindow;
import com.sun.star.awt.XWindowPeer;
import com.sun.star.beans.PropertyValue;
import com.sun.star.comp.helper.BootstrapException;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XModel;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.script.provider.XScriptContext;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;

import ooo.connector.BootstrapSocketConnector;

// Sources I used, to get this example working:
// 1) OpenOffice.org Forum
//   - Simple MessageBox in Python: http://www.oooforum.org/forum/viewtopic.phtml?t=59580&highlight=messagebox
//   - Using Xray from Beanshell: http://www.oooforum.org/forum/viewtopic.phtml?t=23333&highlight=getservicemanager+beanshell
// 2) Online API IDL reference documentation
//   - service Toolkit: http://api.openoffice.org/docs/common/ref/com/sun/star/awt/Toolkit.html
//   - interface XMessageBoxFactory: http://api.openoffice.org/docs/common/ref/com/sun/star/awt/XMessageBoxFactory.html

public class OOoMessageBox {
 
  private static final String OOO_EXEC_FOLDER = "C:/Program Files/OpenOffice.org 2.3/program/";

  private static final String TYPE_INFO_MESSAGE_BOX = "infobox"; // infobox always shows one OK button alone!
  private static final String TYPE_WARN_MESSAGE_BOX = "warningbox";
  private static final String TYPE_ERROR_MESSAGE_BOX = "errorbox";
  private static final String TYPE_QUESTION_MESSAGE_BOX = "querybox";
  private static final String TYPE_SIMPLE_MESSAGE_BOX = "messbox";

  private static final int RESULT_CANCLE_ABORT = 0;
  private static final int RESULT_OK = 1;
  private static final int RESULT_YES = 2;
  private static final int RESULT_NO = 3;
  private static final int RESULT_RETRY = 4;
  private static final int RESULT_IGNORE = 5;

  /**
   * Called from a toolbar.
   */
  public static void showMessageBoxExamples(XScriptContext xScriptContext, Short ignored) {
	showMessageBoxExamples(xScriptContext);
  }

  /**
   * Called from a button with an action.
   */
  public static void showMessageBoxExamples(XScriptContext xScriptContext, ActionEvent ignored) {
	showMessageBoxExamples(xScriptContext);
  }

  /**
   * Called from a button with a key.
   */
  public static void showMessageBoxExamples(XScriptContext xScriptContext, KeyEvent ignored) {
	showMessageBoxExamples(xScriptContext);
  }

  /**
   * Called from a button with the mouse.
   */
  public static void showMessageBoxExamples(XScriptContext xScriptContext, MouseEvent ignored) {
	showMessageBoxExamples(xScriptContext);
  }

  /**
   * Called from a menu or the "Run Macro..." menu.
   */
  public static void showMessageBoxExamples(XScriptContext xScriptContext) {
	XModel document = xScriptContext.getDocument();
	showMessageBoxExamples(document);
  }

  private static void showMessageBoxExamples(XModel document) {
	if (document == null)
	  return;

	String messageBoxTitle;
	String message;
	short result;

	// Get the parent window and access to the window toolkit of the parent window
	XWindow parentWindow = document.getCurrentController().getFrame().getContainerWindow();
	XWindowPeer parentWindowPeer = (XWindowPeer) UnoRuntime.queryInterface(XWindowPeer.class, parentWindow);

	// Show examples of different message boxes
	messageBoxTitle = "Simple Message Box";
	message = "A message in a SimpleMessageBox.";
	result = showSimpleMessageBox(parentWindowPeer,messageBoxTitle,message);
	showResult(parentWindowPeer,result);

	messageBoxTitle = "Info Message Box";
	message = "A message in an InfoMessageBox.";
	result = showInfoMessageBox(parentWindowPeer,messageBoxTitle,message);
	showResult(parentWindowPeer,result);

	messageBoxTitle = "Warning Message Box";
	message = "A message in a WarningMessageBox.";
	result = showYesNoWarningMessageBox(parentWindowPeer,messageBoxTitle,message);
	showResult(parentWindowPeer,result);

	messageBoxTitle = "Another Warning Message Box";
	message = "A message in another WarningMessageBox.";
	result = showOkCancelWarningMessageBox(parentWindowPeer,messageBoxTitle,message);
	showResult(parentWindowPeer,result);

	messageBoxTitle = "Question Message Box";
	message = "A message in a QuestionMessageBox.";
	result = showQuestionMessageBox(parentWindowPeer,messageBoxTitle,message);
	showResult(parentWindowPeer,result);

	messageBoxTitle = "Error Message Box";
	message = "A message in an ErrorMessageBox.";
	result = showAbortRetryIgnoreErrorMessageBox(parentWindowPeer,messageBoxTitle,message);
	showResult(parentWindowPeer,result);

	messageBoxTitle = "Another Error Message Box";
	message = "A message in another ErrorMessageBox.";
	result = showRetryCancelErrorMessageBox(parentWindowPeer,messageBoxTitle,message);
	showResult(parentWindowPeer,result);
  }

  private static void showResult(XWindowPeer parentWindowPeer,short result) {
	if (parentWindowPeer == null)
	  return;

	String button;
	switch (result) {
	  case RESULT_CANCLE_ABORT:
		button = "Cancel or Abort";
		break;
	  case RESULT_OK:
		button = "OK";
		break;
	  case RESULT_YES:
		button = "Yes";
		break;
	  case RESULT_NO:
		button = "No";
		break;
	  case RESULT_RETRY:
		button = "Retry";
		break;
	  case RESULT_IGNORE:
		button = "Ignore";
		break;
	  default:
		button = "Unknown";
	}
		   
	String messageBoxTitle = "Result";
	String message = "Button selected: "+button;
	showInfoMessageBox(parentWindowPeer,messageBoxTitle,message);
  }

  private static short showSimpleMessageBox(XWindowPeer parentWindowPeer,String messageBoxTitle,String message) {
	if (parentWindowPeer == null || messageBoxTitle == null || message == null)
	  return 0;

	return showMessageBox(parentWindowPeer,TYPE_SIMPLE_MESSAGE_BOX,MessageBoxButtons.BUTTONS_YES_NO+MessageBoxButtons.DEFAULT_BUTTON_YES,messageBoxTitle,message);
  }

  private static short showInfoMessageBox(XWindowPeer parentWindowPeer,String messageBoxTitle,String message) {
	if (parentWindowPeer == null || messageBoxTitle == null || message == null)
	  return 0;

	return showMessageBox(parentWindowPeer,TYPE_INFO_MESSAGE_BOX,MessageBoxButtons.BUTTONS_OK,messageBoxTitle,message);
  }

  private static short showYesNoWarningMessageBox(XWindowPeer parentWindowPeer,String messageBoxTitle,String message) {
	if (parentWindowPeer == null || messageBoxTitle == null || message == null)
	  return 0;

	return showMessageBox(parentWindowPeer,TYPE_WARN_MESSAGE_BOX,MessageBoxButtons.BUTTONS_YES_NO+MessageBoxButtons.DEFAULT_BUTTON_NO,messageBoxTitle,message);
  }

  private static short showOkCancelWarningMessageBox(XWindowPeer parentWindowPeer,String messageBoxTitle,String message) {
	if (parentWindowPeer == null || messageBoxTitle == null || message == null)
	  return 0;

	return showMessageBox(parentWindowPeer,TYPE_WARN_MESSAGE_BOX,MessageBoxButtons.BUTTONS_OK_CANCEL+MessageBoxButtons.DEFAULT_BUTTON_OK,messageBoxTitle,message);
  }

  private static short showQuestionMessageBox(XWindowPeer parentWindowPeer,String messageBoxTitle,String message) {
	if (parentWindowPeer == null || messageBoxTitle == null || message == null)
	  return 0;

	return showMessageBox(parentWindowPeer,TYPE_QUESTION_MESSAGE_BOX,MessageBoxButtons.BUTTONS_YES_NO_CANCEL+MessageBoxButtons.DEFAULT_BUTTON_YES,messageBoxTitle,message);
  }

  private static short showAbortRetryIgnoreErrorMessageBox(XWindowPeer parentWindowPeer,String messageBoxTitle,String message) {
	if (parentWindowPeer == null || messageBoxTitle == null || message == null)
	  return 0;

	return showMessageBox(parentWindowPeer,TYPE_ERROR_MESSAGE_BOX,MessageBoxButtons.BUTTONS_ABORT_IGNORE_RETRY+MessageBoxButtons.DEFAULT_BUTTON_RETRY,messageBoxTitle,message);
  }

  private static short showRetryCancelErrorMessageBox(XWindowPeer parentWindowPeer,String messageBoxTitle,String message) {
	if (parentWindowPeer == null || messageBoxTitle == null || message == null)
	  return 0;

	return showMessageBox(parentWindowPeer,TYPE_ERROR_MESSAGE_BOX,MessageBoxButtons.BUTTONS_RETRY_CANCEL+MessageBoxButtons.DEFAULT_BUTTON_CANCEL,messageBoxTitle,message);
  }

  private static short showMessageBox(XWindowPeer parentWindowPeer,String messageBoxType,int messageBoxButtons,String messageBoxTitle,String message) {
	if (parentWindowPeer == null || messageBoxType == null || messageBoxTitle == null || message == null)
	  return 0;

	// Initialize the message box factory
	XMessageBoxFactory messageBoxFactory = (XMessageBoxFactory) UnoRuntime.queryInterface(XMessageBoxFactory.class,parentWindowPeer.getToolkit());

	Rectangle messageBoxRectangle = new Rectangle();

	XMessageBox box = messageBoxFactory.createMessageBox(parentWindowPeer, messageBoxRectangle, messageBoxType, messageBoxButtons, messageBoxTitle, message) ;
	return box.execute();
  }

  public static void main(String[] args) {
	// This example works with the following arguments:
	// 1) A valid name of an OOo document like "file:///c:/temp/writer.odt"
	// 2) "private:factory/swriter" or "private:factory/scalc" to create a new OOo document
	// 3) No argument at all to get the current OOo document
	String loadUrl = (args.length > 0)? args[0]: null;
	try {
	  XComponentContext context = BootstrapSocketConnector.bootstrap(OOO_EXEC_FOLDER);
	   
	  XMultiComponentFactory multiComponentFactory = context.getServiceManager();
	  Object desktopFrame = multiComponentFactory.createInstanceWithContext("com.sun.star.frame.Desktop", context);
	  XComponentLoader componentloader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class,desktopFrame);

	  Object component;
	  if (loadUrl != null) {
		// Load the document
		try {
		  component = componentloader.loadComponentFromURL(loadUrl, "_blank", 0, new PropertyValue[0]);
		} catch (Exception e) {
		  component = null;
		}
	  } else {
		// Get the current document
		XDesktop desktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class,desktopFrame);
		component = desktop.getCurrentComponent();
	  }

	  // Get the Writer document of the component
	  XModel model = (XModel)UnoRuntime.queryInterface(XModel.class, component);
	  if (model != null) {
		System.out.println("File URL: "+model.getURL());
	  }
	 
	  if(model == null) {
		// Either the document couldn't be loaded or there wasn't a current
		// document. Whatever the reason has been, we create a new document.
		component = componentloader.loadComponentFromURL("private:factory/swriter", "_blank", 0, new PropertyValue[0]);
		model = (XModel) UnoRuntime.queryInterface(XModel.class, component);
	  }

	  showMessageBoxExamples(model);
	} catch (BootstrapException e) {
	  e.printStackTrace();
	} catch (Exception e) {
	  e.printStackTrace();
	} finally {
	  System.exit(0);
	}
  }
}
This Java example shows several message box examples and the selected buttons for each example. The example works as a stand alone Java application, using the BootstrapSocketConnector or as a Java script, if you provide an additional parcel-descriptor.xml like it has been described in [Java] OOo Writer and Calc macro examples.

BeanShell script solution
After the Java code worked, it was easy to transform the code to a BeanShell script:

Code: Select all

import com.sun.star.uno.UnoRuntime;

import com.sun.star.awt.MessageBoxButtons;
import com.sun.star.awt.Rectangle;
import com.sun.star.awt.XMessageBox;
import com.sun.star.awt.XMessageBoxFactory;
import com.sun.star.awt.XWindow;
import com.sun.star.awt.XWindowPeer;


TYPE_INFO_MESSAGE_BOX = "infobox"; // infobox always shows one OK button alone!
TYPE_WARN_MESSAGE_BOX = "warningbox";
TYPE_ERROR_MESSAGE_BOX = "errorbox";
TYPE_QUESTION_MESSAGE_BOX = "querybox";
TYPE_SIMPLE_MESSAGE_BOX = "messbox";

RESULT_CANCLE_ABORT = 0;
RESULT_OK = 1;
RESULT_YES = 2;
RESULT_NO = 3;
RESULT_RETRY = 4;
RESULT_IGNORE = 5;


void showResult(XWindowPeer parentWindowPeer,short result) {
  if (parentWindowPeer == null)
    return;

  switch (result) {
    case RESULT_CANCLE_ABORT:
      button = "Cancel or Abort";
      break;
    case RESULT_OK:
      button = "OK";
      break;
    case RESULT_YES:
      button = "Yes";
      break;
    case RESULT_NO:
      button = "No";
      break;
    case RESULT_RETRY:
      button = "Retry";
      break;
    case RESULT_IGNORE:
      button = "Ignore";
      break;
    default:
      button = "Unknown";
  }
		
  messageBoxTitle = "Result";
  message = "Button selected: "+button;
  showInfoMessageBox(parentWindowPeer,messageBoxTitle,message);
}

short showSimpleMessageBox(XWindowPeer parentWindowPeer,String messageBoxTitle,String message) {
  if (parentWindowPeer == null || messageBoxTitle == null || message == null)
    return 0;

  return showMessageBox(parentWindowPeer,TYPE_SIMPLE_MESSAGE_BOX,MessageBoxButtons.BUTTONS_YES_NO+MessageBoxButtons.DEFAULT_BUTTON_YES,messageBoxTitle,message);
}

short showInfoMessageBox(XWindowPeer parentWindowPeer,String messageBoxTitle,String message) {
  if (parentWindowPeer == null || messageBoxTitle == null || message == null)
    return 0;

  return showMessageBox(parentWindowPeer,TYPE_INFO_MESSAGE_BOX,MessageBoxButtons.BUTTONS_OK,messageBoxTitle,message);
}

short showYesNoWarningMessageBox(XWindowPeer parentWindowPeer,String messageBoxTitle,String message) {
  if (parentWindowPeer == null || messageBoxTitle == null || message == null)
    return 0;

  return showMessageBox(parentWindowPeer,TYPE_WARN_MESSAGE_BOX,MessageBoxButtons.BUTTONS_YES_NO+MessageBoxButtons.DEFAULT_BUTTON_NO,messageBoxTitle,message);
}

short showOkCancelWarningMessageBox(XWindowPeer parentWindowPeer,String messageBoxTitle,String message) {
  if (parentWindowPeer == null || messageBoxTitle == null || message == null)
    return 0;

  return showMessageBox(parentWindowPeer,TYPE_WARN_MESSAGE_BOX,MessageBoxButtons.BUTTONS_OK_CANCEL+MessageBoxButtons.DEFAULT_BUTTON_OK,messageBoxTitle,message);
}

short showQuestionMessageBox(XWindowPeer parentWindowPeer,String messageBoxTitle,String message) {
  if (parentWindowPeer == null || messageBoxTitle == null || message == null)
    return 0;

  return showMessageBox(parentWindowPeer,TYPE_QUESTION_MESSAGE_BOX,MessageBoxButtons.BUTTONS_YES_NO_CANCEL+MessageBoxButtons.DEFAULT_BUTTON_YES,messageBoxTitle,message);
}

short showAbortRetryIgnoreErrorMessageBox(XWindowPeer parentWindowPeer,String messageBoxTitle,String message) {
  if (parentWindowPeer == null || messageBoxTitle == null || message == null)
    return 0;

  return showMessageBox(parentWindowPeer,TYPE_ERROR_MESSAGE_BOX,MessageBoxButtons.BUTTONS_ABORT_IGNORE_RETRY+MessageBoxButtons.DEFAULT_BUTTON_RETRY,messageBoxTitle,message);
}

short showRetryCancelErrorMessageBox(XWindowPeer parentWindowPeer,String messageBoxTitle,String message) {
  if (parentWindowPeer == null || messageBoxTitle == null || message == null)
    return 0;

  return showMessageBox(parentWindowPeer,TYPE_ERROR_MESSAGE_BOX,MessageBoxButtons.BUTTONS_RETRY_CANCEL+MessageBoxButtons.DEFAULT_BUTTON_CANCEL,messageBoxTitle,message);
}

short showMessageBox(XWindowPeer parentWindowPeer,String messageBoxType,int messageBoxButtons,String messageBoxTitle,String message) {
  if (parentWindowPeer == null || messageBoxType == null || messageBoxTitle == null || message == null)
    return 0;

  // Initialize the message box factory
  messageBoxFactory = UnoRuntime.queryInterface(XMessageBoxFactory.class,parentWindowPeer.getToolkit());

  messageBoxRectangle = new Rectangle();

  box = messageBoxFactory.createMessageBox(parentWindowPeer, messageBoxRectangle, messageBoxType, messageBoxButtons, messageBoxTitle, message) ;
  return box.execute();
}


// Get the document
document = XSCRIPTCONTEXT.getDocument();

// Get the parent window and access to the window toolkit of the parent window
XWindow parentWindow = document.getCurrentController().getFrame().getContainerWindow();
XWindowPeer parentWindowPeer = (XWindowPeer) UnoRuntime.queryInterface(XWindowPeer.class, parentWindow); 

// Show examples of different message boxes
messageBoxTitle = "Simple Message Box";
message = "A message in a SimpleMessageBox.";
result = showSimpleMessageBox(parentWindowPeer,messageBoxTitle,message);
showResult(parentWindowPeer,result);

messageBoxTitle = "Info Message Box";
message = "A message in an InfoMessageBox.";
result = showInfoMessageBox(parentWindowPeer,messageBoxTitle,message);
showResult(parentWindowPeer,result);

messageBoxTitle = "Warning Message Box";
message = "A message in a WarningMessageBox.";
result = showYesNoWarningMessageBox(parentWindowPeer,messageBoxTitle,message);
showResult(parentWindowPeer,result);

messageBoxTitle = "Another Warning Message Box";
message = "A message in another WarningMessageBox.";
result = showOkCancelWarningMessageBox(parentWindowPeer,messageBoxTitle,message);
showResult(parentWindowPeer,result);

messageBoxTitle = "Question Message Box";
message = "A message in a QuestionMessageBox.";
result = showQuestionMessageBox(parentWindowPeer,messageBoxTitle,message);
showResult(parentWindowPeer,result);

messageBoxTitle = "Error Message Box";
message = "A message in an ErrorMessageBox.";
result = showAbortRetryIgnoreErrorMessageBox(parentWindowPeer,messageBoxTitle,message);
showResult(parentWindowPeer,result);

messageBoxTitle = "Another Error Message Box";
message = "A message in another ErrorMessageBox.";
result = showRetryCancelErrorMessageBox(parentWindowPeer,messageBoxTitle,message);
showResult(parentWindowPeer,result);


// BeanShell OpenOffice.org scripts should always return 0
return 0;
How to install a BeanShell script has been described in [BeanShell] OOo Calc macro example.

JavaScript solution
And finally, to convert the Java code to JavaScript has been easy, too:

Code: Select all

importClass(Packages.com.sun.star.uno.UnoRuntime);

importClass(Packages.com.sun.star.awt.MessageBoxButtons);
importClass(Packages.com.sun.star.awt.Rectangle);
importClass(Packages.com.sun.star.awt.XMessageBox);
importClass(Packages.com.sun.star.awt.XMessageBoxFactory);
importClass(Packages.com.sun.star.awt.XWindow);
importClass(Packages.com.sun.star.awt.XWindowPeer);


TYPE_INFO_MESSAGE_BOX = "infobox"; // infobox always shows one OK button alone!
TYPE_WARN_MESSAGE_BOX = "warningbox";
TYPE_ERROR_MESSAGE_BOX = "errorbox";
TYPE_QUESTION_MESSAGE_BOX = "querybox";
TYPE_SIMPLE_MESSAGE_BOX = "messbox";

RESULT_CANCLE_ABORT = 0;
RESULT_OK = 1;
RESULT_YES = 2;
RESULT_NO = 3;
RESULT_RETRY = 4;
RESULT_IGNORE = 5;


function showResult(parentWindowPeer,result) {
  if (parentWindowPeer == null)
    return;

  switch (result) {
    case RESULT_CANCLE_ABORT:
      button = "Cancel or Abort";
      break;
    case RESULT_OK:
      button = "OK";
      break;
    case RESULT_YES:
      button = "Yes";
      break;
    case RESULT_NO:
      button = "No";
      break;
    case RESULT_RETRY:
      button = "Retry";
      break;
    case RESULT_IGNORE:
      button = "Ignore";
      break;
    default:
      button = "Unknown";
  }
		
  messageBoxTitle = "Result";
  message = "Button selected: "+button;
  showInfoMessageBox(parentWindowPeer,messageBoxTitle,message);
}

function showSimpleMessageBox(parentWindowPeer,messageBoxTitle,message) {
  if (parentWindowPeer == null || messageBoxTitle == null || message == null)
    return 0;

  return showMessageBox(parentWindowPeer,TYPE_SIMPLE_MESSAGE_BOX,MessageBoxButtons.BUTTONS_YES_NO+MessageBoxButtons.DEFAULT_BUTTON_YES,messageBoxTitle,message);
}

function showInfoMessageBox(parentWindowPeer,messageBoxTitle,message) {
  if (parentWindowPeer == null || messageBoxTitle == null || message == null)
    return 0;

  return showMessageBox(parentWindowPeer,TYPE_INFO_MESSAGE_BOX,MessageBoxButtons.BUTTONS_OK,messageBoxTitle,message);
}

function showYesNoWarningMessageBox(parentWindowPeer,messageBoxTitle,message) {
  if (parentWindowPeer == null || messageBoxTitle == null || message == null)
    return 0;

  return showMessageBox(parentWindowPeer,TYPE_WARN_MESSAGE_BOX,MessageBoxButtons.BUTTONS_YES_NO+MessageBoxButtons.DEFAULT_BUTTON_NO,messageBoxTitle,message);
}

function showOkCancelWarningMessageBox(parentWindowPeer,messageBoxTitle,message) {
  if (parentWindowPeer == null || messageBoxTitle == null || message == null)
    return 0;

  return showMessageBox(parentWindowPeer,TYPE_WARN_MESSAGE_BOX,MessageBoxButtons.BUTTONS_OK_CANCEL+MessageBoxButtons.DEFAULT_BUTTON_OK,messageBoxTitle,message);
}

function showQuestionMessageBox(parentWindowPeer,messageBoxTitle,message) {
  if (parentWindowPeer == null || messageBoxTitle == null || message == null)
    return 0;

  return showMessageBox(parentWindowPeer,TYPE_QUESTION_MESSAGE_BOX,MessageBoxButtons.BUTTONS_YES_NO_CANCEL+MessageBoxButtons.DEFAULT_BUTTON_YES,messageBoxTitle,message);
}

function showAbortRetryIgnoreErrorMessageBox(parentWindowPeer,messageBoxTitle,message) {
  if (parentWindowPeer == null || messageBoxTitle == null || message == null)
    return 0;

  return showMessageBox(parentWindowPeer,TYPE_ERROR_MESSAGE_BOX,MessageBoxButtons.BUTTONS_ABORT_IGNORE_RETRY+MessageBoxButtons.DEFAULT_BUTTON_RETRY,messageBoxTitle,message);
}

function showRetryCancelErrorMessageBox(parentWindowPeer,messageBoxTitle,message) {
  if (parentWindowPeer == null || messageBoxTitle == null || message == null)
    return 0;

  return showMessageBox(parentWindowPeer,TYPE_ERROR_MESSAGE_BOX,MessageBoxButtons.BUTTONS_RETRY_CANCEL+MessageBoxButtons.DEFAULT_BUTTON_CANCEL,messageBoxTitle,message);
}

function showMessageBox(parentWindowPeer,messageBoxType,messageBoxButtons,messageBoxTitle,message) {
  if (parentWindowPeer == null || messageBoxType == null || messageBoxTitle == null || message == null)
    return 0;

  // Initialize the message box factory
  messageBoxFactory = UnoRuntime.queryInterface(XMessageBoxFactory,parentWindowPeer.getToolkit());

  messageBoxRectangle = new Rectangle();

  box = messageBoxFactory.createMessageBox(parentWindowPeer, messageBoxRectangle, messageBoxType, messageBoxButtons, messageBoxTitle, message) ;
  return box.execute();
}


// Get the document
document = XSCRIPTCONTEXT.getDocument();

// Get the parent window and access to the window toolkit of the parent window
parentWindow = document.getCurrentController().getFrame().getContainerWindow();
parentWindowPeer = UnoRuntime.queryInterface(XWindowPeer, parentWindow); 

// Show examples of different message boxes
messageBoxTitle = "Simple Message Box";
message = "A message in a SimpleMessageBox.";
result = showSimpleMessageBox(parentWindowPeer,messageBoxTitle,message);
showResult(parentWindowPeer,result);

messageBoxTitle = "Info Message Box";
message = "A message in an InfoMessageBox.";
result = showInfoMessageBox(parentWindowPeer,messageBoxTitle,message);
showResult(parentWindowPeer,result);

messageBoxTitle = "Warning Message Box";
message = "A message in a WarningMessageBox.";
result = showYesNoWarningMessageBox(parentWindowPeer,messageBoxTitle,message);
showResult(parentWindowPeer,result);

messageBoxTitle = "Another Warning Message Box";
message = "A message in another WarningMessageBox.";
result = showOkCancelWarningMessageBox(parentWindowPeer,messageBoxTitle,message);
showResult(parentWindowPeer,result);

messageBoxTitle = "Question Message Box";
message = "A message in a QuestionMessageBox.";
result = showQuestionMessageBox(parentWindowPeer,messageBoxTitle,message);
showResult(parentWindowPeer,result);

messageBoxTitle = "Error Message Box";
message = "A message in an ErrorMessageBox.";
result = showAbortRetryIgnoreErrorMessageBox(parentWindowPeer,messageBoxTitle,message);
showResult(parentWindowPeer,result);

messageBoxTitle = "Another Error Message Box";
message = "A message in another ErrorMessageBox.";
result = showRetryCancelErrorMessageBox(parentWindowPeer,messageBoxTitle,message);
showResult(parentWindowPeer,result);
To install the JavaScript code is very similar to installing a BeanShell script.
Last edited by hol.sten on Sun Mar 09, 2008 9:23 pm, edited 2 times in total.
OOo 3.2.0 on Ubuntu 10.04 • OOo 3.2.1 on Windows 7 64-bit and MS Windows XP
hol.sten
Volunteer
Posts: 495
Joined: Mon Oct 08, 2007 1:31 am
Location: Hamburg, Germany

Re: [Java, BSH and JS Script examples] Display a message box

Post by hol.sten »

09. Mar. 2008: Enhanced Java code example that can be called from a toolbar and a button, too (http://www.rugludallur.com/index.php?id=31)
17. Feb. 2008: Creation of the script examples
Last edited by hol.sten on Sun Mar 09, 2008 9:24 pm, edited 1 time in total.
OOo 3.2.0 on Ubuntu 10.04 • OOo 3.2.1 on Windows 7 64-bit and MS Windows XP
User avatar
Villeroy
Volunteer
Posts: 31279
Joined: Mon Oct 08, 2007 1:35 am
Location: Germany

Re: [Java, BSH and JS Script examples] Display a message box

Post by Villeroy »

Since hol.sten mentioned it, I copied my Python class from the old forum. Initialize with a parent window, such as XSCRIPTCONTEXT.getDesktop().CurrentController.ContainerWindow(). Method msgbox takes the same arguments as it's Basic equivalent and also returns the same values. Addionaly you can use the named constants of this class.
Small API bug: Notice the comments on DEFAULT_BUTTON_IGNORE. Issue 79327 has been resolved. DEFAULT_BUTTON_IGNORE should work since version 2.4

Code: Select all

class MessageBox:
    '''Message box for OpenOffice.org, like the one in the Basic macro language. To specify a MsgBox type, use the named constants of this class or the equivalent numbers described in the StarBasic online help. Specify a parent window on initialization.'''

    # Named constants for ease of use:
    OK = 0
    OK_CANCEL = 1
    ABORT_RETRY_IGNORE = 2
    YES_NO_CANCEL = 3
    YES_NO = 4
    RETRY_CANCEL = 5
    ERROR = 16
    QUERY = 32
    WARN = 48
    INFO = 64
    DEFAULT_FIRST = 128
    DEFAULT_SECOND = 256
    DEFAULT_THIRD = 512
    RESULT_OK = 1
    RESULT_CANCEL = 2
    RESULT_ABORT = 3
    RESULT_RETRY = 4
    RESULT_IGNORE = 5
    RESULT_YES = 6
    RESULT_NO = 7

    # Mapping above StarBasic MsgBox constants to awt.MessageBoxButtons and icons:
    dInput = {
        OK_CANCEL : BUTTONS_OK_CANCEL,
        # the following constant should be named BUTTONS_ABORT_RETRY_IGNORE:
        ABORT_RETRY_IGNORE : BUTTONS_ABORT_IGNORE_RETRY,
        YES_NO_CANCEL : BUTTONS_YES_NO_CANCEL,
        YES_NO : BUTTONS_YES_NO,
        RETRY_CANCEL : BUTTONS_RETRY_CANCEL,
        ERROR : 'errorbox',
        QUERY : 'querybox',
        WARN : 'warningbox',
        INFO : 'infobox', # info always shows one OK button alone!
        129 : BUTTONS_OK_CANCEL + DEFAULT_BUTTON_OK,
        130 : BUTTONS_ABORT_IGNORE_RETRY + DEFAULT_BUTTON_CANCEL,
        131 : BUTTONS_YES_NO_CANCEL + DEFAULT_BUTTON_YES,
        132 : BUTTONS_YES_NO + DEFAULT_BUTTON_YES,
        133 : BUTTONS_RETRY_CANCEL + DEFAULT_BUTTON_RETRY,
        257 : BUTTONS_OK_CANCEL + DEFAULT_BUTTON_CANCEL,
        258 : BUTTONS_ABORT_IGNORE_RETRY + DEFAULT_BUTTON_RETRY, # retry is 2nd!
        259 : BUTTONS_YES_NO_CANCEL + DEFAULT_BUTTON_NO,
        260 : BUTTONS_YES_NO + DEFAULT_BUTTON_NO,
        261 : BUTTONS_RETRY_CANCEL + DEFAULT_BUTTON_CANCEL,
        # DEFAULT_BUTTON_IGNORE works since OOo 2.4:
        514 : BUTTONS_ABORT_IGNORE_RETRY  + DEFAULT_BUTTON_IGNORE,
        # OOo <2.4 DEFAULT_BUTTON_IGNORE doesn't work at all. Use retry in this case:
        # 514 : BUTTONS_ABORT_IGNORE_RETRY  + DEFAULT_BUTTON_RETRY,
        515 : BUTTONS_YES_NO_CANCEL + DEFAULT_BUTTON_CANCEL,
        }
    dOutput = {
        1 : RESULT_OK,
        2 : RESULT_YES,
        3 : RESULT_NO,
        4 : RESULT_RETRY,
        5 : RESULT_IGNORE,
        0 : RESULT_CANCEL, # there is no constant for ABORT
        }
       
    def __init__(self, XParentWindow):
        '''Set needed objects on init'''
        try:
            self.Parent = XParentWindow
            self.Toolkit = XParentWindow.getToolkit()
        except:
            raise AttributeError, 'Did not get a valid parent window'
           
    def msgbox(self, message='', flag=0, title=''):
        '''Wrapper for com.sun.star.awt.XMessageBoxFactory.'''
        rect = uno.createUnoStruct('com.sun.star.awt.Rectangle')
        stype, buttons = self.getFlags(flag)
        box = self.Toolkit.createMessageBox(self.Parent, rect, stype, buttons, title, message)
        e = box.execute()
        # the result of execute() does not distinguish between Cancel and Abort:
        if (e == 0) and (buttons & BUTTONS_ABORT_IGNORE_RETRY == BUTTONS_ABORT_IGNORE_RETRY):
            r  = self.RESULT_ABORT
        else:
            try:
                r = self.dOutput[e]
            except KeyError:
                raise KeyError, 'Lookup of message box result '+ str(e) +' failed'

        return r

    def getFlags(self, flag):
        s = self.dInput.get(flag & 112, 'messbox')
        try:
            b = self.dInput[flag & 903]
        except KeyError:
            b = self.dInput.get(flag & 7, BUTTONS_OK)
        # print 'B/D-Flag:', flag & 7, flag & 896, 'Return:', hex(b), s
        return s, b 
Please, edit this topic's initial post and add "[Solved]" to the subject line if your problem has been solved.
Ubuntu 18.04 with LibreOffice 6.0, latest OpenOffice and LibreOffice
alexbodn
Posts: 3
Joined: Sun Jan 25, 2009 3:13 am

Re: [Java, BSH and JS Script examples] Display a message box

Post by alexbodn »

hello friends,
i've taken villeroy's final version for python, completed it from http://community.i-rs.ru/index.php/topi ... l#msg86863, and massaged it so that the msgbox function can be used without additional parameters.

Code: Select all


# downloaded from 
# http://user.services.openoffice.org/en/forum/viewtopic.php?f=45&t=2721&hilit=+beanshell+python+javascript#p12010
# with completion from
# http://community.i-rs.ru/index.php/topic,14500.msg86863.html#msg86863

# Initialize with a parent window, such as 
# XSCRIPTCONTEXT.getDesktop().CurrentController.ContainerWindow(). 
# Method msgbox takes the same arguments as it's Basic equivalent and 
# also returns the same values. Addionaly you can use the named constants 
# of this class.

from com.sun.star.awt.MessageBoxButtons import BUTTONS_OK, BUTTONS_OK_CANCEL, BUTTONS_ABORT_IGNORE_RETRY, BUTTONS_YES_NO_CANCEL, BUTTONS_YES_NO, BUTTONS_RETRY_CANCEL, DEFAULT_BUTTON_OK, DEFAULT_BUTTON_CANCEL, DEFAULT_BUTTON_RETRY, DEFAULT_BUTTON_YES, DEFAULT_BUTTON_NO, DEFAULT_BUTTON_IGNORE
import uno

class MessageBox:
    '''Message box for OpenOffice.org, like the one in the Basic macro language. 
    To specify a MsgBox type, use the named constants of this class or the 
    equivalent numbers described in the StarBasic online help. Specify a parent 
    window on initialization.'''

    # Named constants for ease of use:
    OK = 0
    OK_CANCEL = 1
    ABORT_RETRY_IGNORE = 2
    YES_NO_CANCEL = 3
    YES_NO = 4
    RETRY_CANCEL = 5
    ERROR = 16
    QUERY = 32
    WARN = 48
    INFO = 64
    DEFAULT_FIRST = 128
    DEFAULT_SECOND = 256
    DEFAULT_THIRD = 512
    RESULT_OK = 1
    RESULT_CANCEL = 2
    RESULT_ABORT = 3
    RESULT_RETRY = 4
    RESULT_IGNORE = 5
    RESULT_YES = 6
    RESULT_NO = 7

    # Mapping above StarBasic MsgBox constants to awt.MessageBoxButtons and icons:
    dInput = {
        OK_CANCEL : BUTTONS_OK_CANCEL,
        # the following constant should be named BUTTONS_ABORT_RETRY_IGNORE:
        ABORT_RETRY_IGNORE : BUTTONS_ABORT_IGNORE_RETRY,
        YES_NO_CANCEL : BUTTONS_YES_NO_CANCEL,
        YES_NO : BUTTONS_YES_NO,
        RETRY_CANCEL : BUTTONS_RETRY_CANCEL,
        ERROR : 'errorbox',
        QUERY : 'querybox',
        WARN : 'warningbox',
        INFO : 'infobox', # info always shows one OK button alone!
        129 : BUTTONS_OK_CANCEL + DEFAULT_BUTTON_OK,
        130 : BUTTONS_ABORT_IGNORE_RETRY + DEFAULT_BUTTON_CANCEL,
        131 : BUTTONS_YES_NO_CANCEL + DEFAULT_BUTTON_YES,
        132 : BUTTONS_YES_NO + DEFAULT_BUTTON_YES,
        133 : BUTTONS_RETRY_CANCEL + DEFAULT_BUTTON_RETRY,
        257 : BUTTONS_OK_CANCEL + DEFAULT_BUTTON_CANCEL,
        258 : BUTTONS_ABORT_IGNORE_RETRY + DEFAULT_BUTTON_RETRY, # retry is 2nd!
        259 : BUTTONS_YES_NO_CANCEL + DEFAULT_BUTTON_NO,
        260 : BUTTONS_YES_NO + DEFAULT_BUTTON_NO,
        261 : BUTTONS_RETRY_CANCEL + DEFAULT_BUTTON_CANCEL,
        # DEFAULT_BUTTON_IGNORE works since OOo 2.4:
        514 : BUTTONS_ABORT_IGNORE_RETRY  + DEFAULT_BUTTON_IGNORE,
        # OOo <2.4 DEFAULT_BUTTON_IGNORE doesn't work at all. Use retry in this case:
        # 514 : BUTTONS_ABORT_IGNORE_RETRY  + DEFAULT_BUTTON_RETRY,
        515 : BUTTONS_YES_NO_CANCEL + DEFAULT_BUTTON_CANCEL,
        }
    dOutput = {
        1 : RESULT_OK,
        2 : RESULT_YES,
        3 : RESULT_NO,
        4 : RESULT_RETRY,
        5 : RESULT_IGNORE,
        0 : RESULT_CANCEL, # there is no constant for ABORT
        }
       
    def __init__(self, XParentWindow):
        '''Set needed objects on init'''
        try:
            self.Parent = XParentWindow
            self.Toolkit = XParentWindow.getToolkit()
        except:
            raise AttributeError, 'Did not get a valid parent window'
           
    def msgbox(self, message='', flag=0, title=''):
        '''Wrapper for com.sun.star.awt.XMessageBoxFactory.'''
        rect = uno.createUnoStruct('com.sun.star.awt.Rectangle')
        stype, buttons = self.getFlags(flag)
        box = self.Toolkit.createMessageBox(self.Parent, rect, stype, buttons, title, message)
        e = box.execute()
        # the result of execute() does not distinguish between Cancel and Abort:
        if (e == 0) and (buttons & BUTTONS_ABORT_IGNORE_RETRY == BUTTONS_ABORT_IGNORE_RETRY):
            r  = self.RESULT_ABORT
        else:
            try:
                r = self.dOutput[e]
            except KeyError:
                raise KeyError, 'Lookup of message box result '+ str(e) +' failed'

        return r

    def getFlags(self, flag):
        s = self.dInput.get(flag & 112, 'messbox')
        try:
            b = self.dInput[flag & 903]
        except KeyError:
            b = self.dInput.get(flag & 7, BUTTONS_OK)
        # print 'B/D-Flag:', flag & 7, flag & 896, 'Return:', hex(b), s
        return s, b 

def msgbox(message='', flags=0, title=''):
    
    ctx = uno.getComponentContext() 
    smgr = ctx.ServiceManager
    oDesktop = smgr.createInstanceWithContext( 'com.sun.star.frame.Desktop',ctx)
    oDoc = oDesktop.getCurrentComponent()
    
    #oFrame = oDesktop.CurrentFrame
    oController = oDoc.CurrentController
    oFrame = oController.Frame
    oWindow = oFrame.ContainerWindow
    
    ddd = MessageBox(oWindow)
    ddd.msgbox(message, flags, title)
# -------------------------
OOo 3.0.X on Debian
Post Reply