diff options
Diffstat (limited to 'extensions/coooder/source/org/libreoffice/coooder/comp')
18 files changed, 0 insertions, 3561 deletions
diff --git a/extensions/coooder/source/org/libreoffice/coooder/comp/CompiledPatternsCache.java b/extensions/coooder/source/org/libreoffice/coooder/comp/CompiledPatternsCache.java deleted file mode 100644 index 0ce5274d6..000000000 --- a/extensions/coooder/source/org/libreoffice/coooder/comp/CompiledPatternsCache.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * LibreOffice extension for syntax highlighting - * Copyright (C) 2008 Cédric Bosdonnat cedric.bosdonnat.ooo@free.fr - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; - * version 2 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ -package org.libreoffice.coooder.comp; - -import java.util.HashMap; -import java.util.regex.Pattern; - -/** - * Manages the compiled regexp patterns in order to save execution time. - * - * <em>This improvement saves only 3% of time on the whole process.</em> - * - * @author cbosdonnat - * - */ -public class CompiledPatternsCache { - - private HashMap mCache = new HashMap(); - - /** - * Get the compiled pattern corresponding to the given regexp and flags. - * - * <p>Get the {@link Pattern} from the cache if it has already been used - * or compile the pattern and store it.</p> - * - * @param pRegexp the regexp to get - * @param pFlags the flags for the regexp - * - * @return the compiled {@link Pattern} object - */ - public Pattern getPattern(String pRegexp, int pFlags) { - String key = pRegexp + "-" + pFlags; - Pattern compiled = (Pattern)mCache.get(key); - - if (compiled == null) { - compiled = Pattern.compile(pRegexp, pFlags); - mCache.put(key, compiled); - } - - return compiled; - } - - /** - * Cleans the cache. - */ - public void cleanCache() { - mCache.clear(); - } -} diff --git a/extensions/coooder/source/org/libreoffice/coooder/comp/DefinitionsConstants.java b/extensions/coooder/source/org/libreoffice/coooder/comp/DefinitionsConstants.java deleted file mode 100644 index d6b08714a..000000000 --- a/extensions/coooder/source/org/libreoffice/coooder/comp/DefinitionsConstants.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * LibreOffice extension for syntax highlighting - * Copyright (C) 2008 Cédric Bosdonnat cedric.bosdonnat.ooo@free.fr - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; - * version 2 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ -package org.libreoffice.coooder.comp; - -/** - * Constants describing the languages.xsd content. - * - * @author cbosdonnat - * - */ -public interface DefinitionsConstants { - - Object NODE_LANGUAGE = "language"; - String ATTR_ID = "id"; - String ATTR_OO = "objectOriented"; - String ATTR_NAME = "name"; - String ATTR_ESCAPE_CHAR = "escapeChar"; - - String NODE_OO_SPLITTERS = "objectSplitters"; - Object NODE_OO_SPLITTER = "splitter"; - - Object NODE_VALUE = "value"; - String NODE_SYMBOLS = "symbols"; - String NODE_QUOTEMARKS = "quotemarks"; - String NODE_HARDQUOTES = "hardquotes"; - String NODE_HARDESCAPES = "hardquoteEscapes"; - - String NODE_COMMENTS = "comments"; - String ATTR_CASE_SENSITIVE = "caseSensitive"; - Object NODE_SINGLE = "single"; - Object NODE_MULTIPLE = "multiple"; - String NODE_OPENING = "opening"; - String NODE_CLOSING = "closing"; - - String NODE_KEYWORDS = "keywords"; - - Object NODE_SET = "set"; - - String NODE_REGEXPS = "regexps"; - String NODE_REGEXP = "regexp"; - String ATTR_VALUE = "value"; - - String NODE_STYLES = "styles"; - String NODE_STYLE = "style"; - String ATTR_ELEMENT = "element"; - String ATTR_BOLD = "bold"; - String ATTR_ITALIC = "italic"; - String ATTR_COLOR = "color"; - - - String STYLE_COMMENT_MULTI = "comment_multi"; - String STYLE_STRING = "string"; - String STYLE_ESCAPED = "escaped"; - String STYLE_SYMBOL = "symbol"; - String STYLE_NUMBER = "number"; - String STYLE_COMMENT = "comment"; - String STYLE_KEYWORD = "keyword"; - String STYLE_REGEXP = "regexp"; - String STYLE_MEMBER = "member"; -} diff --git a/extensions/coooder/source/org/libreoffice/coooder/comp/HighlighterImpl.java b/extensions/coooder/source/org/libreoffice/coooder/comp/HighlighterImpl.java deleted file mode 100644 index fb3d1869f..000000000 --- a/extensions/coooder/source/org/libreoffice/coooder/comp/HighlighterImpl.java +++ /dev/null @@ -1,640 +0,0 @@ -/* - * LibreOffice extension for syntax highlighting - * Copyright (C) 2008 Cédric Bosdonnat cedric.bosdonnat.ooo@free.fr - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; - * version 2 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ -package org.libreoffice.coooder.comp; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.libreoffice.coooder.HighlightingException; -import org.libreoffice.coooder.XHighlighter; -import org.libreoffice.coooder.XLanguage; - -import com.sun.star.frame.XController; -import com.sun.star.frame.XDesktop; -import com.sun.star.frame.XModel; -import com.sun.star.lang.XComponent; -import com.sun.star.lang.XMultiComponentFactory; -import com.sun.star.lang.XServiceInfo; -import com.sun.star.lang.XSingleComponentFactory; -import com.sun.star.lib.uno.helper.Factory; -import com.sun.star.lib.uno.helper.WeakBase; -import com.sun.star.registry.XRegistryKey; -import com.sun.star.task.XStatusIndicator; -import com.sun.star.text.XParagraphCursor; -import com.sun.star.text.XTextCursor; -import com.sun.star.text.XTextDocument; -import com.sun.star.text.XTextRange; -import com.sun.star.text.XTextViewCursor; -import com.sun.star.text.XTextViewCursorSupplier; -import com.sun.star.uno.Exception; -import com.sun.star.uno.UnoRuntime; -import com.sun.star.uno.XComponentContext; - -/** - * Highlighter implementation using the GeSHi algorithm adapted to LibreOffice API. - * - * @author cbosdonnat - */ -public final class HighlighterImpl extends WeakBase implements XServiceInfo, XHighlighter { - - private static final String IMPLEMENTATION_NAME = HighlighterImpl.class.getName(); - private static final String[] SERVICE_NAMES = { "org.libreoffice.coooder.Highlighter" }; - - private static final int OPEN = 0; - private static final int CLOSE = 1; - - private static final String NUMBER_REGEX = "[-+]?\\b(?:[0-9]*\\.)?[0-9]+\\b"; - - - private final XComponentContext mContext; - private XLanguage mLanguage; - - private CompiledPatternsCache mPatternsCache; - - private XTextRange mSelectionStart; - private XTextDocument mTextDocument; - private int mLength; - - private XStatusIndicator mStatus; - - public HighlighterImpl(XComponentContext pContext) { - mContext = pContext; - mPatternsCache = new CompiledPatternsCache(); - }; - - public static XSingleComponentFactory __getComponentFactory( String pImplementationName ) { - XSingleComponentFactory xFactory = null; - - if (pImplementationName.equals(IMPLEMENTATION_NAME)) { - xFactory = Factory.createComponentFactory(HighlighterImpl.class, SERVICE_NAMES); - } - return xFactory; - } - - public static boolean __writeRegistryServiceInfo(XRegistryKey pRegistryKey) { - return Factory.writeRegistryServiceInfo(IMPLEMENTATION_NAME, - SERVICE_NAMES, pRegistryKey); - } - - - //------------------------------------------ com.sun.star.lang.XServiceInfo - - - public String getImplementationName() { - return IMPLEMENTATION_NAME; - } - - public boolean supportsService( String sService ) { - int len = SERVICE_NAMES.length; - - for( int i=0; i < len; i++) { - if (sService.equals(SERVICE_NAMES[i])) - return true; - } - return false; - } - - public String[] getSupportedServiceNames() { - return SERVICE_NAMES; - } - - - //------------------------------------- org.libreoffice.coooder.XHighlighter - - public XLanguage getLanguage() { - return mLanguage; - } - - public void setLanguage(XLanguage pLanguage) { - mLanguage = pLanguage; - } - - public void setStatusIndicator(XStatusIndicator pStatus) { - mStatus = pStatus; - } - - public void parse() throws HighlightingException { - XMultiComponentFactory mngr = mContext.getServiceManager(); - try { - // Start with a clean patterns cache - mPatternsCache.cleanCache(); - - updateProgress(0); - - boolean COMMENT_MATCHED = false; - int parseStartPos = 0; - int parseEndPos = 0; - - // Get the visual cursor - XTextViewCursor selection = null; - - Object o = mngr.createInstanceWithContext("com.sun.star.frame.Desktop", mContext); - XDesktop desktop = (XDesktop)UnoRuntime.queryInterface(XDesktop.class, o); - - XComponent component = desktop.getCurrentComponent(); - XServiceInfo compInfos = (XServiceInfo)UnoRuntime.queryInterface(XServiceInfo.class, component); - if (compInfos.supportsService("com.sun.star.text.TextDocument")) { - XModel model = (XModel)UnoRuntime.queryInterface(XModel.class, component); - XController controller = model.getCurrentController(); - XTextViewCursorSupplier cursSupplier = (XTextViewCursorSupplier)UnoRuntime.queryInterface( - XTextViewCursorSupplier.class, controller); - selection = cursSupplier.getViewCursor(); - } - String selectedString = Utils.getSelection(selection); - - mSelectionStart = selection.getStart(); - mLength = selectedString.length(); - - // Create an invisible cursor. - mTextDocument = (XTextDocument)UnoRuntime.queryInterface( - XTextDocument.class, component); - XTextCursor cursor = mTextDocument.getText().createTextCursor(); - - // Iterate over each character of the selected text - for (int i = 0; i < selectedString.length(); i++) { - - String car = selectedString.substring(i, i + 1); - String hq = ""; - if (mLanguage.getHardquote().length > 0) { - hq = mLanguage.getHardquote()[0]; - } - - if (Utils.arrayContains(mLanguage.getQuotemarks(), car)) { - // A string has been found - - // Parse the non-string part before this string - parseNonString(cursor, parseStartPos, parseEndPos); - - // Get the end of the string - String escape = ""; - if (!mLanguage.getEscapeChar().equals("")) { - escape = mLanguage.getEscapeChar(); - } - int closePos = getClosePos(selectedString, i + 1, car, escape); - - String style = getStyleName(DefinitionsConstants.STYLE_STRING, null); - setStyle(cursor, style, i, closePos + 1); - - // Parse the string to highlight escaped characters - parseString(cursor, i + 1, closePos); - - i = closePos; - - // Set the positions for non string parsing for after the string - parseStartPos = closePos + 1; - updateProgress(Math.round((parseStartPos * 100) / mLength)); - - } else if (!hq.equals("") && - i + hq.length() < selectedString.length() && - selectedString.substring(i, i + hq.length()).equals(hq)) { - // The start of a hard quoted string - - // Parse the non-string part before this string - parseNonString(cursor, parseStartPos, parseEndPos); - - // Get the end of the hardquoted string - String close = mLanguage.getHardquote()[1]; - i += hq.length() - 1; - int closePos = getHardquotedClosePos(selectedString, i + hq.length(), - close, mLanguage.getHardEscapes()); - - // Set the string style on the characters - String style = getStyleName(DefinitionsConstants.STYLE_STRING, null); - setStyle(cursor, style, i - 1, closePos + close.length()); - - // Parse the hardquoted string - parseHarquoted(cursor, i + hq.length() - 1, closePos + 1); - i = closePos; - - // Set the positions for non string parsing for after the string - parseStartPos = closePos + 1; - updateProgress(Math.round((parseStartPos * 100) / mLength)); - - } else { - // Is this a multiline comment? - for (int j = 0; j < mLanguage.getCommentMulti().length; j++) { - String open = mLanguage.getCommentMulti()[j][OPEN]; - String close = mLanguage.getCommentMulti()[j][CLOSE]; - - // Get the text of the open delimiter length from the cursor - String test_str = ""; - if (i + open.length() < selectedString.length()) { - test_str = selectedString.substring(i, i + open.length()); - } - - if (open.equals(test_str)) { - COMMENT_MATCHED = true; - - // Parse the non-string part before this comment - parseNonString(cursor, parseStartPos, parseEndPos); - - // Find the position of the close element - int closePos = selectedString.indexOf(close, i + open.length()); - - if (closePos == -1) { - closePos = selectedString.length(); - } else { - closePos -= open.length() - close.length(); - } - - // Set the comment style on the characters - String style = getStyleName(DefinitionsConstants.STYLE_COMMENT_MULTI, null); - setStyle(cursor, style, i, closePos + close.length()); - - // Short-cut through all the multiline code - i = closePos + open.length() - 1; - - // Set the parse positions for after the comment - parseStartPos = i + 1; - updateProgress(Math.round((parseStartPos * 100) / mLength)); - - break; - } - } - - // If we haven't matched a multiline comment, try single-line comments - if (!COMMENT_MATCHED) { - for (int j = 0; j < mLanguage.getCommentSingle().length; j++) { - String commentMark = mLanguage.getCommentSingle()[j]; - String test_str = ""; - if (i + commentMark.length() < selectedString.length()) { - test_str = selectedString.substring(i, i + commentMark.length()); - } - - boolean match = commentMark.equals(test_str); - // Check for case sensitivity - if (!mLanguage.getCommentCaseSensitivity()) { - match = commentMark.toLowerCase().equals(test_str.toLowerCase()); - } - if (match) { - - // Parse the non-string part before this comment - parseNonString(cursor, parseStartPos, parseEndPos); - - COMMENT_MATCHED = true; - - // Get the end of the paragraph - cursor.gotoRange(mSelectionStart, false); - Utils.goRight(cursor, i, false); - - XParagraphCursor paraCursor = (XParagraphCursor)UnoRuntime.queryInterface( - XParagraphCursor.class, cursor); - paraCursor.gotoEndOfParagraph(true); - - // Set the comment style on the characters - String style = getStyleName(DefinitionsConstants.STYLE_COMMENT, Integer.valueOf(j)); - Utils.createStyle(mTextDocument, style, mLanguage); - Utils.setStyle(paraCursor, style); - - int length = paraCursor.getString().length(); - i += length; - - // Set the parse positions for the after the comment - parseStartPos = i; - updateProgress(Math.round((parseStartPos * 100) / mLength)); - } - } - } - } - - parseEndPos = i + 1; - - // Where are we adding this char? - if (COMMENT_MATCHED) { - COMMENT_MATCHED = false; - } - } - - parseNonString(cursor, parseStartPos, parseEndPos); - - updateProgress(100); - - } catch (Exception e) { - throw new HighlightingException("Parsing error", e); - } - } - - - //-------------------------------------------------------- Internal methods - - private void updateProgress(int pValue) { - if (mStatus != null) { - mStatus.setValue(pValue); - } - } - - private void parseNonString(XTextCursor pCursor, int pStart, int pEnd) throws Exception { - - // Get the selected String - pCursor.gotoRange(mSelectionStart, false); - String selected = Utils.getSelection(pCursor, pStart, pEnd); - - // Use Matcher.find() and its regionStart and regionEnd fields for all this method - - // Regular expressions - // Loop over the language's regular expressions and highlight them - for (int i = 0; i < mLanguage.getRegexps().length; i++) { - String regexp = mLanguage.getRegexps()[i]; - - // FIXME A Regexp can be more complex than just a simple string (eg: css.php) - String style = getStyleName(DefinitionsConstants.STYLE_REGEXP, Integer.valueOf(i)); - replaceStyle(style, regexp, 0, 0, selected, pCursor, pStart); - } - - // Look for the numbers and highlight the numbers - String style = getStyleName(DefinitionsConstants.STYLE_NUMBER, null); - replaceStyle(style, NUMBER_REGEX, 0, 0, selected, pCursor, pStart); - - // Loop over the keywords and their categories to highlight them - String[][] keywords = mLanguage.getKeywords(); - for (int i = 0; i < keywords.length; i++) { - String[] keywordset = keywords[i]; - for (int j = 0; j < keywordset.length; j++) { - - int flags = 0; - // Check if the keyword is case insensitive - if (!mLanguage.isKeywordCaseSensitive(i)) { - flags = Pattern.CASE_INSENSITIVE; - } - - String keyword = keywordset[j]; - style = getStyleName(DefinitionsConstants.STYLE_KEYWORD, Integer.valueOf(i)); - - // Escapes the possible leading ? to avoid breaking the regexp - if (keyword.startsWith("?")) { - keyword = "\\" + keyword; - } - - String regexp = "([^a-zA-Z0-9\\$_\\|\\#;>|^]|^)(" + keyword - + ")(?=[^a-zA-Z0-9_<\\|%\\-&]|$)"; - - replaceStyle(style, regexp, flags, 2, selected, pCursor, pStart); - } - } - - // Highlight the object's methods and fields - if (mLanguage.getObjectOriented()) { - for (int i = 0; i < mLanguage.getObjectSplitters().length; i++) { - String splitter = mLanguage.getObjectSplitters()[i]; - if (selected.contains(splitter)) { - String regexp = "(" + Pattern.quote(splitter) + "[\\s]*)([a-zA-Z\\*\\(][a-zA-Z0-9_\\*]*)"; - style = getStyleName(DefinitionsConstants.STYLE_MEMBER, Integer.valueOf(i)); - replaceStyle(style, regexp, 0, 2, selected, pCursor, pStart); - } - } - } - - // Highlight the symbols - for (int i = 0; i < mLanguage.getSymbols().length; i++) { - String[] symbolsSet = mLanguage.getSymbols()[i]; - for (int j = 0; j < symbolsSet.length; j++) { - String regexp = Pattern.quote(symbolsSet[j]); - style = getStyleName(DefinitionsConstants.STYLE_SYMBOL, Integer.valueOf(i)); - replaceStyle(style, regexp, 0, 0, selected, pCursor, pStart); - } - } - } - - /** - * Parse a string and highlight the escaped characters and the - * character following them. - * - * @param pCursor the cursor - * @param pStart the start position of the string - * @param pStop the end position of the string - * - * @throws Exception if the styles can't be set on the escaped strings. - */ - private void parseString(XTextCursor pCursor, int pStart, int pStop) throws Exception { - - if (!mLanguage.getEscapeChar().equals("")) { - // Get the selected String - pCursor.gotoRange(mSelectionStart, false); - String selected = Utils.getSelection(pCursor, pStart, pStop); - - // Highlight the escaped characters - String escapeChar = mLanguage.getEscapeChar(); - for (int i = 0; i < selected.length(); i++) { - - if (i < selected.length() - 1 && - selected.subSequence(i, i + 1).equals(escapeChar)) { - // Highlight with the next character - String style = getStyleName(DefinitionsConstants.STYLE_ESCAPED, null); - setStyle(pCursor, style, - pStart + i, pStart + i + 2); - i++; - } - } - } - } - - /** - * Parse a hardquoted string and highlight the escaped strings. - * - * @param pCursor the cursor - * @param pStart the start position of the string - * @param pStop the end position of the string - * - * @throws Exception if the styles can't be set on the escaped strings. - */ - private void parseHarquoted(XTextCursor pCursor, int pStart, int pStop) throws Exception { - String[] hardescapes = mLanguage.getHardEscapes(); - - pCursor.gotoRange(mSelectionStart, false); - String selected = Utils.getSelection(pCursor, pStart, pStop); - - // Highlight the hardescaped strings - for (int i = 0; i < selected.length(); i++) { - String hardescaped = ""; - int j = 0; - while (hardescaped.equals("") && j < hardescapes.length) { - String hardescape = hardescapes[j]; - if (hardescape.length() + i < selected.length()) { - String test_str = selected.substring(i, i + hardescape.length()); - if (test_str.equals(hardescape)) { - hardescaped = test_str; - } - } - j++; - } - - if (!hardescaped.equals("")) { - String style = getStyleName(DefinitionsConstants.STYLE_ESCAPED, null); - setStyle(pCursor, style, pStart + i, - pStart + i + hardescaped.length()); - } - } - } - - /** - * Set the given character style to all the elements matching the regexp. - * - * @param pStyle the style to apply - * @param pRegexp the regexp to match - * @param pFlags the regexp flags - * @param pGroup the group of the regexp on which to apply the style - * @param pSelected the text to search - * @param pCursor the text cursor - * @param pStart the start position of the text to search relative to the selection start - * - * @throws Exception if anything wrong happens - */ - private void replaceStyle(String pStyle, String pRegexp, int pFlags, int pGroup, String pSelected, - XTextCursor pCursor, int pStart) throws Exception { - Matcher matcher = mPatternsCache.getPattern(pRegexp, pFlags).matcher(pSelected); - while (matcher.find()) { - int start = matcher.start(pGroup); - int end = matcher.end(pGroup); - - setStyle(pCursor, pStyle, pStart + start, pStart + end); - } - } - - /** - * Finds the first non-escaped occurrence of the close string in the - * selection after the start position. - * - * @param pSelected the selection where to look for the close string - * @param pStart the position from which to start searching - * @param pClose the close string to look for - * @param pEscape the escape sequence - * - * @return the position of the close string or <code>-1</code> - */ - private int getClosePos(String pSelected, int pStart, String pClose, String pEscape) { - - int closePos = -1; - - boolean escape_open = false; - - int i = pStart; - while (closePos < 0 && i < pSelected.length()) { - - String test_close = pSelected.substring(i, i + pClose.length()); - if (!escape_open && test_close.equals(pClose)) { - // Test the closing char - closePos = i; - } else if (!escape_open) { - - // Test for an escape character - String escaped = ""; - if (i + pEscape.length() < pSelected.length()) { - String test_escape = pSelected.substring(i, i + pEscape.length()); - - if (test_escape.equals(pEscape)) { - escaped = test_escape; - } - } - - if (!escaped.equals("")) { - i += escaped.length(); - escape_open = true; - } else { - i++; - } - } else { - i++; - escape_open = false; - } - } - - - if (closePos == -1) { - closePos = pSelected.length() - 1; - } - - return closePos; - } - - /** - * Finds the first non-escaped occurrence of the close string in the - * selection after the start position. - * - * @param pSelected the selection where to look for the close string - * @param pStart the position from which to start searching - * @param pClose the close string to look for - * @param pEscapes the escape sequences that doesn't count as a close string - * - * @return the position of the close string or <code>-1</code> - */ - private int getHardquotedClosePos(String pSelected, int pStart, String pClose, String[] pEscapes) { - - int closePos = -1; - - int i = pStart; - while (closePos < 0 && i < pSelected.length()) { - - // Test the closing char - String test_close = pSelected.substring(i, i + pClose.length()); - if (test_close.equals(pClose)) { - closePos = i; - } - - // Test for an escape sequence - String escaped = ""; - - int j = 0; - while (j < pEscapes.length && escaped.equals("")) { - String escape = pEscapes[j]; - if (i + escape.length() < pSelected.length()) { - String test_escape = pSelected.substring(i, i + escape.length()); - - if (test_escape.equals(escape)) { - escaped = test_escape; - } - } - j++; - } - - if (!escaped.equals("")) { - i += escaped.length() - 1; - } - i++; - } - - - if (closePos == -1) { - closePos = pSelected.length() - 1; - } - - return closePos; - } - - private String getStyleName(String pStyle, Object pArgument) { - - String style = pStyle; - if (pArgument != null) { - style += pArgument.toString(); - } - style += "_" + mLanguage.getId(); - - return style; - } - - private void setStyle(XTextCursor pSelection, String pStyle, int pStart, int pStop) - throws Exception { - - pSelection.gotoRange(mSelectionStart, false); - Utils.goRight(pSelection, pStart, false); - Utils.goRight(pSelection, pStop - pStart, true); - - Utils.createStyle(mTextDocument, pStyle, mLanguage); - Utils.setStyle(pSelection, pStyle); - } -} diff --git a/extensions/coooder/source/org/libreoffice/coooder/comp/LanguageImpl.java b/extensions/coooder/source/org/libreoffice/coooder/comp/LanguageImpl.java deleted file mode 100644 index 8e41c0808..000000000 --- a/extensions/coooder/source/org/libreoffice/coooder/comp/LanguageImpl.java +++ /dev/null @@ -1,707 +0,0 @@ -/* - * LibreOffice extension for syntax highlighting - * Copyright (C) 2008 Cédric Bosdonnat cedric.bosdonnat.ooo@free.fr - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; - * version 2 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ -package org.libreoffice.coooder.comp; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map.Entry; - -import org.libreoffice.coooder.HighlightingException; -import org.libreoffice.coooder.XLanguage; - -import com.sun.star.io.XInputStream; -import com.sun.star.lang.XMultiComponentFactory; -import com.sun.star.lang.XServiceInfo; -import com.sun.star.lang.XSingleComponentFactory; -import com.sun.star.lib.uno.helper.Factory; -import com.sun.star.lib.uno.helper.WeakBase; -import com.sun.star.registry.XRegistryKey; -import com.sun.star.ucb.XSimpleFileAccess2; -import com.sun.star.uno.UnoRuntime; -import com.sun.star.uno.XComponentContext; -import com.sun.star.xml.dom.XDocument; -import com.sun.star.xml.dom.XDocumentBuilder; -import com.sun.star.xml.dom.XNode; -import com.sun.star.xml.dom.XNodeList; - - -public final class LanguageImpl extends WeakBase implements XServiceInfo, XLanguage { - - private static final String IMPLEMENTATION_NAME = LanguageImpl.class.getName(); - private static final String[] SERVICE_NAMES = { "org.libreoffice.coooder.Language" }; - - private XComponentContext mContext; - - private String mId; - private String mName; - - private String[] mCommentSingle; - private String[][] mCommentMulti; - private String[] mHardquote = new String[0]; - private String[] mHardEscapes = new String[0]; - private String[] mQuotemarks; - private String mEscapeChar; - private String[] mRegexps; - private String[][] mKeywords; - private boolean mObjectOriented; - private String[] mObjectSplitters; - private String[][] mSymbols; - private boolean mCommentCaseSensitivity; - private HashMap mKeywordCaseSensitivity = new HashMap(); - private HashMap mStyles; - - - public LanguageImpl(XComponentContext pContext) { - mContext = pContext; - }; - - public static XSingleComponentFactory __getComponentFactory(String pImplementationName) { - XSingleComponentFactory xFactory = null; - - if (pImplementationName.equals(IMPLEMENTATION_NAME)) { - xFactory = Factory.createComponentFactory(LanguageImpl.class, SERVICE_NAMES); - } - return xFactory; - } - - public static boolean __writeRegistryServiceInfo( XRegistryKey pRegistryKey ) { - return Factory.writeRegistryServiceInfo(IMPLEMENTATION_NAME, - SERVICE_NAMES, pRegistryKey); - } - - - //------------------------------------------ com.sun.star.lang.XServiceInfo - - - public String getImplementationName() { - return IMPLEMENTATION_NAME; - } - - public boolean supportsService( String sService ) { - int len = SERVICE_NAMES.length; - - for( int i=0; i < len; i++) { - if (sService.equals(SERVICE_NAMES[i])) - return true; - } - return false; - } - - public String[] getSupportedServiceNames() { - return SERVICE_NAMES; - } - - //---------------------------------------- org.libreoffice.coooder.XLanguage - - - public String getId() { - return mId; - } - - public void setId(String pId) { - mId = pId; - } - - public String getName() { - return mName; - } - - public void setName(String pName) { - mName = pName; - } - - public String[] getCommentSingle() { - return mCommentSingle; - } - - public void setCommentSingle(String[] pComments) { - mCommentSingle = pComments; - } - - public String[][] getCommentMulti() { - return mCommentMulti; - } - - public void setCommentMulti(String[][] pComments) { - mCommentMulti = pComments; - } - - public String[] getHardquote() { - return mHardquote; - } - - public void setHardquote(String[] pHardquote) { - mHardquote = pHardquote; - } - - public String[] getHardEscapes() { - return mHardEscapes; - } - - public void setHardEscapes(String[] pHardEscapes) { - mHardEscapes = pHardEscapes; - } - - public String[] getQuotemarks() { - return mQuotemarks; - } - - public void setQuotemarks(String[] pQuotemarks) { - mQuotemarks = pQuotemarks; - } - - public String getEscapeChar() { - return mEscapeChar; - } - - public void setEscapeChar(String pEscapeChar) { - mEscapeChar = pEscapeChar; - } - - public String[] getRegexps() { - return mRegexps; - } - - public void setRegexps(String[] pRegexps) { - mRegexps = pRegexps; - } - - public String[][] getKeywords() { - return mKeywords; - } - - public void setKeywords(String[][] pKeywords) { - mKeywords = pKeywords; - } - - public boolean getObjectOriented() { - return mObjectOriented; - } - - public void setObjectOriented(boolean pObjectOriented) { - mObjectOriented = pObjectOriented; - } - - public String[] getObjectSplitters() { - return mObjectSplitters; - } - - public void setObjectSplitters(String[] pObjectSplitters) { - mObjectSplitters = pObjectSplitters; - } - - public String[][] getSymbols() { - return mSymbols; - } - - public void setSymbols(String[][] pSymbols) { - mSymbols = pSymbols; - } - - public boolean getCommentCaseSensitivity() { - return mCommentCaseSensitivity; - } - - public void setCommentCaseSensitivity(boolean pCommentCaseSensitivity) { - mCommentCaseSensitivity = pCommentCaseSensitivity; - } - - public boolean isKeywordCaseSensitive(int pKeywordGroup) { - boolean caseSensitive = true; - Integer key = Integer.valueOf(pKeywordGroup); - if (mKeywordCaseSensitivity.containsKey(key)) { - caseSensitive = ((Boolean)mKeywordCaseSensitivity.get(key)).booleanValue(); - } - return caseSensitive; - } - - public void setKeywordCaseSensitivity(int pKeywordGroup, boolean pCaseSensitive) { - - Integer key = Integer.valueOf(pKeywordGroup); - Boolean value = Boolean.valueOf(pCaseSensitive); - mKeywordCaseSensitivity.put(key, value); - } - - public HashMap getStyles() { - return mStyles; - } - - public void defineFromXml(String pFileUrl) throws HighlightingException { - - long start = Calendar.getInstance().getTimeInMillis(); - - XInputStream in = null; - try { - XMultiComponentFactory xFactory = mContext.getServiceManager(); - Object o = xFactory.createInstanceWithContext( - "com.sun.star.ucb.SimpleFileAccess", mContext); - XSimpleFileAccess2 xFileAccess = (XSimpleFileAccess2)UnoRuntime.queryInterface( - XSimpleFileAccess2.class, o); - in = xFileAccess.openFileRead(pFileUrl); - - // Parse the XML file - o = xFactory.createInstanceWithContext( - "com.sun.star.xml.dom.DocumentBuilder", mContext); - XDocumentBuilder xDocBuilder = (XDocumentBuilder)UnoRuntime.queryInterface( - XDocumentBuilder.class, o); - - XDocument xDom = xDocBuilder.parse(in); - - // Initialize the language service instance from the configuration - XNode languageNode = xDom.getFirstChild(); - - // Normalize the tree - languageNode.normalize(); - - if (languageNode.getNodeName().equals(DefinitionsConstants.NODE_LANGUAGE)) { - - // Initialize the main properties - mId = Utils.getAttribute(languageNode, DefinitionsConstants.ATTR_ID); - mName = Utils.getAttribute(languageNode, DefinitionsConstants.ATTR_NAME); - - String oo = Utils.getAttribute(languageNode, DefinitionsConstants.ATTR_OO); - mObjectOriented = Boolean.parseBoolean(oo); - - mEscapeChar = Utils.getAttribute(languageNode, DefinitionsConstants.ATTR_ESCAPE_CHAR); - - // Map of map of ids - HashMap ids = new HashMap(); - - // Initialize the object splitters - HashMap splittersIds = initSplitters(languageNode); - ids.put(DefinitionsConstants.STYLE_MEMBER, splittersIds); - - // Initialize the comments - HashMap commentsIds = initComments(languageNode); - ids.put(DefinitionsConstants.STYLE_COMMENT, commentsIds); - - // Initialize the symbols - HashMap symbolsIds = initSymbols(languageNode); - ids.put(DefinitionsConstants.STYLE_SYMBOL, symbolsIds); - - // Initialize the quotemarks - mQuotemarks = Utils.getValues(languageNode, - DefinitionsConstants.NODE_QUOTEMARKS, true); - - // Initialize the hardquotes - mHardquote = Utils.getValues(languageNode, - DefinitionsConstants.NODE_HARDQUOTES, false); - - // Initialize the hardquote escapes - mHardEscapes = Utils.getValues(languageNode, - DefinitionsConstants.NODE_HARDESCAPES, false); - - // Initialize the keywords - HashMap keywordsIds = initKeywords(languageNode); - ids.put(DefinitionsConstants.STYLE_KEYWORD, keywordsIds); - - // Initialize the regexps - HashMap regexpIds = initRegexps(languageNode); - ids.put(DefinitionsConstants.STYLE_REGEXP, regexpIds); - - // Initialize the styles informations - initStyles(languageNode, ids); - } - - } catch (Exception e) { - // Raises Highlighting exception - throw new HighlightingException(e.getMessage()); - } finally { - // Close the stream properly - try { in.closeInput(); } catch (Exception e) { } - - long end = Calendar.getInstance().getTimeInMillis(); - long duration = end - start; - - System.out.println("Language file parsing: (in ms)" + duration); - } - } - - /** - * Initializes the object splitters from the DOM language node and build a map - * of the splitters IDs. - * - * @param pLanguageNode the DOM language node. - * - * @return a map of {@link String} to {@link Integer} mapping the object - * splitters ID to their position in the splitters array. - */ - private HashMap initSplitters(XNode pLanguageNode) { - HashMap ids = new HashMap(); - - // Get the splitters into a temporary list - ArrayList splitters = new ArrayList(); - XNode splittersNode = Utils.getChild(pLanguageNode, - DefinitionsConstants.NODE_OO_SPLITTERS); - if (splittersNode != null) { - XNodeList children = splittersNode.getChildNodes(); - for (int i = 0, length = children.getLength(); i < length; i++) { - XNode regexpNode = children.item(i); - - if (regexpNode.getNodeName().equals( - DefinitionsConstants.NODE_OO_SPLITTER)) { - try { - // Get the ID - String id = Utils.getAttribute(regexpNode, - DefinitionsConstants.ATTR_ID); - - // Get the value - String value = Utils.getAttribute(regexpNode, - DefinitionsConstants.ATTR_VALUE); - - // Update the list and map - splitters.add(value); - int pos = splitters.size() - 1; - ids.put(id, Integer.valueOf(pos)); - - } catch (HighlightingException e) { - // Do not add the splitter without ID or value - } - } - } - } - - // Set the splitters - mObjectSplitters = new String[splitters.size()]; - for (int i = 0, length = mObjectSplitters.length; i < length; i++) { - mObjectSplitters[i] = (String) splitters.get(i); - } - - return ids; - } - - /** - * Sets the comments and build a mapping with their IDs for use to associate the styles. - * - * @param pLanguageNode the language DOM node from which to extract the comments - * - * @return a map of {@link String} to {@link Integer} mapping the single comments ID - * to their position in the single comments array. - */ - private HashMap initComments(XNode pLanguageNode) { - - XNode commentsNode = Utils.getChild(pLanguageNode, DefinitionsConstants.NODE_COMMENTS); - - // Temporary arrays for the comments - ArrayList singleComments = new ArrayList(); - ArrayList multiComments = new ArrayList(); - - // Map for the single-line comments ids - HashMap ids = new HashMap(); - - if (commentsNode != null) { - // Get the case sensitivity of the comments - try { - String value = Utils.getAttribute(commentsNode, DefinitionsConstants.ATTR_CASE_SENSITIVE); - mCommentCaseSensitivity = Boolean.parseBoolean(value); - } catch (Exception e) { - // Default is true - mCommentCaseSensitivity = true; - } - - // Get the comments themselves - XNodeList children = commentsNode.getChildNodes(); - for (int i = 0, length = children.getLength(); i < length; i++) { - XNode commentNode = children.item(i); - - boolean isSingle = commentNode.getNodeName().equals( - DefinitionsConstants.NODE_SINGLE); - boolean isMultiple = commentNode.getNodeName().equals( - DefinitionsConstants.NODE_MULTIPLE); - - if (isSingle) { - // Get the opening symbol - XNode openNode = Utils.getChild(commentNode, DefinitionsConstants.NODE_OPENING); - String open = Utils.getTextValue(openNode); - - // Update the map and list - try { - String id = Utils.getAttribute(commentNode, DefinitionsConstants.ATTR_ID); - singleComments.add(open); - - int pos = singleComments.size() - 1; - ids.put(id, Integer.valueOf(pos)); - } catch (HighlightingException e) { - // Do not add the comment: it has no ID - } - } - - if (isMultiple) { - // Get the opening symbol - XNode openNode = Utils.getChild(commentNode, DefinitionsConstants.NODE_OPENING); - String open = Utils.getTextValue(openNode); - - // Get the closing symbol - XNode closeNode = Utils.getChild(commentNode, DefinitionsConstants.NODE_CLOSING); - String close = Utils.getTextValue(closeNode); - - // Update the list - multiComments.add(new String[]{open, close}); - } - } - } - - // Set the single comments from their temporary list - mCommentSingle = new String[singleComments.size()]; - for (int i = 0, length = mCommentSingle.length; i < length; i++) { - mCommentSingle[i] = (String) singleComments.get(i); - } - - // Set the multiple comments from their temporary list - mCommentMulti = new String[multiComments.size()][]; - for (int i = 0, length = mCommentMulti.length; i < length; i++) { - mCommentMulti[i] = (String[]) multiComments.get(i); - } - - return ids; - } - - /** - * Initializes the keywords from the DOM language node and build a map - * of the keywords sets IDs. - * - * @param pLanguageNode the DOM language node. - * - * @return a map of {@link String} to {@link Integer} mapping the keywords sets ID - * to their position in the keywords array. - */ - private HashMap initKeywords(XNode pLanguageNode) { - - HashMap ids = new HashMap(); - XNode keywordsNode = Utils.getChild(pLanguageNode, - DefinitionsConstants.NODE_KEYWORDS); - - // Get the keywords in a temporary list - ArrayList keywordSets = new ArrayList(); - if (keywordsNode != null) { - XNodeList children = keywordsNode.getChildNodes(); - for (int i = 0, length = children.getLength(); i < length; i++) { - XNode keywordsSet = children.item(i); - SetNode set = new SetNode(keywordsSet); - - if (set.getId() != null && set.getValues() != null) { - // Update the list and map - keywordSets.add(set.getValues()); - int pos = keywordSets.size() - 1; - ids.put(set.getId(), Integer.valueOf(pos)); - - setKeywordCaseSensitivity(pos, set.isCaseSensitive()); - } - } - } - - // Set the keywords from the temporary list - String[][] aKeywords = new String[keywordSets.size()][]; - for (int i = 0, length = aKeywords.length; i < length; i++) { - aKeywords[i] = (String[])keywordSets.get(i); - } - mKeywords = aKeywords; - - return ids; - } - - /** - * Initializes the symbols from the DOM language node and build a map - * of the symbols sets IDs. - * - * @param pLanguageNode the DOM language node. - * - * @return a map of {@link String} to {@link Integer} mapping the symbols sets ID - * to their position in the symbols array. - */ - private HashMap initSymbols(XNode pLanguageNode) { - - HashMap ids = new HashMap(); - XNode symbolsNode = Utils.getChild(pLanguageNode, - DefinitionsConstants.NODE_SYMBOLS); - - // Get the keywords in a temporary list - ArrayList symbolsSets = new ArrayList(); - if (symbolsNode != null) { - XNodeList children = symbolsNode.getChildNodes(); - for (int i = 0, length = children.getLength(); i < length; i++) { - XNode symbolsSet = children.item(i); - SetNode set = new SetNode(symbolsSet); - - if (set.getId() != null && set.getValues() != null) { - // Update the list and map - symbolsSets.add(set.getValues()); - int pos = symbolsSets.size() - 1; - ids.put(set.getId(), Integer.valueOf(pos)); - } - } - } - - // Set the keywords from the temporary list - String[][] aSymbols = new String[symbolsSets.size()][]; - for (int i = 0, length = aSymbols.length; i < length; i++) { - aSymbols[i] = (String[])symbolsSets.get(i); - } - mSymbols = aSymbols; - - return ids; - } - - /** - * Initializes the regexps from the DOM language node and build a map - * of the regexps IDs. - * - * @param pLanguageNode the DOM language node. - * - * @return a map of {@link String} to {@link Integer} mapping the regexps ID - * to their position in the regexps array. - */ - private HashMap initRegexps(XNode pLanguageNode) { - - HashMap ids = new HashMap(); - - // Get the regexps into a temporary list - ArrayList regexps = new ArrayList(); - XNode regexpsNode = Utils.getChild(pLanguageNode, - DefinitionsConstants.NODE_REGEXPS); - if (regexpsNode != null) { - XNodeList children = regexpsNode.getChildNodes(); - for (int i = 0, length = children.getLength(); i < length; i++) { - XNode regexpNode = children.item(i); - - if (regexpNode.getNodeName().equals( - DefinitionsConstants.NODE_REGEXP)) { - try { - // Get the ID - String id = Utils.getAttribute(regexpNode, - DefinitionsConstants.ATTR_ID); - - // Get the value - String value = Utils.getAttribute(regexpNode, - DefinitionsConstants.ATTR_VALUE); - - // Update the list and map - regexps.add(value); - int pos = regexps.size() - 1; - ids.put(id, Integer.valueOf(pos)); - - } catch (HighlightingException e) { - // Do not add the regexp without ID or value - } - } - } - } - - // Set the regexps - String[] aRegexps = new String[regexps.size()]; - for (int i = 0, length = aRegexps.length; i < length; i++) { - aRegexps[i] = (String) regexps.get(i); - } - mRegexps = aRegexps; - - return ids; - } - - private void initStyles(XNode pLanguageNode, HashMap pIds) { - - XNode stylesNode = Utils.getChild(pLanguageNode, DefinitionsConstants.NODE_STYLES); - - // Get all the defined styles in a structure - XNodeList children = stylesNode.getChildNodes(); - mStyles = new HashMap(); - for (int i = 0, length = children.getLength(); i < length; i++) { - XNode child = children.item(i); - - if (child.getNodeName().equals( - DefinitionsConstants.NODE_STYLE)) { - - boolean bold = false; - try { - String value = Utils.getAttribute(child, DefinitionsConstants.ATTR_BOLD); - bold = Boolean.parseBoolean(value); - } catch (HighlightingException e) { - bold = false; - } - - boolean italic = false; - try { - String value = Utils.getAttribute(child, DefinitionsConstants.ATTR_ITALIC); - italic = Boolean.parseBoolean(value); - } catch (HighlightingException e) { - italic = false; - } - - try { - String element = Utils.getAttribute(child, DefinitionsConstants.ATTR_ELEMENT); - String color = Utils.getAttribute(child, DefinitionsConstants.ATTR_COLOR); - - // Correct the element for the single comments, regexps, splitters, - // and keywords - element = computeStyleName(element, pIds); - - mStyles.put(element, new Style(color, bold, italic)); - } catch (HighlightingException e) { - // Do not add the style if one of the mandatory attribute is missing - } - } - } - - // Loop over the ids to see if there is no missing style - Iterator iter = pIds.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = (Entry)iter.next(); - String style = (String)entry.getKey(); - HashMap ids = (HashMap)entry.getValue(); - - addMissingStyles(ids, style); - } - } - - private void addMissingStyles(HashMap pIds, String pStyle) { - Iterator iter = pIds.values().iterator(); - while (iter.hasNext()) { - Integer value = (Integer)iter.next(); - - String styleName = pStyle + value.toString() + "_" + getId(); - - if (!mStyles.containsKey(styleName)) { - mStyles.put(styleName, new Style()); - } - } - } - - private String computeStyleName(String pElement, HashMap pIds) { - - String styleName = null; - - Iterator iter = pIds.entrySet().iterator(); - while (iter.hasNext() && styleName == null) { - Entry entry = (Entry)iter.next(); - HashMap ids = (HashMap)entry.getValue(); - - if (ids.containsKey(pElement)) { - Integer id = (Integer)ids.get(pElement); - styleName = (String)entry.getKey() + id.toString(); - } - } - - if (styleName == null) { - styleName = pElement; - } - - return styleName + "_" + getId(); - } -} diff --git a/extensions/coooder/source/org/libreoffice/coooder/comp/RegistrationHandler.classes b/extensions/coooder/source/org/libreoffice/coooder/comp/RegistrationHandler.classes deleted file mode 100644 index d55d43384..000000000 --- a/extensions/coooder/source/org/libreoffice/coooder/comp/RegistrationHandler.classes +++ /dev/null @@ -1,4 +0,0 @@ -org.libreoffice.coooder.comp.HighlighterImpl -org.libreoffice.coooder.comp.LanguageImpl -org.libreoffice.coooder.comp.theLanguagesManagerImpl -org.libreoffice.coooder.comp.ui.ParseTriggerImpl diff --git a/extensions/coooder/source/org/libreoffice/coooder/comp/RegistrationHandler.java b/extensions/coooder/source/org/libreoffice/coooder/comp/RegistrationHandler.java deleted file mode 100644 index f1bd49d1c..000000000 --- a/extensions/coooder/source/org/libreoffice/coooder/comp/RegistrationHandler.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * LibreOffice extension for syntax highlighting - * Copyright (C) 2008 Cédric Bosdonnat cedric.bosdonnat.ooo@free.fr - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; - * version 2 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ -package org.libreoffice.coooder.comp; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.LineNumberReader; -import java.lang.reflect.Method; -import java.util.ArrayList; - -import com.sun.star.lang.XSingleComponentFactory; -import com.sun.star.registry.XRegistryKey; - -/** - * Component main registration class. - * - * <p><strong>This class should not be modified.</strong></p> - * - * @author Cedric Bosdonnat aka. cedricbosdo - * - */ -public class RegistrationHandler { - - /** - * Get a component factory for the implementations handled by this class. - * - * <p>This method calls all the methods of the same name from the classes listed - * in the <code>RegistrationHandler.classes</code> file. <strong>This method - * should not be modified.</strong></p> - * - * @param pImplementationName the name of the implementation to create. - * - * @return the factory which can create the implementation. - */ - public static XSingleComponentFactory __getComponentFactory(String sImplementationName ) { - XSingleComponentFactory xFactory = null; - - Class[] classes = findServicesImplementationClasses(); - - int i = 0; - while (i < classes.length && xFactory == null) { - Class clazz = classes[i]; - if ( sImplementationName.equals( clazz.getCanonicalName() ) ) { - try { - Class[] getTypes = new Class[]{String.class}; - Method getFactoryMethod = clazz.getMethod("__getComponentFactory", getTypes); - Object o = getFactoryMethod.invoke(null, new String[]{sImplementationName}); - xFactory = (XSingleComponentFactory)o; - } catch (Exception e) { - // Nothing to do: skip - System.err.println("Error happened"); - e.printStackTrace(); - } - } - i++; - } - return xFactory; - } - - /** - * Writes the services implementation informations to the UNO registry. - * - * <p>This method calls all the methods of the same name from the classes listed - * in the <code>RegistrationHandler.classes</code> file. <strong>This method - * should not be modified.</strong></p> - * - * @param pRegistryKey the root registry key where to write the informations. - * - * @return <code>true</code> if the informations have been successfully written - * to the registry key, <code>false</code> otherwise. - */ - public static boolean __writeRegistryServiceInfo(XRegistryKey xRegistryKey ) { - - Class[] classes = findServicesImplementationClasses(); - - boolean success = true; - int i = 0; - while (i < classes.length && success) { - Class clazz = classes[i]; - try { - Class[] writeTypes = new Class[]{XRegistryKey.class}; - Method getFactoryMethod = clazz.getMethod("__writeRegistryServiceInfo", writeTypes); - Object o = getFactoryMethod.invoke(null, new Object[]{xRegistryKey}); - success = success && ((Boolean)o).booleanValue(); - } catch (Exception e) { - success = false; - e.printStackTrace(); - } - i++; - } - return success; - } - - /** - * @return all the UNO implementation classes. - */ - private static Class[] findServicesImplementationClasses() { - - ArrayList classes = new ArrayList(); - - InputStream in = RegistrationHandler.class.getResourceAsStream("RegistrationHandler.classes"); - LineNumberReader reader = new LineNumberReader(new InputStreamReader(in)); - - try { - String line = reader.readLine(); - while (line != null) { - if (!line.equals("")) { - line = line.trim(); - try { - Class clazz = Class.forName(line); - - Class[] writeTypes = new Class[]{XRegistryKey.class}; - Class[] getTypes = new Class[]{String.class}; - - Method writeRegMethod = clazz.getMethod("__writeRegistryServiceInfo", writeTypes); - Method getFactoryMethod = clazz.getMethod("__getComponentFactory", getTypes); - - if (writeRegMethod != null && getFactoryMethod != null) { - classes.add(clazz); - } - - } catch (Exception e) { - e.printStackTrace(); - } - } - line = reader.readLine(); - } - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - reader.close(); - in.close(); - } catch (Exception e) {}; - } - - Class[] aClasses = new Class[classes.size()]; - for (int i = 0; i < aClasses.length; i++) { - aClasses[i] = (Class)classes.get(i); - } - return aClasses; - } -} diff --git a/extensions/coooder/source/org/libreoffice/coooder/comp/SetNode.java b/extensions/coooder/source/org/libreoffice/coooder/comp/SetNode.java deleted file mode 100644 index 46a608511..000000000 --- a/extensions/coooder/source/org/libreoffice/coooder/comp/SetNode.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * LibreOffice extension for syntax highlighting - * Copyright (C) 2008 Cédric Bosdonnat cedric.bosdonnat.ooo@free.fr - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; - * version 2 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ -package org.libreoffice.coooder.comp; - -import org.libreoffice.coooder.HighlightingException; - -import com.sun.star.xml.dom.XNode; - -public class SetNode { - - private boolean mCaseSensitive; - private String mId; - private String[] mValues; - - public SetNode (XNode pSetXmlNode) { - - if (pSetXmlNode.getNodeName().equals(DefinitionsConstants.NODE_SET)) { - // Check for case sensitivity - try { - String value = Utils.getAttribute(pSetXmlNode, DefinitionsConstants.ATTR_CASE_SENSITIVE); - mCaseSensitive = Boolean.parseBoolean(value); - } catch (HighlightingException e) { - // Default value is true - mCaseSensitive = true; - } - - // Get the keyword set id - try { - mId = Utils.getAttribute(pSetXmlNode, DefinitionsConstants.ATTR_ID); - - // Get the keywords - mValues = Utils.getValues(pSetXmlNode); - } catch (HighlightingException e) { - // No ID: no keywordset - } - } - } - - public boolean isCaseSensitive() { - return mCaseSensitive; - } - - public String getId() { - return mId; - } - - public String[] getValues() { - return mValues; - } -} diff --git a/extensions/coooder/source/org/libreoffice/coooder/comp/Style.java b/extensions/coooder/source/org/libreoffice/coooder/comp/Style.java deleted file mode 100644 index 4e16522af..000000000 --- a/extensions/coooder/source/org/libreoffice/coooder/comp/Style.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * LibreOffice extension for syntax highlighting - * Copyright (C) 2008 Cédric Bosdonnat cedric.bosdonnat.ooo@free.fr - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; - * version 2 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ -package org.libreoffice.coooder.comp; - -import com.sun.star.awt.FontSlant; -import com.sun.star.awt.FontWeight; - -public class Style { - - private String mColor = "000000"; - private boolean mBold = false; - private boolean mItalic = false; - - public Style() { - } - - public Style(String pColor, boolean pBold, boolean pItalic) { - mColor = pColor; - mBold = pBold; - mItalic = pItalic; - } - - public Integer getColor() { - Integer color = new Integer(0); - - // Rearrange the color on 6 digits - if (mColor.length() == 3) { - char red = mColor.charAt(0); - char green = mColor.charAt(1); - char blue = mColor.charAt(2); - - mColor = new String(new char[]{red, red, green, green, blue, blue}); - } - - color = Integer.valueOf(mColor, 16); - - return color; - } - - public Float getFontWeight() { - Float weight = Float.valueOf(FontWeight.NORMAL); - if (mBold) { - weight = Float.valueOf(FontWeight.BOLD); - } - - return weight; - } - - public FontSlant getFontSlant() { - FontSlant posture = FontSlant.NONE; - if (mItalic) { - posture = FontSlant.ITALIC; - } - - return posture; - } -} diff --git a/extensions/coooder/source/org/libreoffice/coooder/comp/Utils.java b/extensions/coooder/source/org/libreoffice/coooder/comp/Utils.java deleted file mode 100644 index df7b67caa..000000000 --- a/extensions/coooder/source/org/libreoffice/coooder/comp/Utils.java +++ /dev/null @@ -1,330 +0,0 @@ -/* - * LibreOffice extension for syntax highlighting - * Copyright (C) 2008 Cédric Bosdonnat cedric.bosdonnat.ooo@free.fr - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; - * version 2 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ -package org.libreoffice.coooder.comp; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.HashMap; - -import org.libreoffice.coooder.HighlightingException; -import org.libreoffice.coooder.XLanguage; - -import com.sun.star.beans.XPropertySet; -import com.sun.star.container.XNameContainer; -import com.sun.star.lang.XMultiServiceFactory; -import com.sun.star.style.XStyle; -import com.sun.star.style.XStyleFamiliesSupplier; -import com.sun.star.text.XTextCursor; -import com.sun.star.text.XTextDocument; -import com.sun.star.uno.Exception; -import com.sun.star.uno.UnoRuntime; -import com.sun.star.xml.dom.NodeType; -import com.sun.star.xml.dom.XAttr; -import com.sun.star.xml.dom.XNamedNodeMap; -import com.sun.star.xml.dom.XNode; -import com.sun.star.xml.dom.XNodeList; - - -/** - * A set of useful methods used in the highlighter implementation. - * - * @author Cedric Bosdonnat - * - */ -public class Utils { - - private static final String UNIX_SEPARATOR = "\n"; - - /** - * Check if an array contains a given value. - * - * @param pArray the array where to look for the value - * @param pItem the value to look for - * - * @return <code>true</code> if the value has been found in the array - */ - public static boolean arrayContains(String[] pArray, String pItem) { - boolean contained = false; - - int i = 0; - while (!contained && i < pArray.length) { - contained = pArray[i].equals(pItem); - i++; - } - - return contained; - } - - /** - * Move the cursor to the right with an offset indicated by an integer. - * - * <p>This method has to be used instead of casting from an integer to - * a short: the result might be different.</p> - * - * @param pCursor the cursor to move - * @param pOffset the number to characters to go after - * @param pExpand <code>true</code> if the cursor expands the selection while - * moving, <code>false</code> otherwise. - */ - public static void goRight(XTextCursor pCursor, int pOffset, boolean pExpand) { - - int i = pOffset; - short move = 0; - - while (i > 0) { - if (pOffset > Short.MAX_VALUE) { - move = Short.MAX_VALUE; - i -= Short.MAX_VALUE; - } else { - move = (short)i; - i = 0; - } - pCursor.goRight(move, pExpand); - } - } - - /** - * Set the given style on the selection of a cursor. - * - * @param pSelection the cursor for which to set the style - * @param pStyle the style to set - * - * @throws Exception if the <code>CharStyleName</code> property can't be set - * on the cursor. - */ - public static void setStyle(XTextCursor pSelection, String pStyle) throws Exception { - XPropertySet props = (XPropertySet)UnoRuntime.queryInterface( - XPropertySet.class, pSelection); - props.setPropertyValue("CharStyleName", pStyle); - } - - public static void createStyle(XTextDocument pDoc, String pStyle, XLanguage pLanguage) throws Exception { - // Create the style in the document if missing - XStyleFamiliesSupplier xStyleFamilies = (XStyleFamiliesSupplier)UnoRuntime.queryInterface( - XStyleFamiliesSupplier.class, pDoc); - Object o = xStyleFamilies.getStyleFamilies().getByName("CharacterStyles"); - XNameContainer xFamily = (XNameContainer)UnoRuntime.queryInterface(XNameContainer.class, o); - - if (!xFamily.hasByName(pStyle)) { - // Get the style definition - HashMap styles = ((LanguageImpl)pLanguage).getStyles(); - Style styleDef = (Style)styles.get(pStyle); - if (styleDef == null) { - styleDef = new Style(); - } - - // Create the style - XMultiServiceFactory xFactory = (XMultiServiceFactory)UnoRuntime.queryInterface( - XMultiServiceFactory.class, pDoc); - Object style = xFactory.createInstance("com.sun.star.style.CharacterStyle"); - XStyle xStyle = (XStyle)UnoRuntime.queryInterface(XStyle.class, style); - - XPropertySet xPropSet = (XPropertySet)UnoRuntime.queryInterface(XPropertySet.class, xStyle); - - xPropSet.setPropertyValue("CharColor", styleDef.getColor()); - xPropSet.setPropertyValue("CharWeight", styleDef.getFontWeight()); - xPropSet.setPropertyValue("CharPosture", styleDef.getFontSlant()); - - // Adds the style to the family - xFamily.insertByName(pStyle, xStyle); - } - } - - /** - * Get the string between the start and stop position using the given cursor. - * - * <p>This method assumes that the cursor is at the position <code>0</code></p> - * - * @param pCursor the cursor to use - * @param pStart the start position of the string - * @param pStop the end position of the string - * - * @return the selected string - */ - public static String getSelection(XTextCursor pCursor, int pStart, int pStop) { - - // Get the selected string - Utils.goRight(pCursor, pStart, false); - Utils.goRight(pCursor, pStop - pStart, true); - - return getSelection(pCursor); - } - - /** - * Returns the cursor selected string with unix end of lines - * - * @param pCursor the text cursor for the selection - * - * @return the string - */ - public static String getSelection(XTextCursor pCursor) { - String string = pCursor.getString(); - String osLF = System.getProperty("line.separator"); - if (!osLF.equals(UNIX_SEPARATOR)) { - string = string.replaceAll(osLF, UNIX_SEPARATOR); - } - return string; - } - - /** - * Get the value of an attribute in a given node. - * - * @param pNode the node containing the attribute - * @param pName the local name of the attribute to look for - * - * @return the attribute value - * - * @throws HighlightingException if the attribute is missing - */ - public static String getAttribute(XNode pNode, String pName) throws HighlightingException { - String result = null; - - XNamedNodeMap attrs = pNode.getAttributes(); - XNode idNode = attrs.getNamedItem(pName); - if (idNode != null) { - XAttr idAttr = (XAttr)UnoRuntime.queryInterface(XAttr.class, idNode); - result = idAttr.getValue(); - } else { - String message = MessageFormat.format("Expected attribute {0} not found in node {1}", - new Object[]{ pName, pNode.getNodeName() }); - throw new HighlightingException(message); - } - return result; - } - - /** - * Get the text values of some elements in a given node. - * - * @param pParentNode the node where to look for the values - * @param pChildName the name of the elements containing the values to get - * @param pMandatory <code>true</code> if the elements are mandatory - * - * @return the list of values. - * - * @throws HighlightingException if there is no value and they are mandatory - */ - public static String[] getValues(XNode pParentNode, String pChildName, - boolean pMandatory) throws HighlightingException { - - XNode valuesNode = getChild(pParentNode, pChildName); - if (pMandatory && valuesNode == null) { - String msg = MessageFormat.format("Element {0} is mandatory in {1}", - new String[]{ pChildName, pParentNode.getNodeName() }); - throw new HighlightingException(msg); - } - - String[] values = new String[0]; - if (valuesNode != null) { - values = getValues(valuesNode); - } - - return values; - } - - /** - * Get the text content of the <strong><value></strong> elements contained in - * the given node. - * - * @param pNode the node to analyze. - * - * @return the list of the values - */ - public static String[] getValues(XNode pNode) { - - ArrayList values = new ArrayList(); - XNodeList children = pNode.getChildNodes(); - - for (int i = 0, length = children.getLength(); i < length; i++) { - XNode child = children.item(i); - - try { - boolean isValueNode = child.getNodeName().equals(DefinitionsConstants.NODE_VALUE); - String value = getTextValue(child); - - if (isValueNode && !value.equals("")) { - values.add(value); - } - } catch (java.lang.Exception e) { - // Do nothing - } - } - - // Convert to String[] - String[] aValues = new String[values.size()]; - for (int i = 0, length = values.size(); i < length; i++) { - aValues[i] = (String)values.get(i); - } - - return aValues; - } - - /** - * Find a child element from a given element using its local name. - * - * @param pParentNode the parent element for which to get a child - * @param pChildName the local name of the child element to get. - * - * @return the element found or <code>null</code>. - */ - public static XNode getChild(XNode pParentNode, String pChildName) { - - XNode node = null; - - XNodeList children = pParentNode.getChildNodes(); - int i = 0; - - while (i < children.getLength() && node == null) { - XNode child = children.item(i); - boolean isElement = child.getNodeType() == NodeType.ELEMENT_NODE; - boolean isSearched = child.getNodeName().equals(pChildName); - - if (isElement && isSearched) { - node = child; - } - i++; - } - - return node; - } - - /** - * Get the text value of the first child of the given node. - * - * @param pNode the node from which to get the text - * - * @return the contained text or an empty string - */ - public static String getTextValue(XNode pNode) { - String value = ""; - - if (pNode != null && pNode.hasChildNodes()) { - XNode child = pNode.getFirstChild(); - boolean isTextNode = child != null && child.getNodeType() == NodeType.TEXT_NODE; - - if (isTextNode) { - XNode text = (XNode)UnoRuntime.queryInterface(XNode.class, child); - try { - value = text.getNodeValue(); - } catch (Exception e) { - } - } - } - return value; - } -} diff --git a/extensions/coooder/source/org/libreoffice/coooder/comp/test/AllTests.java b/extensions/coooder/source/org/libreoffice/coooder/comp/test/AllTests.java deleted file mode 100644 index 73d6509e9..000000000 --- a/extensions/coooder/source/org/libreoffice/coooder/comp/test/AllTests.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * LibreOffice extension for syntax highlighting - * Copyright (C) 2008 Cédric Bosdonnat cedric.bosdonnat.ooo@free.fr - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; - * version 2 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ -package org.libreoffice.coooder.comp.test; - -import junit.framework.Test; - -import org.libreoffice.coooder.comp.test.base.UnoTestSuite; - - -public class AllTests { - - public static Test suite() { - - // The tests to run by the suite - Class[] testClasses = new Class[] { - SyntaxTest.class - }; - - // Create the test suite - UnoTestSuite suite = new UnoTestSuite(testClasses); - - return suite; - } -} diff --git a/extensions/coooder/source/org/libreoffice/coooder/comp/test/SyntaxTest.java b/extensions/coooder/source/org/libreoffice/coooder/comp/test/SyntaxTest.java deleted file mode 100644 index 6000aac90..000000000 --- a/extensions/coooder/source/org/libreoffice/coooder/comp/test/SyntaxTest.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * LibreOffice extension for syntax highlighting - * Copyright (C) 2008 Cédric Bosdonnat cedric.bosdonnat.ooo@free.fr - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; - * version 2 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ -package org.libreoffice.coooder.comp.test; - -import java.io.File; -import java.io.FileInputStream; - -import org.libreoffice.coooder.comp.test.base.UnoTestCase; -import org.libreoffice.coooder.XHighlighter; -import org.libreoffice.coooder.XLanguage; -import org.libreoffice.coooder.theLanguagesManager; - -import com.sun.star.beans.PropertyValue; -import com.sun.star.frame.FrameSearchFlag; -import com.sun.star.frame.XComponentLoader; -import com.sun.star.lang.XComponent; -import com.sun.star.lang.XMultiComponentFactory; -import com.sun.star.text.XTextDocument; -import com.sun.star.uno.UnoRuntime; -import com.sun.star.view.XSelectionSupplier; - - -public class SyntaxTest extends UnoTestCase { - - public void testSyntaxHighlighting() { - try { - // Generate the document - XTextDocument xDoc = generateDocument("css"); - - // Highlight the selection - highlight("css"); - - // Compare with the geshi generated file - compareWithGeshi(xDoc, "css"); - - } catch (Exception e) { - fail("Shouldn't have thrown an exception"); - } - } - - private XTextDocument generateDocument(String pLanguage) throws Exception { - // Create a new text document - XTextDocument xDoc = loadDocument("private:factory/swriter"); - - // Copy the test string in the document - String testString = readTestFile(pLanguage); - xDoc.getText().setString(testString); - - // Select the whole inserted text - Object oController = xDoc.getCurrentController(); - XSelectionSupplier xSelSupplier = (XSelectionSupplier)UnoRuntime.queryInterface( - XSelectionSupplier.class, oController); - xSelSupplier.select(xDoc.getText()); - - return xDoc; - } - - private void highlight(String pLanguage) throws Exception { - XMultiComponentFactory xMngr = getContext().getServiceManager(); - Object oHighlighter = xMngr.createInstanceWithContext( - "org.libreoffice.coooder.Highlighter", getContext()); - XHighlighter xHL = (XHighlighter)UnoRuntime.queryInterface(XHighlighter.class, oHighlighter); - - XLanguage xLang = theLanguagesManager.get(getContext()).getLanguage(pLanguage); - xHL.setLanguage(xLang); - - // There is no need of a progress monitor here. - xHL.parse(); - } - - private void compareWithGeshi(XTextDocument pDoc, String pLanguage) { - // TODO Load the HTML document generated by Geshi - - - // TODO Loop over each character and compare its color, wont weight and slant - } - - private String readTestFile(String pLanguage) throws Exception { - String pwd = System.getenv("user.dir"); - File file = new File(pwd, pLanguage + ".txt"); - - FileInputStream fi = new FileInputStream(file); - byte[] buf = new byte[fi.available()]; - fi.read(buf); - String text = new String(buf); - - return text; - } - - private XTextDocument loadDocument(String pUrl) throws Exception { - XMultiComponentFactory xMngr = getContext().getServiceManager(); - Object oDesktop = xMngr.createInstanceWithContext("com.sun.star.frame.Desktop", getContext()); - XComponentLoader xLoader = (XComponentLoader)UnoRuntime.queryInterface( - XComponentLoader.class, oDesktop); - - XComponent xDoc = xLoader.loadComponentFromURL(pUrl, "_default", - FrameSearchFlag.ALL, new PropertyValue[0]); - - XTextDocument xTextDoc = (XTextDocument)UnoRuntime.queryInterface(XTextDocument.class, xDoc); - return xTextDoc; - } -} diff --git a/extensions/coooder/source/org/libreoffice/coooder/comp/test/base/Bootstrap.java b/extensions/coooder/source/org/libreoffice/coooder/comp/test/base/Bootstrap.java deleted file mode 100644 index 839cf14cb..000000000 --- a/extensions/coooder/source/org/libreoffice/coooder/comp/test/base/Bootstrap.java +++ /dev/null @@ -1,337 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: Bootstrap.java,v $ - * $Revision: 1.16 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * <http://www.openoffice.org/license.html> - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -package org.libreoffice.coooder.comp.test.base; - -import java.io.BufferedReader; -import java.io.File; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.PrintStream; -import java.net.URLClassLoader; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Random; - -import com.sun.star.bridge.UnoUrlResolver; -import com.sun.star.bridge.XUnoUrlResolver; -import com.sun.star.comp.helper.BootstrapException; -import com.sun.star.comp.helper.ComponentContext; -import com.sun.star.comp.helper.ComponentContextEntry; -import com.sun.star.comp.loader.JavaLoader; -import com.sun.star.container.XSet; -import com.sun.star.lang.XInitialization; -import com.sun.star.lang.XMultiComponentFactory; -import com.sun.star.lang.XMultiServiceFactory; -import com.sun.star.lang.XSingleComponentFactory; -import com.sun.star.lib.util.NativeLibraryLoader; -import com.sun.star.loader.XImplementationLoader; -import com.sun.star.uno.UnoRuntime; -import com.sun.star.uno.XComponentContext; - -/** Bootstrap offers functionality to obtain a context or simply - a service manager. - The service manager can create a few basic services, whose implementations are: - <ul> - <li>com.sun.star.comp.loader.JavaLoader</li> - <li>com.sun.star.comp.urlresolver.UrlResolver</li> - <li>com.sun.star.comp.bridgefactory.BridgeFactory</li> - <li>com.sun.star.comp.connections.Connector</li> - <li>com.sun.star.comp.connections.Acceptor</li> - <li>com.sun.star.comp.servicemanager.ServiceManager</li> - </ul> - - Other services can be inserted into the service manager by - using its XSet interface: - <pre> - XSet xSet = (XSet)UnoRuntime.queryInterface( XSet.class, aMultiComponentFactory ); - // insert the service manager - xSet.insert( aSingleComponentFactory ); - </pre> - - @author cbosdo Changed the class for a better control of the bootstrap using a custom classloader -*/ -public class Bootstrap { - - private static void insertBasicFactories( - XSet xSet, XImplementationLoader xImpLoader ) - throws Exception - { - // insert the factory of the loader - xSet.insert( xImpLoader.activate( - "com.sun.star.comp.loader.JavaLoader", null, null, null ) ); - - // insert the factory of the URLResolver - xSet.insert( xImpLoader.activate( - "com.sun.star.comp.urlresolver.UrlResolver", null, null, null ) ); - - // insert the bridgefactory - xSet.insert( xImpLoader.activate( - "com.sun.star.comp.bridgefactory.BridgeFactory", null, null, null ) ); - - // insert the connector - xSet.insert( xImpLoader.activate( - "com.sun.star.comp.connections.Connector", null, null, null ) ); - - // insert the acceptor - xSet.insert( xImpLoader.activate( - "com.sun.star.comp.connections.Acceptor", null, null, null ) ); - } - - /** Bootstraps an initial component context with service manager and basic - jurt components inserted. - @param context_entries the hash table contains mappings of entry names (type string) to - context entries (type class ComponentContextEntry). - @return a new context. - */ - static public XComponentContext createInitialComponentContext( Hashtable context_entries ) - throws Exception - { - XImplementationLoader xImpLoader = (XImplementationLoader)UnoRuntime.queryInterface( - XImplementationLoader.class, new JavaLoader() ); - - // Get the factory of the ServiceManager - XSingleComponentFactory smgr_fac = (XSingleComponentFactory)UnoRuntime.queryInterface( - XSingleComponentFactory.class, xImpLoader.activate( - "com.sun.star.comp.servicemanager.ServiceManager", null, null, null ) ); - - // Create an instance of the ServiceManager - XMultiComponentFactory xSMgr = (XMultiComponentFactory)UnoRuntime.queryInterface( - XMultiComponentFactory.class, smgr_fac.createInstanceWithContext( null ) ); - - // post init loader - XInitialization xInit = (XInitialization)UnoRuntime.queryInterface( - XInitialization.class, xImpLoader ); - Object[] args = new Object [] { xSMgr }; - xInit.initialize( args ); - - // initial component context - if (context_entries == null) - context_entries = new Hashtable( 1 ); - // add smgr - context_entries.put( - "/singletons/com.sun.star.lang.theServiceManager", - new ComponentContextEntry( null, xSMgr ) ); - // ... xxx todo: add standard entries - XComponentContext xContext = new ComponentContext( context_entries, null ); - - // post init smgr - xInit = (XInitialization)UnoRuntime.queryInterface( - XInitialization.class, xSMgr ); - args = new Object [] { null, xContext }; // no registry, default context - xInit.initialize( args ); - - XSet xSet = (XSet)UnoRuntime.queryInterface( XSet.class, xSMgr ); - // insert the service manager - xSet.insert( smgr_fac ); - // and basic jurt factories - insertBasicFactories( xSet, xImpLoader ); - - return xContext; - } - - /** - * Bootstraps a servicemanager with the jurt base components registered. - * <p> - * @return a freshly boostrapped service manager - * @see com.sun.star.lang.ServiceManager - */ - static public XMultiServiceFactory createSimpleServiceManager() throws Exception - { - return (XMultiServiceFactory)UnoRuntime.queryInterface( - XMultiServiceFactory.class, createInitialComponentContext( null ).getServiceManager() ); - } - - - /** Bootstraps the initial component context from a native UNO installation. - - @see cppuhelper/defaultBootstrap_InitialComponentContext() - */ - static public final XComponentContext defaultBootstrap_InitialComponentContext() - throws Exception - { - return defaultBootstrap_InitialComponentContext( null, null ); - } - /** Bootstraps the initial component context from a native UNO installation. - - @param ini_file - ini_file (may be null: uno.rc besides cppuhelper lib) - @param bootstrap_parameters - bootstrap parameters (maybe null) - - @see cppuhelper/defaultBootstrap_InitialComponentContext() - */ - static public final XComponentContext defaultBootstrap_InitialComponentContext( - String ini_file, Hashtable bootstrap_parameters ) - throws Exception - { - // jni convenience: easier to iterate over array than calling Hashtable - String pairs [] = null; - if (null != bootstrap_parameters) - { - pairs = new String [ 2 * bootstrap_parameters.size() ]; - Enumeration keys = bootstrap_parameters.keys(); - int n = 0; - while (keys.hasMoreElements()) - { - String name = (String)keys.nextElement(); - pairs[ n++ ] = name; - pairs[ n++ ] = (String)bootstrap_parameters.get( name ); - } - } - - if (! m_loaded_juh) - { - System.loadLibrary( "juh" ); - m_loaded_juh = true; - } - return (XComponentContext)UnoRuntime.queryInterface( - XComponentContext.class, - cppuhelper_bootstrap( - ini_file, pairs, Bootstrap.class.getClassLoader() ) ); - } - - static private boolean m_loaded_juh = false; - static private native Object cppuhelper_bootstrap( - String ini_file, String bootstrap_parameters [], ClassLoader loader ) - throws Exception; - - /** - * Bootstraps the component context from a UNO installation. - * - * @return a bootstrapped component context. - * - * @since UDK 3.1.0 - */ - public static final XComponentContext bootstrap(URLClassLoader loader) - throws BootstrapException { - - XComponentContext xContext = null; - - try { - // create default local component context - XComponentContext xLocalContext = - createInitialComponentContext( null ); - if ( xLocalContext == null ) - throw new BootstrapException( "no local component context!" ); - - // find office executable relative to this class's class loader - String sOffice = - System.getProperty( "os.name" ).startsWith( "Windows" ) ? - "soffice.exe" : "soffice"; - File fOffice = NativeLibraryLoader.getResource( loader, sOffice ); - if ( fOffice == null ) - throw new BootstrapException( "no office executable found!" ); - - // create random pipe name - String sPipeName = "uno" + - Long.toString( (new Random()).nextLong() & 0x7fffffffffffffffL ); - - // create call with arguments - String[] cmdArray = new String[7]; - cmdArray[0] = fOffice.getPath(); - cmdArray[1] = "-nologo"; - cmdArray[2] = "-nodefault"; - cmdArray[3] = "-norestore"; - cmdArray[4] = "-nocrashreport"; - cmdArray[5] = "-nolockcheck"; - cmdArray[6] = "-accept=pipe,name=" + sPipeName + ";urp;"; - - // start office process - Process p = Runtime.getRuntime().exec( cmdArray ); - pipe( p.getInputStream(), System.out, "CO> " ); - pipe( p.getErrorStream(), System.err, "CE> " ); - - // initial service manager - XMultiComponentFactory xLocalServiceManager = - xLocalContext.getServiceManager(); - if ( xLocalServiceManager == null ) - throw new BootstrapException( "no initial service manager!" ); - - // create a URL resolver - XUnoUrlResolver xUrlResolver = - UnoUrlResolver.create( xLocalContext ); - - // connection string - String sConnect = "uno:pipe,name=" + sPipeName + - ";urp;StarOffice.ComponentContext"; - - // wait until office is started - for (int i = 0;; ++i) { - try { - // try to connect to office - Object context = xUrlResolver.resolve( sConnect ); - xContext = (XComponentContext) UnoRuntime.queryInterface( - XComponentContext.class, context); - if ( xContext == null ) - throw new BootstrapException( "no component context!" ); - break; - } catch ( com.sun.star.connection.NoConnectException ex ) { - // Wait 500 ms, then try to connect again, but do not wait - // longer than 5 min (= 600 * 500 ms) total: - if (i == 600) { - throw new BootstrapException(ex.toString()); - } - Thread.sleep( 500 ); - } - } - } catch ( BootstrapException e ) { - throw e; - } catch ( java.lang.RuntimeException e ) { - throw e; - } catch ( java.lang.Exception e ) { - throw new BootstrapException( e ); - } - - return xContext; - } - - private static void pipe( - final InputStream in, final PrintStream out, final String prefix ) { - - new Thread( "Pipe: " + prefix) { - public void run() { - BufferedReader r = new BufferedReader( - new InputStreamReader( in ) ); - try { - for ( ; ; ) { - String s = r.readLine(); - if ( s == null ) { - break; - } - out.println( prefix + s ); - } - } catch ( java.io.IOException e ) { - e.printStackTrace( System.err ); - } - } - }.start(); - } -} diff --git a/extensions/coooder/source/org/libreoffice/coooder/comp/test/base/UnoTestCase.java b/extensions/coooder/source/org/libreoffice/coooder/comp/test/base/UnoTestCase.java deleted file mode 100644 index 187deaca7..000000000 --- a/extensions/coooder/source/org/libreoffice/coooder/comp/test/base/UnoTestCase.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * LibreOffice extension for syntax highlighting - * Copyright (C) 2008 Cédric Bosdonnat cedric.bosdonnat.ooo@free.fr - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; - * version 2 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ -package org.libreoffice.coooder.comp.test.base; - -import junit.framework.TestCase; - -import com.sun.star.uno.XComponentContext; - -/** - * Base for all test cases to use along with {@link UnoTestSuite}. - * - * @author cbosdo - * - */ -public abstract class UnoTestCase extends TestCase { - - /** - * Default constructor. - */ - public UnoTestCase() { - super(); - } - - /** - * Constructor to use to run only one test - * - * @param pName the test name - */ - public UnoTestCase(String pName) { - super(pName); - } - - - private XComponentContext mContext; - - /** - * Set the office context to use in the tests. - * - * @param pContext the remote office context - */ - public void setContext(XComponentContext pContext) { - mContext = pContext; - } - - /** - * Get the office context to use in the tests. - * - * @return the remote office context - */ - protected XComponentContext getContext() { - return mContext; - } -} diff --git a/extensions/coooder/source/org/libreoffice/coooder/comp/test/base/UnoTestSuite.java b/extensions/coooder/source/org/libreoffice/coooder/comp/test/base/UnoTestSuite.java deleted file mode 100644 index d76a71a64..000000000 --- a/extensions/coooder/source/org/libreoffice/coooder/comp/test/base/UnoTestSuite.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * LibreOffice extension for syntax highlighting - * Copyright (C) 2008 Cédric Bosdonnat cedric.bosdonnat.ooo@free.fr - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; - * version 2 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */package org.libreoffice.coooder.comp.test.base; - - -import java.io.File; -import java.net.URL; -import java.net.URLClassLoader; - -import junit.framework.Test; -import junit.framework.TestResult; -import junit.framework.TestSuite; - -import com.sun.star.frame.XDesktop; -import com.sun.star.lang.XMultiComponentFactory; -import com.sun.star.uno.UnoRuntime; -import com.sun.star.uno.XComponentContext; - -/** - * This is a test suite for an OOo extension unit tests: - * it bootstraps an OOo instance and handles the connection with it. - * - * The extension to test has to be already installed on OOo for the - * current user. - * - * @author cbosdo - * - */ -public class UnoTestSuite extends TestSuite { - - private XComponentContext mContext; - private boolean mHandleConnection = false; - - - public UnoTestSuite() { - super(); - } - - public UnoTestSuite(Class pTheClass, String pName) { - super(pTheClass, pName); - } - - public UnoTestSuite(Class pTheClass) { - super(pTheClass); - } - - public UnoTestSuite(Class[] pClasses, String pName) { - super(pClasses, pName); - } - - public UnoTestSuite(Class[] pClasses) { - // Override to create UnoTestSuites instead of TestSuites - for (int i= 0; i < pClasses.length; i++) { - addTest(new UnoTestSuite(pClasses[i])); - } - } - - public UnoTestSuite(String pName) { - super(pName); - } - - public void run(TestResult pResult) { - - try { - startOffice(); - - super.run(pResult); - } catch (Exception e) { - System.err.println("Unable to run the tests"); - e.printStackTrace(); - } - - stopOffice(); - } - - public void runTest(Test pTest, TestResult pResult) { - // Try to set the context on the test - if (pTest instanceof UnoTestCase) { - ((UnoTestCase)pTest).setContext(mContext); - } else if (pTest instanceof UnoTestSuite) { - UnoTestSuite suite = (UnoTestSuite)pTest; - suite.setContext(mContext); - } - - super.runTest(pTest, pResult); - } - - protected void setContext(XComponentContext pContext) { - mContext = pContext; - } - - protected void setHandleConnection(boolean pHandle) { - mHandleConnection = pHandle; - } - - /** - * Starts LibreOffice only if the context isn't set. - * - * @throws Exception if anything wrong happens when starting the office - */ - private void startOffice() throws Exception { - if (mContext == null) { - String path = System.getProperty("libreoffice.program.path"); - if (path == null) { - throw new Exception("The libreoffice.install.path variable is missing"); - } - - File baseDir = new File(path); - URLClassLoader classLoader = new URLClassLoader(new URL[]{baseDir.toURI().toURL()}); - mContext = Bootstrap.bootstrap(classLoader); - mHandleConnection = true; - } - } - - private void stopOffice() { - try { - if (mContext != null && mHandleConnection) { - // Only the uno test suite which started the office can stop it - XMultiComponentFactory xMngr = mContext.getServiceManager(); - Object oDesktop = xMngr.createInstanceWithContext("com.sun.star.frame.Desktop", mContext); - XDesktop xDesktop = (XDesktop)UnoRuntime.queryInterface(XDesktop.class, oDesktop); - - xDesktop.terminate(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/extensions/coooder/source/org/libreoffice/coooder/comp/theLanguagesManagerImpl.java b/extensions/coooder/source/org/libreoffice/coooder/comp/theLanguagesManagerImpl.java deleted file mode 100644 index 38457d6b9..000000000 --- a/extensions/coooder/source/org/libreoffice/coooder/comp/theLanguagesManagerImpl.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * LibreOffice extension for syntax highlighting - * Copyright (C) 2008 Cédric Bosdonnat cedric.bosdonnat.ooo@free.fr - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; - * version 2 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ -package org.libreoffice.coooder.comp; - -import java.io.File; -import java.io.FilenameFilter; -import java.net.URI; -import java.util.Arrays; -import java.util.HashMap; - -import org.libreoffice.coooder.HighlightingException; -import org.libreoffice.coooder.XLanguage; -import org.libreoffice.coooder.XLanguagesManager; - -import com.sun.star.beans.PropertyValue; -import com.sun.star.beans.XHierarchicalPropertySet; -import com.sun.star.lang.XMultiComponentFactory; -import com.sun.star.lang.XMultiServiceFactory; -import com.sun.star.lang.XServiceInfo; -import com.sun.star.lang.XSingleComponentFactory; -import com.sun.star.lib.uno.helper.Factory; -import com.sun.star.lib.uno.helper.WeakBase; -import com.sun.star.registry.InvalidRegistryException; -import com.sun.star.registry.XRegistryKey; -import com.sun.star.uno.UnoRuntime; -import com.sun.star.uno.XComponentContext; -import com.sun.star.uri.XExternalUriReferenceTranslator; -import com.sun.star.util.XMacroExpander; - - -public final class theLanguagesManagerImpl extends WeakBase - implements XServiceInfo, XLanguagesManager { - - private static final String IMPLEMENTATION_NAME = theLanguagesManagerImpl.class.getName(); - private static final String[] SERVICE_NAMES = { "org.libreoffice.coooder.theLanguagesManager" }; - - private XComponentContext mContext; - private HashMap mLoadedLanguages = new HashMap(); - - - public theLanguagesManagerImpl( XComponentContext pContext ) { - mContext = pContext; - }; - - public static XSingleComponentFactory __getComponentFactory( String pImplementationName ) { - XSingleComponentFactory xFactory = null; - - if (pImplementationName.equals(IMPLEMENTATION_NAME)) { - xFactory = Factory.createComponentFactory(theLanguagesManagerImpl.class, SERVICE_NAMES); - } - return xFactory; - } - - public static boolean __writeRegistryServiceInfo(XRegistryKey pRegistryKey) { - return Factory.writeRegistryServiceInfo(IMPLEMENTATION_NAME, - SERVICE_NAMES, pRegistryKey) && writeSingletonKey(pRegistryKey); - } - - public static boolean writeSingletonKey(XRegistryKey pRegistryKey) { - boolean success = false; - - try { - XRegistryKey xNewKey = pRegistryKey - .createKey("/" - + theLanguagesManagerImpl.class.getName() - + "/UNO/SINGLETONS/org.libreoffice.coooder.theLanguagesManager"); - xNewKey.setStringValue(theLanguagesManagerImpl.class.getName()); - success = true; - } catch (InvalidRegistryException e) { - System.err.println("Error creating singleton key: " + e.toString()); - } - - return success; - } - - - //------------------------------------------ com.sun.star.lang.XServiceInfo - - - public String getImplementationName() { - return IMPLEMENTATION_NAME; - } - - public boolean supportsService( String sService ) { - int len = SERVICE_NAMES.length; - - for( int i=0; i < len; i++) { - if (sService.equals(SERVICE_NAMES[i])) - return true; - } - return false; - } - - public String[] getSupportedServiceNames() { - return SERVICE_NAMES; - } - - - //-------------------------------- org.libreoffice.coooder.XLanguagesManager - - - public XLanguage getLanguage(String pId) throws HighlightingException { - LanguageImpl language = null; - try { - XMultiComponentFactory xServiceMngr = mContext.getServiceManager(); - - // Check the loaded languages cache first - Object fromCache = mLoadedLanguages.get(pId); - if (fromCache != null) { - - // The language is already in the cache: no need to reload it! - language = (LanguageImpl)fromCache; - - } else { - - language = new LanguageImpl(mContext); - - File xml = new File(getLangDirectory(), pId + ".xml"); - - Object translator = xServiceMngr.createInstanceWithContext( - "com.sun.star.uri.ExternalUriReferenceTranslator", mContext); - XExternalUriReferenceTranslator xTranslator = (XExternalUriReferenceTranslator)UnoRuntime. - queryInterface(XExternalUriReferenceTranslator.class, translator); - - String path = xTranslator.translateToInternal(xml.toURI().toString()); - language.defineFromXml(path); - - // Add to the language cache - mLoadedLanguages.put(pId, language); - } - } catch (Exception e) { - throw new HighlightingException("Can't get the language " + pId, e); - } - - return language; - } - - public String[] getLanguagesIdsList() throws HighlightingException { - String[] ids = null; - - try { - File dir = getLangDirectory(); - String[] files = dir.list(new FilenameFilter() { - - public boolean accept(File pDir, String pName) { - return pName.endsWith(".xml"); - } - - }); - - ids = new String[files.length]; - for (int i = 0; i < ids.length; i++) { - String filename = files[i]; - int posExt = filename.indexOf("."); - String id = filename.substring(0, posExt); - - ids[i] = id; - } - - Arrays.sort(ids); - - } catch (Exception e) { - throw new HighlightingException("Can't get the list of language Ids", e); - } - return ids; - } - - public String getLanguageFilesPath() throws HighlightingException { - String path = null; - - try { - XMultiComponentFactory xServiceMngr = mContext.getServiceManager(); - Object configProvider = xServiceMngr.createInstanceWithContext( - "com.sun.star.configuration.ConfigurationProvider", mContext); - XMultiServiceFactory xConfigProvider = (XMultiServiceFactory)UnoRuntime.queryInterface( - XMultiServiceFactory.class, configProvider); - - PropertyValue[] params = new PropertyValue[1]; - params[0] = new PropertyValue(); - params[0].Name = new String("nodepath"); - params[0].Value = "/org.libreoffice.Coooder/LanguageFiles"; - - Object access = xConfigProvider.createInstanceWithArguments( - "com.sun.star.configuration.ConfigurationAccess", params); - XHierarchicalPropertySet xProps = (XHierarchicalPropertySet)UnoRuntime.queryInterface( - XHierarchicalPropertySet.class, access); - - Object value = xProps.getHierarchicalPropertyValue("Path"); - path = (String)value; - } catch (Exception e) { - throw new HighlightingException("Can't get languages files path", e); - } - - return path; - } - - private File getLangDirectory() throws HighlightingException { - File dir = null; - try { - String path = getLanguageFilesPath(); - - int pos = path.lastIndexOf(":"); - path = path.substring(pos + 1); - - Object expander = mContext.getValueByName("/singletons/com.sun.star.util.theMacroExpander"); - XMacroExpander xExpander = (XMacroExpander)UnoRuntime.queryInterface( - XMacroExpander.class, expander); - - path = xExpander.expandMacros(path); - - XMultiComponentFactory xServiceMngr = mContext.getServiceManager(); - Object translator = xServiceMngr.createInstanceWithContext( - "com.sun.star.uri.ExternalUriReferenceTranslator", mContext); - XExternalUriReferenceTranslator xTranslator = (XExternalUriReferenceTranslator)UnoRuntime. - queryInterface(XExternalUriReferenceTranslator.class, translator); - - path = xTranslator.translateToExternal(path); - - dir = new File(new URI(path)); - - } catch (Exception e) { - throw new HighlightingException("Can't get the list of language Ids", e); - } - return dir; - } -} diff --git a/extensions/coooder/source/org/libreoffice/coooder/comp/ui/AbstractDialog.java b/extensions/coooder/source/org/libreoffice/coooder/comp/ui/AbstractDialog.java deleted file mode 100644 index f4d258b4f..000000000 --- a/extensions/coooder/source/org/libreoffice/coooder/comp/ui/AbstractDialog.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * LibreOffice extension for syntax highlighting - * Copyright (C) 2008 Cédric Bosdonnat cedric.bosdonnat.ooo@free.fr - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; - * version 2 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ -package org.libreoffice.coooder.comp.ui; - -import com.sun.star.awt.MessageBoxButtons; -import com.sun.star.awt.Rectangle; -import com.sun.star.awt.XControl; -import com.sun.star.awt.XControlContainer; -import com.sun.star.awt.XControlModel; -import com.sun.star.awt.XDialog; -import com.sun.star.awt.XMessageBox; -import com.sun.star.awt.XMessageBoxFactory; -import com.sun.star.awt.XToolkit; -import com.sun.star.awt.XWindow; -import com.sun.star.awt.XWindowPeer; -import com.sun.star.beans.XPropertySet; -import com.sun.star.container.XNameContainer; -import com.sun.star.frame.XDesktop; -import com.sun.star.lang.XMultiComponentFactory; -import com.sun.star.lang.XMultiServiceFactory; -import com.sun.star.ui.dialogs.ExecutableDialogResults; -import com.sun.star.uno.UnoRuntime; -import com.sun.star.uno.XComponentContext; - -public abstract class AbstractDialog { - - private XComponentContext mContext; - private XControl mDialog; - - public AbstractDialog(XComponentContext pContext, String pTitle) { - mContext = pContext; - - initialize(pTitle); - } - - protected XComponentContext getContext() { - return mContext; - } - - protected void initialize(String pTitle) { - mDialog = null; - try { - // Create the dialog - XMultiComponentFactory xMngr = mContext.getServiceManager(); - Object dlg = xMngr.createInstanceWithContext( - "com.sun.star.awt.UnoControlDialog", mContext); - Object model = xMngr.createInstanceWithContext( - "com.sun.star.awt.UnoControlDialogModel", mContext); - - int[] bounds = getDialogBounds(); - XPropertySet dlgProps = setBounds(model, bounds[0], bounds[1], bounds[2], bounds[3]); - dlgProps.setPropertyValue("Title", pTitle); - - XControl xDlgControl = (XControl)UnoRuntime.queryInterface( - XControl.class, dlg); - XControlModel xDlgModel = (XControlModel)UnoRuntime.queryInterface( - XControlModel.class, model); - xDlgControl.setModel(xDlgModel); - - mDialog = xDlgControl; - - // Create the dialog controls - createControls(xDlgControl); - } catch (Exception e) { - mDialog = null; - } - } - - protected abstract int[] getDialogBounds(); - - protected abstract void createControls(XControl pDlgControl) throws Exception; - - protected short doExecute() { - short status = ExecutableDialogResults.CANCEL; - - if (mDialog != null) { - try { - XMultiComponentFactory xMngr = mContext.getServiceManager(); - - // Execute the dialog - Object toolkit = xMngr.createInstanceWithContext( - "com.sun.star.awt.Toolkit", mContext); - XToolkit xToolkit = (XToolkit)UnoRuntime.queryInterface(XToolkit.class, toolkit); - - XControl xControl = (XControl)UnoRuntime.queryInterface(XControl.class, mDialog); - xControl.createPeer(xToolkit, null); - - XDialog xDlg = (XDialog)UnoRuntime.queryInterface(XDialog.class, mDialog); - status = xDlg.execute(); - } catch (Exception e) { - status = ExecutableDialogResults.CANCEL; - } - } - - return status; - } - - protected void doEndExecute() { - XDialog xDlg = (XDialog)UnoRuntime.queryInterface(XDialog.class, mDialog); - xDlg.endExecute(); - } - - protected XPropertySet setBounds(Object pModel, int pX, int pY, int pH, int pW) throws Exception { - - XPropertySet xProps = (XPropertySet)UnoRuntime.queryInterface( - XPropertySet.class, pModel); - xProps.setPropertyValue("PositionX", Integer.valueOf(pX)); - xProps.setPropertyValue("PositionY", Integer.valueOf(pY)); - xProps.setPropertyValue("Height", Integer.valueOf(pH)); - xProps.setPropertyValue("Width", Integer.valueOf(pW)); - - return xProps; - } - - protected XMultiServiceFactory getFactory() { - return (XMultiServiceFactory)UnoRuntime.queryInterface( - XMultiServiceFactory.class, mDialog.getModel()); - } - - protected XNameContainer getModelContainer() { - return (XNameContainer)UnoRuntime.queryInterface( - XNameContainer.class, mDialog.getModel()); - } - - protected XControlContainer getControlContainer() { - return (XControlContainer)UnoRuntime.queryInterface( - XControlContainer.class, mDialog); - } - - public static void showErrorDialog(XComponentContext pContext, String pTitle, String pMsg) { - try { - XMultiComponentFactory xMngr = pContext.getServiceManager(); - - // Execute the dialog - Object toolkit = xMngr.createInstanceWithContext("com.sun.star.awt.Toolkit", pContext); - XMessageBoxFactory xFactory = (XMessageBoxFactory)UnoRuntime.queryInterface( - XMessageBoxFactory.class, toolkit); - - // Get the peer parent window - Object oDesktop = xMngr.createInstanceWithContext("com.sun.star.frame.Desktop", pContext); - XDesktop xDesktop = (XDesktop)UnoRuntime.queryInterface(XDesktop.class, oDesktop); - XWindow xWin = xDesktop.getCurrentFrame().getContainerWindow(); - XWindowPeer xPeer = (XWindowPeer)UnoRuntime.queryInterface(XWindowPeer.class, xWin); - - XMessageBox msgBox = xFactory.createMessageBox(xPeer, new Rectangle(), "errorbox", - MessageBoxButtons.BUTTONS_OK, pTitle, pMsg); - - msgBox.execute(); - - } catch (Exception e) { - // Nothing to do - } - } -} diff --git a/extensions/coooder/source/org/libreoffice/coooder/comp/ui/LanguageDialog.java b/extensions/coooder/source/org/libreoffice/coooder/comp/ui/LanguageDialog.java deleted file mode 100644 index b663f351e..000000000 --- a/extensions/coooder/source/org/libreoffice/coooder/comp/ui/LanguageDialog.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * LibreOffice extension for syntax highlighting - * Copyright (C) 2008 Cédric Bosdonnat cedric.bosdonnat.ooo@free.fr - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; - * version 2 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ -package org.libreoffice.coooder.comp.ui; - -import org.libreoffice.coooder.theLanguagesManager; - -import com.sun.star.awt.ActionEvent; -import com.sun.star.awt.PushButtonType; -import com.sun.star.awt.XActionListener; -import com.sun.star.awt.XControl; -import com.sun.star.awt.XControlContainer; -import com.sun.star.awt.XListBox; -import com.sun.star.beans.XPropertySet; -import com.sun.star.container.XNameContainer; -import com.sun.star.lang.EventObject; -import com.sun.star.lang.XMultiServiceFactory; -import com.sun.star.ui.dialogs.ExecutableDialogResults; -import com.sun.star.uno.UnoRuntime; -import com.sun.star.uno.XComponentContext; - -public class LanguageDialog extends AbstractDialog { - - public class LanguagesListListener implements XActionListener { - private XControlContainer mControls; - - public LanguagesListListener(XControlContainer pControls) { - mControls = pControls; - } - - public void actionPerformed(ActionEvent pEvent) { - try { - XControl list = mControls.getControl(LIST_NAME); - XListBox xList = (XListBox)UnoRuntime.queryInterface(XListBox.class, list); - - mLangId = xList.getSelectedItem(); - - XControl okBtn = mControls.getControl(OK_NAME); - XPropertySet xProps = (XPropertySet)UnoRuntime.queryInterface( - XPropertySet.class, okBtn.getModel()); - xProps.setPropertyValue("Enabled", Boolean.valueOf(!mLangId.equals(""))); - } catch (Exception e) { - // Nothing to do - } - } - - public void disposing(EventObject pEvent) { - mControls = null; - } - } - - private static final String OK_NAME = "btnOk"; - private static final String LABEL_NAME = "lblLanguages"; - private static final String LIST_NAME = "lstLanguages"; - private static final String CANCEL_NAME = "btnCancel"; - - private String mLangId; - - public LanguageDialog(XComponentContext pContext) { - super(pContext, "Language selection"); - } - - public String execute() { - short status = doExecute(); - - // Return the selected language or null - if (status == ExecutableDialogResults.CANCEL) { - mLangId = null; - } - - return mLangId; - } - - protected int[] getDialogBounds() { - return new int[]{100, 100, 70, 155}; - } - - protected void createControls(XControl pDlgControl) throws Exception { - - // Create the language field - createLanguageField(pDlgControl); - - // Create the OK / Cancel buttons - createButtons(pDlgControl); - } - - private void createLanguageField(XControl pDlg) throws Exception { - XMultiServiceFactory xFactory = getFactory(); - XNameContainer xModelContainer = getModelContainer(); - - // Create the label - Object label = xFactory.createInstance("com.sun.star.awt.UnoControlFixedTextModel"); - XPropertySet labelProps = setBounds(label, 5, 13, 10, 40); - labelProps.setPropertyValue("Label", "Language"); - labelProps.setPropertyValue("Name", LABEL_NAME); - - xModelContainer.insertByName(LABEL_NAME, label); - - // Create the list - Object list = xFactory.createInstance("com.sun.star.awt.UnoControlListBoxModel"); - XPropertySet listProps = setBounds(list, 50, 10, 15, 100); - listProps.setPropertyValue("TabIndex", Short.valueOf((short)0)); - listProps.setPropertyValue("LineCount", Short.valueOf((short)10)); - listProps.setPropertyValue("Dropdown", Boolean.TRUE); - listProps.setPropertyValue("Name", LIST_NAME); - - // TODO Get the display names - String[] ids = theLanguagesManager.get(getContext()).getLanguagesIdsList(); - listProps.setPropertyValue("StringItemList", ids); - - xModelContainer.insertByName(LIST_NAME, list); - - XControlContainer xControlCont = getControlContainer(); - Object listControl = xControlCont.getControl(LIST_NAME); - XListBox xList = (XListBox)UnoRuntime.queryInterface(XListBox.class, listControl); - - xList.addActionListener(new LanguagesListListener(xControlCont)); - } - - private void createButtons(XControl pDlg) throws Exception { - XMultiServiceFactory xFactory = getFactory(); - XNameContainer xModelContainer = getModelContainer(); - - // Create the OK Button - Object okBtn = xFactory.createInstance("com.sun.star.awt.UnoControlButtonModel"); - XPropertySet xOkProps = setBounds(okBtn, 40, 45, 15, 50); - xOkProps.setPropertyValue("Name", OK_NAME); - xOkProps.setPropertyValue("Enabled", Boolean.FALSE); - xOkProps.setPropertyValue("TabIndex", Short.valueOf((short)1)); - xOkProps.setPropertyValue("Label", "OK"); - xOkProps.setPropertyValue("DefaultButton", Boolean.TRUE); - xOkProps.setPropertyValue("PushButtonType", Short.valueOf((short)PushButtonType.OK_value)); - - xModelContainer.insertByName(OK_NAME, okBtn); - - // Create the Cancel Button - Object cancelBtn = xFactory.createInstance("com.sun.star.awt.UnoControlButtonModel"); - XPropertySet xCancelProps = setBounds(cancelBtn, 100, 45, 15, 50); - xCancelProps.setPropertyValue("Name", CANCEL_NAME); - xCancelProps.setPropertyValue("TabIndex", Short.valueOf((short)2)); - xCancelProps.setPropertyValue("Label", "Cancel"); - xCancelProps.setPropertyValue("PushButtonType", Short.valueOf((short)PushButtonType.CANCEL_value)); - - xModelContainer.insertByName(CANCEL_NAME, xCancelProps); - } -} diff --git a/extensions/coooder/source/org/libreoffice/coooder/comp/ui/ParseTriggerImpl.java b/extensions/coooder/source/org/libreoffice/coooder/comp/ui/ParseTriggerImpl.java deleted file mode 100644 index f9aaefb48..000000000 --- a/extensions/coooder/source/org/libreoffice/coooder/comp/ui/ParseTriggerImpl.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * LibreOffice extension for syntax highlighting - * Copyright (C) 2008 Cédric Bosdonnat cedric.bosdonnat.ooo@free.fr - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; - * version 2 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ -package org.libreoffice.coooder.comp.ui; - -import java.util.Calendar; - -import org.libreoffice.coooder.XHighlighter; -import org.libreoffice.coooder.XLanguage; -import org.libreoffice.coooder.theLanguagesManager; - -import com.sun.star.frame.XDesktop; -import com.sun.star.frame.XFrame; -import com.sun.star.frame.XModel; -import com.sun.star.lang.XComponent; -import com.sun.star.lang.XMultiComponentFactory; -import com.sun.star.lang.XServiceInfo; -import com.sun.star.lang.XSingleComponentFactory; -import com.sun.star.lib.uno.helper.Factory; -import com.sun.star.lib.uno.helper.WeakBase; -import com.sun.star.registry.XRegistryKey; -import com.sun.star.task.XJobExecutor; -import com.sun.star.task.XStatusIndicator; -import com.sun.star.task.XStatusIndicatorFactory; -import com.sun.star.uno.UnoRuntime; -import com.sun.star.uno.XComponentContext; - - -public final class ParseTriggerImpl extends WeakBase implements XServiceInfo, XJobExecutor { - - private static final String IMPLEMENTATION_NAME = ParseTriggerImpl.class.getName(); - private static final String[] SERVICE_NAMES = { "org.libreoffice.coooder.ui.ParseTrigger" }; - - private final XComponentContext mContext; - - - public ParseTriggerImpl(XComponentContext pContext) { - mContext = pContext; - }; - - public static XSingleComponentFactory __getComponentFactory(String pImplementationName) { - XSingleComponentFactory xFactory = null; - - if (pImplementationName.equals(IMPLEMENTATION_NAME)) { - xFactory = Factory.createComponentFactory(ParseTriggerImpl.class, SERVICE_NAMES); - } - return xFactory; - } - - public static boolean __writeRegistryServiceInfo(XRegistryKey pRegistryKey) { - return Factory.writeRegistryServiceInfo(IMPLEMENTATION_NAME, - SERVICE_NAMES, pRegistryKey); - } - - - //------------------------------------------ com.sun.star.lang.XServiceInfo - - - public String getImplementationName() { - return IMPLEMENTATION_NAME; - } - - public boolean supportsService(String pService) { - int len = SERVICE_NAMES.length; - - for( int i=0; i < len; i++) { - if (pService.equals(SERVICE_NAMES[i])) - return true; - } - return false; - } - - public String[] getSupportedServiceNames() { - return SERVICE_NAMES; - } - - - //------------------------------------------ com.sun.star.task.XJobExecutor - - - public void trigger(String pEvent) - { - XStatusIndicator monitor = null; - try { - // Check if the selection is a text selection - XMultiComponentFactory xMngr = mContext.getServiceManager(); - Object desktop = xMngr.createInstanceWithContext("com.sun.star.frame.Desktop", mContext); - XDesktop xDesktop = (XDesktop)UnoRuntime.queryInterface(XDesktop.class, desktop); - XComponent xComponent = xDesktop.getCurrentComponent(); - XModel xDocModel = (XModel)UnoRuntime.queryInterface(XModel.class, xComponent); - - XServiceInfo xInfos = (XServiceInfo)UnoRuntime.queryInterface( - XServiceInfo.class, xDocModel.getCurrentSelection()); - if (!xInfos.supportsService("com.sun.star.text.TextRanges")) { - throw new Exception("Can only highlight code snippets"); - } - - // Ask for the language - String langId = askLanguage(); - - if (langId != null) { - - XLanguage xLanguage = theLanguagesManager.get(mContext).getLanguage(langId); - - // Parse - Object highlighter = xMngr.createInstanceWithContext( - "org.libreoffice.coooder.Highlighter", mContext); - XHighlighter xHighlighter = (XHighlighter)UnoRuntime.queryInterface( - XHighlighter.class, highlighter); - - xHighlighter.setLanguage(xLanguage); - - // Create and set the status indicator - XFrame xFrm = xDocModel.getCurrentController().getFrame(); - XStatusIndicatorFactory xStatusFactory = (XStatusIndicatorFactory)UnoRuntime.queryInterface( - XStatusIndicatorFactory.class, xFrm ); - monitor = xStatusFactory.createStatusIndicator(); - xHighlighter.setStatusIndicator( monitor ); - monitor.start( "Hightlighting...", 100 ); - - - // Parse the code snippet - long debut = Calendar.getInstance().getTimeInMillis(); - xHighlighter.parse(); - long fin = Calendar.getInstance().getTimeInMillis(); - long duree = fin - debut; - - System.out.println("Highlighting duration: (in ms)" + duree); - - monitor.end(); - } - } catch (Exception e) { - monitor.end(); - - String title = "Error during syntax highlighting"; - AbstractDialog.showErrorDialog(mContext, title, e.getMessage()); - } - } - - private String askLanguage() { - LanguageDialog dlg = new LanguageDialog(mContext); - return dlg.execute(); - } -} |