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.shell.ScreenContext; 023 024 import java.io.Closeable; 025 import java.io.IOException; 026 import java.io.Writer; 027 028 public class RenderWriter extends Writer implements ScreenContext<Chunk> { 029 030 /** . */ 031 private final ScreenContext out; 032 033 /** . */ 034 private final Closeable closeable; 035 036 /** . */ 037 private boolean closed; 038 039 /** . */ 040 private boolean empty; 041 042 public RenderWriter(ScreenContext out) throws NullPointerException { 043 this(out, null); 044 } 045 046 public RenderWriter(ScreenContext 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 Class<Chunk> getConsumedType() { 070 return Chunk.class; 071 } 072 073 public void provide(Chunk element) throws IOException { 074 if (element instanceof Text) { 075 Text text = (Text)element; 076 empty &= text.getText().length() == 0; 077 } 078 out.provide(element); 079 } 080 081 @Override 082 public void write(char[] cbuf, int off, int len) throws IOException { 083 if (closed) { 084 throw new IOException("Already closed"); 085 } 086 if (len > 0) { 087 Text text = new Text(); 088 text.buffer.append(cbuf, off, len); 089 provide(text); 090 } 091 } 092 093 @Override 094 public void flush() throws IOException { 095 if (closed) { 096 throw new IOException("Already closed"); 097 } 098 out.flush(); 099 } 100 101 @Override 102 public void close() throws IOException { 103 if (!closed) { 104 closed = true; 105 if (closeable != null) { 106 closeable.close(); 107 } 108 } 109 } 110 }