2 * This file is part of the LibreOffice project.
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 * This file incorporates work covered by the following license notice:
10 * Licensed to the Apache Software Foundation (ASF) under one or more
11 * contributor license agreements. See the NOTICE file distributed
12 * with this work for additional information regarding copyright
13 * ownership. The ASF licenses this file to you under the Apache
14 * License, Version 2.0 (the "License"); you may not use this file
15 * except in compliance with the License. You may obtain a copy of
16 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
18 // Provides a word count of the selected text in A Writer document.
19 import com.sun.star.uno.UnoRuntime;
20 import com.sun.star.frame.XModel;
21 import com.sun.star.view.XSelectionSupplier;
22 import com.sun.star.container.XIndexAccess;
23 import com.sun.star.text.XText;
24 import com.sun.star.text.XTextRange;
25 import com.sun.star.script.provider.XScriptContext;
27 // display the count in a Swing dialog
28 void doDisplay(numWords) {
29 wordsLabel = new JLabel("Word count = " + numWords);
30 closeButton = new JButton("Close");
31 frame = new JFrame("Word Count");
32 closeButton.addActionListener(new ActionListener() {
33 actionPerformed(ActionEvent e) {
34 frame.setVisible(false);
37 frame.getContentPane().setLayout(new BorderLayout());
38 frame.getContentPane().add(wordsLabel, BorderLayout.CENTER);
39 frame.getContentPane().add(closeButton, BorderLayout.SOUTH);
41 frame.setSize(190,90);
42 frame.setLocation(430,430);
43 frame.setVisible(true);
50 // iterate through each of the selections
51 count = xIndexAccess.getCount();
52 for(i=0;i<count;i++) {
53 // get the XTextRange of the selection
54 xTextRange = (XTextRange)
55 UnoRuntime.queryInterface(XTextRange.class, xIndexAccess.getByIndex(i));
56 //System.out.println("string: "+xTextRange.getString());
57 // use the standard J2SE delimiters to tokenize the string
58 // obtained from the XTextRange
59 strTok = new StringTokenizer(xTextRange.getString());
60 result += strTok.countTokens();
67 // The XSCRIPTCONTEXT variable is of type XScriptContext and is available to
68 // all BeanShell scripts executed by the Script Framework
70 UnoRuntime.queryInterface(XModel.class, XSCRIPTCONTEXT.getDocument());
71 //the writer controller impl supports the css.view.XSelectionSupplier interface
72 xSelectionSupplier = (XSelectionSupplier)
73 UnoRuntime.queryInterface(XSelectionSupplier.class, xModel.getCurrentController());
74 //see section 7.5.1 of developers' guide
75 // the getSelection provides an XIndexAccess to the one or more selections
76 xIndexAccess = (XIndexAccess)
77 UnoRuntime.queryInterface(XIndexAccess.class, xSelectionSupplier.getSelection());
80 System.out.println("count = "+count);