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