src/main/java/org/vaadin/console/Console.java
author indvdum
Fri, 20 May 2011 17:52:09 +0400
changeset 9 dbc3bbf10535
parent 7 a778386e297f
child 10 1f81f87f3283
permissions -rw-r--r--
+ new option - setSmartScrollToEnd: scrollToEnd work only if last scroll state is was "end"
indvdum@0
     1
package org.vaadin.console;
indvdum@0
     2
indvdum@0
     3
import java.io.ByteArrayOutputStream;
indvdum@0
     4
import java.io.IOException;
indvdum@0
     5
import java.io.OutputStream;
indvdum@0
     6
import java.io.PrintStream;
indvdum@0
     7
import java.io.Serializable;
indvdum@0
     8
import java.util.ArrayList;
indvdum@0
     9
import java.util.Collections;
indvdum@0
    10
import java.util.HashMap;
indvdum@0
    11
import java.util.HashSet;
indvdum@0
    12
import java.util.List;
indvdum@0
    13
import java.util.Map;
indvdum@0
    14
import java.util.Set;
indvdum@0
    15
indvdum@0
    16
import org.vaadin.rpc.ServerSideHandler;
indvdum@0
    17
import org.vaadin.rpc.ServerSideProxy;
indvdum@0
    18
import org.vaadin.rpc.client.Method;
indvdum@0
    19
indvdum@0
    20
import com.vaadin.terminal.PaintException;
indvdum@0
    21
import com.vaadin.terminal.PaintTarget;
indvdum@0
    22
import com.vaadin.ui.AbstractComponent;
indvdum@0
    23
import com.vaadin.ui.Component;
indvdum@0
    24
indvdum@0
    25
/**
indvdum@0
    26
 * Server side component for the VTextConsole widget.
indvdum@0
    27
 *
indvdum@0
    28
 * @author Sami Ekblad / Vaadin
indvdum@0
    29
 *
indvdum@0
    30
 */
indvdum@0
    31
@com.vaadin.ui.ClientWidget(org.vaadin.console.client.ui.VTextConsole.class)
indvdum@0
    32
public class Console extends AbstractComponent implements Component.Focusable {
indvdum@0
    33
indvdum@0
    34
    private static final long serialVersionUID = 590258219352859644L;
indvdum@0
    35
    private Handler handler;
indvdum@0
    36
    private final HashMap<String, Command> commands = new HashMap<String, Command>();
indvdum@0
    37
    private final Config config = new Config();
indvdum@0
    38
indvdum@0
    39
    private static final String DEFAULT_PS = "}> ";
indvdum@0
    40
    private static final String DEFAULT_GREETING = "Console ready.";
indvdum@0
    41
    private static final int DEFAULT_BUFFER = 0;
indvdum@0
    42
    private static final int DEFAULT_COLS = -1;
indvdum@0
    43
    private static final int DEFAULT_ROWS = -1;
indvdum@0
    44
    private static final boolean DEFAULT_WRAP = true;
indvdum@9
    45
    private static final boolean DEFAULT_PRINT_PROMPT_ON_INPUT = true;
indvdum@9
    46
    private static final boolean DEFAULT_SMART_SCROLL_TO_END = false;
indvdum@0
    47
    private static final int MAX_COLS = 500;
indvdum@0
    48
    private static final int MAX_ROWS = 200;
indvdum@0
    49
indvdum@0
    50
    public boolean isWrap() {
indvdum@0
    51
        return config.wrap;
indvdum@0
    52
    }
indvdum@0
    53
indvdum@0
    54
    public void setWrap(final boolean wrap) {
indvdum@0
    55
        config.wrap = wrap;
indvdum@0
    56
        client.call("setWrap", wrap);
indvdum@0
    57
    }
indvdum@9
    58
indvdum@9
    59
	public boolean isPrintPromptOnInput() {
indvdum@9
    60
		return config.isPrintPromptOnInput;
indvdum@9
    61
	}
indvdum@9
    62
indvdum@9
    63
	public void setPrintPromptOnInput(final boolean isPrintPromptOnInput) {
indvdum@9
    64
		config.isPrintPromptOnInput = isPrintPromptOnInput;
indvdum@9
    65
		client.call("setPrintPromptOnInput", isPrintPromptOnInput);
indvdum@9
    66
	}
indvdum@9
    67
indvdum@9
    68
	public boolean isSmartScrollToEnd() {
indvdum@9
    69
		return config.isSmartScrollToEnd;
indvdum@9
    70
	}
indvdum@9
    71
indvdum@9
    72
	public void setSmartScrollToEnd(final boolean isSmartScrollToEnd) {
indvdum@9
    73
		config.isSmartScrollToEnd = isSmartScrollToEnd;
indvdum@9
    74
		client.call("setSmartScrollToEnd", isSmartScrollToEnd);
indvdum@9
    75
	}
indvdum@0
    76
indvdum@0
    77
    private final ServerSideProxy client = new ServerSideProxy(
indvdum@0
    78
            new ClientCallback());
indvdum@0
    79
indvdum@0
    80
    /**
indvdum@0
    81
     * Inner class to handle client calls.
indvdum@0
    82
     *
indvdum@0
    83
     */
indvdum@0
    84
    public class ClientCallback implements ServerSideHandler {
indvdum@0
    85
indvdum@0
    86
        private static final long serialVersionUID = 3992611573500588703L;
indvdum@0
    87
indvdum@0
    88
        public void requestRepaint() {
indvdum@0
    89
            Console.this.requestRepaint();
indvdum@0
    90
        }
indvdum@0
    91
indvdum@0
    92
        public Object[] initRequestFromClient() {
indvdum@9
    93
            return new Object[] { 
indvdum@9
    94
            		config.cols, 
indvdum@9
    95
            		config.rows,
indvdum@9
    96
                    config.maxBufferSize, 
indvdum@9
    97
                    config.wrap, 
indvdum@9
    98
                    config.isPrintPromptOnInput, 
indvdum@9
    99
                    config.isSmartScrollToEnd, 
indvdum@9
   100
                    config.greeting, 
indvdum@9
   101
                    config.ps 
indvdum@9
   102
                    };
indvdum@0
   103
        }
indvdum@0
   104
indvdum@0
   105
        public void callFromClient(String method, Object[] params) {
indvdum@0
   106
            // TODO Auto-generated method stub
indvdum@0
   107
indvdum@0
   108
        }
indvdum@0
   109
indvdum@0
   110
    }
indvdum@0
   111
indvdum@0
   112
    /**
indvdum@0
   113
     * The tab order number of this field.
indvdum@0
   114
     */
indvdum@0
   115
    private int tabIndex = 0;
indvdum@0
   116
    @SuppressWarnings("unused")
indvdum@0
   117
    private Integer fontw;
indvdum@0
   118
    @SuppressWarnings("unused")
indvdum@0
   119
    private Integer fonth;
indvdum@0
   120
    private PrintStream printStream;
indvdum@0
   121
    private String lastSuggestInput;
indvdum@0
   122
    private List<CommandProvider> commandProviders;
indvdum@0
   123
indvdum@0
   124
    /**
indvdum@0
   125
     * An inner class for holding the configuration data.
indvdum@0
   126
     */
indvdum@0
   127
    public static class Config implements Serializable {
indvdum@0
   128
indvdum@0
   129
        private static final long serialVersionUID = -812601232248504108L;
indvdum@0
   130
indvdum@0
   131
        int maxBufferSize = DEFAULT_BUFFER;
indvdum@0
   132
        int cols = DEFAULT_COLS;
indvdum@0
   133
        int rows = DEFAULT_ROWS;
indvdum@0
   134
        boolean wrap = DEFAULT_WRAP;
indvdum@4
   135
        boolean isPrintPromptOnInput = DEFAULT_PRINT_PROMPT_ON_INPUT;
indvdum@9
   136
        boolean isSmartScrollToEnd = DEFAULT_SMART_SCROLL_TO_END;
indvdum@0
   137
        String ps = DEFAULT_PS;
indvdum@0
   138
        String greeting = DEFAULT_GREETING;
indvdum@0
   139
indvdum@0
   140
    }
indvdum@0
   141
indvdum@0
   142
    /**
indvdum@0
   143
     * Console Handler interface.
indvdum@0
   144
     *
indvdum@0
   145
     * Handler provides a hook to handle various console related events and
indvdum@0
   146
     * override the default processing.
indvdum@0
   147
     *
indvdum@0
   148
     */
indvdum@0
   149
    public interface Handler extends Serializable {
indvdum@0
   150
indvdum@0
   151
        /**
indvdum@0
   152
         * Called when user uses TAB to complete the command entered into the
indvdum@0
   153
         * Console input.
indvdum@0
   154
         *
indvdum@0
   155
         * @param console
indvdum@0
   156
         * @param lastInput
indvdum@0
   157
         * @return
indvdum@0
   158
         */
indvdum@0
   159
        Set<String> getSuggestions(Console console, String lastInput);
indvdum@0
   160
indvdum@0
   161
        /**
indvdum@0
   162
         * Called when user has entered input to the Console and presses enter
indvdum@0
   163
         * to execute it.
indvdum@0
   164
         *
indvdum@0
   165
         * @param console
indvdum@0
   166
         * @param lastInput
indvdum@0
   167
         */
indvdum@0
   168
        void inputReceived(Console console, String lastInput);
indvdum@0
   169
indvdum@0
   170
        /**
indvdum@0
   171
         * Handle an exception during a Command execution.
indvdum@0
   172
         *
indvdum@0
   173
         * @param console
indvdum@0
   174
         * @param e
indvdum@0
   175
         * @param cmd
indvdum@0
   176
         * @param argv
indvdum@0
   177
         */
indvdum@0
   178
        void handleException(Console console, Exception e, Command cmd,
indvdum@0
   179
                String[] argv);
indvdum@0
   180
indvdum@0
   181
        /**
indvdum@0
   182
         * Handle situation where a command could not be found.
indvdum@0
   183
         *
indvdum@0
   184
         * @param console
indvdum@0
   185
         * @param argv
indvdum@0
   186
         */
indvdum@0
   187
        void commandNotFound(Console console, String[] argv);
indvdum@0
   188
indvdum@0
   189
    }
indvdum@0
   190
indvdum@0
   191
    /**
indvdum@0
   192
     * Commands that can be executed against the Component instance. They
indvdum@0
   193
     * provide convenient string to method mapping. Basically, a Command is a
indvdum@0
   194
     * method that that can be executed in Component. It can have parameters or
indvdum@0
   195
     * not.
indvdum@0
   196
     *
indvdum@0
   197
     */
indvdum@0
   198
    public interface Command extends Serializable {
indvdum@0
   199
indvdum@0
   200
        /**
indvdum@0
   201
         * Execute a Command with arguments.
indvdum@0
   202
         *
indvdum@0
   203
         * @param console
indvdum@0
   204
         * @param argv
indvdum@0
   205
         * @return
indvdum@0
   206
         * @throws Exception
indvdum@0
   207
         */
indvdum@0
   208
        public Object execute(Console console, String[] argv) throws Exception;
indvdum@0
   209
indvdum@0
   210
        /**
indvdum@0
   211
         * Get usage information about this command.
indvdum@0
   212
         *
indvdum@0
   213
         * @param console
indvdum@0
   214
         * @param argv
indvdum@0
   215
         * @return
indvdum@0
   216
         */
indvdum@0
   217
        public String getUsage(Console console, String[] argv);
indvdum@0
   218
    }
indvdum@0
   219
indvdum@0
   220
    /**
indvdum@0
   221
     * Interface for providing Commands to the console. One can register a
indvdum@0
   222
     * command providers to console instead of individual commands to provide a
indvdum@0
   223
     * lot of commands.
indvdum@0
   224
     *
indvdum@0
   225
     */
indvdum@0
   226
    public interface CommandProvider extends Serializable {
indvdum@0
   227
indvdum@0
   228
        /**
indvdum@0
   229
         * List all available command from this provider.
indvdum@0
   230
         *
indvdum@0
   231
         * @param console
indvdum@0
   232
         * @return
indvdum@0
   233
         */
indvdum@0
   234
        Set<String> getAvailableCommands(Console console);
indvdum@0
   235
indvdum@0
   236
        /**
indvdum@0
   237
         * Get Command instance based on command name.
indvdum@0
   238
         *
indvdum@0
   239
         * @param console
indvdum@0
   240
         * @param commandName
indvdum@0
   241
         * @return
indvdum@0
   242
         */
indvdum@0
   243
        Command getCommand(Console console, String commandName);
indvdum@0
   244
indvdum@0
   245
    }
indvdum@0
   246
indvdum@0
   247
    public void addCommandProvider(final CommandProvider commandProvider) {
indvdum@0
   248
        if (commandProviders == null) {
indvdum@0
   249
            commandProviders = new ArrayList<CommandProvider>();
indvdum@0
   250
        }
indvdum@0
   251
        commandProviders.add(commandProvider);
indvdum@0
   252
    }
indvdum@0
   253
indvdum@0
   254
    public void removeCommandProvider(final CommandProvider commandProvider) {
indvdum@0
   255
        if (commandProviders == null) {
indvdum@0
   256
            return;
indvdum@0
   257
        }
indvdum@0
   258
        commandProviders.remove(commandProvider);
indvdum@0
   259
    }
indvdum@0
   260
indvdum@0
   261
    public void removeAllCommandProviders() {
indvdum@0
   262
        if (commandProviders == null) {
indvdum@0
   263
            return;
indvdum@0
   264
        }
indvdum@0
   265
        commandProviders.clear();
indvdum@0
   266
    }
indvdum@0
   267
indvdum@0
   268
    public Console(final Console.Handler handler) {
indvdum@0
   269
        this();
indvdum@0
   270
        setHandler(handler);
indvdum@0
   271
    }
indvdum@0
   272
indvdum@0
   273
    public Console() {
indvdum@0
   274
        setImmediate(true);
indvdum@0
   275
        setHandler(new DefaultConsoleHandler());
indvdum@0
   276
        registerCallbacks();
indvdum@0
   277
    }
indvdum@0
   278
indvdum@0
   279
    private void registerCallbacks() {
indvdum@0
   280
        client.register("suggest", new Method() {
indvdum@0
   281
indvdum@0
   282
            public void invoke(String methodName, Object[] params) {
indvdum@0
   283
                handleSuggest((String) params[0]);
indvdum@0
   284
            }
indvdum@0
   285
        });
indvdum@0
   286
        client.register("input", new Method() {
indvdum@0
   287
indvdum@0
   288
            public void invoke(String methodName, Object[] params) {
indvdum@0
   289
                handleInput((String) params[0]);
indvdum@0
   290
            }
indvdum@0
   291
        });
indvdum@0
   292
indvdum@0
   293
    }
indvdum@0
   294
indvdum@0
   295
    @Override
indvdum@0
   296
    public void paintContent(final PaintTarget target) throws PaintException {
indvdum@0
   297
        super.paintContent(target);
indvdum@0
   298
        client.paintContent(target);
indvdum@0
   299
    }
indvdum@0
   300
indvdum@0
   301
    @Override
indvdum@0
   302
    public void changeVariables(final Object source,
indvdum@0
   303
            final Map<String, Object> variables) {
indvdum@0
   304
        super.changeVariables(source, variables);
indvdum@0
   305
        client.changeVariables(source, variables);
indvdum@0
   306
        if (variables.containsKey("width")) {
indvdum@0
   307
            setWidth((String) variables.get("width"));
indvdum@0
   308
        }
indvdum@0
   309
        if (variables.containsKey("height")) {
indvdum@0
   310
            setHeight((String) variables.get("height"));
indvdum@0
   311
        }
indvdum@0
   312
        if (variables.containsKey("fontw")) {
indvdum@0
   313
            fontw = (Integer) variables.get("fontw");
indvdum@0
   314
        }
indvdum@0
   315
        if (variables.containsKey("fonth")) {
indvdum@0
   316
            fonth = (Integer) variables.get("fonth");
indvdum@0
   317
        }
indvdum@0
   318
        if (variables.containsKey("cols")) {
indvdum@0
   319
            config.cols = (Integer) variables.get("cols");
indvdum@0
   320
        }
indvdum@0
   321
        if (variables.containsKey("rows")) {
indvdum@0
   322
            config.rows = (Integer) variables.get("rows");
indvdum@0
   323
        }
indvdum@0
   324
    }
indvdum@0
   325
indvdum@0
   326
    /**
indvdum@0
   327
     * Overridden to filter client-side calculation/changes and avoid loops.
indvdum@0
   328
     *
indvdum@0
   329
     */
indvdum@0
   330
    @Override
indvdum@0
   331
    public void setWidth(float width, int unit) {
indvdum@0
   332
        if (width != getWidth() || unit != getWidthUnits()) {
indvdum@0
   333
            super.setWidth(width, unit);
indvdum@0
   334
        }
indvdum@0
   335
    }
indvdum@0
   336
indvdum@0
   337
    /**
indvdum@0
   338
     * Overridden to filter client-side calculation/changes and avoid loops.
indvdum@0
   339
     *
indvdum@0
   340
     */
indvdum@0
   341
    @Override
indvdum@0
   342
    public void setHeight(float height, int unit) {
indvdum@0
   343
        if (height != getHeight() || unit != getHeightUnits()) {
indvdum@0
   344
            super.setHeight(height, unit);
indvdum@0
   345
        }
indvdum@0
   346
    }
indvdum@0
   347
indvdum@0
   348
    protected void handleSuggest(final String input) {
indvdum@0
   349
indvdum@0
   350
        final boolean cancelIfNotASingleMatch = (input != null && !input
indvdum@0
   351
                .equals(lastSuggestInput));
indvdum@0
   352
        lastSuggestInput = input;
indvdum@0
   353
indvdum@0
   354
        final Set<String> matches = handler.getSuggestions(this, input);
indvdum@0
   355
indvdum@0
   356
        if (matches == null || matches.size() == 0) {
indvdum@0
   357
            bell();
indvdum@0
   358
            return;
indvdum@0
   359
        }
indvdum@0
   360
indvdum@0
   361
        // Output the original
indvdum@0
   362
        final String prefix = parseCommandPrefix(input);
indvdum@0
   363
        String output = input.substring(0, input.lastIndexOf(prefix));
indvdum@0
   364
        if (matches.size() == 1) {
indvdum@0
   365
            // Output the only match
indvdum@0
   366
            output += matches.iterator().next() + " "; // append the single
indvdum@0
   367
            // match
indvdum@0
   368
        } else {
indvdum@0
   369
indvdum@0
   370
            // We output until the common prefix
indvdum@0
   371
            StringBuilder commonPrefix = new StringBuilder(prefix);
indvdum@0
   372
            final int maxLen = matches.iterator().next().length();
indvdum@0
   373
            for (int i = prefix.length(); i < maxLen; i++) {
indvdum@0
   374
                char c = 0;
indvdum@0
   375
                boolean charMatch = true;
indvdum@0
   376
                for (final String m : matches) {
indvdum@0
   377
                    if (c == 0) {
indvdum@0
   378
                        c = m.charAt(i);
indvdum@0
   379
                    } else if (i < m.length()) {
indvdum@0
   380
                        charMatch &= m.charAt(i) == c;
indvdum@0
   381
                        if (!charMatch) {
indvdum@0
   382
                            break;
indvdum@0
   383
                        }
indvdum@0
   384
                    } else {
indvdum@0
   385
                        charMatch = false;
indvdum@0
   386
                        break;
indvdum@0
   387
                    }
indvdum@0
   388
                }
indvdum@0
   389
                if (charMatch) {
indvdum@0
   390
                    commonPrefix.append(c);
indvdum@0
   391
                }
indvdum@0
   392
            }
indvdum@0
   393
            output += commonPrefix.toString();
indvdum@0
   394
            if (prefix.equals(commonPrefix.toString())
indvdum@0
   395
                    && !cancelIfNotASingleMatch) {
indvdum@0
   396
                final StringBuffer suggestions = new StringBuffer("\n");
indvdum@0
   397
                for (final String m : matches) {
indvdum@0
   398
                    suggestions.append(" " + m);
indvdum@0
   399
                }
indvdum@0
   400
                print(suggestions.toString());
indvdum@0
   401
            } else {
indvdum@0
   402
                bell();
indvdum@0
   403
                lastSuggestInput = output; // next suggest will not beep
indvdum@0
   404
            }
indvdum@0
   405
        }
indvdum@0
   406
        prompt(output);
indvdum@0
   407
        focus();
indvdum@0
   408
indvdum@0
   409
    }
indvdum@0
   410
indvdum@0
   411
    public void bell() {
indvdum@0
   412
        client.call("bell");
indvdum@0
   413
    }
indvdum@0
   414
indvdum@0
   415
    protected void handleInput(final String input) {
indvdum@0
   416
indvdum@0
   417
        // Ask registered handler
indvdum@0
   418
        handler.inputReceived(this, input);
indvdum@0
   419
indvdum@0
   420
    }
indvdum@0
   421
indvdum@0
   422
    protected void parseAndExecuteCommand(final String input) {
indvdum@0
   423
        final String[] argv = parseInput(input);
indvdum@0
   424
        if (argv != null && argv.length > 0) {
indvdum@0
   425
            final Command c = getCommand(argv[0]);
indvdum@0
   426
            if (c != null) {
indvdum@0
   427
                final String result = executeCommand(c, argv);
indvdum@0
   428
                if (result != null) {
indvdum@0
   429
                    print(result);
indvdum@0
   430
                }
indvdum@0
   431
            } else {
indvdum@0
   432
                handler.commandNotFound(this, argv);
indvdum@0
   433
            }
indvdum@0
   434
        }
indvdum@0
   435
    }
indvdum@0
   436
indvdum@0
   437
    protected String executeCommand(final Command cmd, final String[] argv) {
indvdum@0
   438
        try {
indvdum@0
   439
            final Object r = cmd.execute(this, argv);
indvdum@0
   440
            return r != null ? "" + r : null;
indvdum@0
   441
        } catch (final Exception e) {
indvdum@0
   442
            handler.handleException(this, e, cmd, argv);
indvdum@0
   443
        }
indvdum@0
   444
        return null;
indvdum@0
   445
    }
indvdum@0
   446
indvdum@0
   447
    protected String parseCommandPrefix(final String input) {
indvdum@0
   448
        if (input == null) {
indvdum@0
   449
            return null;
indvdum@0
   450
        }
indvdum@0
   451
        if (!input.endsWith(" ")) {
indvdum@0
   452
            final String[] argv = parseInput(input);
indvdum@0
   453
            if (argv != null && argv.length > 0) {
indvdum@0
   454
                return argv[argv.length - 1];
indvdum@0
   455
            }
indvdum@0
   456
        }
indvdum@0
   457
        return "";
indvdum@0
   458
    }
indvdum@0
   459
indvdum@0
   460
    protected static String[] parseInput(final String input) {
indvdum@0
   461
        if (input != null && !"".equals(input.trim())) {
indvdum@0
   462
            final String[] temp = input.split(" ");
indvdum@0
   463
            if (temp != null && temp.length > 0) {
indvdum@0
   464
                final List<String> parsed = new ArrayList<String>(temp.length);
indvdum@0
   465
                String current = null;
indvdum@0
   466
                for (final String element : temp) {
indvdum@0
   467
                    final int quotCount = count(element, '\"');
indvdum@0
   468
                    if (quotCount > 0 && quotCount % 2 != 0) {
indvdum@0
   469
                        // uneven number of quotes star or end combining params
indvdum@0
   470
                        if (current != null) {
indvdum@0
   471
                            parsed.add(current + " "
indvdum@0
   472
                                    + element.replaceAll("\"", "")); // end
indvdum@0
   473
                            current = null;
indvdum@0
   474
                        } else {
indvdum@0
   475
                            current = element.replaceAll("\"", ""); // start
indvdum@0
   476
                        }
indvdum@0
   477
                    } else if (current != null) {
indvdum@0
   478
                        current += " " + element.replaceAll("\"", "");
indvdum@0
   479
                    } else {
indvdum@0
   480
                        parsed.add(element.replaceAll("\"", ""));
indvdum@0
   481
                    }
indvdum@0
   482
                }
indvdum@0
   483
indvdum@0
   484
                // TODO: actually this is not quite right: We have an open quote
indvdum@0
   485
                // somewhere. Exception maybe?
indvdum@0
   486
                if (current != null) {
indvdum@0
   487
                    parsed.add(current.replaceAll("\"", ""));
indvdum@0
   488
                }
indvdum@0
   489
                return parsed.toArray(new String[] {});
indvdum@0
   490
            }
indvdum@0
   491
        }
indvdum@0
   492
        return new String[] {};
indvdum@0
   493
    }
indvdum@0
   494
indvdum@0
   495
    protected static int count(final String sourceString, final char lookFor) {
indvdum@0
   496
        if (sourceString == null) {
indvdum@0
   497
            return -1;
indvdum@0
   498
        }
indvdum@0
   499
        int count = 0;
indvdum@0
   500
        for (int i = 0; i < sourceString.length(); i++) {
indvdum@0
   501
            final char c = sourceString.charAt(i);
indvdum@0
   502
            if (c == lookFor) {
indvdum@0
   503
                count++;
indvdum@0
   504
            }
indvdum@0
   505
        }
indvdum@0
   506
        return count;
indvdum@0
   507
    }
indvdum@0
   508
indvdum@0
   509
    public void print(final String output) {
indvdum@0
   510
        client.call("print", output);
indvdum@0
   511
    }
indvdum@0
   512
indvdum@7
   513
	/**
indvdum@7
   514
	 * @param output
indvdum@7
   515
	 * @param className CSS class name for string
indvdum@7
   516
	 */
indvdum@7
   517
	public void print(final String output, final String className) {
indvdum@7
   518
		client.call("print", output, className);
indvdum@7
   519
	}
indvdum@7
   520
indvdum@0
   521
    public String getGreeting() {
indvdum@0
   522
        return config.greeting;
indvdum@0
   523
    }
indvdum@0
   524
indvdum@0
   525
    public String getPs() {
indvdum@0
   526
        return config.ps;
indvdum@0
   527
    }
indvdum@0
   528
indvdum@0
   529
    public int getMaxBufferSize() {
indvdum@0
   530
        return config.maxBufferSize;
indvdum@0
   531
    }
indvdum@0
   532
indvdum@0
   533
    public int getRows() {
indvdum@0
   534
        return config.rows;
indvdum@0
   535
    }
indvdum@0
   536
indvdum@0
   537
    public void setGreeting(final String greeting) {
indvdum@0
   538
        config.greeting = greeting;
indvdum@0
   539
        client.call("setGreeting", greeting);
indvdum@0
   540
    }
indvdum@0
   541
indvdum@0
   542
    public void setPs(final String ps) {
indvdum@0
   543
        config.ps = ps == null ? DEFAULT_PS : ps;
indvdum@0
   544
        client.call("setPs", config.ps);
indvdum@0
   545
    }
indvdum@0
   546
indvdum@0
   547
    public void setMaxBufferSize(final int lines) {
indvdum@0
   548
        config.maxBufferSize = lines > 0 ? lines : 0;
indvdum@0
   549
        client.call("setMaxBufferSize", config.maxBufferSize);
indvdum@0
   550
    }
indvdum@0
   551
indvdum@0
   552
    public void setRows(final int rows) {
indvdum@0
   553
        config.rows = rows;
indvdum@0
   554
        if (config.rows < 1) {
indvdum@0
   555
            config.rows = 1;
indvdum@0
   556
        }
indvdum@0
   557
        if (config.rows > MAX_ROWS) {
indvdum@0
   558
            config.rows = MAX_ROWS;
indvdum@0
   559
        }
indvdum@0
   560
        client.call("setRows", rows);
indvdum@0
   561
    }
indvdum@0
   562
indvdum@0
   563
    public int getCols() {
indvdum@0
   564
        return config.cols;
indvdum@0
   565
    }
indvdum@0
   566
indvdum@0
   567
    public void setCols(final int cols) {
indvdum@0
   568
        config.cols = cols;
indvdum@0
   569
        if (config.cols < 1) {
indvdum@0
   570
            config.cols = 1;
indvdum@0
   571
        }
indvdum@0
   572
        if (config.cols > MAX_COLS) {
indvdum@0
   573
            config.cols = MAX_COLS;
indvdum@0
   574
        }
indvdum@0
   575
        client.call("setCols", config.cols);
indvdum@0
   576
    }
indvdum@0
   577
indvdum@0
   578
    public void prompt() {
indvdum@0
   579
        client.call("prompt");
indvdum@0
   580
    }
indvdum@0
   581
indvdum@0
   582
    public void prompt(final String initialInput) {
indvdum@0
   583
        client.call("prompt", initialInput);
indvdum@0
   584
    }
indvdum@0
   585
indvdum@0
   586
    public void println(final String string) {
indvdum@0
   587
        client.call("println", string);
indvdum@0
   588
    }
indvdum@7
   589
indvdum@7
   590
	/**
indvdum@7
   591
	 * @param string
indvdum@7
   592
	 * @param className CSS class name for string
indvdum@7
   593
	 */
indvdum@7
   594
	public void println(final String string, final String className) {
indvdum@7
   595
		client.call("println", string, className);
indvdum@7
   596
	}
indvdum@3
   597
    
indvdum@3
   598
    public void append(final String string) {
indvdum@3
   599
    	client.call("append", string);
indvdum@3
   600
    }
indvdum@0
   601
indvdum@7
   602
	/**
indvdum@7
   603
	 * @param string
indvdum@7
   604
	 * @param className CSS class name for string
indvdum@7
   605
	 */
indvdum@7
   606
	public void append(final String string, final String className) {
indvdum@7
   607
		client.call("append", string, className);
indvdum@7
   608
	}
indvdum@7
   609
indvdum@0
   610
    public void newLine() {
indvdum@0
   611
        client.call("newLine");
indvdum@0
   612
    }
indvdum@0
   613
indvdum@6
   614
	public void newLineIfNotEndsWithNewLine() {
indvdum@6
   615
		client.call("newLineIfNotEndsWithNewLine");
indvdum@6
   616
	}
indvdum@6
   617
indvdum@0
   618
    public void reset() {
indvdum@0
   619
        client.call("reset");
indvdum@0
   620
    }
indvdum@0
   621
indvdum@0
   622
    public void clear() {
indvdum@0
   623
        formFeed();
indvdum@0
   624
    }
indvdum@0
   625
indvdum@0
   626
    public void formFeed() {
indvdum@0
   627
        client.call("ff");
indvdum@0
   628
    }
indvdum@0
   629
indvdum@0
   630
    public void carriageReturn() {
indvdum@0
   631
        client.call("cr");
indvdum@0
   632
    }
indvdum@0
   633
indvdum@0
   634
    public void lineFeed() {
indvdum@0
   635
        client.call("lf");
indvdum@0
   636
    }
indvdum@0
   637
indvdum@0
   638
    public void clearCommandHistory() {
indvdum@0
   639
        client.call("clearHistory");
indvdum@0
   640
    }
indvdum@0
   641
indvdum@0
   642
    public void clearBuffer() {
indvdum@0
   643
        client.call("clearBuffer");
indvdum@0
   644
    }
indvdum@0
   645
indvdum@0
   646
    public void scrollToEnd() {
indvdum@0
   647
        client.call("scrollToEnd");
indvdum@0
   648
    }
indvdum@1
   649
    
indvdum@1
   650
    public void focusInput() {
indvdum@1
   651
    	client.call("focusInput");
indvdum@1
   652
    }
indvdum@0
   653
indvdum@0
   654
    /**
indvdum@0
   655
     * Gets the Tabulator index of this Focusable component.
indvdum@0
   656
     *
indvdum@0
   657
     * @see com.vaadin.ui.Component.Focusable#getTabIndex()
indvdum@0
   658
     */
indvdum@0
   659
    public int getTabIndex() {
indvdum@0
   660
        return tabIndex;
indvdum@0
   661
    }
indvdum@0
   662
indvdum@0
   663
    /**
indvdum@0
   664
     * Sets the Tabulator index of this Focusable component.
indvdum@0
   665
     *
indvdum@0
   666
     * @see com.vaadin.ui.Component.Focusable#setTabIndex(int)
indvdum@0
   667
     */
indvdum@0
   668
    public void setTabIndex(final int tabIndex) {
indvdum@0
   669
        this.tabIndex = tabIndex;
indvdum@0
   670
    }
indvdum@0
   671
indvdum@0
   672
    /**
indvdum@0
   673
     * {@inheritDoc}
indvdum@0
   674
     */
indvdum@0
   675
    @Override
indvdum@0
   676
    public void focus() {
indvdum@0
   677
        super.focus();
indvdum@0
   678
    }
indvdum@0
   679
indvdum@0
   680
    /* PrintStream implementation for console output. */
indvdum@0
   681
indvdum@0
   682
    public PrintStream getPrintStream() {
indvdum@0
   683
        if (printStream == null) {
indvdum@0
   684
            printStream = new PrintStream(new OutputStream() {
indvdum@0
   685
indvdum@0
   686
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();
indvdum@0
   687
indvdum@0
   688
                @Override
indvdum@0
   689
                public void write(final int b) throws IOException {
indvdum@0
   690
                    buffer.write(b);
indvdum@0
   691
                    // Line buffering
indvdum@0
   692
                    if (13 == b) {
indvdum@0
   693
                        flush();
indvdum@0
   694
                    }
indvdum@0
   695
                }
indvdum@0
   696
indvdum@0
   697
                @Override
indvdum@0
   698
                public void flush() throws IOException {
indvdum@0
   699
                    super.flush();
indvdum@0
   700
                    buffer.flush();
indvdum@0
   701
                    Console.this.print(buffer.toString());
indvdum@0
   702
                    buffer.reset();
indvdum@0
   703
                }
indvdum@0
   704
            }, true);
indvdum@0
   705
        }
indvdum@0
   706
        return printStream;
indvdum@0
   707
    }
indvdum@0
   708
indvdum@0
   709
    /* Generic command handling */
indvdum@0
   710
indvdum@0
   711
    /**
indvdum@0
   712
     * Add a Command to this Console.
indvdum@0
   713
     *
indvdum@0
   714
     * This will override the any commands of the same name available via
indvdum@0
   715
     * {@link CommandProvider}.
indvdum@0
   716
     */
indvdum@0
   717
    public void addCommand(final String name, final Command cmd) {
indvdum@0
   718
        commands.put(name, cmd);
indvdum@0
   719
    }
indvdum@0
   720
indvdum@0
   721
    /**
indvdum@0
   722
     * Remove a command from this console.
indvdum@0
   723
     *
indvdum@0
   724
     * This does not remove Command available from {@link CommandProvider}.
indvdum@0
   725
     *
indvdum@0
   726
     * @param cmdName
indvdum@0
   727
     */
indvdum@0
   728
    public void removeCommand(final String cmdName) {
indvdum@0
   729
        commands.remove(cmdName);
indvdum@0
   730
    }
indvdum@0
   731
indvdum@0
   732
    /**
indvdum@0
   733
     * Get a Command by its name.
indvdum@0
   734
     *
indvdum@0
   735
     * @param cmdName
indvdum@0
   736
     * @return
indvdum@0
   737
     */
indvdum@0
   738
    public Command getCommand(final String cmdName) {
indvdum@0
   739
indvdum@0
   740
        // Try directly registered command first
indvdum@0
   741
        Command cmd = commands.get(cmdName);
indvdum@0
   742
        if (cmd != null) {
indvdum@0
   743
            return cmd;
indvdum@0
   744
        }
indvdum@0
   745
indvdum@0
   746
        // Ask from the providers
indvdum@0
   747
        if (commandProviders != null) {
indvdum@0
   748
            for (final CommandProvider cp : commandProviders) {
indvdum@0
   749
                cmd = cp.getCommand(this, cmdName);
indvdum@0
   750
                if (cmd != null) {
indvdum@0
   751
                    return cmd;
indvdum@0
   752
                }
indvdum@0
   753
            }
indvdum@0
   754
        }
indvdum@0
   755
indvdum@0
   756
        // Not found
indvdum@0
   757
        return null;
indvdum@0
   758
    }
indvdum@0
   759
indvdum@0
   760
    /**
indvdum@0
   761
     * Get the current Console Handler.
indvdum@0
   762
     *
indvdum@0
   763
     * @return
indvdum@0
   764
     */
indvdum@0
   765
    public Handler getHandler() {
indvdum@0
   766
        return handler;
indvdum@0
   767
    }
indvdum@0
   768
indvdum@0
   769
    /**
indvdum@0
   770
     * Set the handler for this console.
indvdum@0
   771
     *
indvdum@0
   772
     * @see Handler
indvdum@0
   773
     * @param handler
indvdum@0
   774
     */
indvdum@0
   775
    public void setHandler(final Handler handler) {
indvdum@0
   776
        this.handler = handler != null ? handler : new DefaultConsoleHandler();
indvdum@0
   777
    }
indvdum@0
   778
indvdum@0
   779
    /**
indvdum@0
   780
     * Get map of available commands in this Console.
indvdum@0
   781
     *
indvdum@0
   782
     * @return
indvdum@0
   783
     */
indvdum@0
   784
    public Set<String> getCommands() {
indvdum@0
   785
        final Set<String> res = new HashSet<String>();
indvdum@0
   786
        if (commandProviders != null) {
indvdum@0
   787
            for (final CommandProvider cp : commandProviders) {
indvdum@0
   788
                res.addAll(cp.getAvailableCommands(this));
indvdum@0
   789
            }
indvdum@0
   790
        }
indvdum@0
   791
        res.addAll(commands.keySet());
indvdum@0
   792
        return Collections.unmodifiableSet(res);
indvdum@0
   793
    }
indvdum@0
   794
indvdum@0
   795
}