trace/traceviewer/com.nokia.traceviewer/src/com/nokia/traceviewer/dialog/FilterAdvancedParser.java
changeset 11 5b9d4d8641ce
equal deleted inserted replaced
10:ed1c9f64298a 11:5b9d4d8641ce
       
     1 /*
       
     2  * Copyright (c) 2007-2010 Nokia Corporation and/or its subsidiary(-ies). 
       
     3  * All rights reserved.
       
     4  * This component and the accompanying materials are made available
       
     5  * under the terms of "Eclipse Public License v1.0"
       
     6  * which accompanies this distribution, and is available
       
     7  * at the URL "http://www.eclipse.org/legal/epl-v10.html".
       
     8  *
       
     9  * Initial Contributors:
       
    10  * Nokia Corporation - initial contribution.
       
    11  *
       
    12  * Contributors:
       
    13  *
       
    14  * Description:
       
    15  *
       
    16  * Parses the rule text field for validity
       
    17  *
       
    18  */
       
    19 package com.nokia.traceviewer.dialog;
       
    20 
       
    21 import java.util.ArrayList;
       
    22 import java.util.Collections;
       
    23 import java.util.Comparator;
       
    24 import java.util.List;
       
    25 
       
    26 import org.eclipse.swt.SWT;
       
    27 import org.eclipse.swt.custom.StyleRange;
       
    28 import org.eclipse.swt.custom.StyledText;
       
    29 import org.eclipse.swt.events.FocusEvent;
       
    30 import org.eclipse.swt.events.FocusListener;
       
    31 import org.eclipse.swt.events.KeyEvent;
       
    32 import org.eclipse.swt.events.KeyListener;
       
    33 import org.eclipse.swt.events.MouseEvent;
       
    34 import org.eclipse.swt.events.MouseListener;
       
    35 import org.eclipse.swt.graphics.Color;
       
    36 import org.eclipse.swt.graphics.Point;
       
    37 import org.eclipse.swt.widgets.TreeItem;
       
    38 
       
    39 import com.nokia.traceviewer.engine.TraceViewerGlobals;
       
    40 import com.nokia.traceviewer.engine.dataprocessor.FilterRuleSet.LogicalOperator;
       
    41 
       
    42 /**
       
    43  * Parses the rule text field for validity
       
    44  */
       
    45 public final class FilterAdvancedParser implements FocusListener, KeyListener,
       
    46 		MouseListener {
       
    47 
       
    48 	/**
       
    49 	 * Indicates the max number of brackets in a rule. Used to shut down while
       
    50 	 * loop if there is something wrong
       
    51 	 */
       
    52 	private static final int MAX_NUMBER_OF_BRACKETS = 50;
       
    53 
       
    54 	/**
       
    55 	 * AND String
       
    56 	 */
       
    57 	public static final String AND = "AND"; //$NON-NLS-1$
       
    58 
       
    59 	/**
       
    60 	 * OR String
       
    61 	 */
       
    62 	public static final String OR = "OR"; //$NON-NLS-1$
       
    63 
       
    64 	/**
       
    65 	 * NOT String
       
    66 	 */
       
    67 	public static final String NOT = "NOT"; //$NON-NLS-1$
       
    68 
       
    69 	/**
       
    70 	 * Start bracket
       
    71 	 */
       
    72 	private static final char START_BRACKET = '(';
       
    73 
       
    74 	/**
       
    75 	 * Start bracket String
       
    76 	 */
       
    77 	public static final String START_BRACKET_STR = "("; //$NON-NLS-1$
       
    78 
       
    79 	/**
       
    80 	 * End bracket
       
    81 	 */
       
    82 	private static final char END_BRACKET = ')';
       
    83 
       
    84 	/**
       
    85 	 * End bracket String
       
    86 	 */
       
    87 	public static final String END_BRACKET_STR = ")"; //$NON-NLS-1$
       
    88 
       
    89 	/**
       
    90 	 * Space
       
    91 	 */
       
    92 	public static final char SPACE = ' ';
       
    93 
       
    94 	/**
       
    95 	 * Space String
       
    96 	 */
       
    97 	public static final String SPACE_STR = " "; //$NON-NLS-1$
       
    98 
       
    99 	/**
       
   100 	 * Empty String
       
   101 	 */
       
   102 	private static final String EMPTY = ""; //$NON-NLS-1$
       
   103 
       
   104 	/**
       
   105 	 * Text field to validate
       
   106 	 */
       
   107 	private final StyledText textField;
       
   108 
       
   109 	/**
       
   110 	 * Rule items
       
   111 	 */
       
   112 	private final TreeItem[] items;
       
   113 
       
   114 	/**
       
   115 	 * Blue color
       
   116 	 */
       
   117 	private final Color blue;
       
   118 
       
   119 	/**
       
   120 	 * Gray color
       
   121 	 */
       
   122 	private final Color gray;
       
   123 
       
   124 	/**
       
   125 	 * Constructor
       
   126 	 * 
       
   127 	 * @param ruleTextfield
       
   128 	 *            rule text field
       
   129 	 * @param items
       
   130 	 *            rule items
       
   131 	 */
       
   132 	public FilterAdvancedParser(StyledText ruleTextfield, TreeItem[] items) {
       
   133 		textField = ruleTextfield;
       
   134 		this.items = items;
       
   135 		blue = textField.getDisplay().getSystemColor(SWT.COLOR_BLUE);
       
   136 		gray = textField.getDisplay().getSystemColor(SWT.COLOR_GRAY);
       
   137 	}
       
   138 
       
   139 	/*
       
   140 	 * (non-Javadoc)
       
   141 	 * 
       
   142 	 * @see
       
   143 	 * org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.
       
   144 	 * KeyEvent)
       
   145 	 */
       
   146 	public void keyPressed(KeyEvent e) {
       
   147 		if (e.keyCode != SWT.CTRL) {
       
   148 			validate();
       
   149 
       
   150 			// Set button states
       
   151 			TraceViewerGlobals.getTraceViewer().getDataProcessorAccess()
       
   152 					.getFilterProcessor().getFilterDialog().getAdvancedDialog()
       
   153 					.setButtonStates();
       
   154 		}
       
   155 	}
       
   156 
       
   157 	/*
       
   158 	 * (non-Javadoc)
       
   159 	 * 
       
   160 	 * @seeorg.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.
       
   161 	 * MouseEvent)
       
   162 	 */
       
   163 	public void mouseUp(MouseEvent e) {
       
   164 		if (textField.getText().length() > 1) {
       
   165 			Point selection = null;
       
   166 			if (textField.getSelectionRange().y > 0) {
       
   167 				selection = textField.getSelection();
       
   168 			}
       
   169 			validate();
       
   170 			// Set button states
       
   171 			TraceViewerGlobals.getTraceViewer().getDataProcessorAccess()
       
   172 					.getFilterProcessor().getFilterDialog().getAdvancedDialog()
       
   173 					.setButtonStates();
       
   174 			if (selection != null) {
       
   175 				textField.setSelection(selection);
       
   176 			}
       
   177 		}
       
   178 	}
       
   179 
       
   180 	/**
       
   181 	 * Validates the text field
       
   182 	 */
       
   183 	void validate() {
       
   184 		textField.getCaret().setVisible(false);
       
   185 		String text = textField.getText();
       
   186 		// Change logical operations to upper case
       
   187 		text = text.replace(" and ", SPACE + AND + SPACE); //$NON-NLS-1$
       
   188 		text = text.replace(" or ", SPACE + OR + SPACE); //$NON-NLS-1$
       
   189 		text = text.replace(" not ", SPACE + NOT + SPACE); //$NON-NLS-1$
       
   190 
       
   191 		StringBuffer newText = new StringBuffer(text);
       
   192 		int caretPos = textField.getCaretOffset();
       
   193 
       
   194 		int removedBeforeCaret = removeDoubleSpaces(newText, caretPos);
       
   195 		caretPos -= removedBeforeCaret;
       
   196 
       
   197 		// Empty, add one space
       
   198 		if (newText.length() == 0) {
       
   199 			newText.append(SPACE);
       
   200 			caretPos = 1;
       
   201 
       
   202 		}
       
   203 
       
   204 		// Insert the text and color the caret
       
   205 		textField.setText(newText.toString());
       
   206 		textField.setCaretOffset(caretPos);
       
   207 		colorCaretAndRules();
       
   208 		textField.getCaret().setVisible(true);
       
   209 	}
       
   210 
       
   211 	/**
       
   212 	 * Removes double spaces
       
   213 	 * 
       
   214 	 * @param newText
       
   215 	 *            StringBuffer to use
       
   216 	 * @param caretPos
       
   217 	 *            old caret position
       
   218 	 * @return number of chars removed before caret position
       
   219 	 */
       
   220 	private int removeDoubleSpaces(StringBuffer newText, int caretPos) {
       
   221 		int charsRemoved = 0;
       
   222 		boolean lastCharSpace = false;
       
   223 		for (int i = 0; i < newText.length(); i++) {
       
   224 			if (newText.charAt(i) == SPACE) {
       
   225 				if (lastCharSpace) {
       
   226 					newText.deleteCharAt(i);
       
   227 					if (i < caretPos) {
       
   228 						charsRemoved++;
       
   229 					}
       
   230 					i--;
       
   231 				}
       
   232 				lastCharSpace = true;
       
   233 			} else {
       
   234 				lastCharSpace = false;
       
   235 			}
       
   236 		}
       
   237 		return charsRemoved;
       
   238 	}
       
   239 
       
   240 	/**
       
   241 	 * Counts occurrences of a character from a string
       
   242 	 * 
       
   243 	 * @param text
       
   244 	 *            text to find from
       
   245 	 * @param c
       
   246 	 *            the character
       
   247 	 * @return number of occurrences in the string
       
   248 	 */
       
   249 	private int countOccurrences(String text, char c) {
       
   250 		int occ = 0;
       
   251 		for (int i = 0; i < text.length(); i++) {
       
   252 			if (text.charAt(i) == c) {
       
   253 				occ++;
       
   254 			}
       
   255 		}
       
   256 		return occ;
       
   257 	}
       
   258 
       
   259 	/**
       
   260 	 * Colors the caret and the rules
       
   261 	 */
       
   262 	private void colorCaretAndRules() {
       
   263 		List<StyleRange> ranges = new ArrayList<StyleRange>();
       
   264 		int caretPos = textField.getCaretOffset();
       
   265 
       
   266 		// Color the rules
       
   267 		if (items != null) {
       
   268 			String text = textField.getText();
       
   269 			text = text.replace(START_BRACKET, SPACE);
       
   270 			text = text.replace(END_BRACKET, SPACE);
       
   271 			StringBuffer buf = new StringBuffer();
       
   272 			ArrayList<String> words = new ArrayList<String>();
       
   273 			ArrayList<Integer> offsets = new ArrayList<Integer>();
       
   274 
       
   275 			// Gather the words
       
   276 			for (int i = 0; i < text.length(); i++) {
       
   277 				char c = text.charAt(i);
       
   278 				if (c == SPACE) {
       
   279 					// If the buffer is not empty, it's a word and should be
       
   280 					// added to the list
       
   281 					if (!buf.toString().replace(SPACE_STR, EMPTY).equals(EMPTY)) {
       
   282 						words.add(buf.toString());
       
   283 						offsets.add(Integer.valueOf(i - buf.length()));
       
   284 					}
       
   285 					buf.setLength(0);
       
   286 				} else {
       
   287 					buf.append(c);
       
   288 				}
       
   289 			}
       
   290 
       
   291 			// Create the style ranges for the basic rules found
       
   292 			for (int j = 0; j < words.size(); j++) {
       
   293 				if (isBasicRule(words.get(j))) {
       
   294 					ranges.add(new StyleRange(offsets.get(j).intValue(), words
       
   295 							.get(j).length(), blue, null));
       
   296 				}
       
   297 			}
       
   298 		}
       
   299 
       
   300 		// Color the caret if not focused
       
   301 		if (!textField.isFocusControl()) {
       
   302 			if (caretPos > textField.getCharCount()) {
       
   303 				caretPos = textField.getCharCount();
       
   304 			}
       
   305 			ranges.add(new StyleRange(caretPos - 1, 1, gray, gray));
       
   306 		}
       
   307 		// Sort and set the ranges
       
   308 		ranges = sortColorRanges(ranges);
       
   309 		textField.setStyleRanges(ranges.toArray(new StyleRange[ranges.size()]));
       
   310 	}
       
   311 
       
   312 	/**
       
   313 	 * Sorts color ranges
       
   314 	 * 
       
   315 	 * @param ranges
       
   316 	 *            color ranges
       
   317 	 * @return ordered list
       
   318 	 */
       
   319 	private List<StyleRange> sortColorRanges(List<StyleRange> ranges) {
       
   320 		Collections.sort(ranges, new Comparator<StyleRange>() {
       
   321 
       
   322 			public int compare(StyleRange o1, StyleRange o2) {
       
   323 				int id1 = o1.start;
       
   324 				int id2 = o2.start;
       
   325 				return id1 > id2 ? 1 : id1 < id2 ? -1 : 0;
       
   326 			}
       
   327 
       
   328 		});
       
   329 		return ranges;
       
   330 	}
       
   331 
       
   332 	/**
       
   333 	 * Finds and returns a set from caret pos
       
   334 	 * 
       
   335 	 * @param text
       
   336 	 *            text to search from
       
   337 	 * @param caretOffset
       
   338 	 *            caret offset
       
   339 	 * @return the set where the caret is on
       
   340 	 */
       
   341 	private String findSet(String text, int caretOffset) {
       
   342 		String set = null;
       
   343 		if (text.length() > 0) {
       
   344 
       
   345 			// Get counts for the brackets
       
   346 			int startCount = countOccurrences(text.substring(0, caretOffset),
       
   347 					START_BRACKET);
       
   348 			int endCount = countOccurrences(text.substring(0, caretOffset),
       
   349 					END_BRACKET);
       
   350 
       
   351 			// Full sets before the caret, start from last end bracket
       
   352 			if (startCount == endCount) {
       
   353 				// Get indices for the nearest brackets
       
   354 				int startIdx = getNearestChar(text, caretOffset, START_BRACKET,
       
   355 						true);
       
   356 				int endIdx = getNearestChar(text, caretOffset, END_BRACKET,
       
   357 						false);
       
   358 				if (startIdx == -1) {
       
   359 					startIdx = text.length();
       
   360 				}
       
   361 				if (endIdx == -1) {
       
   362 					endIdx = 0;
       
   363 				} else {
       
   364 					endIdx++;
       
   365 				}
       
   366 				set = text.substring(endIdx, startIdx);
       
   367 			} else {
       
   368 				// Get indices for the nearest brackets
       
   369 				int startIdx = getNearestChar(text, caretOffset, START_BRACKET,
       
   370 						false);
       
   371 				int endIdx = getNearestChar(text, caretOffset, END_BRACKET,
       
   372 						true);
       
   373 				if (startIdx == -1) {
       
   374 					startIdx = 0;
       
   375 				} else {
       
   376 					startIdx++;
       
   377 				}
       
   378 				if (endIdx == -1) {
       
   379 					endIdx = text.length();
       
   380 				}
       
   381 				set = text.substring(startIdx, endIdx);
       
   382 			}
       
   383 		}
       
   384 		return set;
       
   385 	}
       
   386 
       
   387 	/**
       
   388 	 * Gets nearest char from a string
       
   389 	 * 
       
   390 	 * @param text
       
   391 	 *            text to search from
       
   392 	 * @param caretOffset
       
   393 	 *            caret offset
       
   394 	 * @param c
       
   395 	 *            character to search for
       
   396 	 * @param forward
       
   397 	 *            forward or backward search
       
   398 	 * @return offset of nearest character. -1 if not found
       
   399 	 */
       
   400 	private int getNearestChar(String text, int caretOffset, char c,
       
   401 			boolean forward) {
       
   402 		int idx = -1;
       
   403 		// Searching forwards
       
   404 		if (forward) {
       
   405 			idx = text.indexOf(c, caretOffset);
       
   406 
       
   407 			// Searching backwards
       
   408 		} else if (text.length() > 0) {
       
   409 			for (int i = caretOffset - 1; i >= 0; i--) {
       
   410 				if (text.charAt(i) == c) {
       
   411 					idx = i;
       
   412 					break;
       
   413 				}
       
   414 			}
       
   415 		}
       
   416 		return idx;
       
   417 	}
       
   418 
       
   419 	/**
       
   420 	 * Tells if a set is open
       
   421 	 * 
       
   422 	 * @return true if set is open
       
   423 	 */
       
   424 	boolean isSetOpen() {
       
   425 		boolean setOpen = false;
       
   426 		int startCount = countOccurrences(textField.getText(), START_BRACKET);
       
   427 		int endCount = countOccurrences(textField.getText(), END_BRACKET);
       
   428 		if (startCount > endCount) {
       
   429 			setOpen = true;
       
   430 		}
       
   431 		return setOpen;
       
   432 	}
       
   433 
       
   434 	/**
       
   435 	 * Check if AND can be inserted to current pos
       
   436 	 * 
       
   437 	 * @return true if AND can be inserted
       
   438 	 */
       
   439 	boolean canAndBeInserted() {
       
   440 		boolean canBeInserted = true;
       
   441 		String set = findSet(textField.getText(), textField.getCaretOffset());
       
   442 		// If there is OR
       
   443 		if (set != null && set.contains(OR)) {
       
   444 			canBeInserted = false;
       
   445 		} else if (set != null && !containsFilterRule(set, items)
       
   446 				&& !isSetOpen()
       
   447 				&& !containsFilterRule(textField.getText(), items)) {
       
   448 			canBeInserted = false;
       
   449 		} else if (set != null && !containsFilterRule(set, items)
       
   450 				&& isSetOpen()) {
       
   451 			canBeInserted = false;
       
   452 		} else if (set == null) {
       
   453 			canBeInserted = false;
       
   454 		}
       
   455 
       
   456 		return canBeInserted;
       
   457 	}
       
   458 
       
   459 	/**
       
   460 	 * Check if OR can be inserted to current pos
       
   461 	 * 
       
   462 	 * @return true if OR can be inserted
       
   463 	 */
       
   464 	boolean canOrBeInserted() {
       
   465 		boolean canBeInserted = true;
       
   466 		String set = findSet(textField.getText(), textField.getCaretOffset());
       
   467 		// If there is AND
       
   468 		if (set != null && set.contains(AND)) {
       
   469 			canBeInserted = false;
       
   470 		} else if (set != null && !containsFilterRule(set, items)
       
   471 				&& !isSetOpen()
       
   472 				&& !containsFilterRule(textField.getText(), items)) {
       
   473 			canBeInserted = false;
       
   474 		} else if (set != null && !containsFilterRule(set, items)
       
   475 				&& isSetOpen()) {
       
   476 			canBeInserted = false;
       
   477 		} else if (set == null) {
       
   478 			canBeInserted = false;
       
   479 		}
       
   480 
       
   481 		return canBeInserted;
       
   482 	}
       
   483 
       
   484 	/**
       
   485 	 * Check if new set can be started to current pos
       
   486 	 * 
       
   487 	 * @return true if new set can be started
       
   488 	 */
       
   489 	boolean canNewSetBeStarted() {
       
   490 		boolean canBeStarted = false;
       
   491 		String text = textField.getText();
       
   492 		int caretPos = textField.getCaretOffset();
       
   493 		boolean ready = false;
       
   494 		StringBuffer buf = new StringBuffer();
       
   495 
       
   496 		// Text has to contain at least one rule
       
   497 		if (containsFilterRule(text, items) && caretPos > 1) {
       
   498 
       
   499 			// Go backwards and check the previous word
       
   500 			for (int i = caretPos - 1; i > 0; i--) {
       
   501 				char c = text.charAt(i);
       
   502 				// Space, do nothing
       
   503 				if (c == SPACE) {
       
   504 					if (ready) {
       
   505 						// Remove NOT
       
   506 						if (buf.toString().equals(NOT)) {
       
   507 							buf.setLength(0);
       
   508 							ready = false;
       
   509 						} else {
       
   510 							break;
       
   511 						}
       
   512 					}
       
   513 				} else {
       
   514 					buf.insert(0, c);
       
   515 					ready = true;
       
   516 				}
       
   517 			}
       
   518 
       
   519 			String word = buf.toString();
       
   520 			if (word.contains(OR) || word.contains(AND)) {
       
   521 				canBeStarted = true;
       
   522 			}
       
   523 		} else {
       
   524 			canBeStarted = true;
       
   525 		}
       
   526 		return canBeStarted;
       
   527 	}
       
   528 
       
   529 	/**
       
   530 	 * Check if a set can be ended here
       
   531 	 * 
       
   532 	 * @return true if a set can be ended here
       
   533 	 */
       
   534 	boolean canSetBeEnded() {
       
   535 		boolean canBeEnded = false;
       
   536 		String text = textField.getText();
       
   537 		int caretPos = textField.getCaretOffset();
       
   538 		boolean ready = false;
       
   539 		StringBuffer buf = new StringBuffer();
       
   540 
       
   541 		// Text has to contain at least one rule
       
   542 		if (containsFilterRule(text, items) && isSetOpen()) {
       
   543 			// Go backwards and check the previous word
       
   544 			for (int i = caretPos - 1; i > 0; i--) {
       
   545 				char c = text.charAt(i);
       
   546 				// Space, do nothing
       
   547 				if (c == SPACE) {
       
   548 					if (ready) {
       
   549 						break;
       
   550 					}
       
   551 				} else {
       
   552 					buf.insert(0, c);
       
   553 					ready = true;
       
   554 				}
       
   555 			}
       
   556 
       
   557 			String word = buf.toString();
       
   558 			if (!word.contains(OR) && !word.contains(AND)) {
       
   559 				canBeEnded = true;
       
   560 			}
       
   561 		}
       
   562 		return canBeEnded;
       
   563 	}
       
   564 
       
   565 	/**
       
   566 	 * Check if apply can be clicked
       
   567 	 * 
       
   568 	 * @return true if apply can be clicked
       
   569 	 */
       
   570 	boolean canApplyBeClicked() {
       
   571 		boolean canBeClicked = false;
       
   572 		if (!isSetOpen()) {
       
   573 			String text = textField.getText();
       
   574 
       
   575 			// Length bigger than one and contains at least one rule
       
   576 			if (text.length() > 1 && containsFilterRule(text, items)) {
       
   577 				int nrOfRules = 0;
       
   578 				// Check that after every rule there cannot be another rule
       
   579 				text = text.replace(START_BRACKET_STR, SPACE_STR);
       
   580 				text = text.replace(END_BRACKET_STR, SPACE_STR);
       
   581 				String[] words = text.split(SPACE_STR);
       
   582 				boolean lastWasRule = false;
       
   583 				for (int i = 0; i < words.length; i++) {
       
   584 					if (containsFilterRule(words[i], items)) {
       
   585 						nrOfRules++;
       
   586 						canBeClicked = true;
       
   587 						if (lastWasRule) {
       
   588 							canBeClicked = false;
       
   589 							break;
       
   590 						}
       
   591 						lastWasRule = true;
       
   592 					} else {
       
   593 						lastWasRule = false;
       
   594 					}
       
   595 
       
   596 				}
       
   597 				// If more than one rule, there has to be logical operator too
       
   598 				if (canBeClicked && nrOfRules > 1) {
       
   599 					// All good
       
   600 					if (text.contains(AND) || text.contains(OR)) {
       
   601 						// Not good
       
   602 					} else {
       
   603 						canBeClicked = false;
       
   604 					}
       
   605 				}
       
   606 
       
   607 				// Check that logical operators have a rule in both sides
       
   608 				if (canBeClicked) {
       
   609 					text = text.replace(START_BRACKET_STR, EMPTY);
       
   610 					text = text.replace(END_BRACKET_STR, EMPTY);
       
   611 					text = text.replace(NOT, EMPTY);
       
   612 
       
   613 					// Remove double spaces
       
   614 					StringBuffer buf = new StringBuffer(text);
       
   615 					removeDoubleSpaces(buf, 0);
       
   616 					text = buf.toString();
       
   617 
       
   618 					canBeClicked = checkLogicalOperatorValidity(canBeClicked,
       
   619 							text, AND);
       
   620 					if (canBeClicked) {
       
   621 						canBeClicked = checkLogicalOperatorValidity(
       
   622 								canBeClicked, text, OR);
       
   623 					}
       
   624 				}
       
   625 
       
   626 				// Length is 0 or 1
       
   627 			} else if (text.length() <= 1) {
       
   628 				canBeClicked = true;
       
   629 			}
       
   630 		}
       
   631 		return canBeClicked;
       
   632 	}
       
   633 
       
   634 	/**
       
   635 	 * Checks that logical operators have filter rule in both sides
       
   636 	 * 
       
   637 	 * @param canBeClicked
       
   638 	 *            variable indicating if apply can be clicked
       
   639 	 * @param text
       
   640 	 *            text to process
       
   641 	 * @param operator
       
   642 	 *            logical operator as string
       
   643 	 * @return true if logical operators are ok
       
   644 	 */
       
   645 	private boolean checkLogicalOperatorValidity(boolean canBeClicked,
       
   646 			String text, String operator) {
       
   647 		StringBuffer buf = new StringBuffer();
       
   648 		int pos = text.indexOf(operator);
       
   649 		// Loop while next operator is found
       
   650 		while (pos != -1) {
       
   651 			// Check backwards
       
   652 			for (int i = pos - 2; i > -1; i--) {
       
   653 				char c = text.charAt(i);
       
   654 				if (c == SPACE) {
       
   655 					break;
       
   656 				}
       
   657 				buf.insert(0, c);
       
   658 			}
       
   659 			if (!ruleInItems(buf.toString(), items)) {
       
   660 				canBeClicked = false;
       
   661 			}
       
   662 			buf.setLength(0);
       
   663 
       
   664 			// Check forwards
       
   665 			for (int i = pos + operator.length() + 1; canBeClicked
       
   666 					&& i < text.length(); i++) {
       
   667 				char c = text.charAt(i);
       
   668 				if (c == SPACE) {
       
   669 					break;
       
   670 				}
       
   671 				buf.append(c);
       
   672 			}
       
   673 			if (!ruleInItems(buf.toString(), items)) {
       
   674 				canBeClicked = false;
       
   675 			}
       
   676 			buf.setLength(0);
       
   677 
       
   678 			pos = text.indexOf(operator, pos + 1);
       
   679 		}
       
   680 
       
   681 		return canBeClicked;
       
   682 	}
       
   683 
       
   684 	/**
       
   685 	 * Checks if a string contains filter rule from the tree
       
   686 	 * 
       
   687 	 * @param text
       
   688 	 *            text to search from
       
   689 	 * @param items
       
   690 	 *            items to go through
       
   691 	 * @return true if at least one rule can be found from the string
       
   692 	 */
       
   693 	boolean containsFilterRule(String text, TreeItem[] items) {
       
   694 		boolean found = false;
       
   695 		if (text != null && items != null) {
       
   696 			for (int i = 0; i < items.length && !found; i++) {
       
   697 
       
   698 				// Contains children, recurse
       
   699 				if (items[i].getItemCount() > 0) {
       
   700 					found = containsFilterRule(text, items[i].getItems());
       
   701 
       
   702 					// Check item
       
   703 				} else if (text.contains(items[i].getText())) {
       
   704 					found = true;
       
   705 				}
       
   706 			}
       
   707 		}
       
   708 		return found;
       
   709 	}
       
   710 
       
   711 	/**
       
   712 	 * Gets logical operator from a text
       
   713 	 * 
       
   714 	 * @param text
       
   715 	 *            text to get logical operator from
       
   716 	 * @return logical operator of this set. Returns OR if this is a basic rule.
       
   717 	 *         Null if both operators are found.
       
   718 	 */
       
   719 	LogicalOperator getLogicalOperator(String text) {
       
   720 		LogicalOperator op = LogicalOperator.OR;
       
   721 		String mainLevel = getMainLevelOfRule(text);
       
   722 
       
   723 		// Contains AND but no OR
       
   724 		if (mainLevel.contains(AND) && !mainLevel.contains(OR)) {
       
   725 			op = LogicalOperator.AND;
       
   726 			// Contains OR but no AND
       
   727 		} else if (mainLevel.contains(OR) && !mainLevel.contains(AND)) {
       
   728 			op = LogicalOperator.OR;
       
   729 			// Contains either both or not any
       
   730 		} else if ((mainLevel.contains(AND) && mainLevel.contains(OR))
       
   731 				|| (!mainLevel.contains(AND) && !mainLevel.contains(OR))) {
       
   732 			String newText = removeStartAndEndBracket(text);
       
   733 			if (newText != null) {
       
   734 				text = newText;
       
   735 			}
       
   736 			text = text.replace(NOT, EMPTY);
       
   737 			text = text.trim();
       
   738 			if (!isBasicRule(text)) {
       
   739 				// Is not basic rule
       
   740 				op = null;
       
   741 			}
       
   742 		}
       
   743 		return op;
       
   744 	}
       
   745 
       
   746 	/**
       
   747 	 * Gets the main level of the rule
       
   748 	 * 
       
   749 	 * @param text
       
   750 	 *            rule text to process
       
   751 	 * @return main level of the rule
       
   752 	 */
       
   753 	private String getMainLevelOfRule(String text) {
       
   754 		int safeCounter = 0;
       
   755 		String mainLevel = removeTextBetweenBrackets(text);
       
   756 		if (mainLevel != null && mainLevel.indexOf(OR) == -1
       
   757 				&& mainLevel.indexOf(AND) == -1) {
       
   758 			mainLevel = text;
       
   759 		}
       
   760 		while (mainLevel != null && mainLevel.indexOf(OR) == -1
       
   761 				&& mainLevel.indexOf(AND) == -1 && mainLevel.length() > 0
       
   762 				&& safeCounter < MAX_NUMBER_OF_BRACKETS) {
       
   763 			safeCounter++;
       
   764 			mainLevel = removeStartAndEndBracket(mainLevel);
       
   765 			mainLevel = removeTextBetweenBrackets(mainLevel);
       
   766 		}
       
   767 		return mainLevel;
       
   768 	}
       
   769 
       
   770 	/**
       
   771 	 * Removes all text between brackets (including brackets)
       
   772 	 * 
       
   773 	 * @param text
       
   774 	 *            text to be processed
       
   775 	 * @return text without information inside brackets
       
   776 	 */
       
   777 	private String removeTextBetweenBrackets(String text) {
       
   778 		StringBuffer str = new StringBuffer();
       
   779 		if (text != null && text.length() > 0) {
       
   780 			int nrOfStartBrackets = 0;
       
   781 			for (int i = 0; i < text.length(); i++) {
       
   782 				char c = text.charAt(i);
       
   783 				if (c == START_BRACKET) {
       
   784 					nrOfStartBrackets++;
       
   785 				} else if (c == END_BRACKET) {
       
   786 					nrOfStartBrackets--;
       
   787 				} else if (nrOfStartBrackets == 0) {
       
   788 					str.append(c);
       
   789 				}
       
   790 			}
       
   791 		}
       
   792 		return str.toString();
       
   793 	}
       
   794 
       
   795 	/**
       
   796 	 * Removes first start and last end bracket
       
   797 	 * 
       
   798 	 * @param text
       
   799 	 *            text to process
       
   800 	 * @return text without first start and last end bracket. Null if cannot
       
   801 	 *         find both brackets
       
   802 	 */
       
   803 	private String removeStartAndEndBracket(String text) {
       
   804 		String ret = null;
       
   805 		int startPos = text.indexOf(START_BRACKET);
       
   806 		int endPos = text.lastIndexOf(END_BRACKET);
       
   807 		if (startPos != -1 && endPos != -1 && startPos + 1 < endPos) {
       
   808 			ret = text.substring(startPos + 1, endPos);
       
   809 		}
       
   810 		return ret;
       
   811 	}
       
   812 
       
   813 	/**
       
   814 	 * Tells if the String given is a basic rule
       
   815 	 * 
       
   816 	 * @param text
       
   817 	 *            String to search from
       
   818 	 * @return true if the String given is a basic rule
       
   819 	 */
       
   820 	boolean isBasicRule(String text) {
       
   821 		boolean basicRule = false;
       
   822 
       
   823 		// Find rule from the tree items
       
   824 		if (text.length() > 0 && !text.equals(SPACE_STR)) {
       
   825 			if (ruleInItems(text, items)) {
       
   826 				basicRule = true;
       
   827 			}
       
   828 		}
       
   829 		return basicRule;
       
   830 	}
       
   831 
       
   832 	/**
       
   833 	 * Checks if rule is contained in the items
       
   834 	 * 
       
   835 	 * @param text
       
   836 	 *            rule text
       
   837 	 * @param items
       
   838 	 *            items array
       
   839 	 * @return true if rule is found from the items
       
   840 	 */
       
   841 	private boolean ruleInItems(String text, TreeItem[] items) {
       
   842 		boolean found = false;
       
   843 		for (int i = 0; i < items.length; i++) {
       
   844 
       
   845 			// Contains children, recurse
       
   846 			if ((items[i].getItemCount() > 0)) {
       
   847 				found = ruleInItems(text, items[i].getItems());
       
   848 
       
   849 				// Check item
       
   850 			} else if (text.equals(items[i].getText())) {
       
   851 				found = true;
       
   852 				break;
       
   853 			}
       
   854 		}
       
   855 		return found;
       
   856 	}
       
   857 
       
   858 	/**
       
   859 	 * Gets children rule sets from a String
       
   860 	 * 
       
   861 	 * @param text
       
   862 	 *            String to split to rule sets
       
   863 	 * @return array of children
       
   864 	 */
       
   865 	String[] getChildren(String text) {
       
   866 		// Add space before start and after end brackets and to both sides of
       
   867 		// each logical operator
       
   868 		text = text.replace(START_BRACKET_STR, SPACE_STR + START_BRACKET_STR);
       
   869 		text = text.replace(END_BRACKET_STR, END_BRACKET_STR + SPACE_STR);
       
   870 		text = text.replace(AND, SPACE_STR + AND + SPACE_STR);
       
   871 		text = text.replace(OR, SPACE_STR + OR + SPACE_STR);
       
   872 		text = text.replace(NOT, SPACE_STR + NOT + SPACE_STR);
       
   873 
       
   874 		String[] strings;
       
   875 		int nrOfStartBrackets = 0;
       
   876 		ArrayList<String> children = new ArrayList<String>();
       
   877 		StringBuffer buf = new StringBuffer();
       
   878 
       
   879 		// Go through every character
       
   880 		for (int i = 0; i < text.length(); i++) {
       
   881 			char c = text.charAt(i);
       
   882 			if (c == START_BRACKET) {
       
   883 				nrOfStartBrackets++;
       
   884 			} else if (c == END_BRACKET) {
       
   885 				nrOfStartBrackets--;
       
   886 
       
   887 				// When brackets are processed, create a child from the
       
   888 				// buffer
       
   889 				if (nrOfStartBrackets == 0) {
       
   890 					addBufferToChildList(children, buf);
       
   891 				}
       
   892 			} else if (nrOfStartBrackets > 0) {
       
   893 				buf.append(c);
       
   894 
       
   895 				// Nr of start brackets is zero
       
   896 			} else {
       
   897 				// Character is space
       
   898 				if (c == SPACE) {
       
   899 					if (buf.length() > 0) {
       
   900 						addBufferToChildList(children, buf);
       
   901 					}
       
   902 				} else {
       
   903 					buf.append(c);
       
   904 					// If processing the last character, add child
       
   905 					if (i == text.length() - 1) {
       
   906 						addBufferToChildList(children, buf);
       
   907 					}
       
   908 				}
       
   909 			}
       
   910 		}
       
   911 
       
   912 		// Insert the strings to a array
       
   913 		strings = new String[children.size()];
       
   914 		for (int j = 0; j < children.size(); j++) {
       
   915 			strings[j] = children.get(j);
       
   916 		}
       
   917 
       
   918 		return strings;
       
   919 	}
       
   920 
       
   921 	/**
       
   922 	 * Adds buffer contents to child list and empties the buffer
       
   923 	 * 
       
   924 	 * @param children
       
   925 	 *            children list
       
   926 	 * @param buf
       
   927 	 *            buffer
       
   928 	 */
       
   929 	private void addBufferToChildList(List<String> children, StringBuffer buf) {
       
   930 		// AND and OR cannot be children
       
   931 		if (!buf.toString().trim().equals(AND)
       
   932 				&& !buf.toString().trim().equals(OR)) {
       
   933 			// Add child to the list
       
   934 			children.add(buf.toString());
       
   935 		}
       
   936 		buf.setLength(0);
       
   937 	}
       
   938 
       
   939 	/**
       
   940 	 * Checks written rules
       
   941 	 * 
       
   942 	 * @param text
       
   943 	 *            text to check
       
   944 	 * @return true if text field contains only valid rules and operations
       
   945 	 */
       
   946 	boolean checkWrittenRules(String text) {
       
   947 		// Replace brackets and logical operations with spaces
       
   948 		text = text.replace(START_BRACKET_STR, SPACE_STR);
       
   949 		text = text.replace(END_BRACKET_STR, SPACE_STR);
       
   950 		text = text.replace(AND, SPACE_STR);
       
   951 		text = text.replace(OR, SPACE_STR);
       
   952 		text = text.replace(NOT, SPACE_STR);
       
   953 
       
   954 		// Add space to start and end and then remove filter rules
       
   955 		StringBuffer buf = new StringBuffer(text);
       
   956 		buf.insert(0, SPACE);
       
   957 		buf.append(SPACE);
       
   958 		text = removeFilterRules(buf.toString(), items);
       
   959 
       
   960 		// Remove spaces
       
   961 		text = text.replace(SPACE_STR, EMPTY);
       
   962 
       
   963 		// Text should now be empty
       
   964 		boolean empty = text.length() == 0;
       
   965 		return empty;
       
   966 	}
       
   967 
       
   968 	/**
       
   969 	 * Removes filter rules from the text
       
   970 	 * 
       
   971 	 * @param text
       
   972 	 *            the text
       
   973 	 * @param items
       
   974 	 *            tree items
       
   975 	 * @return original text without filter rules
       
   976 	 */
       
   977 	private String removeFilterRules(String text, TreeItem[] items) {
       
   978 		for (int i = 0; i < items.length; i++) {
       
   979 
       
   980 			// Has children, recurse
       
   981 			if (items[i].getItemCount() > 0) {
       
   982 				text = removeFilterRules(text, items[i].getItems());
       
   983 
       
   984 				// Remove the rule from the text.
       
   985 			} else {
       
   986 				text = text.replace(items[i].getText() + SPACE_STR, EMPTY);
       
   987 			}
       
   988 		}
       
   989 		return text;
       
   990 	}
       
   991 
       
   992 	/**
       
   993 	 * Gets previous word from the text field
       
   994 	 * 
       
   995 	 * @param text
       
   996 	 *            text to search from
       
   997 	 * @param pos
       
   998 	 *            position where to read
       
   999 	 * @return previous word
       
  1000 	 */
       
  1001 	String getPreviousWord(String text, int pos) {
       
  1002 		StringBuffer buf = new StringBuffer();
       
  1003 		for (int i = pos; i >= 0; i--) {
       
  1004 			char c = text.charAt(i);
       
  1005 
       
  1006 			// Space, break
       
  1007 			if ((c == SPACE) && (i < pos - 1)) {
       
  1008 				break;
       
  1009 			}
       
  1010 			buf.insert(0, c);
       
  1011 		}
       
  1012 		return buf.toString().trim();
       
  1013 	}
       
  1014 
       
  1015 	/*
       
  1016 	 * (non-Javadoc)
       
  1017 	 * 
       
  1018 	 * @see
       
  1019 	 * org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events
       
  1020 	 * .FocusEvent)
       
  1021 	 */
       
  1022 	public void focusGained(FocusEvent e) {
       
  1023 		colorCaretAndRules();
       
  1024 	}
       
  1025 
       
  1026 	/*
       
  1027 	 * (non-Javadoc)
       
  1028 	 * 
       
  1029 	 * @see
       
  1030 	 * org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events
       
  1031 	 * .FocusEvent)
       
  1032 	 */
       
  1033 	public void focusLost(FocusEvent e) {
       
  1034 		colorCaretAndRules();
       
  1035 	}
       
  1036 
       
  1037 	/*
       
  1038 	 * (non-Javadoc)
       
  1039 	 * 
       
  1040 	 * @see
       
  1041 	 * org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events
       
  1042 	 * .KeyEvent)
       
  1043 	 */
       
  1044 	public void keyReleased(KeyEvent e) {
       
  1045 	}
       
  1046 
       
  1047 	/*
       
  1048 	 * (non-Javadoc)
       
  1049 	 * 
       
  1050 	 * @see
       
  1051 	 * org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt
       
  1052 	 * .events.MouseEvent)
       
  1053 	 */
       
  1054 	public void mouseDoubleClick(MouseEvent e) {
       
  1055 	}
       
  1056 
       
  1057 	/*
       
  1058 	 * (non-Javadoc)
       
  1059 	 * 
       
  1060 	 * @see
       
  1061 	 * org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events
       
  1062 	 * .MouseEvent)
       
  1063 	 */
       
  1064 	public void mouseDown(MouseEvent e) {
       
  1065 	}
       
  1066 }