carl 83 posts since
Oct 17, 2007
6.
Re: Is there any accessor like max-chars, but it evaluate the byte count? Jul 29, 2008 10:35 PM

in response to:
markecho
It's certainly possible, but you will have to determine exactly what encodings you're targeting. The
encode-characters proc and method would probably be of use to you here. You could convert the
String value of the
TextField to a
ByteVec and see how long that is. I recommend looking at the documentation for
encode-characters and
CharEncoding. There's an example in "Encoding Strings of Characters" in the documentation chapter "Reading and Writing Text Files".
For the best implementation, you would want to override the
TextFieldUI you were using, probably just to check every time an insertable
KeyPress happens, and possibly even the
TextField itself. You could avoid some of that work if you were willing to just truncate the value in the
TextField on an overflow, or something similar.
As a quick example, the following writes out the length in bytes for the given encoding on each ValueChanged. The target encoding is utf8 here, though you might be looking for "shift-jis" or "euc-jp".
{TextField
{on ValueChanged at tf:TextField do
def in = tf.value
let unicodeout:ByteVec =
{ByteVec
max-size = {value in.size} *
CharEncoding.utf8.transcode-max-expansion-factor
}
|| Use get-character-encoding-by-name procedure
let encoding:CharEncoding =
{get-character-encoding-by-name "utf8"}
let unicodecount:int =
{encode-characters in, unicodeout, encoding}
{dump unicodeout.size}
}
}