001 /*
002 * Copyright (C) 2012 eXo Platform SAS.
003 *
004 * This is free software; you can redistribute it and/or modify it
005 * under the terms of the GNU Lesser General Public License as
006 * published by the Free Software Foundation; either version 2.1 of
007 * the License, or (at your option) any later version.
008 *
009 * This software is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * You should have received a copy of the GNU Lesser General Public
015 * License along with this software; if not, write to the Free
016 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
017 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
018 */
019
020 package org.crsh.text;
021
022 import org.crsh.io.IOContext;
023
024 import java.io.Closeable;
025 import java.io.IOException;
026 import java.io.Writer;
027
028 public class RenderWriter extends Writer implements IOContext<Chunk> {
029
030 /** . */
031 private final IOContext out;
032
033 /** . */
034 private final Closeable closeable;
035
036 /** . */
037 private boolean closed;
038
039 /** . */
040 private boolean empty;
041
042 public RenderWriter(IOContext out) throws NullPointerException {
043 this(out, null);
044 }
045
046 public RenderWriter(IOContext out, Closeable closeable) throws NullPointerException {
047 if (out == null) {
048 throw new NullPointerException("No null appendable expected");
049 }
050
051 //
052 this.out = out;
053 this.empty = true;
054 this.closeable = closeable;
055 }
056
057 public boolean isEmpty() {
058 return empty;
059 }
060
061 public int getWidth() {
062 return out.getWidth();
063 }
064
065 public int getHeight() {
066 return out.getHeight();
067 }
068
069 public void provide(Chunk element) throws IOException {
070 if (element instanceof Text) {
071 Text text = (Text)element;
072 empty &= text.getText().length() == 0;
073 }
074 out.provide(element);
075 }
076
077 @Override
078 public void write(char[] cbuf, int off, int len) throws IOException {
079 if (closed) {
080 throw new IOException("Already closed");
081 }
082 if (len > 0) {
083 Text text = new Text();
084 text.buffer.append(cbuf, off, len);
085 provide(text);
086 }
087 }
088
089 @Override
090 public void flush() throws IOException {
091 if (closed) {
092 throw new IOException("Already closed");
093 }
094 out.flush();
095 }
096
097 @Override
098 public void close() throws IOException {
099 if (!closed) {
100 closed = true;
101 if (closeable != null) {
102 closeable.close();
103 }
104 }
105 }
106 }