From 16acc95621e76fccdfb8ea1493361e58351d2103 Mon Sep 17 00:00:00 2001 From: mniip Date: Sun, 29 Apr 2018 04:08:03 +0300 Subject: [PATCH 01/27] Enlarge the font by adding 2 pixels above the cap height --- data/font.h | 578 ++++++++++++++--------------- font/editor.c | 2 +- font/packer.c | 2 +- font/unpacker.c | 2 +- src/graphics/Graphics.cpp | 30 +- src/graphics/RasterDrawMethods.inl | 6 +- 6 files changed, 310 insertions(+), 310 deletions(-) diff --git a/data/font.h b/data/font.h index f6cde74f6..80506b85b 100644 --- a/data/font.h +++ b/data/font.h @@ -1,299 +1,299 @@ #ifndef FONT_H_CHECK #define FONT_H_CHECK -#define FONT_H 10 +#define FONT_H 12 #ifdef INCLUDE_FONTDATA unsigned char font_data[] = { - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x03, 0xC7, 0x31, 0x0C, 0x02, 0x70, 0x04, 0x00, 0x00, - 0x05, 0xCC, 0x74, 0x23, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x06, 0x00, 0x80, 0x19, 0xCC, 0xE0, 0x3F, 0xCC, 0xF0, 0x2F, 0xCC, 0x90, 0x09, 0x00, 0x00, 0x00, - 0x06, 0x30, 0xD0, 0x3F, 0x33, 0xE1, 0x07, 0xF4, 0x12, 0x33, 0xFF, 0x00, 0x03, 0x00, 0x00, 0x00, - 0x07, 0x2D, 0xCE, 0xCC, 0xE1, 0x1D, 0xC0, 0x03, 0x74, 0x4B, 0x33, 0xB3, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x06, 0x7D, 0x30, 0x0C, 0x13, 0xD0, 0x32, 0xB3, 0x33, 0x1C, 0x7D, 0x07, 0x00, 0x00, 0x00, 0x00, - 0x03, 0x4C, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x04, 0x34, 0x1D, 0x07, 0x03, 0x07, 0x1D, 0x34, 0x00, 0x00, 0x00, - 0x04, 0x07, 0x1D, 0x34, 0x30, 0x34, 0x1D, 0x07, 0x00, 0x00, 0x00, - 0x06, 0x44, 0xD0, 0x1C, 0x64, 0xF0, 0x3F, 0x64, 0xD0, 0x1C, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x06, 0x00, 0x00, 0x02, 0x30, 0xE0, 0x2F, 0x30, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0D, 0x03, 0x00, - 0x05, 0x00, 0x00, 0x00, 0xC0, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x03, 0x00, 0x00, 0x00, 0x40, 0x70, 0x00, 0x00, 0x00, - 0x06, 0x80, 0x02, 0x0C, 0xA0, 0x00, 0x03, 0x28, 0xC0, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x06, 0xF8, 0xE0, 0x39, 0x07, 0x33, 0x32, 0x03, 0xB3, 0x38, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x30, 0xF0, 0x60, 0x03, 0x0C, 0x30, 0xC0, 0x40, 0x07, 0x00, 0x00, 0x00, 0x00, - 0x06, 0xFC, 0xB1, 0x34, 0x41, 0x03, 0x0A, 0x2C, 0x70, 0x00, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, - 0x06, 0xFC, 0x71, 0x34, 0x01, 0x03, 0x1E, 0x00, 0x33, 0x34, 0xFE, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x06, 0xC0, 0x03, 0x37, 0x1C, 0x73, 0x34, 0xBF, 0x03, 0x30, 0x40, 0x03, 0x00, 0x00, 0x00, 0x00, - 0x06, 0xFF, 0x33, 0x00, 0x57, 0xE0, 0x2F, 0x00, 0x13, 0x30, 0xFE, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x06, 0xF4, 0xD3, 0x00, 0x07, 0xF0, 0x1F, 0x03, 0x33, 0x34, 0xFD, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x06, 0xFF, 0x07, 0x34, 0x80, 0x03, 0x0E, 0x38, 0xD0, 0x00, 0x0D, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x06, 0xFC, 0xB1, 0x34, 0x03, 0xD3, 0x1F, 0x03, 0x73, 0x34, 0xFD, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x06, 0xFC, 0xB1, 0x34, 0x03, 0xC3, 0x3F, 0x40, 0x23, 0x30, 0xFD, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x03, 0x00, 0x70, 0x04, 0x40, 0x70, 0x00, 0x00, 0x00, - 0x04, 0x00, 0x00, 0x1C, 0x04, 0x00, 0x0C, 0x0D, 0x03, 0x00, 0x00, - 0x06, 0x00, 0x00, 0x00, 0xC0, 0xC3, 0x0B, 0x1B, 0xC0, 0x0B, 0xC0, 0x03, 0x00, 0x00, 0x00, 0x00, - 0x06, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F, 0x00, 0xF0, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x06, 0x00, 0x00, 0x00, 0x0F, 0x80, 0x0F, 0x90, 0x83, 0x0F, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x06, 0xFD, 0x71, 0x30, 0x81, 0x03, 0x0E, 0x34, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x08, 0xF8, 0x0F, 0x1D, 0x30, 0xE7, 0x37, 0x73, 0x1C, 0xE3, 0x2F, 0x07, 0x00, 0xFD, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x06, 0x74, 0xD0, 0x1D, 0x47, 0x33, 0x30, 0xFF, 0x33, 0x30, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, - 0x06, 0xBF, 0x30, 0x38, 0x43, 0xF3, 0x1F, 0x43, 0x33, 0x34, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x06, 0xF4, 0xD1, 0x34, 0x03, 0x31, 0x00, 0x03, 0x70, 0x34, 0xFD, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x06, 0x7F, 0x30, 0x1D, 0x43, 0x33, 0x30, 0x03, 0x33, 0x34, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x06, 0xFF, 0x32, 0x00, 0x03, 0xF0, 0x0B, 0x03, 0x30, 0x10, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, - 0x06, 0xFF, 0x33, 0x10, 0x03, 0xF0, 0x0B, 0x03, 0x30, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x06, 0xF4, 0xD1, 0x34, 0x03, 0x30, 0x3E, 0x03, 0x73, 0x34, 0xFD, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x06, 0x47, 0x33, 0x30, 0x03, 0xF3, 0x3F, 0x03, 0x33, 0x30, 0x47, 0x03, 0x00, 0x00, 0x00, 0x00, - 0x04, 0x1D, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1D, 0x00, 0x00, 0x00, - 0x06, 0xD0, 0x01, 0x0C, 0xC0, 0x00, 0x0C, 0xC0, 0x10, 0x0D, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x07, 0x47, 0xC3, 0x34, 0x70, 0x03, 0xBC, 0x00, 0xB3, 0xC0, 0xB0, 0x70, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x06, 0x07, 0x30, 0x00, 0x03, 0x30, 0x00, 0x03, 0x30, 0x10, 0xFF, 0x02, 0x00, 0x00, 0x00, 0x00, - 0x08, 0x03, 0x30, 0x1F, 0x3D, 0x7B, 0x3B, 0xE3, 0x32, 0x83, 0x30, 0x03, 0x30, 0x03, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x07, 0x07, 0xCD, 0x03, 0x73, 0xC3, 0x8C, 0x32, 0xC3, 0xCD, 0xC0, 0x33, 0xD0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x07, 0xF4, 0x41, 0xC7, 0x71, 0xD0, 0x0C, 0x30, 0x03, 0xCD, 0xD1, 0xD1, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x06, 0x7F, 0x30, 0x1D, 0x43, 0x73, 0x34, 0xFF, 0x31, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x07, 0xF4, 0x41, 0xD3, 0x71, 0xD0, 0x0C, 0x30, 0xC3, 0xCD, 0xD1, 0xD1, 0xDF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x06, 0xFF, 0x31, 0x34, 0x03, 0xF3, 0x0F, 0xD7, 0x30, 0x34, 0x07, 0x07, 0x00, 0x00, 0x00, 0x00, - 0x06, 0xFC, 0xB1, 0x31, 0x07, 0xD0, 0x0F, 0x90, 0x23, 0x34, 0xFE, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x06, 0xFF, 0x13, 0x13, 0x30, 0x00, 0x03, 0x30, 0x00, 0x03, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x07, 0x03, 0xCC, 0x00, 0x33, 0xC0, 0x0C, 0x30, 0x03, 0xCD, 0xD2, 0xD1, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x06, 0x03, 0x33, 0x30, 0x03, 0xB3, 0x38, 0xCD, 0xC1, 0x0D, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x08, 0x03, 0x30, 0x43, 0x30, 0xC7, 0x34, 0xCD, 0x1C, 0xED, 0x1E, 0x2C, 0x0E, 0x0C, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x07, 0x03, 0x4C, 0xC3, 0x81, 0x3B, 0xD0, 0x03, 0xDC, 0x42, 0xC3, 0x31, 0xC0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x06, 0x03, 0xB3, 0x38, 0xDC, 0x40, 0x07, 0x30, 0x00, 0x03, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x07, 0xFF, 0x0F, 0xD0, 0x02, 0x2C, 0xC0, 0x02, 0x2D, 0xC0, 0x06, 0xF0, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x04, 0x2F, 0x03, 0x03, 0x03, 0x03, 0x03, 0x2F, 0x00, 0x00, 0x00, - 0x05, 0x03, 0x28, 0xC0, 0x00, 0x0A, 0x30, 0x80, 0x02, 0x0C, 0x00, 0x00, 0x00, 0x00, - 0x04, 0x3E, 0x30, 0x30, 0x30, 0x30, 0x30, 0x3E, 0x00, 0x00, 0x00, - 0x04, 0x1D, 0x37, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, - 0x03, 0x83, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0xD0, 0x47, 0x30, 0xFC, 0x0C, 0xD3, 0x1F, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x07, 0x0C, 0xF0, 0xC7, 0x35, 0xC3, 0x0C, 0xF3, 0x07, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0xD0, 0xC3, 0x25, 0x03, 0x4C, 0xD2, 0x03, 0x00, 0x00, 0x00, 0x00, - 0x05, 0xD0, 0x00, 0x83, 0x8F, 0x33, 0xC3, 0x1C, 0xD3, 0x1F, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0xD0, 0xC7, 0x30, 0xBF, 0x0C, 0xD0, 0x0B, 0x00, 0x00, 0x00, 0x00, - 0x04, 0x3D, 0x07, 0x03, 0x2F, 0x03, 0x03, 0x07, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0xC0, 0xCB, 0x32, 0xC3, 0xF4, 0x03, 0x4C, 0x30, 0x7E, 0x00, 0x00, - 0x05, 0x03, 0x0C, 0xF0, 0xC7, 0x39, 0xC3, 0x0C, 0x73, 0x1C, 0x00, 0x00, 0x00, 0x00, - 0x04, 0x04, 0x1C, 0x00, 0x0D, 0x0C, 0x0C, 0x1D, 0x00, 0x00, 0x00, - 0x04, 0x00, 0x30, 0x00, 0x34, 0x30, 0x30, 0x30, 0x30, 0x1E, 0x00, - 0x05, 0x03, 0x0C, 0x31, 0xCE, 0x0E, 0x1F, 0xCC, 0x31, 0x1C, 0x00, 0x00, 0x00, 0x00, - 0x04, 0x03, 0x03, 0x03, 0x03, 0x03, 0x47, 0x3D, 0x00, 0x00, 0x00, - 0x06, 0x00, 0x00, 0x00, 0x9B, 0x71, 0x37, 0x33, 0x33, 0x32, 0x43, 0x03, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0xF0, 0xC7, 0x31, 0xC3, 0x0C, 0x33, 0x0D, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0xD0, 0xC7, 0x31, 0xC3, 0x4C, 0xD3, 0x07, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0xF0, 0xC7, 0x31, 0xC3, 0x4C, 0xF3, 0xC7, 0x00, 0x03, 0x00, 0x00, - 0x05, 0x00, 0x00, 0xD0, 0xDF, 0x31, 0xC3, 0x4C, 0xD3, 0x0F, 0x30, 0xC0, 0x00, 0x05, - 0x04, 0x00, 0x00, 0x33, 0x1F, 0x07, 0x03, 0x03, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0xC0, 0xC7, 0x10, 0x3C, 0x04, 0xF3, 0x03, 0x00, 0x00, 0x00, 0x00, - 0x04, 0x0C, 0x0C, 0x3F, 0x0C, 0x0C, 0x1C, 0x74, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x70, 0xDC, 0x30, 0xC3, 0x4C, 0xD3, 0x1F, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x30, 0xCC, 0x30, 0xD3, 0xDC, 0xC2, 0x02, 0x00, 0x00, 0x00, 0x00, - 0x06, 0x00, 0x00, 0x00, 0x47, 0x33, 0x32, 0x33, 0x73, 0x37, 0xCD, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x30, 0xCD, 0x32, 0x7D, 0x8C, 0x73, 0x0C, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x30, 0xCC, 0x30, 0xC7, 0x74, 0x43, 0x07, 0x0C, 0x1F, 0x00, 0x00, - 0x05, 0x00, 0x00, 0xF0, 0x4F, 0x2C, 0x2C, 0x2C, 0xF1, 0x0F, 0x00, 0x00, 0x00, 0x00, - 0x04, 0x38, 0x0C, 0x0C, 0x03, 0x0C, 0x0C, 0x38, 0x00, 0x00, 0x00, - 0x02, 0x32, 0x33, 0x33, 0x13, 0x00, - 0x04, 0x0B, 0x0C, 0x0C, 0x30, 0x0C, 0x0C, 0x0B, 0x00, 0x00, 0x00, - 0x06, 0x00, 0x00, 0x00, 0x1D, 0x72, 0x37, 0xD2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x04, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x08, 0x07, 0x00, 0x1F, 0x00, 0x7F, 0x00, 0xFF, 0x01, 0xFF, 0x07, 0xFF, 0x1F, 0xFF, 0x7F, 0xFF, 0x1B, 0xBF, 0x01, 0x1B, 0x00, - 0x0C, 0x00, 0x40, 0xFF, 0x00, 0x00, 0xF8, 0xF0, 0x3F, 0xEE, 0x2C, 0x30, 0xCB, 0x0B, 0x30, 0x42, 0xC3, 0x33, 0x00, 0x03, 0x30, 0x00, 0xF3, 0x33, 0x00, 0x03, 0x30, 0x00, 0xFF, 0x3F, 0x00, - 0x0C, 0xC2, 0x00, 0x00, 0xCB, 0x00, 0x00, 0xEE, 0xC0, 0xFF, 0xF8, 0xB0, 0xC0, 0xFF, 0x2C, 0xC0, 0x00, 0x0C, 0xCF, 0x00, 0x0C, 0xC0, 0x00, 0xCC, 0xCF, 0x00, 0x0C, 0xC0, 0x00, 0xFC, 0xFF, - 0x0A, 0x00, 0x00, 0x0D, 0x00, 0x70, 0x00, 0x00, 0xF3, 0xFF, 0xD3, 0x03, 0xE0, 0x3C, 0x3F, 0x38, 0x03, 0xD0, 0x33, 0xFF, 0x38, 0x03, 0xE0, 0xF0, 0xFF, 0x03, - 0x0C, 0x00, 0x00, 0x00, 0xFC, 0x00, 0x00, 0x8B, 0xF7, 0x0C, 0x13, 0x9F, 0x3B, 0x37, 0x00, 0xC0, 0x23, 0xFF, 0xFF, 0x8B, 0x03, 0x00, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x0A, 0xD0, 0x7F, 0x80, 0x03, 0x2C, 0x0D, 0x00, 0x37, 0x00, 0xC0, 0xF3, 0xFF, 0x3C, 0xFF, 0xCF, 0x03, 0x00, 0xDC, 0x00, 0x70, 0x38, 0xC0, 0x02, 0xFD, 0x07, - 0x0A, 0x00, 0x00, 0x00, 0xFC, 0x03, 0xF0, 0xFF, 0xC0, 0xFF, 0x3F, 0xFC, 0xFF, 0xC3, 0xFF, 0x3F, 0xFC, 0xFF, 0x03, 0xFF, 0x0F, 0xC0, 0x3F, 0x00, 0x00, 0x00, - 0x0A, 0xFF, 0xFF, 0x3F, 0x00, 0xC0, 0x03, 0x00, 0x3C, 0xF0, 0xC0, 0xC3, 0x3A, 0x3C, 0x0B, 0xCE, 0x2B, 0x80, 0x7E, 0x00, 0xD0, 0x03, 0x00, 0xFC, 0xFF, 0xFF, - 0x0A, 0x00, 0x00, 0xC0, 0xFF, 0x3F, 0xFC, 0xFF, 0xC3, 0xFF, 0x3F, 0xFC, 0xFF, 0xC3, 0xFF, 0x3F, 0xFC, 0xFF, 0xC3, 0xFF, 0x3F, 0xFC, 0xFF, 0x03, 0x00, 0x00, - 0x0A, 0xD0, 0x7F, 0x80, 0x03, 0x2C, 0x0D, 0x0F, 0x37, 0xF0, 0xC0, 0xF3, 0xFF, 0x3C, 0xFF, 0xCF, 0x03, 0x0F, 0xDC, 0xF0, 0x70, 0x38, 0xC0, 0x02, 0xFD, 0x07, - 0x0A, 0x40, 0x1F, 0x00, 0xAD, 0x07, 0xB0, 0xC5, 0x00, 0x17, 0x0C, 0x70, 0xD0, 0x00, 0x0C, 0x03, 0xBC, 0xEF, 0xB3, 0x11, 0xE0, 0x07, 0x05, 0x3C, 0x52, 0xC8, - 0x0A, 0x00, 0x00, 0x00, 0xF0, 0x00, 0xC0, 0x3F, 0x00, 0xFC, 0x03, 0xC0, 0x3F, 0x00, 0xF0, 0x00, 0xC0, 0x30, 0xC0, 0xFF, 0x3F, 0xFC, 0xFF, 0xC3, 0xFF, 0x3F, - 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x00, 0x00, 0xFC, 0xFF, 0x0F, 0xFC, 0xFF, 0x3F, 0xFC, 0x00, 0x00, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x06, 0x00, 0x00, 0x00, 0xB8, 0xE0, 0x2F, 0xFF, 0xE3, 0x2F, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x0A, 0xD0, 0x7F, 0x80, 0xFF, 0x2F, 0xFD, 0xFF, 0xF7, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xDF, 0xFF, 0x7F, 0xF8, 0xFF, 0x02, 0xFD, 0x07, - 0x0A, 0x40, 0x01, 0x00, 0x02, 0x00, 0xC8, 0x07, 0x10, 0xC3, 0x00, 0x31, 0x0D, 0x00, 0xFD, 0x01, 0x00, 0x74, 0x00, 0x00, 0x1D, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x0A, 0x00, 0x00, 0x00, 0x0F, 0x0F, 0xF0, 0xF0, 0x00, 0x0F, 0x0F, 0xF0, 0xF0, 0x00, 0x0F, 0x0F, 0xF0, 0xF0, 0x00, 0x0F, 0x0F, 0xF0, 0xF0, 0x00, 0x00, 0x00, - 0x0A, 0x40, 0x05, 0x80, 0xFF, 0x8B, 0x1E, 0xD0, 0x2E, 0x00, 0xF0, 0x00, 0xE0, 0xFF, 0x0B, 0x00, 0x0F, 0x00, 0xB8, 0x03, 0xB0, 0xE2, 0xFF, 0x02, 0x50, 0x01, - 0x08, 0xFF, 0x07, 0x03, 0x1E, 0x03, 0x73, 0x03, 0xEF, 0x03, 0xC0, 0x03, 0xC0, 0x03, 0xC0, 0x03, 0xC0, 0x03, 0xC0, 0xFF, 0xFF, - 0x0B, 0x00, 0x00, 0x00, 0xE4, 0x2F, 0xE0, 0x1B, 0x0C, 0x1D, 0x00, 0xFF, 0x03, 0xBE, 0xF0, 0xC1, 0x01, 0xAD, 0x34, 0xC0, 0x36, 0x0B, 0x30, 0xDC, 0xE4, 0x07, 0xFD, 0x1B, 0x00, - 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA8, 0x02, 0xA0, 0xAA, 0x00, 0xA8, 0xC2, 0x0F, 0x2A, 0xFF, 0x03, 0xCA, 0x3F, 0x80, 0xFC, 0x0F, 0x20, 0x0F, 0x00, 0x00, 0x00, 0x00, - 0x0C, 0x00, 0xC0, 0x01, 0x00, 0xC0, 0x07, 0xAA, 0xEA, 0x1F, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0xAA, 0xEA, 0x1F, 0x00, 0xC0, 0x07, 0x00, 0xC0, 0x01, 0x00, 0x00, 0x00, - 0x0C, 0x40, 0x03, 0x00, 0xD0, 0x03, 0x00, 0xF4, 0xAB, 0xAA, 0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFD, 0xFF, 0xFF, 0xF4, 0xAB, 0xAA, 0xD0, 0x03, 0x00, 0x40, 0x03, 0x00, 0x00, 0x00, 0x00, - 0x09, 0xFE, 0xFF, 0xE3, 0xFF, 0x0F, 0xAA, 0x3E, 0x0A, 0xF8, 0x2E, 0xE0, 0xBF, 0x80, 0xFF, 0xAA, 0xFE, 0xFF, 0xE2, 0xFF, 0x02, 0x02, 0x00, 0x00, - 0x09, 0x00, 0x80, 0x04, 0xD0, 0xE2, 0xFF, 0x02, 0x00, 0x00, 0xFF, 0x6F, 0x00, 0x40, 0xE6, 0xAF, 0x50, 0x00, 0x09, 0x00, 0x20, 0x00, 0x64, 0x00, - 0x09, 0xE0, 0x3F, 0x70, 0x60, 0x63, 0xC0, 0xE4, 0x80, 0xC2, 0x03, 0x07, 0x0F, 0x1E, 0x6C, 0xFF, 0x27, 0xFF, 0x3F, 0xE0, 0x2F, 0x00, 0x00, 0x00, - 0x09, 0x44, 0x44, 0x00, 0x12, 0x41, 0x88, 0x04, 0x21, 0x21, 0x84, 0x48, 0x20, 0x23, 0xC2, 0xCC, 0x08, 0x30, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x09, 0x00, 0x1D, 0x00, 0x1D, 0x00, 0x78, 0x00, 0xB4, 0x07, 0xF0, 0x2F, 0xC0, 0xFB, 0x00, 0xBE, 0x02, 0xF4, 0x07, 0xFD, 0xFF, 0x01, 0x00, 0x00, - 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x40, 0x01, 0x00, 0x19, 0x00, 0xA8, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x09, 0x00, 0x00, 0xFC, 0xFF, 0x3F, 0x00, 0xF0, 0xDC, 0xCB, 0x03, 0x00, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x09, 0x00, 0x00, 0xFC, 0xFF, 0x3F, 0x00, 0xF0, 0xDC, 0xCB, 0x03, 0x00, 0xFF, 0xFF, 0x0F, 0x30, 0x00, 0xC0, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, - 0x09, 0x00, 0x00, 0xFC, 0xFF, 0x3F, 0x00, 0xF0, 0xDC, 0xCB, 0x03, 0x00, 0xFF, 0xFF, 0x0F, 0x40, 0x07, 0x00, 0x74, 0x00, 0x40, 0x03, 0x00, 0x00, - 0x09, 0x00, 0x00, 0xFC, 0xFF, 0x3F, 0x00, 0xF0, 0xDC, 0xCB, 0x03, 0x00, 0xFF, 0xFF, 0x4F, 0x07, 0x40, 0x07, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, - 0x09, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0x0F, 0xFF, 0x3F, 0xFC, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x0A, 0xFF, 0xFF, 0x3F, 0x00, 0xC0, 0x07, 0x00, 0xBD, 0x02, 0xE8, 0xB3, 0xE0, 0x3C, 0xAC, 0xC3, 0x03, 0x0F, 0x3C, 0x00, 0xC0, 0x03, 0x00, 0xFC, 0xFF, 0xFF, - 0x0B, 0xC0, 0xC8, 0xC0, 0x91, 0x1B, 0xCD, 0x36, 0xE7, 0x00, 0x47, 0x03, 0xA7, 0x80, 0x36, 0xFD, 0xFF, 0xC1, 0x9B, 0xF9, 0xB8, 0xB8, 0xB8, 0xB7, 0x99, 0xF7, 0xFF, 0xFF, 0x0F, - 0x0B, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0xF0, 0x03, 0x00, 0xFC, 0x00, 0xC0, 0xFF, 0x00, 0xF0, 0x3F, 0x00, 0xFF, 0x3F, 0xF0, 0xFF, 0x3F, 0xFC, 0xFF, 0xCF, 0xFF, 0xFF, 0x0F, - 0x08, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x1F, 0xCB, 0x30, 0xC3, 0x3F, 0xC7, 0x00, 0x7E, 0x2F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x0A, 0xFC, 0xFF, 0xC3, 0xFF, 0x3F, 0x0C, 0x00, 0xC3, 0xFC, 0x33, 0x0C, 0x24, 0xC3, 0xC0, 0x31, 0x0C, 0x06, 0xC3, 0x30, 0x30, 0x0C, 0x00, 0xC3, 0xFF, 0x3F, - 0x0A, 0xFF, 0x3F, 0x30, 0x00, 0x03, 0xC3, 0x30, 0x30, 0x3F, 0xFF, 0xFF, 0x3F, 0x3C, 0x00, 0xFF, 0xFF, 0xFF, 0x0C, 0x0C, 0xC3, 0xC0, 0x00, 0x0C, 0xFC, 0xFF, - 0x0A, 0x00, 0x00, 0xC0, 0xFF, 0x00, 0xFC, 0x0F, 0xC0, 0xFF, 0x00, 0xFC, 0x0F, 0xC0, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x03, 0x00, 0x3C, 0x00, 0xC0, 0x03, 0xF0, 0x3F, 0x00, 0xFF, 0x03, 0x00, 0x00, - 0x09, 0xE0, 0x2F, 0xF0, 0xFF, 0xE3, 0xB8, 0xEC, 0x9B, 0xF9, 0xBF, 0xF8, 0xBF, 0x99, 0xEF, 0xB8, 0x2C, 0xFF, 0x3F, 0xE0, 0x2F, 0x00, 0x00, 0x00, - 0x04, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, - 0x03, 0x87, 0x87, 0xC3, 0x30, 0x0C, 0xE3, 0xDE, 0x01, - 0x03, 0x74, 0xBB, 0x0C, 0xC3, 0x30, 0x2C, 0x2D, 0x0D, - 0x05, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x0F, - 0x05, 0x00, 0x00, 0xD0, 0xC7, 0x34, 0xC3, 0x0C, 0x73, 0x4C, 0x1F, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x03, 0x0F, 0x39, 0xC0, 0x00, 0x43, 0x2F, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0xD0, 0x87, 0x30, 0x60, 0x60, 0x60, 0xC0, 0x3F, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0xD0, 0x87, 0x30, 0xB8, 0x00, 0x23, 0x4C, 0x1F, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x0E, 0x36, 0xC6, 0xFC, 0x03, 0x0C, 0x30, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0xF0, 0xCB, 0x00, 0x7F, 0x40, 0x13, 0x8C, 0x1F, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0xD0, 0xCB, 0x10, 0x2F, 0x4C, 0x33, 0x4C, 0x1F, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0xF0, 0x0F, 0x30, 0x60, 0x60, 0xC0, 0x00, 0x03, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0xD0, 0xC7, 0x30, 0x7D, 0x4C, 0x33, 0x4C, 0x1F, 0x00, 0x00, 0x00, - 0x05, 0x00, 0x00, 0xD0, 0xC7, 0x30, 0xC6, 0xE0, 0x03, 0x8C, 0x1F, 0x00, 0x00, 0x00, - 0x04, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, - 0x03, 0xC0, 0xF0, 0x3C, 0xCF, 0xF3, 0x3C, 0x03, 0x00, - 0x03, 0x00, 0xCC, 0xF3, 0x3C, 0xCF, 0xF3, 0x30, 0x00, - 0x05, 0x00, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x03, 0x00, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x03, 0x30, 0xC0, 0x0F, 0x30, 0x00, 0x00, - 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0xD0, 0x7F, 0x40, 0xFF, 0x1F, 0xFC, 0xFF, 0x43, 0xFF, 0x1F, 0x40, 0x15, 0x00, 0x00, 0x00, - 0x0A, 0xE4, 0x06, 0x90, 0x91, 0x01, 0x06, 0x24, 0x30, 0x90, 0x1B, 0x46, 0x6E, 0x96, 0xB9, 0x91, 0xE4, 0x06, 0x0C, 0x18, 0x90, 0x40, 0x46, 0x06, 0x90, 0x1B, - 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x3F, 0x02, 0xC2, 0xAB, 0xAA, 0x3E, 0x20, 0xE0, 0xAB, 0xAA, 0x3E, 0x02, 0xC2, 0xFF, 0xFF, 0x0F, 0x00, 0x00, - 0x0A, 0x00, 0x00, 0x00, 0x08, 0x02, 0xC0, 0x30, 0x00, 0x0C, 0x03, 0xF0, 0xFF, 0x00, 0xFE, 0x0B, 0xD0, 0x7F, 0x00, 0xA4, 0x01, 0x00, 0x0A, 0x00, 0xA0, 0x00, - 0x0A, 0x00, 0x80, 0x00, 0x81, 0x24, 0x10, 0x85, 0x00, 0x20, 0x66, 0x40, 0x15, 0x45, 0x62, 0x90, 0x4D, 0xD0, 0xF1, 0x23, 0x01, 0xFD, 0x41, 0x41, 0x07, 0x00, - 0x0A, 0x00, 0x05, 0x00, 0xA0, 0x00, 0x40, 0x1F, 0x00, 0xF8, 0x02, 0xD0, 0x7F, 0x00, 0xFE, 0x0B, 0xF0, 0xEF, 0x00, 0xFF, 0x0D, 0xD0, 0x77, 0x00, 0xF4, 0x01, - 0x0A, 0x00, 0x20, 0x00, 0x00, 0x3C, 0x00, 0xD4, 0x01, 0xD0, 0x06, 0x40, 0x7F, 0x00, 0xFD, 0x01, 0xF4, 0x07, 0xD0, 0x1F, 0x00, 0x7F, 0x00, 0xD0, 0x01, 0x00, - 0x0A, 0x40, 0x15, 0x00, 0xFE, 0x0B, 0x88, 0x2F, 0x52, 0xF0, 0x50, 0x01, 0x0A, 0xD4, 0xAF, 0x7F, 0xFD, 0xF5, 0xC7, 0x0B, 0x3E, 0x70, 0xD0, 0x00, 0xA8, 0x02, - 0x0A, 0x80, 0x2F, 0x80, 0x5F, 0x2F, 0x0C, 0x00, 0xC3, 0x00, 0x30, 0x0C, 0x00, 0xC3, 0x01, 0x34, 0x34, 0xC0, 0x01, 0x07, 0x0D, 0xD0, 0x75, 0x00, 0xF4, 0x01, - 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0xF4, 0x01, 0xC0, 0x3F, 0x00, 0xF0, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x0A, 0x00, 0x00, 0x00, 0xF0, 0x00, 0xE0, 0xEF, 0x00, 0xBB, 0x0B, 0xA0, 0xAA, 0x00, 0xAA, 0x0A, 0x80, 0x19, 0x00, 0x64, 0x02, 0x00, 0x05, 0x00, 0x00, 0x00, - 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x10, 0x2D, 0x80, 0xE7, 0x0B, 0xBE, 0xF8, 0xFA, 0x02, 0xFE, 0x0B, 0x80, 0x2F, 0x00, 0x50, 0x00, - 0x0A, 0x00, 0x05, 0x00, 0xF8, 0x02, 0xE0, 0xBF, 0x80, 0xAF, 0x2F, 0xBE, 0xE0, 0xDB, 0x02, 0x78, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x0A, 0x00, 0x05, 0x00, 0xA0, 0x00, 0x40, 0x1F, 0x50, 0xFE, 0x5B, 0xFD, 0xFF, 0x47, 0xFF, 0x1F, 0xE0, 0xBF, 0x00, 0xFE, 0x0B, 0xF0, 0xF5, 0x40, 0x01, 0x14, - 0x0A, 0x40, 0x1A, 0x00, 0x09, 0x06, 0x20, 0x80, 0x00, 0x02, 0x08, 0xFC, 0xFF, 0xC3, 0x00, 0x30, 0x0C, 0x00, 0xC3, 0x00, 0x30, 0x0C, 0x00, 0xC3, 0xFF, 0x3F, - 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x0A, 0xF0, 0xFF, 0x00, 0xAA, 0x0A, 0xF0, 0xFF, 0x00, 0x00, 0x00, - 0x09, 0xE0, 0x2F, 0xF0, 0xFF, 0xE3, 0xFF, 0xED, 0xFF, 0xE1, 0xDF, 0xE1, 0x2F, 0xE1, 0xEF, 0xE2, 0x2F, 0xEF, 0x3F, 0xE0, 0x2F, 0x00, 0x00, 0x00, - 0x0A, 0xC0, 0x31, 0x00, 0x30, 0x01, 0x40, 0x34, 0x00, 0xCC, 0x00, 0x00, 0x0A, 0x00, 0xF8, 0x02, 0xE0, 0xBF, 0x80, 0xFF, 0x2F, 0xFE, 0xFF, 0xFB, 0xFF, 0xFF, - 0x0A, 0x00, 0x00, 0x80, 0xFF, 0x2F, 0xFC, 0xFF, 0xC3, 0x07, 0x3D, 0x3C, 0xC0, 0xC3, 0x03, 0x3C, 0x7C, 0xD0, 0xC3, 0xFF, 0x3F, 0xF8, 0xFF, 0x02, 0x00, 0x00, - 0x0A, 0x00, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x3C, 0x00, 0xC0, 0x03, 0x00, 0x00, 0x00, 0xC0, 0xF3, 0x3C, 0x3C, 0xCF, 0x03, 0x00, 0x00, - 0x0A, 0xB9, 0x91, 0xE3, 0x46, 0x2E, 0x1B, 0xB9, 0x61, 0xE4, 0x06, 0x91, 0x1B, 0x41, 0x6E, 0x24, 0xB9, 0x91, 0xE3, 0x46, 0x2E, 0x1B, 0xB9, 0x01, 0x00, 0x00, - 0x0A, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x0C, 0xC0, 0x23, 0x00, 0x80, 0x08, 0x00, 0x20, 0x0F, 0xC0, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x0A, 0xE0, 0x2F, 0xC0, 0x01, 0x0D, 0x06, 0x40, 0x32, 0x00, 0x30, 0x03, 0x00, 0x33, 0x00, 0x30, 0x06, 0x40, 0xC2, 0x01, 0x0D, 0xE0, 0x2F, 0x00, 0x00, 0x00, - 0x0A, 0x00, 0x00, 0x00, 0x20, 0x00, 0x20, 0x23, 0x80, 0x32, 0x0A, 0x0D, 0xC3, 0xD1, 0x10, 0x1C, 0x0D, 0xC0, 0x81, 0x02, 0x0A, 0xE0, 0x2F, 0x00, 0x54, 0x00, - 0x0A, 0x00, 0x00, 0x00, 0xFC, 0x03, 0xB0, 0xE0, 0x00, 0x03, 0x0C, 0x30, 0xC0, 0x00, 0x0B, 0x0E, 0xC0, 0x3F, 0x00, 0xAC, 0x03, 0xC0, 0x3A, 0x00, 0xAC, 0x03, - 0x05, 0x6F, 0xBC, 0xF1, 0xC6, 0x1B, 0x6F, 0xBC, 0xF1, 0xC6, 0x1B, 0x6F, 0x00, 0x00, - 0x08, 0xE4, 0x6F, 0xE4, 0x6F, 0xE4, 0x6F, 0xE4, 0x6F, 0xE4, 0x6F, 0xE4, 0x6F, 0xE4, 0x6F, 0xE4, 0x6F, 0xE4, 0x6F, 0x00, 0x00, - 0x09, 0x00, 0xE4, 0x03, 0x90, 0x0F, 0x40, 0x3E, 0x00, 0xF9, 0x00, 0xE4, 0x03, 0x90, 0x0F, 0x40, 0x3E, 0x00, 0xF9, 0x00, 0xE4, 0x03, 0x00, 0x00, - 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F, 0x00, 0xFF, 0x03, 0xF0, 0x3F, 0x00, 0xFF, 0x03, 0xF0, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x0A, 0x08, 0x82, 0xE0, 0xBA, 0x2E, 0x08, 0x82, 0x80, 0x20, 0x08, 0xAE, 0xEB, 0x82, 0x20, 0x08, 0x08, 0x82, 0xE0, 0xBA, 0x2E, 0x08, 0x82, 0x00, 0x00, 0x00, - 0x0A, 0x00, 0x30, 0x00, 0x00, 0x03, 0x30, 0xFC, 0x00, 0x43, 0x07, 0xFC, 0x20, 0x40, 0x07, 0x30, 0x20, 0x00, 0x03, 0x00, 0xFC, 0x00, 0x40, 0x07, 0x00, 0x20, - 0x0A, 0x00, 0x43, 0xC0, 0x20, 0x1D, 0x20, 0x61, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x84, 0x01, 0x24, 0xB4, 0xF1, 0x01, 0xFE, 0x0F, 0xD0, 0x0F, 0x00, 0xFC, - 0x0A, 0x00, 0x00, 0x00, 0x54, 0x00, 0x90, 0x1A, 0x40, 0xFE, 0x06, 0xE4, 0x6F, 0x40, 0xFE, 0x06, 0x90, 0x1A, 0x00, 0x54, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x10, 0x88, 0x88, 0x88, 0x55, 0x55, 0x55, 0xFF, 0x00, 0x54, 0x55, 0x55, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x0A, 0x00, 0x01, 0x00, 0x10, 0x00, 0x00, 0x02, 0x00, 0x64, 0x00, 0xA5, 0x6B, 0x01, 0x64, 0x00, 0x00, 0x02, 0x00, 0x10, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x0A, 0x00, 0x00, 0xC0, 0x00, 0x00, 0xFF, 0x86, 0xC0, 0x00, 0x2C, 0x40, 0xFE, 0x0B, 0xE4, 0xBF, 0x0C, 0xC0, 0xF2, 0x6F, 0x08, 0x0C, 0x00, 0x00, 0x00, 0x00, - 0x0A, 0x00, 0x05, 0x00, 0xF4, 0x01, 0xC0, 0x30, 0x00, 0x0D, 0x07, 0xF0, 0xF0, 0x40, 0x5F, 0x1F, 0xFC, 0xFA, 0xD3, 0xFF, 0x7F, 0xFF, 0xF0, 0xDF, 0xFF, 0x7F, - 0x0C, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x1E, 0x00, 0x80, 0x07, 0x00, 0xE0, 0x01, 0x00, 0x78, 0x60, 0x00, 0x24, 0x98, 0x01, 0x80, 0x42, 0x06, 0x00, 0x00, 0x19, 0x00, 0x00, 0x04, - 0x0A, 0x00, 0x00, 0x40, 0x7F, 0x00, 0x5C, 0x0D, 0xC0, 0xC1, 0x00, 0x1C, 0x0C, 0x40, 0xFF, 0x01, 0x00, 0x74, 0x00, 0x00, 0x1D, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x0A, 0x00, 0x00, 0x01, 0x00, 0x68, 0x00, 0xA2, 0x02, 0x80, 0x0A, 0x00, 0x25, 0x00, 0x44, 0x08, 0x10, 0x01, 0x40, 0x04, 0x00, 0x14, 0x00, 0x10, 0x00, 0x00, - 0x0A, 0xF0, 0xFF, 0x00, 0xFF, 0x0F, 0xF0, 0xFF, 0x00, 0xFF, 0x0F, 0xF0, 0xFF, 0x00, 0xFF, 0x0F, 0xF0, 0xFA, 0x00, 0x5B, 0x0E, 0x60, 0x90, 0x00, 0x01, 0x04, - 0x06, 0xCD, 0xF1, 0x3F, 0xFD, 0x41, 0x06, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, - 0x06, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x70, 0x1C, 0xC3, 0x20, 0x00, 0x47, 0x00, 0x00, + 0x05, 0x00, 0x00, 0xC0, 0x4C, 0x37, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x00, 0x80, 0x19, 0xCC, 0xE0, 0x3F, 0xCC, 0xF0, 0x2F, 0xCC, 0x90, 0x09, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x30, 0xD0, 0x3F, 0x33, 0xE1, 0x07, 0xF4, 0x12, 0x33, 0xFF, 0x00, 0x03, 0x00, 0x00, 0x00, + 0x07, 0x00, 0x00, 0x00, 0xD0, 0xE2, 0xCC, 0x1C, 0xDE, 0x01, 0x3C, 0x40, 0xB7, 0x34, 0x33, 0x8B, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x7D, 0x30, 0x0C, 0x13, 0xD0, 0x32, 0xB3, 0x33, 0x1C, 0x7D, 0x07, 0x00, 0x00, 0x00, 0x00, + 0x03, 0x00, 0xC0, 0x34, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x34, 0x1D, 0x07, 0x03, 0x07, 0x1D, 0x34, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x07, 0x1D, 0x34, 0x30, 0x34, 0x1D, 0x07, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x44, 0xD0, 0x1C, 0x64, 0xF0, 0x3F, 0x64, 0xD0, 0x1C, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x30, 0xE0, 0x2F, 0x30, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0D, 0x03, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x07, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x80, 0x02, 0x0C, 0xA0, 0x00, 0x03, 0x28, 0xC0, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0xF8, 0xE0, 0x39, 0x07, 0x33, 0x32, 0x03, 0xB3, 0x38, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x03, 0x0F, 0x36, 0xC0, 0x00, 0x03, 0x0C, 0x74, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0xFC, 0xB1, 0x34, 0x41, 0x03, 0x0A, 0x2C, 0x70, 0x00, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0xFC, 0x71, 0x34, 0x01, 0x03, 0x1E, 0x00, 0x33, 0x34, 0xFE, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0xC0, 0x03, 0x37, 0x1C, 0x73, 0x34, 0xBF, 0x03, 0x30, 0x40, 0x03, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0xFF, 0x33, 0x00, 0x57, 0xE0, 0x2F, 0x00, 0x13, 0x30, 0xFE, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0xF4, 0xD3, 0x00, 0x07, 0xF0, 0x1F, 0x03, 0x33, 0x34, 0xFD, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0xFF, 0x07, 0x34, 0x80, 0x03, 0x0E, 0x38, 0xD0, 0x00, 0x0D, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0xFC, 0xB1, 0x34, 0x03, 0xD3, 0x1F, 0x03, 0x73, 0x34, 0xFD, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0xFC, 0xB1, 0x34, 0x03, 0xC3, 0x3F, 0x40, 0x23, 0x30, 0xFD, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x07, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x00, 0x1C, 0x04, 0x00, 0x0C, 0x0D, 0x03, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xC3, 0x0B, 0x1B, 0xC0, 0x0B, 0xC0, 0x03, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F, 0x00, 0xF0, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x80, 0x0F, 0x90, 0x83, 0x0F, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0xFD, 0x71, 0x30, 0x81, 0x03, 0x0E, 0x34, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x08, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x0F, 0x1D, 0x30, 0xE7, 0x37, 0x73, 0x1C, 0xE3, 0x2F, 0x07, 0x00, 0xFD, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xD0, 0x1D, 0x47, 0x33, 0x30, 0xFF, 0x33, 0x30, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0xBF, 0x30, 0x38, 0x43, 0xF3, 0x1F, 0x43, 0x33, 0x34, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0xF4, 0xD1, 0x34, 0x03, 0x31, 0x00, 0x03, 0x70, 0x34, 0xFD, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x7F, 0x30, 0x1D, 0x43, 0x33, 0x30, 0x03, 0x33, 0x34, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0xFF, 0x32, 0x00, 0x03, 0xF0, 0x0B, 0x03, 0x30, 0x10, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0xFF, 0x33, 0x10, 0x03, 0xF0, 0x0B, 0x03, 0x30, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0xF4, 0xD1, 0x34, 0x03, 0x30, 0x3E, 0x03, 0x73, 0x34, 0xFD, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x47, 0x33, 0x30, 0x03, 0xF3, 0x3F, 0x03, 0x33, 0x30, 0x47, 0x03, 0x00, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x1D, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1D, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0xD0, 0x01, 0x0C, 0xC0, 0x00, 0x0C, 0xC0, 0x10, 0x0D, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x07, 0x00, 0x00, 0x00, 0x70, 0x34, 0x4C, 0x03, 0x37, 0xC0, 0x0B, 0x30, 0x0B, 0x0C, 0x0B, 0x47, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x07, 0x30, 0x00, 0x03, 0x30, 0x00, 0x03, 0x30, 0x10, 0xFF, 0x02, 0x00, 0x00, 0x00, 0x00, + 0x08, 0x00, 0x00, 0x00, 0x00, 0x03, 0x30, 0x1F, 0x3D, 0x7B, 0x3B, 0xE3, 0x32, 0x83, 0x30, 0x03, 0x30, 0x03, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x07, 0x00, 0x00, 0x00, 0x70, 0xD0, 0x3C, 0x30, 0x37, 0xCC, 0x28, 0x33, 0xDC, 0x0C, 0x3C, 0x03, 0x0D, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x07, 0x00, 0x00, 0x00, 0x40, 0x1F, 0x74, 0x1C, 0x07, 0xCD, 0x00, 0x33, 0xD0, 0x1C, 0x1D, 0xFD, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x7F, 0x30, 0x1D, 0x43, 0x73, 0x34, 0xFF, 0x31, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x07, 0x00, 0x00, 0x00, 0x40, 0x1F, 0x34, 0x1D, 0x07, 0xCD, 0x00, 0x33, 0xDC, 0x1C, 0x1D, 0xFD, 0x1D, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0xFF, 0x31, 0x34, 0x03, 0xF3, 0x0F, 0xD7, 0x30, 0x34, 0x07, 0x07, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0xFC, 0xB1, 0x31, 0x07, 0xD0, 0x0F, 0x90, 0x23, 0x34, 0xFE, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0xFF, 0x13, 0x13, 0x30, 0x00, 0x03, 0x30, 0x00, 0x03, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x07, 0x00, 0x00, 0x00, 0x30, 0xC0, 0x0C, 0x30, 0x03, 0xCC, 0x00, 0x33, 0xD0, 0x2C, 0x1D, 0xFD, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x03, 0x33, 0x30, 0x03, 0xB3, 0x38, 0xCD, 0xC1, 0x0D, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x08, 0x00, 0x00, 0x00, 0x00, 0x03, 0x30, 0x43, 0x30, 0xC7, 0x34, 0xCD, 0x1C, 0xED, 0x1E, 0x2C, 0x0E, 0x0C, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x07, 0x00, 0x00, 0x00, 0x30, 0xC0, 0x34, 0x1C, 0xB8, 0x03, 0x3D, 0xC0, 0x2D, 0x34, 0x1C, 0x03, 0x1C, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x03, 0xB3, 0x38, 0xDC, 0x40, 0x07, 0x30, 0x00, 0x03, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x07, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0x00, 0x2D, 0xC0, 0x02, 0x2C, 0xD0, 0x02, 0x6C, 0x00, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x2F, 0x03, 0x03, 0x03, 0x03, 0x03, 0x2F, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x30, 0x80, 0x02, 0x0C, 0xA0, 0x00, 0x03, 0x28, 0xC0, 0x00, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x3E, 0x30, 0x30, 0x30, 0x30, 0x30, 0x3E, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x1D, 0x37, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x30, 0x18, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7D, 0x04, 0xC3, 0xCF, 0x30, 0xFD, 0x01, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x70, 0xC0, 0x00, 0x7F, 0x5C, 0x33, 0xCC, 0x30, 0x7F, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3D, 0x5C, 0x32, 0xC0, 0x24, 0x3D, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x0D, 0x30, 0xF8, 0x38, 0x33, 0xCC, 0x31, 0xFD, 0x01, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7D, 0x0C, 0xF3, 0xCB, 0x00, 0xBD, 0x00, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x3D, 0x07, 0x03, 0x2F, 0x03, 0x03, 0x07, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBC, 0x2C, 0x33, 0x4C, 0x3F, 0xC0, 0x04, 0xE3, 0x07, 0x00, + 0x05, 0x00, 0x00, 0x30, 0xC0, 0x00, 0x7F, 0x9C, 0x33, 0xCC, 0x30, 0xC7, 0x01, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x04, 0x1C, 0x00, 0x0D, 0x0C, 0x0C, 0x1D, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x30, 0x00, 0x34, 0x30, 0x30, 0x30, 0x30, 0x1E, 0x00, + 0x05, 0x00, 0x00, 0x30, 0xC0, 0x10, 0xE3, 0xEC, 0xF0, 0xC1, 0x1C, 0xC3, 0x01, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x03, 0x03, 0x03, 0x03, 0x03, 0x47, 0x3D, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9B, 0x71, 0x37, 0x33, 0x33, 0x32, 0x43, 0x03, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x1C, 0x33, 0xCC, 0x30, 0xD3, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7D, 0x1C, 0x33, 0xCC, 0x34, 0x7D, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x1C, 0x33, 0xCC, 0x34, 0x7F, 0x0C, 0x30, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFD, 0x1D, 0x33, 0xCC, 0x34, 0xFD, 0x00, 0x03, 0x0C, 0x50, + 0x04, 0x00, 0x00, 0x00, 0x00, 0x33, 0x1F, 0x07, 0x03, 0x03, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x0C, 0xC1, 0x43, 0x30, 0x3F, 0x00, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x0C, 0x0C, 0x3F, 0x0C, 0x0C, 0x1C, 0x74, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC7, 0x0D, 0x33, 0xCC, 0x34, 0xFD, 0x01, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC3, 0x0C, 0x33, 0xCD, 0x2D, 0x2C, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x33, 0x32, 0x33, 0x73, 0x37, 0xCD, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD3, 0x2C, 0xD3, 0xC7, 0x38, 0xC7, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC3, 0x0C, 0x73, 0x4C, 0x37, 0x74, 0xC0, 0xF0, 0x01, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xC4, 0xC2, 0xC2, 0x12, 0xFF, 0x00, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x38, 0x0C, 0x0C, 0x03, 0x0C, 0x0C, 0x38, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x32, 0x33, 0x33, 0x13, 0x00, + 0x04, 0x00, 0x00, 0x0B, 0x0C, 0x0C, 0x30, 0x0C, 0x0C, 0x0B, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1D, 0x72, 0x37, 0xD2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x08, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x1F, 0x00, 0x7F, 0x00, 0xFF, 0x01, 0xFF, 0x07, 0xFF, 0x1F, 0xFF, 0x7F, 0xFF, 0x1B, 0xBF, 0x01, 0x1B, 0x00, + 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0xFF, 0x00, 0x00, 0xF8, 0xF0, 0x3F, 0xEE, 0x2C, 0x30, 0xCB, 0x0B, 0x30, 0x42, 0xC3, 0x33, 0x00, 0x03, 0x30, 0x00, 0xF3, 0x33, 0x00, 0x03, 0x30, 0x00, 0xFF, 0x3F, 0x00, + 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC2, 0x00, 0x00, 0xCB, 0x00, 0x00, 0xEE, 0xC0, 0xFF, 0xF8, 0xB0, 0xC0, 0xFF, 0x2C, 0xC0, 0x00, 0x0C, 0xCF, 0x00, 0x0C, 0xC0, 0x00, 0xCC, 0xCF, 0x00, 0x0C, 0xC0, 0x00, 0xFC, 0xFF, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0D, 0x00, 0x70, 0x00, 0x00, 0xF3, 0xFF, 0xD3, 0x03, 0xE0, 0x3C, 0x3F, 0x38, 0x03, 0xD0, 0x33, 0xFF, 0x38, 0x03, 0xE0, 0xF0, 0xFF, 0x03, + 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x00, 0x00, 0x8B, 0xF7, 0x0C, 0x13, 0x9F, 0x3B, 0x37, 0x00, 0xC0, 0x23, 0xFF, 0xFF, 0x8B, 0x03, 0x00, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0x7F, 0x80, 0x03, 0x2C, 0x0D, 0x00, 0x37, 0x00, 0xC0, 0xF3, 0xFF, 0x3C, 0xFF, 0xCF, 0x03, 0x00, 0xDC, 0x00, 0x70, 0x38, 0xC0, 0x02, 0xFD, 0x07, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x03, 0xF0, 0xFF, 0xC0, 0xFF, 0x3F, 0xFC, 0xFF, 0xC3, 0xFF, 0x3F, 0xFC, 0xFF, 0x03, 0xFF, 0x0F, 0xC0, 0x3F, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x3F, 0x00, 0xC0, 0x03, 0x00, 0x3C, 0xF0, 0xC0, 0xC3, 0x3A, 0x3C, 0x0B, 0xCE, 0x2B, 0x80, 0x7E, 0x00, 0xD0, 0x03, 0x00, 0xFC, 0xFF, 0xFF, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0x3F, 0xFC, 0xFF, 0xC3, 0xFF, 0x3F, 0xFC, 0xFF, 0xC3, 0xFF, 0x3F, 0xFC, 0xFF, 0xC3, 0xFF, 0x3F, 0xFC, 0xFF, 0x03, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0x7F, 0x80, 0x03, 0x2C, 0x0D, 0x0F, 0x37, 0xF0, 0xC0, 0xF3, 0xFF, 0x3C, 0xFF, 0xCF, 0x03, 0x0F, 0xDC, 0xF0, 0x70, 0x38, 0xC0, 0x02, 0xFD, 0x07, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x1F, 0x00, 0xAD, 0x07, 0xB0, 0xC5, 0x00, 0x17, 0x0C, 0x70, 0xD0, 0x00, 0x0C, 0x03, 0xBC, 0xEF, 0xB3, 0x11, 0xE0, 0x07, 0x05, 0x3C, 0x52, 0xC8, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x00, 0xC0, 0x3F, 0x00, 0xFC, 0x03, 0xC0, 0x3F, 0x00, 0xF0, 0x00, 0xC0, 0x30, 0xC0, 0xFF, 0x3F, 0xFC, 0xFF, 0xC3, 0xFF, 0x3F, + 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x00, 0x00, 0xFC, 0xFF, 0x0F, 0xFC, 0xFF, 0x3F, 0xFC, 0x00, 0x00, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB8, 0xE0, 0x2F, 0xFF, 0xE3, 0x2F, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0x7F, 0x80, 0xFF, 0x2F, 0xFD, 0xFF, 0xF7, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xDF, 0xFF, 0x7F, 0xF8, 0xFF, 0x02, 0xFD, 0x07, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x01, 0x00, 0x02, 0x00, 0xC8, 0x07, 0x10, 0xC3, 0x00, 0x31, 0x0D, 0x00, 0xFD, 0x01, 0x00, 0x74, 0x00, 0x00, 0x1D, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x0F, 0xF0, 0xF0, 0x00, 0x0F, 0x0F, 0xF0, 0xF0, 0x00, 0x0F, 0x0F, 0xF0, 0xF0, 0x00, 0x0F, 0x0F, 0xF0, 0xF0, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x05, 0x80, 0xFF, 0x8B, 0x1E, 0xD0, 0x2E, 0x00, 0xF0, 0x00, 0xE0, 0xFF, 0x0B, 0x00, 0x0F, 0x00, 0xB8, 0x03, 0xB0, 0xE2, 0xFF, 0x02, 0x50, 0x01, + 0x08, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x07, 0x03, 0x1E, 0x03, 0x73, 0x03, 0xEF, 0x03, 0xC0, 0x03, 0xC0, 0x03, 0xC0, 0x03, 0xC0, 0x03, 0xC0, 0xFF, 0xFF, + 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0xFE, 0x02, 0xBE, 0xC1, 0xD0, 0x01, 0xF0, 0x3F, 0xE0, 0x0B, 0x1F, 0x1C, 0xD0, 0x4A, 0x03, 0x6C, 0xB3, 0x00, 0xC3, 0x4D, 0x7E, 0xD0, 0xBF, 0x01, + 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x2A, 0x00, 0xAA, 0x0A, 0x80, 0x2A, 0xFC, 0xA0, 0xF2, 0x3F, 0xA0, 0xFC, 0x03, 0xC8, 0xFF, 0x00, 0xF2, 0x00, 0x00, 0x00, 0x00, + 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x01, 0x00, 0xC0, 0x07, 0xAA, 0xEA, 0x1F, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0xAA, 0xEA, 0x1F, 0x00, 0xC0, 0x07, 0x00, 0xC0, 0x01, 0x00, 0x00, 0x00, + 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x03, 0x00, 0xD0, 0x03, 0x00, 0xF4, 0xAB, 0xAA, 0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFD, 0xFF, 0xFF, 0xF4, 0xAB, 0xAA, 0xD0, 0x03, 0x00, 0x40, 0x03, 0x00, 0x00, 0x00, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0x3F, 0xFE, 0xFF, 0xA0, 0xEA, 0xA3, 0x80, 0xEF, 0x02, 0xFE, 0x0B, 0xF8, 0xAF, 0xEA, 0xFF, 0x2F, 0xFE, 0x2F, 0x20, 0x00, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x00, 0x2D, 0xFE, 0x2F, 0x00, 0x00, 0xF0, 0xFF, 0x06, 0x00, 0x64, 0xFE, 0x0A, 0x05, 0x90, 0x00, 0x00, 0x02, 0x40, 0x06, + 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x03, 0x07, 0x36, 0x06, 0x4C, 0x0E, 0x28, 0x3C, 0x70, 0xF0, 0xE0, 0xC1, 0xF6, 0x7F, 0xF2, 0xFF, 0x03, 0xFE, 0x02, 0x00, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x00, 0x40, 0x44, 0x04, 0x20, 0x11, 0x84, 0x48, 0x10, 0x12, 0x42, 0x88, 0x04, 0x32, 0x22, 0xCC, 0x8C, 0x00, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0x01, 0xD0, 0x01, 0x80, 0x07, 0x40, 0x7B, 0x00, 0xFF, 0x02, 0xBC, 0x0F, 0xE0, 0x2B, 0x40, 0x7F, 0xD0, 0xFF, 0x1F, 0x00, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x14, 0x00, 0x90, 0x01, 0x80, 0x0A, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0xFF, 0x03, 0x00, 0xCF, 0xBD, 0x3C, 0x00, 0xF0, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0xFF, 0x03, 0x00, 0xCF, 0xBD, 0x3C, 0x00, 0xF0, 0xFF, 0xFF, 0x00, 0x03, 0x00, 0x0C, 0x00, 0x30, 0x00, 0x00, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0xFF, 0x03, 0x00, 0xCF, 0xBD, 0x3C, 0x00, 0xF0, 0xFF, 0xFF, 0x00, 0x74, 0x00, 0x40, 0x07, 0x00, 0x34, 0x00, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0xFF, 0x03, 0x00, 0xCF, 0xBD, 0x3C, 0x00, 0xF0, 0xFF, 0xFF, 0x74, 0x00, 0x74, 0x00, 0x70, 0x00, 0x00, 0x00, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xF0, 0xFF, 0xC3, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x3F, 0x00, 0xC0, 0x07, 0x00, 0xBD, 0x02, 0xE8, 0xB3, 0xE0, 0x3C, 0xAC, 0xC3, 0x03, 0x0F, 0x3C, 0x00, 0xC0, 0x03, 0x00, 0xFC, 0xFF, 0xFF, + 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8C, 0x0C, 0x1C, 0xB9, 0xD1, 0x6C, 0x73, 0x0E, 0x70, 0x34, 0x70, 0x0A, 0x68, 0xD3, 0xFF, 0x1F, 0xBC, 0x99, 0x8F, 0x8B, 0x8B, 0x7B, 0x9B, 0x79, 0xFF, 0xFF, 0xFF, + 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x3F, 0x00, 0xC0, 0x0F, 0x00, 0xFC, 0x0F, 0x00, 0xFF, 0x03, 0xF0, 0xFF, 0x03, 0xFF, 0xFF, 0xC3, 0xFF, 0xFF, 0xFC, 0xFF, 0xFF, + 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x1F, 0xCB, 0x30, 0xC3, 0x3F, 0xC7, 0x00, 0x7E, 0x2F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xC3, 0xFF, 0x3F, 0x0C, 0x00, 0xC3, 0xFC, 0x33, 0x0C, 0x24, 0xC3, 0xC0, 0x31, 0x0C, 0x06, 0xC3, 0x30, 0x30, 0x0C, 0x00, 0xC3, 0xFF, 0x3F, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x3F, 0x30, 0x00, 0x03, 0xC3, 0x30, 0x30, 0x3F, 0xFF, 0xFF, 0x3F, 0x3C, 0x00, 0xFF, 0xFF, 0xFF, 0x0C, 0x0C, 0xC3, 0xC0, 0x00, 0x0C, 0xFC, 0xFF, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0x00, 0xFC, 0x0F, 0xC0, 0xFF, 0x00, 0xFC, 0x0F, 0xC0, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x03, 0x00, 0x3C, 0x00, 0xC0, 0x03, 0xF0, 0x3F, 0x00, 0xFF, 0x03, 0x00, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x02, 0xFF, 0x3F, 0x8E, 0xCB, 0xBE, 0x99, 0xFF, 0x8B, 0xFF, 0x9B, 0xF9, 0x8E, 0xCB, 0xF2, 0xFF, 0x03, 0xFE, 0x02, 0x00, 0x00, + 0x04, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, + 0x03, 0x00, 0x70, 0x78, 0x38, 0x0C, 0xC3, 0x30, 0xEE, 0x1D, + 0x03, 0x00, 0x40, 0xB7, 0xCB, 0x30, 0x0C, 0xC3, 0xD2, 0xD2, + 0x05, 0x00, 0x00, 0xF0, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFF, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7D, 0x4C, 0x33, 0xCC, 0x30, 0xC7, 0xF4, 0x01, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0xF0, 0x90, 0x03, 0x0C, 0x30, 0xF4, 0x02, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7D, 0x08, 0x03, 0x06, 0x06, 0x06, 0xFC, 0x03, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7D, 0x08, 0x83, 0x0B, 0x30, 0xC2, 0xF4, 0x01, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x60, 0x63, 0xCC, 0x3F, 0xC0, 0x00, 0x03, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x0C, 0xF0, 0x07, 0x34, 0xC1, 0xF8, 0x01, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBD, 0x0C, 0xF1, 0xC2, 0x34, 0xC3, 0xF4, 0x01, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x03, 0x06, 0x06, 0x0C, 0x30, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7D, 0x0C, 0xD3, 0xC7, 0x34, 0xC3, 0xF4, 0x01, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7D, 0x0C, 0x63, 0x0C, 0x3E, 0xC0, 0xF8, 0x01, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, + 0x03, 0x00, 0x00, 0x0C, 0xCF, 0xF3, 0x3C, 0xCF, 0x33, 0x00, + 0x03, 0x00, 0x00, 0xC0, 0x3C, 0xCF, 0xF3, 0x3C, 0x0F, 0x03, + 0x05, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x03, 0x30, 0xC0, 0x0F, 0x30, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0xD0, 0x7F, 0x40, 0xFF, 0x1F, 0xFC, 0xFF, 0x43, 0xFF, 0x1F, 0x40, 0x15, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE4, 0x06, 0x90, 0x91, 0x01, 0x06, 0x24, 0x30, 0x90, 0x1B, 0x46, 0x6E, 0x96, 0xB9, 0x91, 0xE4, 0x06, 0x0C, 0x18, 0x90, 0x40, 0x46, 0x06, 0x90, 0x1B, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x3F, 0x02, 0xC2, 0xAB, 0xAA, 0x3E, 0x20, 0xE0, 0xAB, 0xAA, 0x3E, 0x02, 0xC2, 0xFF, 0xFF, 0x0F, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x02, 0xC0, 0x30, 0x00, 0x0C, 0x03, 0xF0, 0xFF, 0x00, 0xFE, 0x0B, 0xD0, 0x7F, 0x00, 0xA4, 0x01, 0x00, 0x0A, 0x00, 0xA0, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x81, 0x24, 0x10, 0x85, 0x00, 0x20, 0x66, 0x40, 0x15, 0x45, 0x62, 0x90, 0x4D, 0xD0, 0xF1, 0x23, 0x01, 0xFD, 0x41, 0x41, 0x07, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0xA0, 0x00, 0x40, 0x1F, 0x00, 0xF8, 0x02, 0xD0, 0x7F, 0x00, 0xFE, 0x0B, 0xF0, 0xEF, 0x00, 0xFF, 0x0D, 0xD0, 0x77, 0x00, 0xF4, 0x01, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x3C, 0x00, 0xD4, 0x01, 0xD0, 0x06, 0x40, 0x7F, 0x00, 0xFD, 0x01, 0xF4, 0x07, 0xD0, 0x1F, 0x00, 0x7F, 0x00, 0xD0, 0x01, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x15, 0x00, 0xFE, 0x0B, 0x88, 0x2F, 0x52, 0xF0, 0x50, 0x01, 0x0A, 0xD4, 0xAF, 0x7F, 0xFD, 0xF5, 0xC7, 0x0B, 0x3E, 0x70, 0xD0, 0x00, 0xA8, 0x02, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x2F, 0x80, 0x5F, 0x2F, 0x0C, 0x00, 0xC3, 0x00, 0x30, 0x0C, 0x00, 0xC3, 0x01, 0x34, 0x34, 0xC0, 0x01, 0x07, 0x0D, 0xD0, 0x75, 0x00, 0xF4, 0x01, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0xF4, 0x01, 0xC0, 0x3F, 0x00, 0xF0, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x00, 0xE0, 0xEF, 0x00, 0xBB, 0x0B, 0xA0, 0xAA, 0x00, 0xAA, 0x0A, 0x80, 0x19, 0x00, 0x64, 0x02, 0x00, 0x05, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x10, 0x2D, 0x80, 0xE7, 0x0B, 0xBE, 0xF8, 0xFA, 0x02, 0xFE, 0x0B, 0x80, 0x2F, 0x00, 0x50, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0xF8, 0x02, 0xE0, 0xBF, 0x80, 0xAF, 0x2F, 0xBE, 0xE0, 0xDB, 0x02, 0x78, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0xA0, 0x00, 0x40, 0x1F, 0x50, 0xFE, 0x5B, 0xFD, 0xFF, 0x47, 0xFF, 0x1F, 0xE0, 0xBF, 0x00, 0xFE, 0x0B, 0xF0, 0xF5, 0x40, 0x01, 0x14, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x1A, 0x00, 0x09, 0x06, 0x20, 0x80, 0x00, 0x02, 0x08, 0xFC, 0xFF, 0xC3, 0x00, 0x30, 0x0C, 0x00, 0xC3, 0x00, 0x30, 0x0C, 0x00, 0xC3, 0xFF, 0x3F, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x0A, 0xF0, 0xFF, 0x00, 0xAA, 0x0A, 0xF0, 0xFF, 0x00, 0x00, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x02, 0xFF, 0x3F, 0xFE, 0xDF, 0xFE, 0x1F, 0xFE, 0x1D, 0xFE, 0x12, 0xFE, 0x2E, 0xFE, 0xF2, 0xFE, 0x03, 0xFE, 0x02, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x31, 0x00, 0x30, 0x01, 0x40, 0x34, 0x00, 0xCC, 0x00, 0x00, 0x0A, 0x00, 0xF8, 0x02, 0xE0, 0xBF, 0x80, 0xFF, 0x2F, 0xFE, 0xFF, 0xFB, 0xFF, 0xFF, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFF, 0x2F, 0xFC, 0xFF, 0xC3, 0x07, 0x3D, 0x3C, 0xC0, 0xC3, 0x03, 0x3C, 0x7C, 0xD0, 0xC3, 0xFF, 0x3F, 0xF8, 0xFF, 0x02, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x3C, 0x00, 0xC0, 0x03, 0x00, 0x00, 0x00, 0xC0, 0xF3, 0x3C, 0x3C, 0xCF, 0x03, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB9, 0x91, 0xE3, 0x46, 0x2E, 0x1B, 0xB9, 0x61, 0xE4, 0x06, 0x91, 0x1B, 0x41, 0x6E, 0x24, 0xB9, 0x91, 0xE3, 0x46, 0x2E, 0x1B, 0xB9, 0x01, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x0C, 0xC0, 0x23, 0x00, 0x80, 0x08, 0x00, 0x20, 0x0F, 0xC0, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x2F, 0xC0, 0x01, 0x0D, 0x06, 0x40, 0x32, 0x00, 0x30, 0x03, 0x00, 0x33, 0x00, 0x30, 0x06, 0x40, 0xC2, 0x01, 0x0D, 0xE0, 0x2F, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x20, 0x23, 0x80, 0x32, 0x0A, 0x0D, 0xC3, 0xD1, 0x10, 0x1C, 0x0D, 0xC0, 0x81, 0x02, 0x0A, 0xE0, 0x2F, 0x00, 0x54, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x03, 0xB0, 0xE0, 0x00, 0x03, 0x0C, 0x30, 0xC0, 0x00, 0x0B, 0x0E, 0xC0, 0x3F, 0x00, 0xAC, 0x03, 0xC0, 0x3A, 0x00, 0xAC, 0x03, + 0x05, 0x00, 0x00, 0xF0, 0xC6, 0x1B, 0x6F, 0xBC, 0xF1, 0xC6, 0x1B, 0x6F, 0xBC, 0xF1, 0x06, 0x00, + 0x08, 0x00, 0x00, 0x00, 0x00, 0xE4, 0x6F, 0xE4, 0x6F, 0xE4, 0x6F, 0xE4, 0x6F, 0xE4, 0x6F, 0xE4, 0x6F, 0xE4, 0x6F, 0xE4, 0x6F, 0xE4, 0x6F, 0x00, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x3E, 0x00, 0xF9, 0x00, 0xE4, 0x03, 0x90, 0x0F, 0x40, 0x3E, 0x00, 0xF9, 0x00, 0xE4, 0x03, 0x90, 0x0F, 0x40, 0x3E, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F, 0x00, 0xFF, 0x03, 0xF0, 0x3F, 0x00, 0xFF, 0x03, 0xF0, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x82, 0xE0, 0xBA, 0x2E, 0x08, 0x82, 0x80, 0x20, 0x08, 0xAE, 0xEB, 0x82, 0x20, 0x08, 0x08, 0x82, 0xE0, 0xBA, 0x2E, 0x08, 0x82, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x03, 0x30, 0xFC, 0x00, 0x43, 0x07, 0xFC, 0x20, 0x40, 0x07, 0x30, 0x20, 0x00, 0x03, 0x00, 0xFC, 0x00, 0x40, 0x07, 0x00, 0x20, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x43, 0xC0, 0x20, 0x1D, 0x20, 0x61, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x84, 0x01, 0x24, 0xB4, 0xF1, 0x01, 0xFE, 0x0F, 0xD0, 0x0F, 0x00, 0xFC, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x54, 0x00, 0x90, 0x1A, 0x40, 0xFE, 0x06, 0xE4, 0x6F, 0x40, 0xFE, 0x06, 0x90, 0x1A, 0x00, 0x54, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x81, 0x88, 0x88, 0x58, 0x55, 0x55, 0xF5, 0x0F, 0x40, 0x55, 0x55, 0x15, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x10, 0x00, 0x00, 0x02, 0x00, 0x64, 0x00, 0xA5, 0x6B, 0x01, 0x64, 0x00, 0x00, 0x02, 0x00, 0x10, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0xFF, 0x86, 0xC0, 0x00, 0x2C, 0x40, 0xFE, 0x0B, 0xE4, 0xBF, 0x0C, 0xC0, 0xF2, 0x6F, 0x08, 0x0C, 0x00, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0xF4, 0x01, 0xC0, 0x30, 0x00, 0x0D, 0x07, 0xF0, 0xF0, 0x40, 0x5F, 0x1F, 0xFC, 0xFA, 0xD3, 0xFF, 0x7F, 0xFF, 0xF0, 0xDF, 0xFF, 0x7F, + 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x1E, 0x00, 0x80, 0x07, 0x00, 0xE0, 0x01, 0x00, 0x78, 0x60, 0x00, 0x24, 0x98, 0x01, 0x80, 0x42, 0x06, 0x00, 0x00, 0x19, 0x00, 0x00, 0x04, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7F, 0x00, 0x5C, 0x0D, 0xC0, 0xC1, 0x00, 0x1C, 0x0C, 0x40, 0xFF, 0x01, 0x00, 0x74, 0x00, 0x00, 0x1D, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x68, 0x00, 0xA2, 0x02, 0x80, 0x0A, 0x00, 0x25, 0x00, 0x44, 0x08, 0x10, 0x01, 0x40, 0x04, 0x00, 0x14, 0x00, 0x10, 0x00, 0x00, + 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0x00, 0xFF, 0x0F, 0xF0, 0xFF, 0x00, 0xFF, 0x0F, 0xF0, 0xFF, 0x00, 0xFF, 0x0F, 0xF0, 0xFA, 0x00, 0x5B, 0x0E, 0x60, 0x90, 0x00, 0x01, 0x04, + 0x06, 0x00, 0x00, 0x00, 0xCD, 0xF1, 0x3F, 0xFD, 0x41, 0x06, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, }; short font_ptrs[] = { - 0x0000, 0x000E, 0x001C, 0x002A, 0x0038, 0x0046, 0x0054, 0x0062, - 0x0070, 0x007E, 0x008C, 0x009A, 0x00A8, 0x00B6, 0x00C4, 0x00D2, - 0x00E0, 0x00EE, 0x00FC, 0x010A, 0x0118, 0x0126, 0x0134, 0x0142, - 0x0150, 0x015E, 0x016C, 0x017A, 0x0188, 0x0196, 0x01A4, 0x01B2, - 0x01C0, 0x01CE, 0x01D7, 0x01E5, 0x01F5, 0x0205, 0x0218, 0x0228, - 0x0231, 0x023C, 0x0247, 0x0257, 0x0267, 0x0272, 0x0280, 0x0289, - 0x0299, 0x02A9, 0x02B7, 0x02C7, 0x02D7, 0x02E7, 0x02F7, 0x0307, - 0x0317, 0x0327, 0x0337, 0x0340, 0x034B, 0x035B, 0x036B, 0x037B, - 0x038B, 0x03A0, 0x03B0, 0x03C0, 0x03D0, 0x03E0, 0x03F0, 0x0400, - 0x0410, 0x0420, 0x042B, 0x043B, 0x044E, 0x045E, 0x0473, 0x0486, - 0x0499, 0x04A9, 0x04BC, 0x04CC, 0x04DC, 0x04EC, 0x04FF, 0x050F, - 0x0524, 0x0537, 0x0547, 0x055A, 0x0565, 0x0573, 0x057E, 0x0589, - 0x0599, 0x05A2, 0x05B0, 0x05BE, 0x05CC, 0x05DA, 0x05E8, 0x05F3, - 0x0601, 0x060F, 0x061A, 0x0625, 0x0633, 0x063E, 0x064E, 0x065C, - 0x066A, 0x0678, 0x0686, 0x0691, 0x069F, 0x06AA, 0x06B8, 0x06C6, - 0x06D6, 0x06E4, 0x06F2, 0x0700, 0x070B, 0x0711, 0x071C, 0x072C, - 0x0737, 0x074C, 0x076B, 0x078A, 0x07A4, 0x07C3, 0x07DD, 0x07F7, - 0x0811, 0x082B, 0x0845, 0x085F, 0x0879, 0x0898, 0x08A8, 0x08C2, - 0x08DC, 0x08F6, 0x0910, 0x0925, 0x0942, 0x095F, 0x097E, 0x099D, - 0x09B5, 0x09CD, 0x09E5, 0x09FD, 0x0A15, 0x0A2D, 0x0A45, 0x0A5D, - 0x0A75, 0x0A8D, 0x0AA5, 0x0ABF, 0x0ADC, 0x0AF9, 0x0B0E, 0x0B28, - 0x0B42, 0x0B5C, 0x0B76, 0x0B8E, 0x0B99, 0x0BA2, 0x0BAB, 0x0BB9, - 0x0BC7, 0x0BD5, 0x0BE3, 0x0BF1, 0x0BFF, 0x0C0D, 0x0C1B, 0x0C29, - 0x0C37, 0x0C45, 0x0C50, 0x0C59, 0x0C62, 0x0C70, 0x0C80, 0x0C90, - 0x0CAA, 0x0CC4, 0x0CDE, 0x0CF8, 0x0D12, 0x0D2C, 0x0D46, 0x0D60, - 0x0D7A, 0x0D94, 0x0DAE, 0x0DC8, 0x0DE2, 0x0DFC, 0x0E16, 0x0E30, - 0x0E48, 0x0E62, 0x0E7C, 0x0E96, 0x0EB0, 0x0ECA, 0x0EE4, 0x0EFE, - 0x0F18, 0x0F26, 0x0F3B, 0x0F53, 0x0F6D, 0x0F87, 0x0FA1, 0x0FBB, - 0x0FD5, 0x0FF2, 0x100C, 0x1026, 0x1040, 0x105F, 0x1079, 0x1093, - 0x10AD, 0x10BD, 0x10CD, 0x10DD, 0x10ED, 0x10FD, 0x110D, 0x111D, - 0x112D, 0x113D, 0x114D, 0x115D, 0x116D, 0x117D, 0x118D, 0x119D, - 0x11AD, 0x11BD, 0x11CD, 0x11DD, 0x11ED, 0x11FD, 0x120D, 0x121D, + 0x0000, 0x0010, 0x0020, 0x0030, 0x0040, 0x0050, 0x0060, 0x0070, + 0x0080, 0x0090, 0x00A0, 0x00B0, 0x00C0, 0x00D0, 0x00E0, 0x00F0, + 0x0100, 0x0110, 0x0120, 0x0130, 0x0140, 0x0150, 0x0160, 0x0170, + 0x0180, 0x0190, 0x01A0, 0x01B0, 0x01C0, 0x01D0, 0x01E0, 0x01F0, + 0x0200, 0x0210, 0x021A, 0x022A, 0x023D, 0x0250, 0x0266, 0x0279, + 0x0283, 0x0290, 0x029D, 0x02B0, 0x02C3, 0x02D0, 0x02E0, 0x02EA, + 0x02FD, 0x0310, 0x0320, 0x0333, 0x0346, 0x0359, 0x036C, 0x037F, + 0x0392, 0x03A5, 0x03B8, 0x03C2, 0x03CF, 0x03E2, 0x03F5, 0x0408, + 0x041B, 0x0434, 0x0447, 0x045A, 0x046D, 0x0480, 0x0493, 0x04A6, + 0x04B9, 0x04CC, 0x04D9, 0x04EC, 0x0502, 0x0515, 0x052E, 0x0544, + 0x055A, 0x056D, 0x0583, 0x0596, 0x05A9, 0x05BC, 0x05D2, 0x05E5, + 0x05FE, 0x0614, 0x0627, 0x063D, 0x064A, 0x065A, 0x0667, 0x0674, + 0x0687, 0x0691, 0x06A1, 0x06B1, 0x06C1, 0x06D1, 0x06E1, 0x06EE, + 0x06FE, 0x070E, 0x071B, 0x0728, 0x0738, 0x0745, 0x0758, 0x0768, + 0x0778, 0x0788, 0x0798, 0x07A5, 0x07B5, 0x07C2, 0x07D2, 0x07E2, + 0x07F5, 0x0805, 0x0815, 0x0825, 0x0832, 0x0839, 0x0846, 0x0859, + 0x0866, 0x087F, 0x08A4, 0x08C9, 0x08E8, 0x090D, 0x092C, 0x094B, + 0x096A, 0x0989, 0x09A8, 0x09C7, 0x09E6, 0x0A0B, 0x0A1E, 0x0A3D, + 0x0A5C, 0x0A7B, 0x0A9A, 0x0AB3, 0x0AD5, 0x0AF7, 0x0B1C, 0x0B41, + 0x0B5D, 0x0B79, 0x0B95, 0x0BB1, 0x0BCD, 0x0BE9, 0x0C05, 0x0C21, + 0x0C3D, 0x0C59, 0x0C75, 0x0C94, 0x0CB6, 0x0CD8, 0x0CF1, 0x0D10, + 0x0D2F, 0x0D4E, 0x0D6D, 0x0D89, 0x0D96, 0x0DA0, 0x0DAA, 0x0DBA, + 0x0DCA, 0x0DDA, 0x0DEA, 0x0DFA, 0x0E0A, 0x0E1A, 0x0E2A, 0x0E3A, + 0x0E4A, 0x0E5A, 0x0E67, 0x0E71, 0x0E7B, 0x0E8B, 0x0E9E, 0x0EB1, + 0x0ED0, 0x0EEF, 0x0F0E, 0x0F2D, 0x0F4C, 0x0F6B, 0x0F8A, 0x0FA9, + 0x0FC8, 0x0FE7, 0x1006, 0x1025, 0x1044, 0x1063, 0x1082, 0x10A1, + 0x10BD, 0x10DC, 0x10FB, 0x111A, 0x1139, 0x1158, 0x1177, 0x1196, + 0x11B5, 0x11C5, 0x11DE, 0x11FA, 0x1219, 0x1238, 0x1257, 0x1276, + 0x1295, 0x12B7, 0x12D6, 0x12F5, 0x1314, 0x1339, 0x1358, 0x1377, + 0x1396, 0x13A9, 0x13BC, 0x13CF, 0x13E2, 0x13F5, 0x1408, 0x141B, + 0x142E, 0x1441, 0x1454, 0x1467, 0x147A, 0x148D, 0x14A0, 0x14B3, + 0x14C6, 0x14D9, 0x14EC, 0x14FF, 0x1512, 0x1525, 0x1538, 0x154B, }; #else extern unsigned char font_data[]; diff --git a/font/editor.c b/font/editor.c index f86db7c67..0ad04c336 100644 --- a/font/editor.c +++ b/font/editor.c @@ -7,7 +7,7 @@ #include #define CELLW 12 -#define CELLH 10 +#define CELLH 12 #define XRES 800 #define YRES 600 diff --git a/font/packer.c b/font/packer.c index 3b3ce65f4..ebd9a0a1b 100644 --- a/font/packer.c +++ b/font/packer.c @@ -6,7 +6,7 @@ #include #define CELLW 12 -#define CELLH 10 +#define CELLH 12 //#define EXTENDED_FONT 1 char font[256][CELLH][CELLW]; diff --git a/font/unpacker.c b/font/unpacker.c index bf02337bf..3ffe38d76 100644 --- a/font/unpacker.c +++ b/font/unpacker.c @@ -11,7 +11,7 @@ #include "font.h" #define CELLW 12 -#define CELLH 10 +#define CELLH 12 char font[256][CELLH][CELLW]; char width[256]; diff --git a/src/graphics/Graphics.cpp b/src/graphics/Graphics.cpp index 69d3ad342..f16b8a347 100644 --- a/src/graphics/Graphics.cpp +++ b/src/graphics/Graphics.cpp @@ -91,7 +91,7 @@ int VideoBuffer::SetCharacter(int x, int y, int c, int r, int g, int b, int a) int i, j, w, bn = 0, ba = 0; unsigned char *rp = font_data + font_ptrs[c]; w = *(rp++); - for (j=0; j=-1; s++) { @@ -637,7 +637,7 @@ void Graphics::textnpos(char *s, int n, int w, int *cx, int *cy) if (x>=w) { x = 0; - y += FONT_H+2; + y += FONT_H; } n--; } @@ -681,7 +681,7 @@ int Graphics::PositionAtCharIndex(char *s, int charIndex, int & positionX, int & if(*s == '\n') { lines++; x = 0; - y += FONT_H+2; + y += FONT_H; charIndex--; continue; } else if(*s =='\b') { @@ -705,12 +705,12 @@ int Graphics::PositionAtCharIndex(char *s, int charIndex, int & positionX, int & int Graphics::CharIndexAtPosition(char *s, int positionX, int positionY) { - int x=0, y=0,charIndex=0,cw; + int x=0, y=-2,charIndex=0,cw; for (; *s; s++) { if(*s == '\n') { x = 0; - y += FONT_H+2; + y += FONT_H; charIndex++; continue; } else if(*s == '\b') { @@ -736,7 +736,7 @@ int Graphics::CharIndexAtPosition(char *s, int positionX, int positionY) int Graphics::textwrapheight(char *s, int width) { - int x=0, height=FONT_H+2, cw; + int x=0, height=FONT_H, cw; int wordlen; int charspace; while (*s) @@ -746,14 +746,14 @@ int Graphics::textwrapheight(char *s, int width) if (charspace=-1; s++) { if (*s == '\n') { x = 0; - height += FONT_H+2; + height += FONT_H; } else if (*s == '\b') { @@ -771,7 +771,7 @@ int Graphics::textwrapheight(char *s, int width) if (x+cw>=width) { x = 0; - height += FONT_H+2; + height += FONT_H; } x += cw; } @@ -785,17 +785,17 @@ void Graphics::textsize(const char * s, int & width, int & height) if(!strlen(s)) { width = 0; - height = FONT_H; + height = FONT_H-2; return; } - int cHeight = FONT_H, cWidth = 0, lWidth = 0; + int cHeight = FONT_H-2, cWidth = 0, lWidth = 0; for (; *s; s++) { if (*s == '\n') { cWidth = 0; - cHeight += FONT_H+2; + cHeight += FONT_H; } else if (*s == '\x0F') { diff --git a/src/graphics/RasterDrawMethods.inl b/src/graphics/RasterDrawMethods.inl index db4270357..0cdca0e4e 100644 --- a/src/graphics/RasterDrawMethods.inl +++ b/src/graphics/RasterDrawMethods.inl @@ -26,7 +26,7 @@ int PIXELMETHODS_CLASS::drawtext(int x, int y, const char *s, int r, int g, int if (*s == '\n') { characterX = startX; - characterY += FONT_H+2; + characterY += FONT_H; } else if (*s == '\x0F') { @@ -112,7 +112,7 @@ int PIXELMETHODS_CLASS::drawchar(int x, int y, int c, int r, int g, int b, int a int i, j, w, bn = 0, ba = 0; unsigned char *rp = font_data + font_ptrs[c]; w = *(rp++); - for (j=0; j Date: Sun, 29 Apr 2018 04:23:03 +0300 Subject: [PATCH 02/27] fix some tools' icons breaking their bounding box --- src/graphics/Renderer.cpp | 2 +- src/gui/game/SampleTool.cpp | 2 +- src/gui/game/SignTool.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/graphics/Renderer.cpp b/src/graphics/Renderer.cpp index fda17c4c0..085b8e54d 100644 --- a/src/graphics/Renderer.cpp +++ b/src/graphics/Renderer.cpp @@ -677,7 +677,7 @@ VideoBuffer * Renderer::WallIcon(int wallID, int width, int height) newTexture->SetPixel(i, j, PIXR(pc), PIXG(pc), PIXB(pc), 255); } } - newTexture->SetCharacter(4, 2, 0x8D, 255, 255, 255, 255); + newTexture->AddCharacter(4, 2, 0x8D, 255, 255, 255, 255); for (i=width/3; iSetPixel(i, 7+(int)(3.9f*cos(i*0.3f)), 255, 255, 255, 255); diff --git a/src/gui/game/SampleTool.cpp b/src/gui/game/SampleTool.cpp index 3e38ea08f..e1c13b76d 100644 --- a/src/gui/game/SampleTool.cpp +++ b/src/gui/game/SampleTool.cpp @@ -15,7 +15,7 @@ VideoBuffer * SampleTool::GetIcon(int toolID, int width, int height) newTexture->SetPixel(x, y, PIXR(pc), PIXG(pc), PIXB(pc), 255); } } - newTexture->SetCharacter((width/2)-5, (height/2)-5, 0xE6, 255, 255, 255, 255); + newTexture->AddCharacter((width/2)-5, (height/2)-5, 0xE6, 255, 255, 255, 255); newTexture->BlendPixel(10, 9, 100, 180, 255, 255); newTexture->BlendPixel(11, 8, 100, 180, 255, 255); newTexture->BlendPixel(12, 7, 100, 180, 255, 255); diff --git a/src/gui/game/SignTool.cpp b/src/gui/game/SignTool.cpp index b319e72e0..50a6de564 100644 --- a/src/gui/game/SignTool.cpp +++ b/src/gui/game/SignTool.cpp @@ -268,7 +268,7 @@ VideoBuffer * SignTool::GetIcon(int toolID, int width, int height) newTexture->SetPixel(x, y, PIXR(pc), PIXG(pc), PIXB(pc), 255); } } - newTexture->SetCharacter((width/2)-5, (height/2)-5, 0xA1, 32, 64, 128, 255); + newTexture->AddCharacter((width/2)-5, (height/2)-5, 0xA1, 32, 64, 128, 255); newTexture->BlendCharacter((width/2)-5, (height/2)-5, 0xA0, 255, 255, 255, 255); return newTexture; } From c0c550e920c037b3a85eb2fed92f403f4137205d Mon Sep 17 00:00:00 2001 From: mniip Date: Sun, 29 Apr 2018 18:49:40 +0300 Subject: [PATCH 03/27] Add a new font editor --- SConscript | 16 +- data/font.h | 5 + src/PowderToySDL.cpp | 9 + src/gui/font/FontEditor.cpp | 544 ++++++++++++++++++++++++++++++++++++ src/gui/font/FontEditor.h | 67 +++++ 5 files changed, 637 insertions(+), 4 deletions(-) create mode 100644 src/gui/font/FontEditor.cpp create mode 100644 src/gui/font/FontEditor.h diff --git a/SConscript b/SConscript index 03e93414b..6cbacf58a 100644 --- a/SConscript +++ b/SConscript @@ -67,6 +67,7 @@ AddSconsOption('static', False, False, "Compile statically.") AddSconsOption('opengl', False, False, "Build with OpenGL interface support.") AddSconsOption('opengl-renderer', False, False, "Build with OpenGL renderer support (turns on --opengl).") #Note: this has nothing to do with --renderer, only tells the game to render particles with opengl AddSconsOption('renderer', False, False, "Build the save renderer.") +AddSconsOption('font', False, False, "Build the font editor.") AddSconsOption('wall', False, False, "Error on all warnings.") AddSconsOption('no-warnings', False, False, "Disable all compiler warnings.") @@ -266,7 +267,7 @@ def findLibs(env, conf): else: FatalError("SDL.h not found") - if not GetOption('nolua') and not GetOption('renderer'): + if not GetOption('nolua') and not GetOption('renderer') and not GetOption('font'): #Look for Lua if platform == "FreeBSD": luaver = "lua-5.1" @@ -494,7 +495,7 @@ if GetOption('static'): #Add other flags and defines if not GetOption('nofft'): env.Append(CPPDEFINES=['GRAVFFT']) -if not GetOption('nolua') and not GetOption('renderer'): +if not GetOption('nolua') and not GetOption('renderer') and not GetOption('font'): env.Append(CPPDEFINES=['LUACONSOLE']) if GetOption('opengl') or GetOption('opengl-renderer'): @@ -507,6 +508,9 @@ if GetOption('renderer'): else: env.Append(CPPDEFINES=['USE_SDL']) +if GetOption('font'): + env.Append(CPPDEFINES=['FONTEDITOR']) + if GetOption("wall"): if msvc: env.Append(CCFLAGS=['/WX']) @@ -540,7 +544,7 @@ if GetOption('beta'): #Generate list of sources to compile sources = Glob("src/*.cpp") + Glob("src/*/*.cpp") + Glob("src/*/*/*.cpp") + Glob("generated/*.cpp") -if not GetOption('nolua') and not GetOption('renderer'): +if not GetOption('nolua') and not GetOption('renderer') and not GetOption('font'): sources += Glob("src/lua/socket/*.c") + Glob("src/lua/LuaCompat.c") if platform == "Windows": @@ -559,7 +563,11 @@ elif platform == "Darwin": if GetOption('output'): programName = GetOption('output') else: - programName = GetOption('renderer') and "render" or "powder" + programName = "powder" + if GetOption('renderer'): + programName = "render" + if GetOption('font'): + programName = "font" if "BIT" in env and env["BIT"] == 64: programName += "64" if isX86 and GetOption('no-sse'): diff --git a/data/font.h b/data/font.h index 80506b85b..b2ead7614 100644 --- a/data/font.h +++ b/data/font.h @@ -1,6 +1,7 @@ #ifndef FONT_H_CHECK #define FONT_H_CHECK #define FONT_H 12 +#ifndef FONTEDITOR #ifdef INCLUDE_FONTDATA unsigned char font_data[] = { 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -299,5 +300,9 @@ short font_ptrs[] = { extern unsigned char font_data[]; extern short font_ptrs[]; #endif +#else +extern unsigned char *font_data; +extern short *font_ptrs; +#endif #endif diff --git a/src/PowderToySDL.cpp b/src/PowderToySDL.cpp index a52d7ef34..45d3fed79 100644 --- a/src/PowderToySDL.cpp +++ b/src/PowderToySDL.cpp @@ -50,6 +50,8 @@ extern "C" { #include "gui/game/GameController.h" #include "gui/game/GameView.h" +#include "gui/font/FontEditor.h" + #include "gui/dialogues/ErrorMessage.h" #include "gui/dialogues/ConfirmPrompt.h" #include "gui/interface/Keys.h" @@ -1108,6 +1110,7 @@ int main(int argc, char * argv[]) try { #endif +#ifndef FONTEDITOR gameController = new GameController(); engine->ShowWindow(gameController->GetView()); @@ -1204,6 +1207,12 @@ int main(int argc, char * argv[]) } } +#else // FONTEDITOR + if(argc <= 1) + throw std::runtime_error("Not enough arguments"); + engine->ShowWindow(new FontEditor(argv[1])); +#endif + //initial mouse coords int sdl_x, sdl_y; SDL_GetMouseState(&sdl_x, &sdl_y); diff --git a/src/gui/font/FontEditor.cpp b/src/gui/font/FontEditor.cpp new file mode 100644 index 000000000..c66f85931 --- /dev/null +++ b/src/gui/font/FontEditor.cpp @@ -0,0 +1,544 @@ +#include +#include +#include +#include +#include +#include + +#include "FontEditor.h" + +#include "Config.h" +#include "gui/interface/Engine.h" +#include "gui/interface/Point.h" +#include "gui/interface/Button.h" +#include "gui/interface/Mouse.h" +#include "gui/interface/Keys.h" +#include "graphics/Graphics.h" + +#ifdef FONTEDITOR +unsigned char *font_data; +short *font_ptrs; + +void FontEditor::ReadHeader(std::string header) +{ + std::fstream file; + file.open(header, std::ios_base::in); + if(!file) + throw std::runtime_error("Could not open " + header); + file >> std::skipws; + + std::string word; + + while(word != "font_data[]") + file >> word; + file >> word >> word; + + size_t startFontData = file.tellg(); + + fontData.clear(); + do + { + unsigned int value; + file >> std::hex >> value; + if(!file.fail()) + { + fontData.push_back(value); + file >> word; + } + } + while(!file.fail()); + file.clear(); + + size_t endFontData = file.tellg(); + + while(word != "font_ptrs[]") + file >> word; + file >> word >> word; + + size_t startFontPtrs = file.tellg(); + + fontPtrs.clear(); + do + { + unsigned int value; + file >> std::hex >> value; + if(!file.fail()) + { + fontPtrs.push_back(value); + file >> word; + } + } + while(!file.fail()); + file.clear(); + + size_t endFontPtrs = file.tellg(); + + do + { + file >> word; + } + while(!file.fail()); + file.clear(); + size_t eof = file.tellg(); + + file.seekg(0); + beforeFontData = std::string(startFontData, 0); + file.read(&beforeFontData[0], startFontData); + + file.seekg(endFontData); + afterFontData = std::string(startFontPtrs - endFontData, 0); + file.read(&afterFontData[0], startFontPtrs - endFontData); + + file.seekg(endFontData); + afterFontData = std::string(startFontPtrs - endFontData, 0); + file.read(&afterFontData[0], startFontPtrs - endFontData); + + file.seekg(endFontPtrs); + afterFontPtrs = std::string(eof - endFontPtrs, 0); + file.read(&afterFontPtrs[0], eof - endFontPtrs); + file.close(); +} + +void FontEditor::WriteHeader(std::string header, std::vector const &fontData, std::vector const &fontPtrs) +{ + std::fstream file; + file.open(header, std::ios_base::out | std::ios_base::trunc); + if(!file) + throw std::runtime_error("Could not open " + header); + + file << std::setfill('0') << std::hex << std::uppercase; + file << beforeFontData << std::endl; + for(int ch = 0; ch < 256; ch++) + { + file << " " << "0x" << std::setw(2) << (unsigned int)fontData[fontPtrs[ch]] << ", "; + for(int i = fontPtrs[ch] + 1; i < (int)(ch == (int)fontPtrs.size() - 1 ? fontData.size() : fontPtrs[ch + 1]); i++) + file << " " << "0x" << std::setw(2) << (unsigned int)fontData[i] << ","; + file << std::endl; + } + file << afterFontData; + for(int ch = 0; ch < 256; ch++) + { + if(!(ch & 7)) + file << std::endl << " "; + else + file << " "; + file << "0x" << std::setw(4) << (unsigned int)fontPtrs[ch] << ","; + } + file << std::endl << afterFontPtrs; + file.close(); +} + +void FontEditor::UnpackData( + std::array &fontWidths, + std::array, FONT_H>, 256> &fontPixels, + std::vector const &fontData, + std::vector const &fontPtrs) +{ + for(int ch = 0; ch < 256; ch++) + { + unsigned char const *data = &fontData[fontPtrs[ch]]; + int bits = 0; + int pixels = 0; + int width = fontWidths[ch] = *(data++); + for(int j = 0; j < FONT_H; j++) + for(int i = 0; i < width; i++) + { + if(!bits) + { + pixels = *(data++); + bits = 8; + } + fontPixels[ch][j][i] = pixels & 3; + pixels >>= 2; + bits -= 2; + } + } +} + +void FontEditor::PackData( + std::array const &fontWidths, + std::array, FONT_H>, 256> const &fontPixels, + std::vector &fontData, + std::vector &fontPtrs) +{ + fontPtrs.clear(); + fontData.clear(); + for(int ch = 0; ch < 256; ch++) + { + fontPtrs.push_back(fontData.size()); + fontData.push_back(fontWidths[ch]); + + int bits = 0; + int pixels = 0; + for(int j = 0; j < FONT_H; j++) + for(int i = 0; i < fontWidths[ch]; i++) + { + if(bits == 8) + { + fontData.push_back(pixels); + bits = 0; + pixels = 0; + } + pixels >>= 2; + pixels |= fontPixels[ch][j][i] << 6; + bits += 2; + } + if(bits) + fontData.push_back(pixels); + } +} + +#define FONT_SCALE 16 +FontEditor::FontEditor(std::string _header): + ui::Window(ui::Point(0, 0), ui::Point(WINDOWW, WINDOWH)), + header(_header), + currentChar(0x80), + fgR(255), fgG(255), fgB(255), bgR(0), bgG(0), bgB(0), + grid(1), + rulers(1) +{ + ReadHeader(header); + UnpackData(fontWidths, fontPixels, fontData, fontPtrs); + font_data = fontData.data(); + font_ptrs = fontPtrs.data(); + + int baseline = 8 + FONT_H * FONT_SCALE + 4 + FONT_H + 4 + 1; + int currentX = 1; + + class PrevCharAction : public ui::ButtonAction + { + FontEditor *v; + public: + PrevCharAction(FontEditor *_v): v(_v) {} + void ActionCallback(ui::Button *) + { + v->PrevChar(); + } + }; + ui::Button *prev = new ui::Button(ui::Point(currentX, baseline), ui::Point(17, 17), "\x96"); + currentX += 18; + prev->SetActionCallback(new PrevCharAction(this)); + AddComponent(prev); + + class CharNumberAction : public ui::TextboxAction + { + FontEditor *v; + public: + CharNumberAction(FontEditor *_v): v(_v) {} + void TextChangedCallback(ui::Textbox *) + { + unsigned int number; + std::stringstream ss(v->currentCharTextbox->GetText()); + ss >> std::hex >> number; + if(number < 256) + v->currentChar = number; + } + }; + currentCharTextbox = new ui::Textbox(ui::Point(currentX, baseline), ui::Point(31, 17)); + currentX += 32; + currentCharTextbox->SetActionCallback(new CharNumberAction(this)); + UpdateCharNumber(); + AddComponent(currentCharTextbox); + + class NextCharAction : public ui::ButtonAction + { + FontEditor *v; + public: + NextCharAction(FontEditor *_v): v(_v) {} + void ActionCallback(ui::Button *) + { + v->NextChar(); + } + }; + ui::Button *next = new ui::Button(ui::Point(currentX, baseline), ui::Point(17, 17), "\x95"); + currentX += 18; + next->SetActionCallback(new NextCharAction(this)); + AddComponent(next); + + class ShrinkCharAction : public ui::ButtonAction + { + FontEditor *v; + public: + ShrinkCharAction(FontEditor *_v): v(_v) {} + void ActionCallback(ui::Button *) + { + v->ShrinkChar(); + } + }; + ui::Button *shrink = new ui::Button(ui::Point(currentX, baseline), ui::Point(17, 17), "><"); + currentX += 18; + shrink->SetActionCallback(new ShrinkCharAction(this)); + AddComponent(shrink); + + class GrowCharAction : public ui::ButtonAction + { + FontEditor *v; + public: + GrowCharAction(FontEditor *_v): v(_v) {} + void ActionCallback(ui::Button *) + { + v->GrowChar(); + } + }; + ui::Button *grow = new ui::Button(ui::Point(currentX, baseline), ui::Point(17, 17), "<>"); + currentX += 18; + grow->SetActionCallback(new GrowCharAction(this)); + AddComponent(grow); + + + class ToggleAction : public ui::ButtonAction + { + int &toggle; + public: + ToggleAction(int &_toggle): toggle(_toggle) {} + void ActionCallback(ui::Button *button) + { + toggle = button->GetToggleState(); + } + }; + ui::Button *showGrid = new ui::Button(ui::Point(currentX, baseline), ui::Point(32, 17), "Grid"); + currentX += 33; + showGrid->SetTogglable(true); + showGrid->SetToggleState(grid); + showGrid->SetActionCallback(new ToggleAction(grid)); + AddComponent(showGrid); + + ui::Button *showRulers = new ui::Button(ui::Point(currentX, baseline), ui::Point(32, 17), "Rulers"); + currentX += 33; + showRulers->SetTogglable(true); + showRulers->SetToggleState(grid); + showRulers->SetActionCallback(new ToggleAction(rulers)); + AddComponent(showRulers); + + baseline += 18; + currentX = 1; + + class ColorComponentAction : public ui::TextboxAction + { + int &color; + public: + ColorComponentAction(int &_color): color(_color) {} + void TextChangedCallback(ui::Textbox *box) + { + std::stringstream ss(box->GetText()); + ss >> color; + } + }; + int *refs[6] = {&fgR, &fgG, &fgB, &bgR, &bgG, &bgB}; + for(int i = 0; i < 6; i++) + { + std::stringstream ss; + ss << *refs[i]; + ui::Textbox *colorComponent = new ui::Textbox(ui::Point(currentX, baseline), ui::Point(27, 17), ss.str()); + currentX += 28; + colorComponent->SetActionCallback(new ColorComponentAction(*refs[i])); + AddComponent(colorComponent); + } + + baseline += 18; + currentX = 1; + + class RenderAction : public ui::ButtonAction + { + FontEditor *v; + public: + RenderAction(FontEditor *_v): v(_v) {} + void ActionCallback(ui::Button *) + { + v->Render(); + } + }; + ui::Button *render = new ui::Button(ui::Point(currentX, baseline), ui::Point(50, 17), "Render"); + currentX += 51; + render->SetActionCallback(new RenderAction(this)); + AddComponent(render); + + class SaveAction : public ui::ButtonAction + { + FontEditor *v; + public: + SaveAction(FontEditor *_v): v(_v) {} + void ActionCallback(ui::Button *) + { + v->Save(); + } + }; + savedButton = new ui::Button(ui::Point(currentX, baseline), ui::Point(50, 17), "Save"); + currentX += 51; + savedButton->SetTogglable(true); + savedButton->SetToggleState(true); + savedButton->SetActionCallback(new SaveAction(this)); + AddComponent(savedButton); + + baseline += 18; + + outputPreview = new ui::Label(ui::Point(0, baseline + (Size.Y - baseline) * 3 / 5), ui::Point(Size.X, (Size.Y - baseline) * 2 / 5), ""); + outputPreview->SetMultiline(true); + outputPreview->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; + outputPreview->Appearance.VerticalAlign = ui::Appearance::AlignTop; + AddComponent(outputPreview); + + class PreviewAction : public ui::TextboxAction + { + FontEditor *v; + public: + PreviewAction(FontEditor *_v): v(_v) {} + void TextChangedCallback(ui::Textbox *box) + { + std::stringstream ss(box->GetText()); + std::string text; + while(!ss.eof()) + { + if(ss.peek() == '\n') + { + text.push_back('\n'); + ss.get(); + } + unsigned int ch; + ss >> std::hex >> ch; + if(ss.fail()) + { + ss.clear(); + char ch = ss.get(); + if(!ss.eof()) + text.push_back(ch); + continue; + } + text.push_back((char)ch); + } + v->outputPreview->SetText(text); + } + }; + ui::Textbox *inputPreview = new ui::Textbox(ui::Point(0, baseline), ui::Point(Size.X, (Size.Y - baseline) * 3 / 5)); + inputPreview->SetMultiline(true); + inputPreview->SetInputType(ui::Textbox::Multiline); + inputPreview->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; + inputPreview->Appearance.VerticalAlign = ui::Appearance::AlignTop; + inputPreview->SetActionCallback(new PreviewAction(this)); + + std::stringstream input; + for(unsigned int ch = 0x20; ch <= 0xFF; ch++) + { + if(!(ch & 0x3F)) + input << "20 "; + input << std::hex << std::setw(2) << ch << " "; + } + inputPreview->SetText(input.str()); + PreviewAction(this).TextChangedCallback(inputPreview); + AddComponent(inputPreview); +} + +void FontEditor::OnDraw() +{ + Graphics *g = GetGraphics(); + + int areaWidth = 8 + fontWidths[currentChar] * FONT_SCALE + 8; + g->fillrect(0, 0, areaWidth, 8 + FONT_H * FONT_SCALE + 4 + FONT_H + 4, bgR, bgG, bgB, 255); + for(int j = 0; j < FONT_H; j++) + for(int i = 0; i < fontWidths[currentChar]; i++) + g->fillrect(8 + i * FONT_SCALE, 8 + j * FONT_SCALE, FONT_SCALE - grid, FONT_SCALE - grid, fgR, fgG, fgB, fontPixels[currentChar][j][i] * 255 / 3); + + for(int j = 0; j < FONT_H; j++) + for(int i = 0; i < fontWidths[currentChar]; i++) + g->blendpixel(8 + i, 8 + FONT_H * FONT_SCALE + 4 + j, fgR, fgG, fgB, fontPixels[currentChar][j][i] * 255 / 3); + + + if(rulers) + { + g->draw_line(0, 7 + 0 * FONT_SCALE , areaWidth - 1, 7 + 0 * FONT_SCALE, 128, 128, 128, 255); + g->draw_line(0, 7 + 2 * FONT_SCALE , areaWidth - 1, 7 + 2 * FONT_SCALE, 128, 128, 128, 255); + g->draw_line(0, 7 + 4 * FONT_SCALE , areaWidth - 1, 7 + 4 * FONT_SCALE, 128, 128, 128, 255); + g->draw_line(0, 7 + 9 * FONT_SCALE , areaWidth - 1, 7 + 9 * FONT_SCALE, 128, 128, 128, 255); + g->draw_line(0, 7 + 12 * FONT_SCALE , areaWidth - 1, 7 + 12 * FONT_SCALE, 128, 128, 128, 255); + + g->draw_line(7, 8, 7, 7 + FONT_H * FONT_SCALE, 128, 128, 128, 255); + g->draw_line(7 + fontWidths[currentChar] * FONT_SCALE, 8, 7 + fontWidths[currentChar] * FONT_SCALE, 7 + FONT_H * FONT_SCALE, 128, 128, 128, 255); + } +} + +void FontEditor::OnMouseDown(int x, int y, unsigned button) +{ + x = (x - 8) / FONT_SCALE; + y = (y - 8) / FONT_SCALE; + if(x >= 0 && y >= 0 && x < fontWidths[currentChar] && y < FONT_H) + { + if(button == SDL_BUTTON_LEFT) + fontPixels[currentChar][y][x] = (fontPixels[currentChar][y][x] + 1) % 4; + else + fontPixels[currentChar][y][x] = (fontPixels[currentChar][y][x] + 3) % 4; + savedButton->SetToggleState(false); + } +} + +void FontEditor::OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool alt) +{ + if(IsFocused(NULL)) + { + switch(key) + { + case SDLK_LEFT: + PrevChar(); break; + case SDLK_RIGHT: + PrevChar(); break; + case SDLK_ESCAPE: + case 'q': + if(savedButton->GetToggleState()) + ui::Engine::Ref().Exit(); + else + ui::Engine::Ref().ConfirmExit(); + break; + } + } +} + +void FontEditor::UpdateCharNumber() +{ + std::stringstream ss; + ss << std::hex << currentChar; + currentCharTextbox->SetText(ss.str()); +} + +void FontEditor::PrevChar() +{ + if(currentChar > 0) + currentChar--; + UpdateCharNumber(); +} + +void FontEditor::NextChar() +{ + if(currentChar < 255) + currentChar++; + UpdateCharNumber(); +} + +void FontEditor::ShrinkChar() +{ + if(fontWidths[currentChar] > 0) + fontWidths[currentChar]--; + savedButton->SetToggleState(false); +} + +void FontEditor::GrowChar() +{ + if(fontWidths[currentChar] < MAX_WIDTH - 1) + fontWidths[currentChar]++; + savedButton->SetToggleState(false); +} + +void FontEditor::Render() +{ + PackData(fontWidths, fontPixels, fontData, fontPtrs); + font_data = fontData.data(); + font_ptrs = fontPtrs.data(); +} + +void FontEditor::Save() +{ + std::vector tmpFontData; + std::vector tmpFontPtrs; + PackData(fontWidths, fontPixels, tmpFontData, tmpFontPtrs); + WriteHeader(header, tmpFontData, tmpFontPtrs); + savedButton->SetToggleState(true); +} +#endif diff --git a/src/gui/font/FontEditor.h b/src/gui/font/FontEditor.h new file mode 100644 index 000000000..bc781e01c --- /dev/null +++ b/src/gui/font/FontEditor.h @@ -0,0 +1,67 @@ +#ifndef FONTEDITOR_H +#define FONTEDITOR_H + +#include +#include + +#include "font.h" + +#include "gui/interface/Window.h" +#include "gui/interface/Textbox.h" + +#define MAX_WIDTH 64 +class FontEditor: public ui::Window +{ +private: + std::string header; + std::array fontWidths; + std::array, FONT_H>, 256> fontPixels; + + std::vector fontData; + std::vector fontPtrs; + + std::string beforeFontData; + std::string afterFontData; + std::string afterFontPtrs; + + void ReadHeader(std::string header); + void WriteHeader(std::string header, std::vector const &fontData, std::vector const &fontPtrs); + static void PackData( + std::array const &fontWidths, + std::array, FONT_H>, 256> const &fontPixels, + std::vector &fontData, + std::vector &fontPtrs); + static void UnpackData( + std::array &fontWidths, + std::array, FONT_H>, 256> &fontPixels, + std::vector const &fontData, + std::vector const &fontPtrs); + + ui::Textbox *currentCharTextbox; + ui::Button *savedButton; + ui::Label *outputPreview; + + int currentChar; + int fgR, fgG, fgB; + int bgR, bgG, bgB; + + int grid; + int rulers; + + void UpdateCharNumber(); + void PrevChar(); + void NextChar(); + void ShrinkChar(); + void GrowChar(); + void Render(); + void Save(); + +public: + FontEditor(std::string header); + + void OnDraw(); + void OnMouseDown(int x, int y, unsigned button); + void OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool alt); +}; + +#endif From 4912674bfe7c168baec0f8ad524ad6799a12aa95 Mon Sep 17 00:00:00 2001 From: mniip Date: Sun, 29 Apr 2018 22:55:00 +0300 Subject: [PATCH 04/27] Add unicode/byte string classes which are supposed to eventually phase out std::string --- src/common/String.cpp | 89 +++++++++++++++++++++++++++++++++++++++++++ src/common/String.h | 60 +++++++++++++++++++++++++++++ 2 files changed, 149 insertions(+) create mode 100644 src/common/String.cpp create mode 100644 src/common/String.h diff --git a/src/common/String.cpp b/src/common/String.cpp new file mode 100644 index 000000000..0dc4a3426 --- /dev/null +++ b/src/common/String.cpp @@ -0,0 +1,89 @@ +#include +#include +#include +#include + +#include "String.h" + +std::string ByteString::ConversionError::formatError(ByteString::value_type const *at, ByteString::value_type const *upto) +{ + std::stringstream ss; + ss << "Could not convert sequence to UTF-8:"; + for(int i = 0; i < 4 && at + i < upto; i++) + ss << " " << std::hex << (unsigned int)std::make_unsigned::type(at[i]); + return ss.str(); +} + + +std::codecvt_utf8 convert(1); + +String ByteString::FromUtf8(bool ignoreError) const +{ + std::vector destination = std::vector(size(), String::value_type()); + std::codecvt_utf8::state_type state; + + ByteString::value_type const *from = data(), *from_next; + String::value_type *to = destination.data(), *to_next; + + while(true) + { + std::codecvt_utf8::result result = convert.in(state, from, data() + size(), from_next, to, destination.data() + destination.size(), to_next); + from = from_next; + to = to_next; + if(result == std::codecvt_base::ok || result == std::codecvt_base::noconv) + { + destination.resize(to - destination.data()); + return String(destination.data(), destination.size()); + } + else if(result == std::codecvt_base::partial && to == destination.data() + destination.size()) + { + String::value_type *old_data = destination.data(); + destination.resize(2 * destination.size()); + to = destination.data() + (to - old_data); + } + else + { + if(!ignoreError) + throw ConversionError(from, data() + size()); + + if(to == destination.data() + destination.size()) + { + String::value_type *old_data = destination.data(); + destination.resize(2 * destination.size()); + to = destination.data() + (to - old_data); + } + *(to++) = std::make_unsigned::type(*(from++)); + } + } +} + +ByteString String::ToUtf8() const +{ + std::vector destination = std::vector(size(), ByteString::value_type()); + std::codecvt_utf8::state_type state; + + String::value_type const *from = data(), *from_next; + ByteString::value_type *to = destination.data(), *to_next; + + while(true) + { + std::codecvt_utf8::result result = convert.out(state, from, data() + size(), from_next, to, destination.data() + destination.size(), to_next); + from = from_next; + to = to_next; + if(result == std::codecvt_base::ok || result == std::codecvt_base::noconv) + { + destination.resize(to - destination.data()); + return ByteString(destination.data(), destination.size()); + } + else if(result == std::codecvt_base::error) + { + throw ByteString::ConversionError(true); + } + else if(result == std::codecvt_base::partial) + { + ByteString::value_type *old_data = destination.data(); + destination.resize(2 * destination.size()); + to = destination.data() + (to - old_data); + } + } +} diff --git a/src/common/String.h b/src/common/String.h new file mode 100644 index 000000000..2d452eae3 --- /dev/null +++ b/src/common/String.h @@ -0,0 +1,60 @@ +#ifndef TPT_STRING +#define TPT_STRING + +#include + +class String; + +class ByteString : public std::basic_string +{ +public: + inline ByteString(): std::basic_string() {} + inline ByteString(size_type count, value_type ch): std::basic_string(count, ch) {} + inline ByteString(value_type const *ch, size_type count): std::basic_string(ch, count) {} + inline ByteString(value_type const *ch): std::basic_string(ch) {} + template inline ByteString(It first, It last): std::basic_string(first, last) {} + inline ByteString(ByteString const &other): std::basic_string(other) {} + inline ByteString(ByteString &&other): std::basic_string(std::move(other)) {} + + ByteString &operator=(ByteString const &other) { std::basic_string::operator=(other); return *this; } + ByteString &operator=(ByteString &&other) { std::basic_string::operator=(std::move(other)); return *this; } + + class ConversionError : public std::runtime_error + { + static std::string formatError(value_type const *at, value_type const *upto); + public: + inline ConversionError(value_type const *at, value_type const *upto): std::runtime_error(formatError(at, upto)) {} + inline ConversionError(bool to): std::runtime_error(to ? "Could not convert to UTF-8" : "Could not convert from UTF-8") {} + }; + + String FromUtf8(bool ignoreError = true) const; + inline String FromAscii() const; +}; + +class String : public std::basic_string +{ +public: + inline String(): std::basic_string() {} + inline String(size_type count, value_type ch): std::basic_string(count, ch) {} + inline String(value_type const *ch, size_type count): std::basic_string(ch, count) {} + inline String(value_type const *ch): std::basic_string(ch) {} + template inline String(It first, It last): std::basic_string(first, last) {} + inline String(String const &other): std::basic_string(other) {} + inline String(String &&other): std::basic_string(std::move(other)) {} + + String &operator=(String const &other) { std::basic_string::operator=(other); return *this; } + String &operator=(String &&other) { std::basic_string::operator=(std::move(other)); return *this; } + + template inline String(ByteString::value_type const (&ch)[N]): std::basic_string(ByteString(ch, N).FromAscii()) {} + + ByteString ToUtf8() const; +}; + +inline String ByteString::FromAscii() const +{ + String destination = String(size(), String::value_type()); + for(size_t i = 0; i < size(); i++) + destination[i] = typename String::value_type(operator[](i)); + return destination; +} +#endif From ff27d694242c2de2d85ccfbed953186bb38a0628 Mon Sep 17 00:00:00 2001 From: mniip Date: Mon, 30 Apr 2018 21:13:24 +0300 Subject: [PATCH 05/27] Switch from std::string to String/ByteString in most of the code Also switch SimulationData from weird arrays to std::vector --- src/Format.cpp | 16 +- src/Format.h | 32 +- src/Misc.h | 2 - src/Platform.cpp | 8 +- src/Platform.h | 6 +- src/PowderToy.h | 5 +- src/PowderToyRenderer.cpp | 25 +- src/PowderToySDL.cpp | 74 ++-- src/Update.cpp | 10 +- src/client/Client.cpp | 385 ++++++++++-------- src/client/Client.h | 106 ++--- src/client/ClientListener.h | 2 +- src/client/Download.cpp | 16 +- src/client/Download.h | 22 +- src/client/GameSave.cpp | 35 +- src/client/GameSave.h | 16 +- src/client/HTTP.cpp | 25 +- src/client/HTTP.h | 8 +- src/client/SaveFile.cpp | 16 +- src/client/SaveFile.h | 22 +- src/client/SaveInfo.cpp | 26 +- src/client/SaveInfo.h | 30 +- src/client/User.h | 10 +- src/client/UserInfo.h | 12 +- src/client/requestbroker/APIRequest.cpp | 14 +- src/client/requestbroker/APIRequest.h | 8 +- src/client/requestbroker/ImageRequest.cpp | 6 +- src/client/requestbroker/ImageRequest.h | 4 +- src/client/requestbroker/RequestBroker.cpp | 11 +- src/client/requestbroker/RequestBroker.h | 8 +- src/client/requestbroker/WebRequest.cpp | 14 +- src/client/requestbroker/WebRequest.h | 8 +- src/common/String.cpp | 132 ++++++ src/common/String.h | 57 ++- src/debug/DebugLines.cpp | 16 +- src/debug/DebugParts.cpp | 7 +- src/debug/ElementPopulation.cpp | 6 +- src/debug/ParticleDebug.cpp | 5 +- src/graphics/DrawMethodsDef.inc | 7 +- src/graphics/Graphics.cpp | 54 ++- src/graphics/Graphics.h | 29 +- src/graphics/OpenGLDrawMethods.inl | 16 +- src/graphics/RasterDrawMethods.inl | 18 +- src/graphics/Renderer.cpp | 18 +- src/graphics/Renderer.h | 9 +- src/gui/colourpicker/ColourPickerActivity.cpp | 4 +- src/gui/colourpicker/ColourPickerActivity.h | 2 +- src/gui/console/ConsoleCommand.h | 10 +- src/gui/console/ConsoleController.cpp | 4 +- src/gui/console/ConsoleController.h | 6 +- src/gui/console/ConsoleModel.cpp | 4 +- src/gui/dialogues/ConfirmPrompt.cpp | 6 +- src/gui/dialogues/ConfirmPrompt.h | 8 +- src/gui/dialogues/ErrorMessage.cpp | 4 +- src/gui/dialogues/ErrorMessage.h | 4 +- src/gui/dialogues/InformationMessage.cpp | 2 +- src/gui/dialogues/InformationMessage.h | 2 +- src/gui/dialogues/LegacyDialogues.h | 8 +- src/gui/dialogues/TextPrompt.cpp | 12 +- src/gui/dialogues/TextPrompt.h | 6 +- .../elementsearch/ElementSearchActivity.cpp | 17 +- src/gui/elementsearch/ElementSearchActivity.h | 7 +- src/gui/filebrowser/FileBrowserActivity.cpp | 33 +- src/gui/filebrowser/FileBrowserActivity.h | 10 +- src/gui/font/FontEditor.cpp | 35 +- src/gui/font/FontEditor.h | 14 +- src/gui/game/DecorationTool.h | 2 +- src/gui/game/Favorite.cpp | 12 +- src/gui/game/Favorite.h | 12 +- src/gui/game/GameController.cpp | 52 +-- src/gui/game/GameController.h | 14 +- src/gui/game/GameModel.cpp | 36 +- src/gui/game/GameModel.h | 22 +- src/gui/game/GameModelException.h | 9 +- src/gui/game/GameView.cpp | 127 +++--- src/gui/game/GameView.h | 16 +- src/gui/game/Menu.h | 17 +- src/gui/game/Notification.h | 6 +- src/gui/game/PropertyTool.cpp | 39 +- src/gui/game/QuickOption.h | 16 +- src/gui/game/RenderPreset.h | 4 +- src/gui/game/SignTool.cpp | 12 +- src/gui/game/Tool.cpp | 16 +- src/gui/game/Tool.h | 29 +- src/gui/game/ToolButton.cpp | 4 +- src/gui/game/ToolButton.h | 4 +- src/gui/interface/AvatarButton.cpp | 2 +- src/gui/interface/AvatarButton.h | 10 +- src/gui/interface/Button.cpp | 10 +- src/gui/interface/Button.h | 18 +- src/gui/interface/Checkbox.cpp | 6 +- src/gui/interface/Checkbox.h | 12 +- src/gui/interface/Component.cpp | 4 +- src/gui/interface/Component.h | 4 +- src/gui/interface/ContextMenu.cpp | 2 +- src/gui/interface/ContextMenu.h | 6 +- src/gui/interface/CopyTextButton.cpp | 4 +- src/gui/interface/CopyTextButton.h | 2 +- src/gui/interface/DropDown.cpp | 18 +- src/gui/interface/DropDown.h | 14 +- src/gui/interface/Label.cpp | 61 ++- src/gui/interface/Label.h | 24 +- src/gui/interface/ProgressBar.cpp | 10 +- src/gui/interface/ProgressBar.h | 8 +- src/gui/interface/RichLabel.cpp | 30 +- src/gui/interface/RichLabel.h | 16 +- src/gui/interface/SaveButton.cpp | 28 +- src/gui/interface/SaveButton.h | 10 +- src/gui/interface/Textbox.cpp | 66 +-- src/gui/interface/Textbox.h | 14 +- src/gui/interface/Window.h | 4 +- .../localbrowser/LocalBrowserController.cpp | 18 +- src/gui/localbrowser/LocalBrowserController.h | 2 +- src/gui/localbrowser/LocalBrowserModel.cpp | 4 +- src/gui/localbrowser/LocalBrowserModel.h | 12 +- .../localbrowser/LocalBrowserModelException.h | 9 +- src/gui/localbrowser/LocalBrowserView.cpp | 9 +- src/gui/login/LoginController.cpp | 2 +- src/gui/login/LoginController.h | 4 +- src/gui/login/LoginModel.cpp | 4 +- src/gui/login/LoginModel.h | 8 +- src/gui/login/LoginView.cpp | 4 +- src/gui/options/OptionsView.cpp | 34 +- src/gui/preview/Comment.h | 10 +- src/gui/preview/PreviewController.cpp | 9 +- src/gui/preview/PreviewController.h | 4 +- src/gui/preview/PreviewModel.cpp | 30 +- src/gui/preview/PreviewModelException.h | 8 +- src/gui/preview/PreviewView.cpp | 27 +- src/gui/preview/PreviewView.h | 10 +- src/gui/profile/ProfileActivity.cpp | 6 +- src/gui/profile/ProfileActivity.h | 6 +- src/gui/render/RenderView.cpp | 4 +- src/gui/render/RenderView.h | 4 +- src/gui/save/LocalSaveActivity.cpp | 10 +- src/gui/save/LocalSaveActivity.h | 2 +- src/gui/save/ServerSaveActivity.cpp | 12 +- src/gui/save/ServerSaveActivity.h | 2 +- src/gui/search/SearchController.cpp | 33 +- src/gui/search/SearchController.h | 6 +- src/gui/search/SearchModel.cpp | 10 +- src/gui/search/SearchModel.h | 22 +- src/gui/search/SearchView.cpp | 24 +- src/gui/search/SearchView.h | 2 +- src/gui/tags/TagsController.cpp | 4 +- src/gui/tags/TagsController.h | 4 +- src/gui/tags/TagsModel.cpp | 12 +- src/gui/tags/TagsModel.h | 6 +- src/gui/tags/TagsModelException.h | 8 +- src/gui/tags/TagsView.cpp | 16 +- src/gui/update/UpdateActivity.cpp | 9 +- src/lua/CommandInterface.cpp | 11 +- src/lua/CommandInterface.h | 14 +- src/lua/LegacyLuaAPI.cpp | 69 ++-- src/lua/LuaButton.cpp | 10 +- src/lua/LuaCheckbox.cpp | 8 +- src/lua/LuaLabel.cpp | 6 +- src/lua/LuaProgressBar.cpp | 6 +- src/lua/LuaScriptHelper.h | 4 +- src/lua/LuaScriptInterface.cpp | 179 ++++---- src/lua/LuaScriptInterface.h | 6 +- src/lua/LuaSlider.cpp | 2 +- src/lua/LuaTextbox.cpp | 10 +- src/lua/LuaWindow.cpp | 28 +- src/lua/TPTSTypes.cpp | 17 +- src/lua/TPTSTypes.h | 20 +- src/lua/TPTScriptInterface.cpp | 106 +++-- src/lua/TPTScriptInterface.h | 24 +- src/powdertoyjava/PowderToyJava.cpp | 2 - src/simulation/GOLMenu.h | 4 +- src/simulation/MenuSection.h | 4 +- src/simulation/Sign.cpp | 11 +- src/simulation/Sign.h | 12 +- src/simulation/Simulation.cpp | 36 +- src/simulation/Simulation.h | 14 +- src/simulation/SimulationData.cpp | 48 +-- src/simulation/SimulationData.h | 13 +- src/simulation/StorageClasses.h | 1 - src/simulation/StructProperty.h | 6 +- src/simulation/WallType.h | 7 +- src/simulation/elements/Element.h | 6 +- src/simulation/elements/LIFE.cpp | 6 +- src/simulation/simtools/SimTool.h | 6 +- src/tasks/Task.cpp | 24 +- src/tasks/Task.h | 18 +- src/tasks/TaskWindow.cpp | 9 +- src/tasks/TaskWindow.h | 7 +- 187 files changed, 1837 insertions(+), 1713 deletions(-) diff --git a/src/Format.cpp b/src/Format.cpp index 5ab9764f5..d06fc253e 100644 --- a/src/Format.cpp +++ b/src/Format.cpp @@ -1,6 +1,6 @@ #include -#include +#include "common/String.h" #include #include #include @@ -9,7 +9,7 @@ #include "Format.h" #include "graphics/Graphics.h" -std::string format::URLEncode(std::string source) +ByteString format::URLEncode(ByteString source) { char * src = (char *)source.c_str(); char * dst = new char[(source.length()*3)+2]; @@ -33,12 +33,12 @@ std::string format::URLEncode(std::string source) } *d = 0; - std::string finalString(dst); + ByteString finalString(dst); delete[] dst; return finalString; } -std::string format::UnixtimeToDate(time_t unixtime, std::string dateFormat) +ByteString format::UnixtimeToDate(time_t unixtime, ByteString dateFormat) { struct tm * timeData; char buffer[128]; @@ -46,10 +46,10 @@ std::string format::UnixtimeToDate(time_t unixtime, std::string dateFormat) timeData = localtime(&unixtime); strftime(buffer, 128, dateFormat.c_str(), timeData); - return std::string(buffer); + return ByteString(buffer); } -std::string format::UnixtimeToDateMini(time_t unixtime) +ByteString format::UnixtimeToDateMini(time_t unixtime) { time_t currentTime = time(NULL); struct tm currentTimeData = *localtime(¤tTime); @@ -69,7 +69,7 @@ std::string format::UnixtimeToDateMini(time_t unixtime) } } -std::string format::CleanString(std::string dirtyString, bool ascii, bool color, bool newlines, bool numeric) +String format::CleanString(String dirtyString, bool ascii, bool color, bool newlines, bool numeric) { for (size_t i = 0; i < dirtyString.size(); i++) { @@ -226,7 +226,7 @@ struct PNGChunk //char[4] CRC(); - PNGChunk(int length, std::string name) + PNGChunk(int length, ByteString name) { if (name.length()!=4) throw std::runtime_error("Invalid chunk name"); diff --git a/src/Format.h b/src/Format.h index 388f82463..19cecf848 100644 --- a/src/Format.h +++ b/src/Format.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "common/String.h" #include class VideoBuffer; @@ -9,24 +9,38 @@ namespace format { const static char hex[] = "0123456789ABCDEF"; - template std::string NumberToString(T number) + template ByteString NumberToByteString(T number) { - std::stringstream ss; + ByteString::Stream ss; ss << number; return ss.str(); } - template T StringToNumber(const std::string & text) + template String NumberToString(T number) { - std::stringstream ss(text); + String::Stream ss; + ss << number; + return ss.str(); + } + + template T ByteStringToNumber(const ByteString & text) + { + ByteString::Stream ss(text); T number; return (ss >> number)?number:0; } - std::string URLEncode(std::string value); - std::string UnixtimeToDate(time_t unixtime, std::string dateFomat = "%d %b %Y"); - std::string UnixtimeToDateMini(time_t unixtime); - std::string CleanString(std::string dirtyString, bool ascii, bool color, bool newlines, bool numeric = false); + template T StringToNumber(const String & text) + { + String::Stream ss(text); + T number; + return (ss >> number)?number:0; + } + + ByteString URLEncode(ByteString value); + ByteString UnixtimeToDate(time_t unixtime, ByteString dateFomat = "%d %b %Y"); + ByteString UnixtimeToDateMini(time_t unixtime); + String CleanString(String dirtyString, bool ascii, bool color, bool newlines, bool numeric = false); std::vector VideoBufferToPNG(const VideoBuffer & vidBuf); std::vector VideoBufferToBMP(const VideoBuffer & vidBuf); std::vector VideoBufferToPPM(const VideoBuffer & vidBuf); diff --git a/src/Misc.h b/src/Misc.h index 9ea14f160..9b876af62 100644 --- a/src/Misc.h +++ b/src/Misc.h @@ -2,8 +2,6 @@ #define UTILS_H #include #include -#include -#include #include //Linear interpolation diff --git a/src/Platform.cpp b/src/Platform.cpp index e6c50a714..0b1f37a6a 100644 --- a/src/Platform.cpp +++ b/src/Platform.cpp @@ -20,9 +20,9 @@ namespace Platform { -std::string ExecutableName() +ByteString ExecutableName() { - std::string ret; + ByteString ret; #if defined(WIN) char *name = (char *)malloc(64); DWORD max = 64, res; @@ -73,7 +73,7 @@ std::string ExecutableName() void DoRestart() { - std::string exename = ExecutableName(); + ByteString exename = ExecutableName(); if (exename.length()) { #ifdef WIN @@ -85,7 +85,7 @@ void DoRestart() exit(-1); } -void OpenURI(std::string uri) +void OpenURI(ByteString uri) { #if defined(WIN) ShellExecute(0, "OPEN", uri.c_str(), NULL, NULL, 0); diff --git a/src/Platform.h b/src/Platform.h index ecbdbf115..3bceb1438 100644 --- a/src/Platform.h +++ b/src/Platform.h @@ -1,14 +1,14 @@ #ifndef PLATFORM_H #define PLATFORM_H -#include +#include "common/String.h" namespace Platform { - std::string ExecutableName(); + ByteString ExecutableName(); void DoRestart(); - void OpenURI(std::string uri); + void OpenURI(ByteString uri); void Millisleep(long int t); long unsigned int GetTime(); diff --git a/src/PowderToy.h b/src/PowderToy.h index a76a95b50..aa20e943d 100644 --- a/src/PowderToy.h +++ b/src/PowderToy.h @@ -1,9 +1,8 @@ #pragma once -#include void EngineProcess(); -void ClipboardPush(std::string text); -std::string ClipboardPull(); +void ClipboardPush(ByteString text); +ByteString ClipboardPull(); int GetModifiers(); bool LoadWindowPosition(int scale); void SetCursorEnabled(int enabled); diff --git a/src/PowderToyRenderer.cpp b/src/PowderToyRenderer.cpp index c019beeb3..aaf5176dc 100644 --- a/src/PowderToyRenderer.cpp +++ b/src/PowderToyRenderer.cpp @@ -2,11 +2,10 @@ #include #include -#include -#include #include #include +#include "common/String.h" #include "Config.h" #include "Format.h" #include "gui/interface/Engine.h" @@ -18,16 +17,16 @@ void EngineProcess() {} -void ClipboardPush(std::string) {} -std::string ClipboardPull() { return ""; } +void ClipboardPush(ByteString) {} +ByteString ClipboardPull() { return ""; } int GetModifiers() { return 0; } void SetCursorEnabled(int enabled) {} unsigned int GetTicks() { return 0; } -void readFile(std::string filename, std::vector & storage) +void readFile(ByteString filename, std::vector & storage) { std::ifstream fileStream; - fileStream.open(std::string(filename).c_str(), std::ios::binary); + fileStream.open(filename.c_str(), std::ios::binary); if(fileStream.is_open()) { fileStream.seekg(0, std::ios::end); @@ -45,10 +44,10 @@ void readFile(std::string filename, std::vector & storage) } } -void writeFile(std::string filename, std::vector & fileData) +void writeFile(ByteString filename, std::vector & fileData) { std::ofstream fileStream; - fileStream.open(std::string(filename).c_str(), std::ios::binary); + fileStream.open(filename.c_str(), std::ios::binary); if(fileStream.is_open()) { fileStream.write(&fileData[0], fileData.size()); @@ -59,13 +58,13 @@ void writeFile(std::string filename, std::vector & fileData) int main(int argc, char *argv[]) { ui::Engine * engine; - std::string outputPrefix, inputFilename; + ByteString outputPrefix, inputFilename; std::vector inputFile; - std::string ppmFilename, ptiFilename, ptiSmallFilename, pngFilename, pngSmallFilename; + ByteString ppmFilename, ptiFilename, ptiSmallFilename, pngFilename, pngSmallFilename; std::vector ppmFile, ptiFile, ptiSmallFile, pngFile, pngSmallFile; - inputFilename = std::string(argv[1]); - outputPrefix = std::string(argv[2]); + inputFilename = argv[1]; + outputPrefix = argv[2]; ppmFilename = outputPrefix+".ppm"; ptiFilename = outputPrefix+".pti"; @@ -88,7 +87,7 @@ int main(int argc, char *argv[]) catch (ParseException e) { //Render the save again later or something? I don't know - if (e.what() == "Save from newer version") + if (ByteString(e.what()).FromUtf8() == "Save from newer version") throw e; } diff --git a/src/PowderToySDL.cpp b/src/PowderToySDL.cpp index 45d3fed79..086dda513 100644 --- a/src/PowderToySDL.cpp +++ b/src/PowderToySDL.cpp @@ -1,7 +1,7 @@ #ifdef USE_SDL #include -#include +#include "common/String.h" #include #include #ifdef WIN @@ -18,9 +18,9 @@ #endif #include -#include -#include +#include "common/String.h" #include "Config.h" +#include "common/String.h" #include "graphics/Graphics.h" #if defined(LIN) #include "icon.h" @@ -68,7 +68,7 @@ SDL_SysWMinfo sdl_wminfo; Atom XA_CLIPBOARD, XA_TARGETS, XA_UTF8_STRING; #endif -std::string clipboardText = ""; +ByteString clipboardText = ""; int desktopWidth = 1280, desktopHeight = 1024; @@ -76,7 +76,7 @@ SDL_Surface * sdl_scrn; int scale = 1; bool fullscreen = false; -void ClipboardPush(std::string text) +void ClipboardPush(ByteString text) { clipboardText = text; #ifdef MACOSX @@ -110,11 +110,11 @@ void ClipboardPush(std::string text) void EventProcess(SDL_Event event); -std::string ClipboardPull() +ByteString ClipboardPull() { #ifdef MACOSX const char *text = readClipboard(); - return text ? std::string(text) : ""; + return text ? ByteString(text).FromUtf8() : ""; #elif defined(WIN) if (OpenClipboard(NULL)) { @@ -125,10 +125,10 @@ std::string ClipboardPull() glbuffer = (char*)GlobalLock(cbuffer); GlobalUnlock(cbuffer); CloseClipboard(); - return glbuffer ? std::string(glbuffer) : ""; + return glbuffer ? ByteString(glbuffer) : ""; } #elif defined(LIN) && defined(SDL_VIDEO_DRIVER_X11) - std::string text = ""; + ByteString text = ""; Window selectionOwner; sdl_wminfo.info.x11.lock_func(); selectionOwner = XGetSelectionOwner(sdl_wminfo.info.x11.display, XA_CLIPBOARD); @@ -168,7 +168,7 @@ std::string ClipboardPull() result = XGetWindowProperty(sdl_wminfo.info.x11.display, sdl_wminfo.info.x11.window, XA_CLIPBOARD, 0, bytesLeft, 0, AnyPropertyType, &type, &format, &len, &bytesLeft, &data); if (result == Success) { - text = data ? (const char*)data : ""; + text = data ? ByteString((char const *)data) : ""; XFree(data); } else @@ -526,9 +526,9 @@ unsigned int GetTicks() return SDL_GetTicks(); } -std::map readArguments(int argc, char * argv[]) +std::map readArguments(int argc, char * argv[]) { - std::map arguments; + std::map arguments; //Defaults arguments["scale"] = ""; @@ -545,12 +545,12 @@ std::map readArguments(int argc, char * argv[]) { if (!strncmp(argv[i], "scale:", 6) && argv[i]+6) { - arguments["scale"] = std::string(argv[i]+6); + arguments["scale"] = argv[i]+6; } else if (!strncmp(argv[i], "proxy:", 6)) { if(argv[i]+6) - arguments["proxy"] = std::string(argv[i]+6); + arguments["proxy"] = argv[i]+6; else arguments["proxy"] = "false"; } @@ -572,17 +572,17 @@ std::map readArguments(int argc, char * argv[]) } else if (!strncmp(argv[i], "open", 5) && i+1g->fillrect(0, 0, engine->GetWidth(), engine->GetHeight(), 17, 114, 169, 210); - std::string errorTitle = "ERROR"; - std::string errorDetails = "Details: " + std::string(detailMessage); - std::string errorHelp = "An unrecoverable fault has occurred, please report the error by visiting the website below\n" + String errorTitle = "ERROR"; + String errorDetails = "Details: " + detailMessage; + String errorHelp = "An unrecoverable fault has occurred, please report the error by visiting the website below\n" "http://" SERVER; int currentY = 0, width, height; int errorWidth = 0; - Graphics::textsize(errorHelp.c_str(), errorWidth, height); + Graphics::textsize(errorHelp, errorWidth, height); engine->g->drawtext((engine->GetWidth()/2)-(errorWidth/2), ((engine->GetHeight()/2)-100) + currentY, errorTitle.c_str(), 255, 255, 255, 255); - Graphics::textsize(errorTitle.c_str(), width, height); + Graphics::textsize(errorTitle, width, height); currentY += height + 4; engine->g->drawtext((engine->GetWidth()/2)-(errorWidth/2), ((engine->GetHeight()/2)-100) + currentY, errorDetails.c_str(), 255, 255, 255, 255); - Graphics::textsize(errorTitle.c_str(), width, height); + Graphics::textsize(errorTitle, width, height); currentY += height + 4; engine->g->drawtext((engine->GetWidth()/2)-(errorWidth/2), ((engine->GetHeight()/2)-100) + currentY, errorHelp.c_str(), 255, 255, 255, 255); - Graphics::textsize(errorTitle.c_str(), width, height); + Graphics::textsize(errorTitle, width, height); currentY += height + 4; //Death loop @@ -985,7 +985,7 @@ int main(int argc, char * argv[]) currentHeight = WINDOWH; - std::map arguments = readArguments(argc, argv); + std::map arguments = readArguments(argc, argv); if(arguments["ddir"].length()) #ifdef WIN @@ -1009,11 +1009,11 @@ int main(int argc, char * argv[]) if(arguments["scale"].length()) { - tempScale = format::StringToNumber(arguments["scale"]); + tempScale = format::ByteStringToNumber(arguments["scale"]); Client::Ref().SetPref("Scale", tempScale); } - std::string proxyString = ""; + ByteString proxyString = ""; if(arguments["proxy"].length()) { if(arguments["proxy"] == "false") @@ -1029,7 +1029,7 @@ int main(int argc, char * argv[]) } else if(Client::Ref().GetPrefString("Proxy", "").length()) { - proxyString = (Client::Ref().GetPrefString("Proxy", "")); + proxyString = (Client::Ref().GetPrefByteString("Proxy", "")); } Client::Ref().Initialise(proxyString); @@ -1140,7 +1140,7 @@ int main(int argc, char * argv[]) } catch(std::exception & e) { - new ErrorMessage("Error", "Could not open save file:\n"+std::string(e.what())) ; + new ErrorMessage("Error", "Could not open save file:\n" + ByteString(e.what()).FromUtf8()) ; } } else @@ -1163,16 +1163,16 @@ int main(int argc, char * argv[]) else blit(engine->g->vid); #endif - std::string ptsaveArg = arguments["ptsave"]; + ByteString ptsaveArg = arguments["ptsave"]; try { if (ptsaveArg.find("ptsave:")) throw std::runtime_error("Invalid save link"); - std::string saveIdPart = ""; + ByteString saveIdPart = ""; int saveId; size_t hashPos = ptsaveArg.find('#'); - if (hashPos != std::string::npos) + if (hashPos != ByteString::npos) { saveIdPart = ptsaveArg.substr(7, hashPos-7); } @@ -1185,7 +1185,7 @@ int main(int argc, char * argv[]) #ifdef DEBUG std::cout << "Got Ptsave: id: " << saveIdPart << std::endl; #endif - saveId = format::StringToNumber(saveIdPart); + saveId = format::ByteStringToNumber(saveIdPart); if (!saveId) throw std::runtime_error("Invalid Save ID"); @@ -1194,7 +1194,7 @@ int main(int argc, char * argv[]) throw std::runtime_error("Could not load save info"); std::vector saveData = Client::Ref().GetSaveData(saveId, 0); if (!saveData.size()) - throw std::runtime_error("Could not load save\n" + Client::Ref().GetLastError()); + throw std::runtime_error(("Could not load save\n" + Client::Ref().GetLastError()).ToUtf8()); GameSave * newGameSave = new GameSave(saveData); newSave->SetGameSave(newGameSave); @@ -1203,7 +1203,7 @@ int main(int argc, char * argv[]) } catch (std::exception & e) { - new ErrorMessage("Error", e.what()); + new ErrorMessage("Error", ByteString(e.what()).FromUtf8()); } } diff --git a/src/Update.cpp b/src/Update.cpp index 853b3d395..a00827f0f 100644 --- a/src/Update.cpp +++ b/src/Update.cpp @@ -26,7 +26,7 @@ // returns 1 on failure, 0 on success int update_start(char *data, unsigned int len) { - std::string exeName = Platform::ExecutableName(), updName; + ByteString exeName = Platform::ExecutableName(), updName; FILE *f; if (!exeName.length()) @@ -34,7 +34,7 @@ int update_start(char *data, unsigned int len) #ifdef WIN updName = exeName; - std::string extension = exeName.substr(exeName.length() - 4); + ByteString extension = exeName.substr(exeName.length() - 4); if (extension == ".exe") updName = exeName.substr(0, exeName.length() - 4); updName = updName + "_upd.exe"; @@ -95,7 +95,7 @@ int update_start(char *data, unsigned int len) int update_finish() { #ifdef WIN - std::string exeName = Platform::ExecutableName(), updName; + ByteString exeName = Platform::ExecutableName(), updName; int timeout = 5, err; #ifdef DEBUG @@ -103,7 +103,7 @@ int update_finish() #endif updName = exeName; - std::string extension = exeName.substr(exeName.length() - 4); + ByteString extension = exeName.substr(exeName.length() - 4); if (extension == ".exe") updName = exeName.substr(0, exeName.length() - 4); updName = updName + "_upd.exe"; @@ -122,7 +122,7 @@ int update_finish() #endif // Old versions of powder toy name their update files with _update.exe, delete that upgrade file here updName = exeName; - std::string extension = exeName.substr(exeName.length() - 4); + ByteString extension = exeName.substr(exeName.length() - 4); if (extension == ".exe") updName = exeName.substr(0, exeName.length() - 4); updName = updName + "_update.exe"; diff --git a/src/client/Client.cpp b/src/client/Client.cpp index f2bccb381..3b7eaf44b 100644 --- a/src/client/Client.cpp +++ b/src/client/Client.cpp @@ -1,7 +1,5 @@ #include #include -#include -#include #include #include #include @@ -26,6 +24,7 @@ #include #endif +#include "common/String.h" #include "Config.h" #include "Format.h" #include "Client.h" @@ -92,10 +91,10 @@ Client::Client(): preferences.clear(); configFile >> preferences; int ID = preferences["User"]["ID"].asInt(); - std::string Username = preferences["User"]["Username"].asString(); - std::string SessionID = preferences["User"]["SessionID"].asString(); - std::string SessionKey = preferences["User"]["SessionKey"].asString(); - std::string Elevation = preferences["User"]["Elevation"].asString(); + ByteString Username = preferences["User"]["Username"].asString(); + ByteString SessionID = preferences["User"]["SessionID"].asString(); + ByteString SessionKey = preferences["User"]["SessionKey"].asString(); + ByteString Elevation = preferences["User"]["Elevation"].asString(); authUser.UserID = ID; authUser.Username = Username; @@ -119,7 +118,7 @@ Client::Client(): firstRun = true; } -void Client::Initialise(std::string proxyString) +void Client::Initialise(ByteString proxyString) { if (GetPrefBool("version.update", false)) { @@ -151,7 +150,7 @@ void Client::Initialise(std::string proxyString) if (authUser.UserID) { - std::string idTempString = format::NumberToString(authUser.UserID); + ByteString idTempString = format::NumberToByteString(authUser.UserID); char *id = new char[idTempString.length() + 1]; std::strcpy (id, idTempString.c_str()); char *session = new char[authUser.SessionID.length() + 1]; @@ -183,7 +182,7 @@ bool Client::DoInstallation() int returnval; LONG rresult; HKEY newkey; - std::string currentfilename2 = Platform::ExecutableName(); + ByteString currentfilename2 = Platform::ExecutableName(); // this isn't necessary but I don't feel like c++ifying this code right now const char *currentfilename = currentfilename2.c_str(); char *iconname = NULL; @@ -350,7 +349,7 @@ bool Client::DoInstallation() #include "icondoc.h" int success = 1; - std::string filename = Platform::ExecutableName(), pathname = filename.substr(0, filename.rfind('/')); + ByteString filename = Platform::ExecutableName(), pathname = filename.substr(0, filename.rfind('/')); for (size_t i = 0; i < filename.size(); i++) { if (filename[i] == '\'') @@ -387,7 +386,7 @@ bool Client::DoInstallation() "NoDisplay=true\n" "Categories=Game;Simulation\n" "Icon=powdertoy.png\n"; - std::stringstream protocolfiledata; + ByteString::Stream protocolfiledata; protocolfiledata << protocolfiledata_tmp << "Exec=" << filename << " ptsave %u\nPath=" << pathname << "\n"; f = fopen("powdertoy-tpt-ptsave.desktop", "wb"); if (!f) @@ -405,7 +404,7 @@ bool Client::DoInstallation() "NoDisplay=true\n" "Categories=Game;Simulation\n" "Icon=powdertoy.png\n"; - std::stringstream desktopopenfiledata; + ByteString::Stream desktopopenfiledata; desktopopenfiledata << desktopopenfiledata_tmp << "Exec=" << filename << " open %f\nPath=" << pathname << "\n"; f = fopen("powdertoy-tpt-open.desktop", "wb"); if (!f) @@ -424,7 +423,7 @@ bool Client::DoInstallation() "Comment=Physics sandbox game\n" "Categories=Game;Simulation\n" "Icon=powdertoy.png\n"; - std::stringstream desktopfiledata; + ByteString::Stream desktopfiledata; desktopfiledata << desktopfiledata_tmp << "Exec=" << filename << "\nPath=" << pathname << "\n"; f = fopen("powdertoy-tpt.desktop", "wb"); if (!f) @@ -467,7 +466,7 @@ bool Client::DoInstallation() #endif } -void Client::SetProxy(std::string proxy) +void Client::SetProxy(ByteString proxy) { http_done(); if(proxy.length()) @@ -476,38 +475,38 @@ void Client::SetProxy(std::string proxy) http_init(NULL); } -std::vector Client::DirectorySearch(std::string directory, std::string search, std::string extension) +std::vector Client::DirectorySearch(ByteString directory, ByteString search, ByteString extension) { - std::vector extensions; + std::vector extensions; extensions.push_back(extension); - for (std::string::iterator iter = search.begin(); iter != search.end(); ++iter) + for (ByteString::iterator iter = search.begin(); iter != search.end(); ++iter) *iter = toupper(*iter); return DirectorySearch(directory, search, extensions); } -std::vector Client::DirectorySearch(std::string directory, std::string search, std::vector extensions) +std::vector Client::DirectorySearch(ByteString directory, ByteString search, std::vector extensions) { //Get full file listing //Normalise directory string, ensure / or \ is present if(*directory.rbegin() != '/' && *directory.rbegin() != '\\') directory += PATH_SEP; - std::vector directoryList; + std::vector directoryList; #if defined(WIN) && !defined(__GNUC__) //Windows struct _finddata_t currentFile; intptr_t findFileHandle; - std::string fileMatch = directory + "*.*"; + ByteString fileMatch = directory + "*.*"; findFileHandle = _findfirst(fileMatch.c_str(), ¤tFile); if (findFileHandle == -1L) { #ifdef DEBUG printf("Unable to open directory: %s\n", directory.c_str()); #endif - return std::vector(); + return std::vector(); } do { - std::string currentFileName = std::string(currentFile.name); + ByteString currentFileName = ByteString(currentFile.name); if(currentFileName.length()>4) directoryList.push_back(directory+currentFileName); } @@ -522,23 +521,23 @@ std::vector Client::DirectorySearch(std::string directory, std::str #ifdef DEBUG printf("Unable to open directory: %s\n", directory.c_str()); #endif - return std::vector(); + return std::vector(); } while ((directoryEntry = readdir(directoryHandle))) { - std::string currentFileName = std::string(directoryEntry->d_name); + ByteString currentFileName = ByteString(directoryEntry->d_name); if(currentFileName.length()>4) directoryList.push_back(directory+currentFileName); } closedir(directoryHandle); #endif - std::vector searchResults; - for(std::vector::iterator iter = directoryList.begin(), end = directoryList.end(); iter != end; ++iter) + std::vector searchResults; + for(std::vector::iterator iter = directoryList.begin(), end = directoryList.end(); iter != end; ++iter) { - std::string filename = *iter, tempfilename = *iter; + ByteString filename = *iter, tempfilename = *iter; bool extensionMatch = !extensions.size(); - for(std::vector::iterator extIter = extensions.begin(), extEnd = extensions.end(); extIter != extEnd; ++extIter) + for(std::vector::iterator extIter = extensions.begin(), extEnd = extensions.end(); extIter != extEnd; ++extIter) { size_t filenameLength = filename.length()-(*extIter).length(); if(filename.find(*extIter, filenameLength) == filenameLength) @@ -548,10 +547,10 @@ std::vector Client::DirectorySearch(std::string directory, std::str break; } } - for (std::string::iterator iter = tempfilename.begin(); iter != tempfilename.end(); ++iter) + for (ByteString::iterator iter = tempfilename.begin(); iter != tempfilename.end(); ++iter) *iter = toupper(*iter); bool searchMatch = !search.size(); - if(search.size() && tempfilename.find(search)!=std::string::npos) + if(search.size() && tempfilename.find(search)!=ByteString::npos) searchMatch = true; if(searchMatch && extensionMatch) @@ -571,13 +570,13 @@ int Client::MakeDirectory(const char * dirName) #endif } -bool Client::WriteFile(std::vector fileData, std::string filename) +bool Client::WriteFile(std::vector fileData, ByteString filename) { bool saveError = false; try { std::ofstream fileStream; - fileStream.open(std::string(filename).c_str(), std::ios::binary); + fileStream.open(filename, std::ios::binary); if(fileStream.is_open()) { fileStream.write((char*)&fileData[0], fileData.size()); @@ -594,13 +593,13 @@ bool Client::WriteFile(std::vector fileData, std::string filename return saveError; } -bool Client::FileExists(std::string filename) +bool Client::FileExists(ByteString filename) { bool exists = false; try { std::ifstream fileStream; - fileStream.open(std::string(filename).c_str(), std::ios::binary); + fileStream.open(filename, std::ios::binary); if(fileStream.is_open()) { exists = true; @@ -614,13 +613,13 @@ bool Client::FileExists(std::string filename) return exists; } -bool Client::WriteFile(std::vector fileData, std::string filename) +bool Client::WriteFile(std::vector fileData, ByteString filename) { bool saveError = false; try { std::ofstream fileStream; - fileStream.open(std::string(filename).c_str(), std::ios::binary); + fileStream.open(filename, std::ios::binary); if(fileStream.is_open()) { fileStream.write(&fileData[0], fileData.size()); @@ -637,12 +636,12 @@ bool Client::WriteFile(std::vector fileData, std::string filename) return saveError; } -std::vector Client::ReadFile(std::string filename) +std::vector Client::ReadFile(ByteString filename) { try { std::ifstream fileStream; - fileStream.open(std::string(filename).c_str(), std::ios::binary); + fileStream.open(filename, std::ios::binary); if(fileStream.is_open()) { fileStream.seekg(0, std::ios::end); @@ -671,24 +670,24 @@ std::vector Client::ReadFile(std::string filename) } } -void Client::SetMessageOfTheDay(std::string message) +void Client::SetMessageOfTheDay(String message) { messageOfTheDay = message; notifyMessageOfTheDay(); } -std::string Client::GetMessageOfTheDay() +String Client::GetMessageOfTheDay() { return messageOfTheDay; } -void Client::AddServerNotification(std::pair notification) +void Client::AddServerNotification(std::pair notification) { serverNotifications.push_back(notification); notifyNewNotification(notification); } -std::vector > Client::GetServerNotifications() +std::vector > Client::GetServerNotifications() { return serverNotifications; } @@ -705,7 +704,7 @@ RequestStatus Client::ParseServerReturn(char *result, int status, bool json) return RequestOkay; if (status != 200) { - std::stringstream httperror; + String::Stream httperror; httperror << "HTTP Error " << status << ": " << http_ret_text(status); lastError = httperror.str(); return RequestFailure; @@ -727,7 +726,7 @@ RequestStatus Client::ParseServerReturn(char *result, int status, bool json) int status = root.get("Status", 1).asInt(); if (status != 1) { - lastError = root.get("Error", "Unspecified Error").asString(); + lastError = ByteString(root.get("Error", "Unspecified Error").asString()).FromUtf8(); return RequestFailure; } } @@ -737,12 +736,12 @@ RequestStatus Client::ParseServerReturn(char *result, int status, bool json) if (!strncmp((const char *)result, "Error: ", 7)) { status = atoi(result+7); - std::stringstream httperror; + String::Stream httperror; httperror << "HTTP Error " << status << ": " << http_ret_text(status); lastError = httperror.str(); return RequestFailure; } - lastError = std::string("Could not read response: ") + e.what(); + lastError = "Could not read response: " + ByteString(e.what()).FromUtf8(); return RequestFailure; } } @@ -750,7 +749,7 @@ RequestStatus Client::ParseServerReturn(char *result, int status, bool json) { if (strncmp((const char *)result, "OK", 2)) { - lastError = std::string(result); + lastError = ByteString(result).FromUtf8(); return RequestFailure; } } @@ -808,10 +807,10 @@ bool Client::CheckUpdate(void *updateRequest, bool checkSession) Json::Value notificationsArray = objDocument["Notifications"]; for (Json::UInt j = 0; j < notificationsArray.size(); j++) { - std::string notificationLink = notificationsArray[j]["Link"].asString(); - std::string notificationText = notificationsArray[j]["Text"].asString(); + ByteString notificationLink = notificationsArray[j]["Link"].asString(); + String notificationText = ByteString(notificationsArray[j]["Text"].asString()).FromUtf8(); - std::pair item = std::pair(notificationText, notificationLink); + std::pair item = std::pair(notificationText, notificationLink); AddServerNotification(item); } @@ -819,7 +818,7 @@ bool Client::CheckUpdate(void *updateRequest, bool checkSession) //MOTD if (!usingAltUpdateServer || !checkSession) { - this->messageOfTheDay = objDocument["MessageOfTheDay"].asString(); + this->messageOfTheDay = ByteString(objDocument["MessageOfTheDay"].asString()).FromUtf8(); notifyMessageOfTheDay(); #ifndef IGNORE_UPDATES @@ -830,8 +829,8 @@ bool Client::CheckUpdate(void *updateRequest, bool checkSession) int stableMajor = stableVersion["Major"].asInt(); int stableMinor = stableVersion["Minor"].asInt(); int stableBuild = stableVersion["Build"].asInt(); - std::string stableFile = stableVersion["File"].asString(); - std::string stableChangelog = stableVersion["Changelog"].asString(); + ByteString stableFile = stableVersion["File"].asString(); + String stableChangelog = ByteString(stableVersion["Changelog"].asString()).FromUtf8(); if (stableBuild > BUILD_NUM) { updateAvailable = true; @@ -845,8 +844,8 @@ bool Client::CheckUpdate(void *updateRequest, bool checkSession) int betaMajor = betaVersion["Major"].asInt(); int betaMinor = betaVersion["Minor"].asInt(); int betaBuild = betaVersion["Build"].asInt(); - std::string betaFile = betaVersion["File"].asString(); - std::string betaChangelog = betaVersion["Changelog"].asString(); + ByteString betaFile = betaVersion["File"].asString(); + String betaChangelog = ByteString(betaVersion["Changelog"].asString()).FromUtf8(); if (betaBuild > BUILD_NUM) { updateAvailable = true; @@ -857,8 +856,8 @@ bool Client::CheckUpdate(void *updateRequest, bool checkSession) #if defined(SNAPSHOT) || MOD_ID > 0 Json::Value snapshotVersion = versions["Snapshot"]; int snapshotSnapshot = snapshotVersion["Snapshot"].asInt(); - std::string snapshotFile = snapshotVersion["File"].asString(); - std::string snapshotChangelog = snapshotVersion["Changelog"].asString(); + ByteString snapshotFile = snapshotVersion["File"].asString(); + String snapshotChangelog = ByteString(snapshotVersion["Changelog"].asString()).FromUtf8(); if (snapshotSnapshot > SNAPSHOT_ID) { updateAvailable = true; @@ -914,7 +913,7 @@ void Client::notifyAuthUserChanged() } } -void Client::notifyNewNotification(std::pair notification) +void Client::notifyNewNotification(std::pair notification) { for (std::vector::iterator iterator = listeners.begin(), end = listeners.end(); iterator != end; ++iterator) { @@ -1003,7 +1002,7 @@ RequestStatus Client::UploadSave(SaveInfo & save) int dataStatus; char * data; int dataLength = 0; - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; if (authUser.UserID) { @@ -1031,9 +1030,9 @@ RequestStatus Client::UploadSave(SaveInfo & save) #endif char *saveName = new char[save.GetName().length() + 1]; - std::strcpy (saveName, save.GetName().c_str()); + std::strcpy (saveName, save.GetName().ToUtf8().c_str()); char *saveDescription = new char[save.GetDescription().length() + 1]; - std::strcpy (saveDescription, save.GetDescription().c_str()); + std::strcpy (saveDescription, save.GetDescription().ToUtf8().c_str()); char *userid = new char[userIDStream.str().length() + 1]; std::strcpy (userid, userIDStream.str().c_str()); char *session = new char[authUser.SessionID.length() + 1]; @@ -1058,7 +1057,7 @@ RequestStatus Client::UploadSave(SaveInfo & save) RequestStatus ret = ParseServerReturn(data, dataStatus, false); if (ret == RequestOkay) { - int saveID = format::StringToNumber(data+3); + int saveID = format::ByteStringToNumber(data+3); if (!saveID) { lastError = "Server did not return Save ID"; @@ -1072,9 +1071,9 @@ RequestStatus Client::UploadSave(SaveInfo & save) return ret; } -void Client::MoveStampToFront(std::string stampID) +void Client::MoveStampToFront(ByteString stampID) { - for (std::list::iterator iterator = stampIDs.begin(), end = stampIDs.end(); iterator != end; ++iterator) + for (std::list::iterator iterator = stampIDs.begin(), end = stampIDs.end(); iterator != end; ++iterator) { if((*iterator) == stampID) { @@ -1086,9 +1085,9 @@ void Client::MoveStampToFront(std::string stampID) updateStamps(); } -SaveFile * Client::GetStamp(std::string stampID) +SaveFile * Client::GetStamp(ByteString stampID) { - std::string stampFile = std::string(STAMPS_DIR PATH_SEP + stampID + ".stm"); + ByteString stampFile = ByteString(STAMPS_DIR PATH_SEP + stampID + ".stm"); SaveFile * file = new SaveFile(stampID); if (!FileExists(stampFile)) stampFile = stampID; @@ -1101,20 +1100,20 @@ SaveFile * Client::GetStamp(std::string stampID) } catch (ParseException & e) { - std::cerr << "Client: Invalid stamp file, " << stampID << " " << std::string(e.what()) << std::endl; - file->SetLoadingError(e.what()); + std::cerr << "Client: Invalid stamp file, " << stampID << " " << e.what() << std::endl; + file->SetLoadingError(ByteString(e.what()).FromUtf8()); } } return file; } -void Client::DeleteStamp(std::string stampID) +void Client::DeleteStamp(ByteString stampID) { - for (std::list::iterator iterator = stampIDs.begin(), end = stampIDs.end(); iterator != end; ++iterator) + for (std::list::iterator iterator = stampIDs.begin(), end = stampIDs.end(); iterator != end; ++iterator) { if((*iterator) == stampID) { - std::stringstream stampFilename; + ByteString::Stream stampFilename; stampFilename << STAMPS_DIR; stampFilename << PATH_SEP; stampFilename << stampID; @@ -1128,7 +1127,7 @@ void Client::DeleteStamp(std::string stampID) updateStamps(); } -std::string Client::AddStamp(GameSave * saveData) +ByteString Client::AddStamp(GameSave * saveData) { unsigned t=(unsigned)time(NULL); if (lastStampTime!=t) @@ -1138,12 +1137,12 @@ std::string Client::AddStamp(GameSave * saveData) } else lastStampName++; - std::stringstream saveID; + ByteString::Stream saveID; //sprintf(saveID, "%08x%02x", lastStampTime, lastStampName); saveID << std::setw(8) << std::setfill('0') << std::hex << lastStampTime << std::setw(2) << std::setfill('0') << std::hex << lastStampName; - std::string filename = std::string(STAMPS_DIR PATH_SEP + saveID.str()+".stm").c_str(); + ByteString filename = STAMPS_DIR PATH_SEP + saveID.str() + ".stm"; MakeDirectory(STAMPS_DIR); @@ -1183,8 +1182,8 @@ void Client::updateStamps() MakeDirectory(STAMPS_DIR); std::ofstream stampsStream; - stampsStream.open(std::string(STAMPS_DIR PATH_SEP "stamps.def").c_str(), std::ios::binary); - for (std::list::const_iterator iterator = stampIDs.begin(), end = stampIDs.end(); iterator != end; ++iterator) + stampsStream.open(ByteString(STAMPS_DIR PATH_SEP "stamps.def").c_str(), std::ios::binary); + for (std::list::const_iterator iterator = stampIDs.begin(), end = stampIDs.end(); iterator != end; ++iterator) { stampsStream.write((*iterator).c_str(), 10); } @@ -1205,7 +1204,7 @@ void Client::RescanStamps() { if(strncmp(entry->d_name, "..", 3) && strncmp(entry->d_name, ".", 2) && strstr(entry->d_name, ".stm") && strlen(entry->d_name) == 14) { - stampIDs.push_front(std::string(entry->d_name).substr(0, 10)); + stampIDs.push_front(ByteString(entry->d_name).substr(0, 10)); } } closedir(directory); @@ -1218,19 +1217,19 @@ int Client::GetStampsCount() return stampIDs.size(); } -std::vector Client::GetStamps(int start, int count) +std::vector Client::GetStamps(int start, int count) { int size = (int)stampIDs.size(); if (start+count > size) { if(start > size) - return std::vector(); + return std::vector(); count = size-start; } - std::vector stampRange; + std::vector stampRange; int index = 0; - for (std::list::const_iterator iterator = stampIDs.begin(), end = stampIDs.end(); iterator != end; ++iterator, ++index) + for (std::list::const_iterator iterator = stampIDs.begin(), end = stampIDs.end(); iterator != end; ++iterator, ++index) { if(index>=start && index < start+count) stampRange.push_back(*iterator); @@ -1248,8 +1247,8 @@ RequestStatus Client::ExecVote(int saveID, int direction) if (authUser.UserID) { char * directionText = (char*)(direction==1?"Up":"Down"); - std::string saveIDText = format::NumberToString(saveID); - std::string userIDText = format::NumberToString(authUser.UserID); + ByteString saveIDText = format::NumberToByteString(saveID); + ByteString userIDText = format::NumberToByteString(authUser.UserID); char *id = new char[saveIDText.length() + 1]; std::strcpy(id, saveIDText.c_str()); @@ -1282,7 +1281,7 @@ unsigned char * Client::GetSaveData(int saveID, int saveDate, int & dataLength) int dataStatus; char *data; dataLength = 0; - std::stringstream urlStream; + ByteString::Stream urlStream; if (saveDate) urlStream << "http://" << STATICSERVER << "/" << saveID << "_" << saveDate << ".cps"; else @@ -1315,7 +1314,7 @@ std::vector Client::GetSaveData(int saveID, int saveDate) RequestBroker::Request * Client::GetSaveDataAsync(int saveID, int saveDate) { - std::stringstream urlStream; + ByteString::Stream urlStream; if(saveDate){ urlStream << "http://" << STATICSERVER << "/" << saveID << "_" << saveDate << ".cps"; } else { @@ -1348,13 +1347,13 @@ RequestBroker::Request * Client::SaveUserInfoAsync(UserInfo info) } virtual ~StatusParser() { } }; - std::map postData; - postData.insert(std::pair("Location", info.location)); - postData.insert(std::pair("Biography", info.biography)); + std::map postData; + postData.insert(std::pair("Location", info.location.ToUtf8())); + postData.insert(std::pair("Biography", info.biography.ToUtf8())); return new APIRequest("http://" SERVER "/Profile.json", postData, new StatusParser()); } -RequestBroker::Request * Client::GetUserInfoAsync(std::string username) +RequestBroker::Request * Client::GetUserInfoAsync(ByteString username) { class UserInfoParser: public APIResultParser { @@ -1369,8 +1368,8 @@ RequestBroker::Request * Client::GetUserInfoAsync(std::string username) return new UserInfo(tempUser["ID"].asInt(), tempUser["Age"].asInt(), tempUser["Username"].asString(), - tempUser["Biography"].asString(), - tempUser["Location"].asString(), + ByteString(tempUser["Biography"].asString()).FromUtf8(), + ByteString(tempUser["Location"].asString()).FromUtf8(), tempUser["Website"].asString(), tempUser["Saves"]["Count"].asInt(), tempUser["Saves"]["AverageScore"].asInt(), @@ -1393,10 +1392,10 @@ RequestBroker::Request * Client::GetUserInfoAsync(std::string username) return new APIRequest("http://" SERVER "/User.json?Name=" + username, new UserInfoParser()); } -LoginStatus Client::Login(std::string username, std::string password, User & user) +LoginStatus Client::Login(ByteString username, ByteString password, User & user) { lastError = ""; - std::stringstream hashStream; + ByteString::Stream hashStream; char passwordHash[33]; char totalHash[33]; @@ -1429,17 +1428,17 @@ LoginStatus Client::Login(std::string username, std::string password, User & use free(data); int userIDTemp = objDocument["UserID"].asInt(); - std::string sessionIDTemp = objDocument["SessionID"].asString(); - std::string sessionKeyTemp = objDocument["SessionKey"].asString(); - std::string userElevationTemp = objDocument["Elevation"].asString(); + ByteString sessionIDTemp = objDocument["SessionID"].asString(); + ByteString sessionKeyTemp = objDocument["SessionKey"].asString(); + ByteString userElevationTemp = objDocument["Elevation"].asString(); Json::Value notificationsArray = objDocument["Notifications"]; for (Json::UInt j = 0; j < notificationsArray.size(); j++) { - std::string notificationLink = notificationsArray[j]["Link"].asString(); - std::string notificationText = notificationsArray[j]["Text"].asString(); + ByteString notificationLink = notificationsArray[j]["Link"].asString(); + String notificationText = ByteString(notificationsArray[j]["Text"].asString()).FromUtf8(); - std::pair item = std::pair(notificationText, notificationLink); + std::pair item = std::pair(notificationText, notificationLink); AddServerNotification(item); } @@ -1447,7 +1446,7 @@ LoginStatus Client::Login(std::string username, std::string password, User & use user.UserID = userIDTemp; user.SessionID = sessionIDTemp; user.SessionKey = sessionKeyTemp; - std::string userElevation = userElevationTemp; + ByteString userElevation = userElevationTemp; if(userElevation == "Admin") user.UserElevation = User::ElevationAdmin; else if(userElevation == "Mod") @@ -1458,7 +1457,7 @@ LoginStatus Client::Login(std::string username, std::string password, User & use } catch (std::exception &e) { - lastError = std::string("Could not read response: ") + e.what(); + lastError = "Could not read response: " + ByteString(e.what()).FromUtf8(); return LoginError; } } @@ -1469,13 +1468,13 @@ LoginStatus Client::Login(std::string username, std::string password, User & use RequestStatus Client::DeleteSave(int saveID) { lastError = ""; - std::stringstream urlStream; + ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse/Delete.json?ID=" << saveID << "&Mode=Delete&Key=" << authUser.SessionKey; if(authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); } @@ -1489,16 +1488,16 @@ RequestStatus Client::DeleteSave(int saveID) return ret; } -RequestStatus Client::AddComment(int saveID, std::string comment) +RequestStatus Client::AddComment(int saveID, String comment) { lastError = ""; - std::stringstream urlStream; + ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse/Comments.json?ID=" << saveID; if(authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; const char *const postNames[] = { "Comment", NULL }; @@ -1519,7 +1518,7 @@ RequestStatus Client::AddComment(int saveID, std::string comment) RequestStatus Client::FavouriteSave(int saveID, bool favourite) { lastError = ""; - std::stringstream urlStream; + ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse/Favourite.json?ID=" << saveID << "&Key=" << authUser.SessionKey; @@ -1527,7 +1526,7 @@ RequestStatus Client::FavouriteSave(int saveID, bool favourite) urlStream << "&Mode=Remove"; if(authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); } @@ -1541,16 +1540,16 @@ RequestStatus Client::FavouriteSave(int saveID, bool favourite) return ret; } -RequestStatus Client::ReportSave(int saveID, std::string message) +RequestStatus Client::ReportSave(int saveID, String message) { lastError = ""; - std::stringstream urlStream; + ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse/Report.json?ID=" << saveID << "&Key=" << authUser.SessionKey; if(authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; const char *const postNames[] = { "Reason", NULL }; @@ -1571,13 +1570,13 @@ RequestStatus Client::ReportSave(int saveID, std::string message) RequestStatus Client::UnpublishSave(int saveID) { lastError = ""; - std::stringstream urlStream; + ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse/Delete.json?ID=" << saveID << "&Mode=Unpublish&Key=" << authUser.SessionKey; if(authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); } @@ -1594,13 +1593,13 @@ RequestStatus Client::UnpublishSave(int saveID) RequestStatus Client::PublishSave(int saveID) { lastError = ""; - std::stringstream urlStream; + ByteString::Stream urlStream; char *data; int dataStatus; urlStream << "http://" << SERVER << "/Browse/View.json?ID=" << saveID << "&Key=" << authUser.SessionKey; if (authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; const char *const postNames[] = { "ActionPublish", NULL }; const char *const postDatas[] = { "" }; @@ -1619,7 +1618,7 @@ RequestStatus Client::PublishSave(int saveID) SaveInfo * Client::GetSave(int saveID, int saveDate) { lastError = ""; - std::stringstream urlStream; + ByteString::Stream urlStream; urlStream << "http://" << SERVER << "/Browse/View.json?ID=" << saveID; if(saveDate) { @@ -1629,7 +1628,7 @@ SaveInfo * Client::GetSave(int saveID, int saveDate) int dataStatus, dataLength; if(authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); } @@ -1649,9 +1648,9 @@ SaveInfo * Client::GetSave(int saveID, int saveDate) int tempScoreUp = objDocument["ScoreUp"].asInt(); int tempScoreDown = objDocument["ScoreDown"].asInt(); int tempMyScore = objDocument["ScoreMine"].asInt(); - std::string tempUsername = objDocument["Username"].asString(); - std::string tempName = objDocument["Name"].asString(); - std::string tempDescription = objDocument["Description"].asString(); + ByteString tempUsername = objDocument["Username"].asString(); + String tempName = ByteString(objDocument["Name"].asString()).FromUtf8(); + String tempDescription = ByteString(objDocument["Description"].asString()).FromUtf8(); int tempCreatedDate = objDocument["DateCreated"].asInt(); int tempUpdatedDate = objDocument["Date"].asInt(); bool tempPublished = objDocument["Published"].asBool(); @@ -1661,7 +1660,7 @@ SaveInfo * Client::GetSave(int saveID, int saveDate) int tempVersion = objDocument["Version"].asInt(); Json::Value tagsArray = objDocument["Tags"]; - std::list tempTags; + std::list tempTags; for (Json::UInt j = 0; j < tagsArray.size(); j++) tempTags.push_back(tagsArray[j].asString()); @@ -1677,7 +1676,7 @@ SaveInfo * Client::GetSave(int saveID, int saveDate) } catch (std::exception & e) { - lastError = std::string("Could not read response: ") + e.what(); + lastError = "Could not read response: " + ByteString(e.what()).FromUtf8(); free(data); return NULL; } @@ -1685,14 +1684,14 @@ SaveInfo * Client::GetSave(int saveID, int saveDate) else { free(data); - lastError = http_ret_text(dataStatus); + lastError = ByteString(http_ret_text(dataStatus)).FromUtf8(); } return NULL; } RequestBroker::Request * Client::GetSaveAsync(int saveID, int saveDate) { - std::stringstream urlStream; + ByteString::Stream urlStream; urlStream << "http://" << SERVER << "/Browse/View.json?ID=" << saveID; if(saveDate) { @@ -1713,9 +1712,9 @@ RequestBroker::Request * Client::GetSaveAsync(int saveID, int saveDate) int tempScoreUp = objDocument["ScoreUp"].asInt(); int tempScoreDown = objDocument["ScoreDown"].asInt(); int tempMyScore = objDocument["ScoreMine"].asInt(); - std::string tempUsername = objDocument["Username"].asString(); - std::string tempName = objDocument["Name"].asString(); - std::string tempDescription = objDocument["Description"].asString(); + ByteString tempUsername = objDocument["Username"].asString(); + String tempName = ByteString(objDocument["Name"].asString()).FromUtf8(); + String tempDescription = ByteString(objDocument["Description"].asString()).FromUtf8(); int tempCreatedDate = objDocument["DateCreated"].asInt(); int tempUpdatedDate = objDocument["Date"].asInt(); bool tempPublished = objDocument["Published"].asBool(); @@ -1725,7 +1724,7 @@ RequestBroker::Request * Client::GetSaveAsync(int saveID, int saveDate) int tempVersion = objDocument["Version"].asInt(); Json::Value tagsArray = objDocument["Tags"]; - std::list tempTags; + std::list tempTags; for (Json::UInt j = 0; j < tagsArray.size(); j++) tempTags.push_back(tagsArray[j].asString()); @@ -1767,12 +1766,12 @@ RequestBroker::Request * Client::GetCommentsAsync(int saveID, int start, int cou for (Json::UInt j = 0; j < commentsArray.size(); j++) { - int userID = format::StringToNumber(commentsArray[j]["UserID"].asString()); - std::string username = commentsArray[j]["Username"].asString(); - std::string formattedUsername = commentsArray[j]["FormattedUsername"].asString(); + int userID = format::ByteStringToNumber(commentsArray[j]["UserID"].asString()); + ByteString username = commentsArray[j]["Username"].asString(); + ByteString formattedUsername = commentsArray[j]["FormattedUsername"].asString(); if (formattedUsername == "jacobot") formattedUsername = "\bt" + formattedUsername; - std::string comment = commentsArray[j]["Text"].asString(); + String comment = ByteString(commentsArray[j]["Text"].asString()).FromUtf8(); commentArray->push_back(new SaveComment(userID, username, formattedUsername, comment)); } return commentArray; @@ -1790,17 +1789,17 @@ RequestBroker::Request * Client::GetCommentsAsync(int saveID, int start, int cou virtual ~CommentsParser() { } }; - std::stringstream urlStream; + ByteString::Stream urlStream; urlStream << "http://" << SERVER << "/Browse/Comments.json?ID=" << saveID << "&Start=" << start << "&Count=" << count; return new APIRequest(urlStream.str(), new CommentsParser()); } -std::vector > * Client::GetTags(int start, int count, std::string query, int & resultCount) +std::vector > * Client::GetTags(int start, int count, String query, int & resultCount) { lastError = ""; resultCount = 0; - std::vector > * tagArray = new std::vector >(); - std::stringstream urlStream; + std::vector > * tagArray = new std::vector >(); + ByteString::Stream urlStream; char * data; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse/Tags.json?Start=" << start << "&Count=" << count; @@ -1808,7 +1807,7 @@ std::vector > * Client::GetTags(int start, int count { urlStream << "&Search_Query="; if(query.length()) - urlStream << format::URLEncode(query); + urlStream << format::URLEncode(query.ToUtf8()); } data = http_simple_get((char *)urlStream.str().c_str(), &dataStatus, &dataLength); @@ -1825,29 +1824,29 @@ std::vector > * Client::GetTags(int start, int count for (Json::UInt j = 0; j < tagsArray.size(); j++) { int tagCount = tagsArray[j]["Count"].asInt(); - std::string tag = tagsArray[j]["Tag"].asString(); - tagArray->push_back(std::pair(tag, tagCount)); + ByteString tag = tagsArray[j]["Tag"].asString(); + tagArray->push_back(std::pair(tag, tagCount)); } } catch (std::exception & e) { - lastError = std::string("Could not read response: ") + e.what(); + lastError = "Could not read response: " + ByteString(e.what()).FromUtf8(); } } else { - lastError = http_ret_text(dataStatus); + lastError = ByteString(http_ret_text(dataStatus)).FromUtf8(); } free(data); return tagArray; } -std::vector * Client::SearchSaves(int start, int count, std::string query, std::string sort, std::string category, int & resultCount) +std::vector * Client::SearchSaves(int start, int count, String query, ByteString sort, ByteString category, int & resultCount) { lastError = ""; resultCount = 0; std::vector * saveArray = new std::vector(); - std::stringstream urlStream; + ByteString::Stream urlStream; char * data; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse.json?Start=" << start << "&Count=" << count; @@ -1855,7 +1854,7 @@ std::vector * Client::SearchSaves(int start, int count, std::string q { urlStream << "&Search_Query="; if(query.length()) - urlStream << format::URLEncode(query); + urlStream << format::URLEncode(query.ToUtf8()); if(sort == "date") { if(query.length()) @@ -1869,7 +1868,7 @@ std::vector * Client::SearchSaves(int start, int count, std::string q } if(authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); } @@ -1895,8 +1894,8 @@ std::vector * Client::SearchSaves(int start, int count, std::string q int tempUpdatedDate = savesArray[j]["Updated"].asInt(); int tempScoreUp = savesArray[j]["ScoreUp"].asInt(); int tempScoreDown = savesArray[j]["ScoreDown"].asInt(); - std::string tempUsername = savesArray[j]["Username"].asString(); - std::string tempName = savesArray[j]["Name"].asString(); + ByteString tempUsername = savesArray[j]["Username"].asString(); + String tempName = ByteString(savesArray[j]["Name"].asString()).FromUtf8(); int tempVersion = savesArray[j]["Version"].asInt(); bool tempPublished = savesArray[j]["Published"].asBool(); SaveInfo * tempSaveInfo = new SaveInfo(tempID, tempCreatedDate, tempUpdatedDate, tempScoreUp, tempScoreDown, tempUsername, tempName); @@ -1907,7 +1906,7 @@ std::vector * Client::SearchSaves(int start, int count, std::string q } catch (std::exception &e) { - lastError = std::string("Could not read response: ") + e.what(); + lastError = "Could not read response: " + ByteString(e.what()).FromUtf8(); } } free(data); @@ -1928,17 +1927,17 @@ void Client::ClearThumbnailRequests() } } -std::list * Client::RemoveTag(int saveID, std::string tag) +std::list * Client::RemoveTag(int saveID, ByteString tag) { lastError = ""; - std::list * tags = NULL; - std::stringstream urlStream; + std::list * tags = NULL; + ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse/EditTag.json?Op=delete&ID=" << saveID << "&Tag=" << tag << "&Key=" << authUser.SessionKey; if(authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); } @@ -1957,30 +1956,30 @@ std::list * Client::RemoveTag(int saveID, std::string tag) dataStream >> responseObject; Json::Value tagsArray = responseObject["Tags"]; - tags = new std::list(); + tags = new std::list(); for (Json::UInt j = 0; j < tagsArray.size(); j++) tags->push_back(tagsArray[j].asString()); } catch (std::exception &e) { - lastError = std::string("Could not read response: ") + e.what(); + lastError = "Could not read response: " + ByteString(e.what()).FromUtf8(); } } free(data); return tags; } -std::list * Client::AddTag(int saveID, std::string tag) +std::list * Client::AddTag(int saveID, ByteString tag) { lastError = ""; - std::list * tags = NULL; - std::stringstream urlStream; + std::list * tags = NULL; + ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse/EditTag.json?Op=add&ID=" << saveID << "&Tag=" << tag << "&Key=" << authUser.SessionKey; if(authUser.UserID) { - std::stringstream userIDStream; + ByteString::Stream userIDStream; userIDStream << authUser.UserID; data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); } @@ -1999,13 +1998,13 @@ std::list * Client::AddTag(int saveID, std::string tag) dataStream >> responseObject; Json::Value tagsArray = responseObject["Tags"]; - tags = new std::list(); + tags = new std::list(); for (Json::UInt j = 0; j < tagsArray.size(); j++) tags->push_back(tagsArray[j].asString()); } catch (std::exception & e) { - lastError = std::string("Could not read response: ") + e.what(); + lastError = "Could not read response: " + ByteString(e.what()).FromUtf8(); } } free(data); @@ -2081,7 +2080,7 @@ void Client::SaveAuthorInfo(Json::Value *saveInto) // powder.pref preference getting / setting functions // Recursively go down the json to get the setting we want -Json::Value Client::GetPref(Json::Value root, std::string prop, Json::Value defaultValue) +Json::Value Client::GetPref(Json::Value root, ByteString prop, Json::Value defaultValue) { try { @@ -2097,7 +2096,7 @@ Json::Value Client::GetPref(Json::Value root, std::string prop, Json::Value defa } } -std::string Client::GetPrefString(std::string prop, std::string defaultValue) +ByteString Client::GetPrefByteString(ByteString prop, ByteString defaultValue) { try { @@ -2109,7 +2108,19 @@ std::string Client::GetPrefString(std::string prop, std::string defaultValue) } } -double Client::GetPrefNumber(std::string prop, double defaultValue) +String Client::GetPrefString(ByteString prop, String defaultValue) +{ + try + { + return ByteString(GetPref(preferences, prop, defaultValue.ToUtf8()).asString()).FromUtf8(false); + } + catch (std::exception & e) + { + return defaultValue; + } +} + +double Client::GetPrefNumber(ByteString prop, double defaultValue) { try { @@ -2121,7 +2132,7 @@ double Client::GetPrefNumber(std::string prop, double defaultValue) } } -int Client::GetPrefInteger(std::string prop, int defaultValue) +int Client::GetPrefInteger(ByteString prop, int defaultValue) { try { @@ -2133,7 +2144,7 @@ int Client::GetPrefInteger(std::string prop, int defaultValue) } } -unsigned int Client::GetPrefUInteger(std::string prop, unsigned int defaultValue) +unsigned int Client::GetPrefUInteger(ByteString prop, unsigned int defaultValue) { try { @@ -2145,7 +2156,7 @@ unsigned int Client::GetPrefUInteger(std::string prop, unsigned int defaultValue } } -bool Client::GetPrefBool(std::string prop, bool defaultValue) +bool Client::GetPrefBool(ByteString prop, bool defaultValue) { try { @@ -2157,11 +2168,11 @@ bool Client::GetPrefBool(std::string prop, bool defaultValue) } } -std::vector Client::GetPrefStringArray(std::string prop) +std::vector Client::GetPrefByteStringArray(ByteString prop) { try { - std::vector ret; + std::vector ret; Json::Value arr = GetPref(preferences, prop); for (int i = 0; i < (int)arr.size(); i++) ret.push_back(arr[i].asString()); @@ -2171,10 +2182,27 @@ std::vector Client::GetPrefStringArray(std::string prop) { } - return std::vector(); + return std::vector(); } -std::vector Client::GetPrefNumberArray(std::string prop) +std::vector Client::GetPrefStringArray(ByteString prop) +{ + try + { + std::vector ret; + Json::Value arr = GetPref(preferences, prop); + for (int i = 0; i < (int)arr.size(); i++) + ret.push_back(ByteString(arr[i].asString()).FromUtf8(false)); + return ret; + } + catch (std::exception & e) + { + + } + return std::vector(); +} + +std::vector Client::GetPrefNumberArray(ByteString prop) { try { @@ -2191,7 +2219,7 @@ std::vector Client::GetPrefNumberArray(std::string prop) return std::vector(); } -std::vector Client::GetPrefIntegerArray(std::string prop) +std::vector Client::GetPrefIntegerArray(ByteString prop) { try { @@ -2208,7 +2236,7 @@ std::vector Client::GetPrefIntegerArray(std::string prop) return std::vector(); } -std::vector Client::GetPrefUIntegerArray(std::string prop) +std::vector Client::GetPrefUIntegerArray(ByteString prop) { try { @@ -2225,7 +2253,7 @@ std::vector Client::GetPrefUIntegerArray(std::string prop) return std::vector(); } -std::vector Client::GetPrefBoolArray(std::string prop) +std::vector Client::GetPrefBoolArray(ByteString prop) { try { @@ -2247,7 +2275,7 @@ std::vector Client::GetPrefBoolArray(std::string prop) // any other way will set the value of a copy of preferences, not the original // This function will recursively go through and create an object with the property we wanted set, // and return it to SetPref to do the actual setting -Json::Value Client::SetPrefHelper(Json::Value root, std::string prop, Json::Value value) +Json::Value Client::SetPrefHelper(Json::Value root, ByteString prop, Json::Value value) { size_t dot = prop.find("."); if (dot == prop.npos) @@ -2261,7 +2289,7 @@ Json::Value Client::SetPrefHelper(Json::Value root, std::string prop, Json::Valu return root; } -void Client::SetPref(std::string prop, Json::Value value) +void Client::SetPref(ByteString prop, Json::Value value) { try { @@ -2279,7 +2307,7 @@ void Client::SetPref(std::string prop, Json::Value value) } } -void Client::SetPref(std::string prop, std::vector value) +void Client::SetPref(ByteString prop, std::vector value) { try { @@ -2295,3 +2323,8 @@ void Client::SetPref(std::string prop, std::vector value) } } + +void Client::SetPrefUnicode(ByteString prop, String value) +{ + SetPref(prop, value.ToUtf8()); +} diff --git a/src/client/Client.h b/src/client/Client.h index 2f3a0b0ed..533122a09 100644 --- a/src/client/Client.h +++ b/src/client/Client.h @@ -5,6 +5,7 @@ #include #include +#include "common/String.h" #include "Config.h" #include "common/Singleton.h" @@ -34,24 +35,24 @@ class UpdateInfo { public: enum BuildType { Stable, Beta, Snapshot }; - std::string File; - std::string Changelog; + ByteString File; + String Changelog; int Major; int Minor; int Build; int Time; BuildType Type; UpdateInfo() : File(""), Changelog(""), Major(0), Minor(0), Build(0), Time(0), Type(Stable) {} - UpdateInfo(int major, int minor, int build, std::string file, std::string changelog, BuildType type) : File(file), Changelog(changelog), Major(major), Minor(minor), Build(build), Time(0), Type(type) {} - UpdateInfo(int time, std::string file, std::string changelog, BuildType type) : File(file), Changelog(changelog), Major(0), Minor(0), Build(0), Time(time), Type(type) {} + UpdateInfo(int major, int minor, int build, ByteString file, String changelog, BuildType type) : File(file), Changelog(changelog), Major(major), Minor(minor), Build(build), Time(0), Type(type) {} + UpdateInfo(int time, ByteString file, String changelog, BuildType type) : File(file), Changelog(changelog), Major(0), Minor(0), Build(0), Time(time), Type(type) {} }; class RequestListener; class ClientListener; class Client: public Singleton { private: - std::string messageOfTheDay; - std::vector > serverNotifications; + String messageOfTheDay; + std::vector > serverNotifications; void * versionCheckRequest; void * alternateVersionCheckRequest; @@ -59,10 +60,10 @@ private: bool updateAvailable; UpdateInfo updateInfo; - std::string lastError; + String lastError; bool firstRun; - std::list stampIDs; + std::list stampIDs; unsigned lastStampTime; int lastStampName; @@ -75,16 +76,16 @@ private: void * activeThumbRequests[IMGCONNS]; int activeThumbRequestTimes[IMGCONNS]; int activeThumbRequestCompleteTimes[IMGCONNS]; - std::string activeThumbRequestIDs[IMGCONNS]; + ByteString activeThumbRequestIDs[IMGCONNS]; void notifyUpdateAvailable(); void notifyAuthUserChanged(); void notifyMessageOfTheDay(); - void notifyNewNotification(std::pair notification); + void notifyNewNotification(std::pair notification); // internal preferences handling Json::Value preferences; - Json::Value GetPref(Json::Value root, std::string prop, Json::Value defaultValue = Json::nullValue); - Json::Value SetPrefHelper(Json::Value root, std::string prop, Json::Value value); + Json::Value GetPref(Json::Value root, ByteString prop, Json::Value defaultValue = Json::nullValue); + Json::Value SetPrefHelper(Json::Value root, ByteString prop, Json::Value value); // Save stealing info Json::Value authors; @@ -107,30 +108,30 @@ public: Client(); ~Client(); - std::vector DirectorySearch(std::string directory, std::string search, std::vector extensions); - std::vector DirectorySearch(std::string directory, std::string search, std::string extension); + std::vector DirectorySearch(ByteString directory, ByteString search, std::vector extensions); + std::vector DirectorySearch(ByteString directory, ByteString search, ByteString extension); - std::string FileOpenDialogue(); + ByteString FileOpenDialogue(); //std::string FileSaveDialogue(); bool DoInstallation(); - std::vector ReadFile(std::string filename); + std::vector ReadFile(ByteString filename); - void AddServerNotification(std::pair notification); - std::vector > GetServerNotifications(); + void AddServerNotification(std::pair notification); + std::vector > GetServerNotifications(); - void SetMessageOfTheDay(std::string message); - std::string GetMessageOfTheDay(); + void SetMessageOfTheDay(String message); + String GetMessageOfTheDay(); - void Initialise(std::string proxyString); - void SetProxy(std::string proxy); + void Initialise(ByteString proxyString); + void SetProxy(ByteString proxy); bool IsFirstRun(); int MakeDirectory(const char * dirname); - bool WriteFile(std::vector fileData, std::string filename); - bool WriteFile(std::vector fileData, std::string filename); - bool FileExists(std::string filename); + bool WriteFile(std::vector fileData, ByteString filename); + bool WriteFile(std::vector fileData, ByteString filename); + bool FileExists(ByteString filename); void AddListener(ClientListener * listener); void RemoveListener(ClientListener * listener); @@ -138,30 +139,30 @@ public: RequestStatus ExecVote(int saveID, int direction); RequestStatus UploadSave(SaveInfo & save); - SaveFile * GetStamp(std::string stampID); - void DeleteStamp(std::string stampID); - std::string AddStamp(GameSave * saveData); - std::vector GetStamps(int start, int count); + SaveFile * GetStamp(ByteString stampID); + void DeleteStamp(ByteString stampID); + ByteString AddStamp(GameSave * saveData); + std::vector GetStamps(int start, int count); void RescanStamps(); int GetStampsCount(); SaveFile * GetFirstStamp(); - void MoveStampToFront(std::string stampID); + void MoveStampToFront(ByteString stampID); void updateStamps(); - RequestStatus AddComment(int saveID, std::string comment); + RequestStatus AddComment(int saveID, String comment); //Retrieves a "UserInfo" object - RequestBroker::Request * GetUserInfoAsync(std::string username); + RequestBroker::Request * GetUserInfoAsync(ByteString username); RequestBroker::Request * SaveUserInfoAsync(UserInfo info); RequestBroker::Request * GetSaveDataAsync(int saveID, int saveDate); unsigned char * GetSaveData(int saveID, int saveDate, int & dataLength); std::vector GetSaveData(int saveID, int saveDate); - LoginStatus Login(std::string username, std::string password, User & user); + LoginStatus Login(ByteString username, ByteString password, User & user); void ClearThumbnailRequests(); - std::vector * SearchSaves(int start, int count, std::string query, std::string sort, std::string category, int & resultCount); - std::vector > * GetTags(int start, int count, std::string query, int & resultCount); + std::vector * SearchSaves(int start, int count, String query, ByteString sort, ByteString category, int & resultCount); + std::vector > * GetTags(int start, int count, String query, int & resultCount); RequestBroker::Request * GetCommentsAsync(int saveID, int start, int count); @@ -169,15 +170,15 @@ public: RequestBroker::Request * GetSaveAsync(int saveID, int saveDate); RequestStatus DeleteSave(int saveID); - RequestStatus ReportSave(int saveID, std::string message); + RequestStatus ReportSave(int saveID, String message); RequestStatus UnpublishSave(int saveID); RequestStatus PublishSave(int saveID); RequestStatus FavouriteSave(int saveID, bool favourite); void SetAuthUser(User user); User GetAuthUser(); - std::list * RemoveTag(int saveID, std::string tag); //TODO RequestStatus - std::list * AddTag(int saveID, std::string tag); - std::string GetLastError() { + std::list * RemoveTag(int saveID, ByteString tag); //TODO RequestStatus + std::list * AddTag(int saveID, ByteString tag); + String GetLastError() { return lastError; } RequestStatus ParseServerReturn(char *result, int status, bool json); @@ -188,19 +189,22 @@ public: // preferences functions void WritePrefs(); - std::string GetPrefString(std::string prop, std::string defaultValue); - double GetPrefNumber(std::string prop, double defaultValue); - int GetPrefInteger(std::string prop, int defaultValue); - unsigned int GetPrefUInteger(std::string prop, unsigned int defaultValue); - bool GetPrefBool(std::string prop, bool defaultValue); - std::vector GetPrefStringArray(std::string prop); - std::vector GetPrefNumberArray(std::string prop); - std::vector GetPrefIntegerArray(std::string prop); - std::vector GetPrefUIntegerArray(std::string prop); - std::vector GetPrefBoolArray(std::string prop); + ByteString GetPrefByteString(ByteString prop, ByteString defaultValue); + String GetPrefString(ByteString prop, String defaultValue); + double GetPrefNumber(ByteString prop, double defaultValue); + int GetPrefInteger(ByteString prop, int defaultValue); + unsigned int GetPrefUInteger(ByteString prop, unsigned int defaultValue); + bool GetPrefBool(ByteString prop, bool defaultValue); + std::vector GetPrefByteStringArray(ByteString prop); + std::vector GetPrefStringArray(ByteString prop); + std::vector GetPrefNumberArray(ByteString prop); + std::vector GetPrefIntegerArray(ByteString prop); + std::vector GetPrefUIntegerArray(ByteString prop); + std::vector GetPrefBoolArray(ByteString prop); - void SetPref(std::string prop, Json::Value value); - void SetPref(std::string property, std::vector value); + void SetPref(ByteString prop, Json::Value value); + void SetPref(ByteString property, std::vector value); + void SetPrefUnicode(ByteString prop, String value); }; #endif // CLIENT_H diff --git a/src/client/ClientListener.h b/src/client/ClientListener.h index e04572e5f..0d3345fa9 100644 --- a/src/client/ClientListener.h +++ b/src/client/ClientListener.h @@ -11,7 +11,7 @@ public: virtual void NotifyUpdateAvailable(Client * sender) {} virtual void NotifyAuthUserChanged(Client * sender) {} virtual void NotifyMessageOfTheDay(Client * sender) {} - virtual void NotifyNewNotification(Client * sender, std::pair notification) {} + virtual void NotifyNewNotification(Client * sender, std::pair notification) {} }; diff --git a/src/client/Download.cpp b/src/client/Download.cpp index b2534501b..da11c4c10 100644 --- a/src/client/Download.cpp +++ b/src/client/Download.cpp @@ -3,7 +3,7 @@ #include "DownloadManager.h" #include "HTTP.h" -Download::Download(std::string uri_, bool keepAlive): +Download::Download(ByteString uri_, bool keepAlive): http(NULL), keepAlive(keepAlive), downloadData(NULL), @@ -17,7 +17,7 @@ Download::Download(std::string uri_, bool keepAlive): downloadCanceled(false), downloadStarted(false) { - uri = std::string(uri_); + uri = ByteString(uri_); DownloadManager::Ref().AddDownload(this); } @@ -31,20 +31,20 @@ Download::~Download() } // add post data to a request -void Download::AddPostData(std::map data) +void Download::AddPostData(std::map data) { postDataBoundary = FindBoundary(data, ""); postData = GetMultipartMessage(data, postDataBoundary); } -void Download::AddPostData(std::pair data) +void Download::AddPostData(std::pair data) { - std::map postData; + std::map postData; postData.insert(data); AddPostData(postData); } // add userID and sessionID headers to the download. Must be done after download starts for some reason -void Download::AuthHeaders(std::string ID, std::string session) +void Download::AuthHeaders(ByteString ID, ByteString session) { if (ID != "0") userID = ID; @@ -68,13 +68,13 @@ void Download::Start() } // for persistent connections (keepAlive = true), reuse the open connection to make another request -bool Download::Reuse(std::string newuri) +bool Download::Reuse(ByteString newuri) { if (!keepAlive || !CheckDone() || CheckCanceled()) { return false; } - uri = std::string(newuri); + uri = newuri; DownloadManager::Ref().Lock(); downloadFinished = false; DownloadManager::Ref().Unlock(); diff --git a/src/client/Download.h b/src/client/Download.h index 9db636a7e..d925f3a46 100644 --- a/src/client/Download.h +++ b/src/client/Download.h @@ -1,12 +1,12 @@ #ifndef DOWNLOAD_H #define DOWNLOAD_H #include -#include +#include "common/String.h" class DownloadManager; class Download { - std::string uri; + ByteString uri; void *http; bool keepAlive; @@ -14,25 +14,25 @@ class Download int downloadSize; int downloadStatus; - std::string postData; - std::string postDataBoundary; + ByteString postData; + ByteString postDataBoundary; - std::string userID; - std::string userSession; + ByteString userID; + ByteString userSession; volatile bool downloadFinished; volatile bool downloadCanceled; volatile bool downloadStarted; public: - Download(std::string uri, bool keepAlive = false); + Download(ByteString uri, bool keepAlive = false); ~Download(); - void AddPostData(std::map data); - void AddPostData(std::pair data); - void AuthHeaders(std::string ID, std::string session); + void AddPostData(std::map data); + void AddPostData(std::pair data); + void AuthHeaders(ByteString ID, ByteString session); void Start(); - bool Reuse(std::string newuri); + bool Reuse(ByteString newuri); char* Finish(int *length, int *status); void Cancel(); diff --git a/src/client/GameSave.cpp b/src/client/GameSave.cpp index 34e188e5d..cedba9f4e 100644 --- a/src/client/GameSave.cpp +++ b/src/client/GameSave.cpp @@ -1,6 +1,5 @@ #include "common/tpt-minmax.h" #include -#include #include #include #include @@ -633,7 +632,7 @@ void GameSave::readOPS(char * data, int dataLength) throw ParseException(ParseException::Corrupt, "Unable to decompress (ret " + format::NumberToString(bz2ret) + ")"); } - set_bson_err_handler([](const char* err) { throw ParseException(ParseException::Corrupt, "BSON error when parsing save: " + std::string(err)); }); + set_bson_err_handler([](const char* err) { throw ParseException(ParseException::Corrupt, "BSON error when parsing save: " + ByteString(err).FromUtf8()); }); bson_init_data_size(&b, (char*)bsonData, bsonDataLen); bson_iterator_init(&iter, &b); @@ -679,7 +678,7 @@ void GameSave::readOPS(char * data, int dataLength) { if (!strcmp(bson_iterator_key(&signiter), "text") && bson_iterator_type(&signiter) == BSON_STRING) { - tempSign.text = format::CleanString(bson_iterator_string(&signiter), true, true, true).substr(0, 45); + tempSign.text = format::CleanString(ByteString(bson_iterator_string(&signiter)).FromUtf8(), true, true, true).substr(0, 45); } else if (!strcmp(bson_iterator_key(&signiter), "justification") && bson_iterator_type(&signiter) == BSON_INT) { @@ -764,7 +763,7 @@ void GameSave::readOPS(char * data, int dataLength) { if (bson_iterator_type(&subiter) == BSON_INT) { - std::string id = std::string(bson_iterator_key(&subiter)); + ByteString id = bson_iterator_key(&subiter); int num = bson_iterator_int(&subiter); palette.push_back(PaletteItem(id, num)); } @@ -806,7 +805,7 @@ void GameSave::readOPS(char * data, int dataLength) if (major > SAVE_VERSION || (major == SAVE_VERSION && minor > MINOR_VERSION)) #endif { - std::stringstream errorMessage; + String::Stream errorMessage; #ifdef RENDERER errorMessage << "Save from a newer version: Requires render version " << renderMajor << "." << renderMinor; #else @@ -1333,18 +1332,8 @@ void GameSave::readPSv(char * saveDataChar, int dataLength) sign tempSign("", 0, 0, sign::Left); //Gol data used to read older saves - int goltype[NGOL]; - int grule[NGOL+1][10]; - - int golRulesCount; - int * golRulesT = LoadGOLRules(golRulesCount); - memcpy(grule, golRulesT, sizeof(int) * (golRulesCount*10)); - free(golRulesT); - - int golTypesCount; - int * golTypesT = LoadGOLTypes(golTypesCount); - memcpy(goltype, golTypesT, sizeof(int) * (golTypesCount)); - free(golTypesT); + std::vector goltype = LoadGOLTypes(); + std::vector > grule = LoadGOLRules(); std::vector elements = GetElements(); @@ -1419,7 +1408,7 @@ void GameSave::readPSv(char * saveDataChar, int dataLength) int bzStatus = 0; if ((bzStatus = BZ2_bzBuffToBuffDecompress((char *)data, (unsigned *)&size, (char *)(saveData+12), dataLength-12, 0, 0))) { - std::stringstream bzStatusStr; + String::Stream bzStatusStr; bzStatusStr << bzStatus; throw ParseException(ParseException::Corrupt, "Cannot decompress: " + bzStatusStr.str()); } @@ -2399,7 +2388,7 @@ char * GameSave::serialiseOPS(unsigned int & dataLength) // Use unique_ptr with a custom deleter to ensure that bson_destroy is called even when an exception is thrown std::unique_ptr b_ptr(&b, bson_deleter); - set_bson_err_handler([](const char* err) { throw BuildException("BSON error when parsing save: " + std::string(err)); }); + set_bson_err_handler([](const char* err) { throw BuildException("BSON error when parsing save: " + ByteString(err).FromUtf8()); }); bson_init(&b); bson_append_start_object(&b, "origin"); bson_append_int(&b, "majorVersion", SAVE_VERSION); @@ -2504,7 +2493,7 @@ char * GameSave::serialiseOPS(unsigned int & dataLength) if(signs[i].text.length() && signs[i].x>=0 && signs[i].x<=fullW && signs[i].y>=0 && signs[i].y<=fullH) { bson_append_start_object(&b, "sign"); - bson_append_string(&b, "text", signs[i].text.c_str()); + bson_append_string(&b, "text", signs[i].text.ToUtf8().c_str()); bson_append_int(&b, "justification", signs[i].ju); bson_append_int(&b, "x", signs[i].x); bson_append_int(&b, "y", signs[i].y); @@ -2563,7 +2552,7 @@ void GameSave::ConvertBsonToJson(bson_iterator *iter, Json::Value *j, int depth) bson_iterator_subiterator(iter, &subiter); while (bson_iterator_next(&subiter)) { - std::string key = bson_iterator_key(&subiter); + ByteString key = bson_iterator_key(&subiter); if (bson_iterator_type(&subiter) == BSON_STRING) (*j)[key] = bson_iterator_string(&subiter); else if (bson_iterator_type(&subiter) == BSON_BOOL) @@ -2604,7 +2593,7 @@ std::set GetNestedSaveIDs(Json::Value j) std::set saveIDs = std::set(); for (Json::Value::Members::iterator iter = members.begin(), end = members.end(); iter != end; ++iter) { - std::string member = *iter; + ByteString member = *iter; if (member == "id" && j[member].isInt()) saveIDs.insert(j[member].asInt()); else if (j[member].isArray()) @@ -2633,7 +2622,7 @@ void GameSave::ConvertJsonToBson(bson *b, Json::Value j, int depth) Json::Value::Members members = j.getMemberNames(); for (Json::Value::Members::iterator iter = members.begin(), end = members.end(); iter != end; ++iter) { - std::string member = *iter; + ByteString member = *iter; if (j[member].isString()) bson_append_string(b, member.c_str(), j[member].asCString()); else if (j[member].isBool()) diff --git a/src/client/GameSave.h b/src/client/GameSave.h index 2e3fa092a..de59763ba 100644 --- a/src/client/GameSave.h +++ b/src/client/GameSave.h @@ -2,7 +2,7 @@ #define The_Powder_Toy_GameSave_h #include -#include +#include "common/String.h" #include "Config.h" #include "Misc.h" @@ -15,24 +15,24 @@ struct ParseException: public std::exception { enum ParseResult { OK = 0, Corrupt, WrongVersion, InvalidDimensions, InternalError, MissingElement }; - std::string message; + String message; ParseResult result; public: - ParseException(ParseResult result, std::string message_): message(message_), result(result) {} + ParseException(ParseResult result, String message_): message(message_), result(result) {} const char * what() const throw() { - return message.c_str(); + return message.ToUtf8().c_str(); } ~ParseException() throw() {} }; struct BuildException: public std::exception { - std::string message; + String message; public: - BuildException(std::string message_): message(message_) {} + BuildException(String message_): message(message_) {} const char * what() const throw() { - return message.c_str(); + return message.ToUtf8().c_str(); } ~BuildException() throw() {} }; @@ -104,7 +104,7 @@ public: StkmData stkm; //Element palette - typedef std::pair PaletteItem; + typedef std::pair PaletteItem; std::vector palette; // author information diff --git a/src/client/HTTP.cpp b/src/client/HTTP.cpp index 6f28a069f..afd21508b 100644 --- a/src/client/HTTP.cpp +++ b/src/client/HTTP.cpp @@ -20,8 +20,7 @@ */ -#include -#include +#include "common/String.h" #include #include #include @@ -193,11 +192,11 @@ void http_init(char *proxy) free(host); free(port); } - std::stringstream userAgentBuilder; + ByteString::Stream userAgentBuilder; userAgentBuilder << "PowderToy/" << SAVE_VERSION << "." << MINOR_VERSION << " "; userAgentBuilder << "(" << IDENT_PLATFORM << "; " << IDENT_BUILD << "; M" << MOD_ID << ") "; userAgentBuilder << "TPTPP/" << SAVE_VERSION << "." << MINOR_VERSION << "." << BUILD_NUM << IDENT_RELTYPE << "." << SNAPSHOT_ID; - std::string newUserAgent = userAgentBuilder.str(); + ByteString newUserAgent = userAgentBuilder.str(); userAgent = new char[newUserAgent.length()+1]; std::copy(newUserAgent.begin(), newUserAgent.end(), userAgent); userAgent[newUserAgent.length()] = 0; @@ -938,13 +937,13 @@ const char *http_ret_text(int ret) // Find the boundary used in the multipart POST request // the boundary is a string that never appears in any of the parts, ex. 'A92' // keeps looking recursively until it finds one -std::string FindBoundary(std::map parts, std::string boundary) +ByteString FindBoundary(std::map parts, ByteString boundary) { // we only look for a-zA-Z0-9 chars unsigned int map[62]; size_t blen = boundary.length(); std::fill(&map[0], &map[62], 0); - for (std::map::iterator iter = parts.begin(); iter != parts.end(); iter++) + for (std::map::iterator iter = parts.begin(); iter != parts.end(); iter++) { // loop through every character in each part and search for the substring, adding 1 to map for every character found (character after the substring) for (ssize_t j = 0; j < (ssize_t)((*iter).second.length()-blen); j++) @@ -986,15 +985,15 @@ std::string FindBoundary(std::map parts, std::string b // Generates a MIME multipart message to be used in POST requests // see https://en.wikipedia.org/wiki/MIME#Multipart_messages // this function used in Download class, and eventually all http requests -std::string GetMultipartMessage(std::map parts, std::string boundary) +ByteString GetMultipartMessage(std::map parts, ByteString boundary) { - std::stringstream data; + ByteString::Stream data; // loop through each part, adding it - for (std::map::iterator iter = parts.begin(); iter != parts.end(); iter++) + for (std::map::iterator iter = parts.begin(); iter != parts.end(); iter++) { - std::string name = (*iter).first; - std::string value = (*iter).second; + ByteString name = (*iter).first; + ByteString value = (*iter).second; data << "--" << boundary << "\r\n"; data << "Content-transfer-encoding: binary" << "\r\n"; @@ -1020,9 +1019,9 @@ std::string GetMultipartMessage(std::map parts, std::s } // add the header needed to make POSTS work -void http_add_multipart_header(void *ctx, std::string boundary) +void http_add_multipart_header(void *ctx, ByteString boundary) { - std::string header = "multipart/form-data; boundary=" + boundary; + ByteString header = "multipart/form-data; boundary=" + boundary; http_async_add_header(ctx, "Content-type", header.c_str()); } diff --git a/src/client/HTTP.h b/src/client/HTTP.h index 1149bd6cd..531342ad2 100644 --- a/src/client/HTTP.h +++ b/src/client/HTTP.h @@ -21,7 +21,7 @@ #define HTTP_H #include -#include +#include "common/String.h" static const char hexChars[] = "0123456789abcdef"; static const long http_timeout = 15; @@ -43,9 +43,9 @@ char *http_async_req_stop(void *ctx, int *ret, int *len); void http_async_req_close(void *ctx); void http_force_close(void *ctx); -std::string FindBoundary(std::map, std::string boundary); -std::string GetMultipartMessage(std::map, std::string boundary); -void http_add_multipart_header(void *ctx, std::string boundary); +ByteString FindBoundary(std::map, ByteString boundary); +ByteString GetMultipartMessage(std::map, ByteString boundary); +void http_add_multipart_header(void *ctx, ByteString boundary); char *http_multipart_post(const char *uri, const char *const *names, const char *const *parts, size_t *plens, const char *user, const char *pass, const char * session_id, int *ret, int *len); void *http_multipart_post_async(const char *uri, const char *const *names, const char *const *parts, int *plens, const char *user, const char *pass, const char *session_id); diff --git a/src/client/SaveFile.cpp b/src/client/SaveFile.cpp index 215d9bf88..b66861657 100644 --- a/src/client/SaveFile.cpp +++ b/src/client/SaveFile.cpp @@ -26,11 +26,11 @@ void SaveFile::SetThumbnail(Thumbnail * thumb) thumbnail = thumb; } -SaveFile::SaveFile(std::string filename): +SaveFile::SaveFile(ByteString filename): thumbnail(NULL), gameSave(NULL), filename(filename), - displayName(filename), + displayName(filename.FromUtf8()), loadingError("") { @@ -46,32 +46,32 @@ void SaveFile::SetGameSave(GameSave * save) gameSave = save; } -std::string SaveFile::GetName() +ByteString SaveFile::GetName() { return filename; } -void SaveFile::SetFileName(std::string fileName) +void SaveFile::SetFileName(ByteString fileName) { this->filename = fileName; } -std::string SaveFile::GetDisplayName() +String SaveFile::GetDisplayName() { return displayName; } -void SaveFile::SetDisplayName(std::string displayName) +void SaveFile::SetDisplayName(String displayName) { this->displayName = displayName; } -std::string SaveFile::GetError() +String SaveFile::GetError() { return loadingError; } -void SaveFile::SetLoadingError(std::string error) +void SaveFile::SetLoadingError(String error) { loadingError = error; } diff --git a/src/client/SaveFile.h b/src/client/SaveFile.h index 23d986e11..ba211ee10 100644 --- a/src/client/SaveFile.h +++ b/src/client/SaveFile.h @@ -1,7 +1,7 @@ #ifndef SAVEFILE_H_ #define SAVEFILE_H_ -#include +#include "common/String.h" class GameSave; class Thumbnail; @@ -9,26 +9,26 @@ class Thumbnail; class SaveFile { public: SaveFile(SaveFile & save); - SaveFile(std::string filename); + SaveFile(ByteString filename); Thumbnail * GetThumbnail(); GameSave * GetGameSave(); void SetThumbnail(Thumbnail * thumb); void SetGameSave(GameSave * save); - std::string GetDisplayName(); - void SetDisplayName(std::string displayName); - std::string GetName(); - void SetFileName(std::string fileName); - std::string GetError(); - void SetLoadingError(std::string error); + String GetDisplayName(); + void SetDisplayName(String displayName); + ByteString GetName(); + void SetFileName(ByteString fileName); + String GetError(); + void SetLoadingError(String error); virtual ~SaveFile(); private: Thumbnail * thumbnail; GameSave * gameSave; - std::string filename; - std::string displayName; - std::string loadingError; + ByteString filename; + String displayName; + String loadingError; }; #endif /* SAVEFILE_H_ */ diff --git a/src/client/SaveInfo.cpp b/src/client/SaveInfo.cpp index 97ba49464..83c35a960 100644 --- a/src/client/SaveInfo.cpp +++ b/src/client/SaveInfo.cpp @@ -19,14 +19,14 @@ SaveInfo::SaveInfo(SaveInfo & save): Published(save.Published), gameSave(NULL) { - std::list tagsSorted = save.tags; + std::list tagsSorted = save.tags; tagsSorted.sort(); tags = tagsSorted; if (save.gameSave) gameSave = new GameSave(*save.gameSave); } -SaveInfo::SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, int _votesDown, std::string _userName, std::string _name): +SaveInfo::SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, int _votesDown, ByteString _userName, String _name): id(_id), createdDate(_createdDate), updatedDate(_updatedDate), @@ -47,7 +47,7 @@ SaveInfo::SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, in } -SaveInfo::SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, int _votesDown, int _vote, std::string _userName, std::string _name, std::string description_, bool published_, std::list tags_): +SaveInfo::SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, int _votesDown, int _vote, ByteString _userName, String _name, String description_, bool published_, std::list tags_): id(_id), createdDate(_createdDate), updatedDate(_updatedDate), @@ -65,7 +65,7 @@ SaveInfo::SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, in tags(), gameSave(NULL) { - std::list tagsSorted = tags_; + std::list tagsSorted = tags_; tagsSorted.sort(); tags=tagsSorted; } @@ -78,20 +78,20 @@ SaveInfo::~SaveInfo() } } -void SaveInfo::SetName(std::string name) +void SaveInfo::SetName(String name) { this->name = name; } -std::string SaveInfo::GetName() +String SaveInfo::GetName() { return name; } -void SaveInfo::SetDescription(std::string description) +void SaveInfo::SetDescription(String description) { Description = description; } -std::string SaveInfo::GetDescription() +String SaveInfo::GetDescription() { return Description; } @@ -114,12 +114,12 @@ int SaveInfo::GetVote() return vote; } -void SaveInfo::SetUserName(std::string userName) +void SaveInfo::SetUserName(ByteString userName) { this->userName = userName; } -std::string SaveInfo::GetUserName() +ByteString SaveInfo::GetUserName() { return userName; } @@ -160,14 +160,14 @@ int SaveInfo::GetVersion() return Version; } -void SaveInfo::SetTags(std::list tags) +void SaveInfo::SetTags(std::list tags) { - std::list tagsSorted = tags; + std::list tagsSorted = tags; tagsSorted.sort(); this->tags=tagsSorted; } -std::list SaveInfo::GetTags() +std::list SaveInfo::GetTags() { return tags; } diff --git a/src/client/SaveInfo.h b/src/client/SaveInfo.h index e366858c8..18f75932d 100644 --- a/src/client/SaveInfo.h +++ b/src/client/SaveInfo.h @@ -3,7 +3,7 @@ #include #include -#include +#include "common/String.h" #include #include @@ -23,34 +23,34 @@ public: int Views; int Version; - std::string userName; + ByteString userName; - std::string name; - std::string Description; + String name; + String Description; bool Published; - std::list tags; + std::list tags; GameSave * gameSave; SaveInfo(SaveInfo & save); - SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, int _votesDown, std::string _userName, std::string _name); + SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, int _votesDown, ByteString _userName, String _name); - SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, int _votesDown, int _vote, std::string _userName, std::string _name, std::string description_, bool published_, std::list tags); + SaveInfo(int _id, int _createdDate, int _updatedDate, int _votesUp, int _votesDown, int _vote, ByteString _userName, String _name, String description_, bool published_, std::list tags); ~SaveInfo(); - void SetName(std::string name); - std::string GetName(); + void SetName(String name); + String GetName(); - void SetDescription(std::string description); - std::string GetDescription(); + void SetDescription(String description); + String GetDescription(); void SetPublished(bool published); bool GetPublished(); - void SetUserName(std::string userName); - std::string GetUserName(); + void SetUserName(ByteString userName); + ByteString GetUserName(); void SetID(int id); int GetID(); @@ -67,8 +67,8 @@ public: void SetVersion(int version); int GetVersion(); - void SetTags(std::list tags); - std::list GetTags(); + void SetTags(std::list tags); + std::list GetTags(); GameSave * GetGameSave(); void SetGameSave(GameSave * gameSave); diff --git a/src/client/User.h b/src/client/User.h index 3bc8f926c..3d9aab469 100644 --- a/src/client/User.h +++ b/src/client/User.h @@ -1,7 +1,7 @@ #ifndef USER_H_ #define USER_H_ -#include +#include "common/String.h" class User @@ -12,11 +12,11 @@ public: ElevationAdmin, ElevationModerator, ElevationNone }; int UserID; - std::string Username; - std::string SessionID; - std::string SessionKey; + ByteString Username; + ByteString SessionID; + ByteString SessionKey; Elevation UserElevation; - User(int id, std::string username): + User(int id, ByteString username): UserID(id), Username(username), SessionID(""), diff --git a/src/client/UserInfo.h b/src/client/UserInfo.h index 0c808a7a4..080f95136 100644 --- a/src/client/UserInfo.h +++ b/src/client/UserInfo.h @@ -1,17 +1,17 @@ #ifndef USERINFO_H_ #define USERINFO_H_ -#include +#include "common/String.h" class UserInfo { public: int UserID; int age; - std::string username; - std::string biography; - std::string location; - std::string website; + ByteString username; + String biography; + String location; + ByteString website; int saveCount; float averageScore; @@ -21,7 +21,7 @@ public: int topicReplies; int reputation; - UserInfo(int id, int age, std::string username, std::string biography, std::string location, std::string website, int saveCount, float averageScore, int highestScore, int topicCount, int topicReplies, int reputation): + UserInfo(int id, int age, ByteString username, String biography, String location, ByteString website, int saveCount, float averageScore, int highestScore, int topicCount, int topicReplies, int reputation): UserID(id), age(age), username(username), diff --git a/src/client/requestbroker/APIRequest.cpp b/src/client/requestbroker/APIRequest.cpp index 2103ade34..dcd2e143a 100644 --- a/src/client/requestbroker/APIRequest.cpp +++ b/src/client/requestbroker/APIRequest.cpp @@ -9,7 +9,7 @@ #include "client/HTTP.h" #include "APIResultParser.h" -APIRequest::APIRequest(std::string url, APIResultParser * parser, ListenerHandle listener, int identifier): +APIRequest::APIRequest(ByteString url, APIResultParser * parser, ListenerHandle listener, int identifier): RequestBroker::Request(API, listener, identifier) { Post = false; @@ -18,7 +18,7 @@ APIRequest::APIRequest(std::string url, APIResultParser * parser, ListenerHandle URL = url; } -APIRequest::APIRequest(std::string url, std::map postData, APIResultParser * parser, ListenerHandle listener, int identifier): +APIRequest::APIRequest(ByteString url, std::map postData, APIResultParser * parser, ListenerHandle listener, int identifier): RequestBroker::Request(API, listener, identifier) { Post = true; @@ -81,11 +81,11 @@ RequestBroker::ProcessResponse APIRequest::Process(RequestBroker & rb) int * postLength = new int[PostData.size()]; int i = 0; - std::map::iterator iter = PostData.begin(); + std::map::iterator iter = PostData.begin(); while(iter != PostData.end()) { - std::string name = iter->first; - std::string data = iter->second; + ByteString name = iter->first; + ByteString data = iter->second; char * cName = new char[name.length() + 1]; char * cData = new char[data.length() + 1]; std::strcpy(cName, name.c_str()); @@ -103,7 +103,7 @@ RequestBroker::ProcessResponse APIRequest::Process(RequestBroker & rb) User user = Client::Ref().GetAuthUser(); char userName[12]; char *userSession = new char[user.SessionID.length() + 1]; - std::strcpy(userName, format::NumberToString(user.UserID).c_str()); + std::strcpy(userName, format::NumberToByteString(user.UserID).c_str()); std::strcpy(userSession, user.SessionID.c_str()); HTTPContext = http_multipart_post_async((char*)URL.c_str(), postNames, postData, postLength, userName, NULL, userSession); delete[] userSession; @@ -122,7 +122,7 @@ RequestBroker::ProcessResponse APIRequest::Process(RequestBroker & rb) User user = Client::Ref().GetAuthUser(); char userName[12]; char *userSession = new char[user.SessionID.length() + 1]; - std::strcpy(userName, format::NumberToString(user.UserID).c_str()); + std::strcpy(userName, format::NumberToByteString(user.UserID).c_str()); std::strcpy(userSession, user.SessionID.c_str()); http_auth_headers(HTTPContext, userName, NULL, userSession); delete[] userSession; diff --git a/src/client/requestbroker/APIRequest.h b/src/client/requestbroker/APIRequest.h index b555d61f4..cebfe1c99 100644 --- a/src/client/requestbroker/APIRequest.h +++ b/src/client/requestbroker/APIRequest.h @@ -7,11 +7,11 @@ class APIRequest: public RequestBroker::Request public: bool Post; APIResultParser * Parser; - std::string URL; - std::map PostData; + ByteString URL; + std::map PostData; void * HTTPContext; - APIRequest(std::string url, APIResultParser * parser, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0); - APIRequest(std::string url, std::map, APIResultParser * parser, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0); + APIRequest(ByteString url, APIResultParser * parser, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0); + APIRequest(ByteString url, std::map, APIResultParser * parser, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0); virtual RequestBroker::ProcessResponse Process(RequestBroker & rb); virtual ~APIRequest(); virtual void Cleanup(); diff --git a/src/client/requestbroker/ImageRequest.cpp b/src/client/requestbroker/ImageRequest.cpp index 482e0346c..b8a3a7f5e 100644 --- a/src/client/requestbroker/ImageRequest.cpp +++ b/src/client/requestbroker/ImageRequest.cpp @@ -5,7 +5,7 @@ #include "graphics/Graphics.h" #include "client/HTTP.h" -ImageRequest::ImageRequest(std::string url, int width, int height, ListenerHandle listener, int identifier): +ImageRequest::ImageRequest(ByteString url, int width, int height, ListenerHandle listener, int identifier): Request(Image, listener, identifier) { URL = url; @@ -24,7 +24,7 @@ RequestBroker::ProcessResponse ImageRequest::Process(RequestBroker & rb) VideoBuffer * image = NULL; //Have a look at the thumbnail cache - for(std::deque >::iterator iter = rb.imageCache.begin(), end = rb.imageCache.end(); iter != end; ++iter) + for(std::deque >::iterator iter = rb.imageCache.begin(), end = rb.imageCache.end(); iter != end; ++iter) { if((*iter).first == URL) { @@ -71,7 +71,7 @@ RequestBroker::ProcessResponse ImageRequest::Process(RequestBroker & rb) delete rb.imageCache.front().second; rb.imageCache.pop_front(); } - rb.imageCache.push_back(std::pair(URL, image)); + rb.imageCache.push_back(std::pair(URL, image)); } else { diff --git a/src/client/requestbroker/ImageRequest.h b/src/client/requestbroker/ImageRequest.h index 22a7342c3..c900a1c22 100644 --- a/src/client/requestbroker/ImageRequest.h +++ b/src/client/requestbroker/ImageRequest.h @@ -4,11 +4,11 @@ class ImageRequest: public RequestBroker::Request { public: int Width, Height; - std::string URL; + ByteString URL; int RequestTime; void * HTTPContext; bool started = false; - ImageRequest(std::string url, int width, int height, ListenerHandle listener, int identifier = 0); + ImageRequest(ByteString url, int width, int height, ListenerHandle listener, int identifier = 0); virtual RequestBroker::ProcessResponse Process(RequestBroker & rb); virtual ~ImageRequest(); virtual void Cleanup(); diff --git a/src/client/requestbroker/RequestBroker.cpp b/src/client/requestbroker/RequestBroker.cpp index 7c59dbb05..b3395e78e 100644 --- a/src/client/requestbroker/RequestBroker.cpp +++ b/src/client/requestbroker/RequestBroker.cpp @@ -1,7 +1,6 @@ #include #include #include -#include #include #include "RequestBroker.h" #include "RequestListener.h" @@ -35,7 +34,7 @@ RequestBroker::RequestBroker() RequestBroker::~RequestBroker() { - for(std::deque >::iterator iter = imageCache.begin(), end = imageCache.end(); iter != end; ++iter) + for(std::deque >::iterator iter = imageCache.begin(), end = imageCache.end(); iter != end; ++iter) { delete (*iter).second; } @@ -98,7 +97,7 @@ void RequestBroker::RenderThumbnail(GameSave * gameSave, bool decorations, bool void RequestBroker::RetrieveThumbnail(int saveID, int saveDate, int width, int height, RequestListener * tListener) { - std::stringstream urlStream; + ByteString::Stream urlStream; urlStream << "http://" << STATICSERVER << "/" << saveID; if(saveDate) { @@ -109,9 +108,9 @@ void RequestBroker::RetrieveThumbnail(int saveID, int saveDate, int width, int h RetrieveImage(urlStream.str(), width, height, tListener); } -void RequestBroker::RetrieveAvatar(std::string username, int width, int height, RequestListener * tListener) +void RequestBroker::RetrieveAvatar(ByteString username, int width, int height, RequestListener * tListener) { - std::stringstream urlStream; + ByteString::Stream urlStream; urlStream << "http://" << STATICSERVER << "/avatars/" << username << ".pti"; RetrieveImage(urlStream.str(), width, height, tListener); @@ -130,7 +129,7 @@ void RequestBroker::Start(Request * request, RequestListener * tListener, int id assureRunning(); } -void RequestBroker::RetrieveImage(std::string imageUrl, int width, int height, RequestListener * tListener) +void RequestBroker::RetrieveImage(ByteString imageUrl, int width, int height, RequestListener * tListener) { ListenerHandle handle = AttachRequestListener(tListener); diff --git a/src/client/requestbroker/RequestBroker.h b/src/client/requestbroker/RequestBroker.h index 23fd381eb..6cee30852 100644 --- a/src/client/requestbroker/RequestBroker.h +++ b/src/client/requestbroker/RequestBroker.h @@ -3,7 +3,7 @@ #include #include #include -#include +#include "common/String.h" #include "common/tpt-thread.h" #include "Config.h" @@ -33,7 +33,7 @@ private: std::vector validListeners; - std::deque > imageCache; + std::deque > imageCache; std::queue completeQueue; std::vector requestQueue; @@ -51,12 +51,12 @@ public: void Shutdown(); void FlushThumbQueue(); - void RetrieveImage(std::string imageUrl, int width, int height, RequestListener * tListener); + void RetrieveImage(ByteString imageUrl, int width, int height, RequestListener * tListener); void RenderThumbnail(GameSave * gameSave, bool decorations, bool fire, int width, int height, RequestListener * tListener); void RenderThumbnail(GameSave * gameSave, int width, int height, RequestListener * tListener); void RetrieveThumbnail(int saveID, int saveDate, int width, int height, RequestListener * tListener); void RetrieveThumbnail(int saveID, int width, int height, RequestListener * tListener); - void RetrieveAvatar(std::string username, int width, int height, RequestListener * tListener); + void RetrieveAvatar(ByteString username, int width, int height, RequestListener * tListener); void Start(Request * request, RequestListener * tLIstener, int identifier = 0); bool CheckRequestListener(ListenerHandle handle); diff --git a/src/client/requestbroker/WebRequest.cpp b/src/client/requestbroker/WebRequest.cpp index 62e96dcb3..bd8b99ea9 100644 --- a/src/client/requestbroker/WebRequest.cpp +++ b/src/client/requestbroker/WebRequest.cpp @@ -10,7 +10,7 @@ #include "client/HTTP.h" #include "APIResultParser.h" -WebRequest::WebRequest(std::string url, ListenerHandle listener, int identifier): +WebRequest::WebRequest(ByteString url, ListenerHandle listener, int identifier): RequestBroker::Request(API, listener, identifier) { Post = false; @@ -18,7 +18,7 @@ WebRequest::WebRequest(std::string url, ListenerHandle listener, int identifier) URL = url; } -WebRequest::WebRequest(std::string url, std::map postData, ListenerHandle listener, int identifier): +WebRequest::WebRequest(ByteString url, std::map postData, ListenerHandle listener, int identifier): RequestBroker::Request(API, listener, identifier) { Post = true; @@ -81,11 +81,11 @@ RequestBroker::ProcessResponse WebRequest::Process(RequestBroker & rb) int * postLength = new int[PostData.size()]; int i = 0; - std::map::iterator iter = PostData.begin(); + std::map::iterator iter = PostData.begin(); while(iter != PostData.end()) { - std::string name = iter->first; - std::string data = iter->second; + ByteString name = iter->first; + ByteString data = iter->second; char * cName = new char[name.length() + 1]; char * cData = new char[data.length() + 1]; std::strcpy(cName, name.c_str()); @@ -106,7 +106,7 @@ RequestBroker::ProcessResponse WebRequest::Process(RequestBroker & rb) User user = Client::Ref().GetAuthUser(); char userName[12]; char *userSession = new char[user.SessionID.length() + 1]; - std::strcpy(userName, format::NumberToString(user.UserID).c_str()); + std::strcpy(userName, format::NumberToByteString(user.UserID).c_str()); std::strcpy(userSession, user.SessionID.c_str()); HTTPContext = http_multipart_post_async((char*)URL.c_str(), postNames, postData, postLength, userName, NULL, userSession); delete[] userSession; @@ -125,7 +125,7 @@ RequestBroker::ProcessResponse WebRequest::Process(RequestBroker & rb) User user = Client::Ref().GetAuthUser(); char userName[12]; char *userSession = new char[user.SessionID.length() + 1]; - std::strcpy(userName, format::NumberToString(user.UserID).c_str()); + std::strcpy(userName, format::NumberToByteString(user.UserID).c_str()); std::strcpy(userSession, user.SessionID.c_str()); http_auth_headers(HTTPContext, userName, NULL, userSession); delete[] userSession; diff --git a/src/client/requestbroker/WebRequest.h b/src/client/requestbroker/WebRequest.h index 255b060e7..a0568220a 100644 --- a/src/client/requestbroker/WebRequest.h +++ b/src/client/requestbroker/WebRequest.h @@ -5,11 +5,11 @@ class WebRequest: public RequestBroker::Request { public: bool Post; - std::string URL; - std::map PostData; + ByteString URL; + std::map PostData; void * HTTPContext; - WebRequest(std::string url, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0); - WebRequest(std::string url, std::map, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0); + WebRequest(ByteString url, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0); + WebRequest(ByteString url, std::map, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0); virtual RequestBroker::ProcessResponse Process(RequestBroker & rb); virtual ~WebRequest(); virtual void Cleanup(); diff --git a/src/common/String.cpp b/src/common/String.cpp index 0dc4a3426..a197d17a6 100644 --- a/src/common/String.cpp +++ b/src/common/String.cpp @@ -87,3 +87,135 @@ ByteString String::ToUtf8() const } } } + +template<> std::ctype::~ctype() +{ +} +template<> std::numpunct::numpunct(size_t ref): std::locale::facet(ref) +{ +} +template<> std::numpunct::~numpunct() +{ +} + +static struct Locale32Impl +{ + std::ctype const &ctype16; + std::numpunct const &numpunct16; + Locale32Impl(): + ctype16(std::use_facet >(std::locale())), + numpunct16(std::use_facet >(std::locale())) + { + std::locale::global(std::locale(std::locale(), new std::ctype())); + std::locale::global(std::locale(std::locale(), new std::numpunct())); + std::locale::global(std::locale(std::locale(), new std::num_put())); + } +} +Locale32Impl; + +template<> bool std::ctype::do_is(mask m, char32_t ch) const +{ + return ch <= 0xFFFF ? Locale32Impl.ctype16.is(m, ch) : (m & print); +} +template<> char32_t const *std::ctype::do_is(char32_t const *low, char32_t const *high, mask *vec) const +{ + while(low < high) + { + if(*low <= 0xFFFF) + { + wchar_t l = *low; + Locale32Impl.ctype16.is(&l, &l + 1, vec); + } + else + *vec = print; + low++; + } + return high; +} +template<> char32_t const *std::ctype::do_scan_is(mask m, char32_t const *beg, char32_t const *end) const +{ + while(beg < end) + if(do_is(m, *beg)) + return beg; + else + beg++; + return end; +} +template<> char32_t const *std::ctype::do_scan_not(mask m, char32_t const *beg, char32_t const *end) const +{ + while(beg < end) + if(!do_is(m, *beg)) + return beg; + else + beg++; + return end; +} +template<> char32_t std::ctype::do_toupper(char32_t ch) const +{ + return ch <= 0xFFFF ? Locale32Impl.ctype16.toupper(ch) : ch; +} +template<> char32_t const *std::ctype::do_toupper(char32_t *beg, char32_t const *end) const +{ + while(beg < end) + { + *beg = do_toupper(*beg); + beg++; + } + return end; +} +template<> char32_t std::ctype::do_tolower(char32_t ch) const +{ + return ch <= 0xFFFF ? Locale32Impl.ctype16.tolower(ch) : ch; +} +template<> char32_t const *std::ctype::do_tolower(char32_t *beg, char32_t const *end) const +{ + while(beg < end) + { + *beg = do_tolower(*beg); + beg++; + } + return end; +} +template<> char32_t std::ctype::do_widen(char ch) const +{ + return Locale32Impl.ctype16.widen(ch); +} +template<> char const *std::ctype::do_widen(char const *beg, char const *end, char32_t *dst) const +{ + while(beg < end) + *(dst++) = do_widen(*(beg++)); + return end; +} +template<> char std::ctype::do_narrow(char32_t ch, char dflt) const +{ + return ch <= 0xFFFF ? Locale32Impl.ctype16.narrow(ch, dflt) : dflt; +} +template<> char32_t const *std::ctype::do_narrow(char32_t const *beg, char32_t const *end, char dflt, char *dst) const +{ + while(beg < end) + *(dst++) = do_narrow(*(beg++), dflt); + return end; +} + +template<> char32_t std::numpunct::do_decimal_point() const +{ + return Locale32Impl.numpunct16.decimal_point(); +} +template<> char32_t std::numpunct::do_thousands_sep() const +{ + return Locale32Impl.numpunct16.thousands_sep(); +} +template<> std::string std::numpunct::do_grouping() const +{ + return Locale32Impl.numpunct16.grouping(); +} +template<> std::basic_string std::numpunct::do_truename() const +{ + std::basic_string name = Locale32Impl.numpunct16.truename(); + return std::basic_string(name.begin(), name.end()); +} +template<> std::basic_string std::numpunct::do_falsename() const +{ + std::basic_string name = Locale32Impl.numpunct16.falsename(); + return std::basic_string(name.begin(), name.end()); +} diff --git a/src/common/String.h b/src/common/String.h index 2d452eae3..0da29b864 100644 --- a/src/common/String.h +++ b/src/common/String.h @@ -1,6 +1,8 @@ #ifndef TPT_STRING #define TPT_STRING +#include +#include #include class String; @@ -13,11 +15,18 @@ public: inline ByteString(value_type const *ch, size_type count): std::basic_string(ch, count) {} inline ByteString(value_type const *ch): std::basic_string(ch) {} template inline ByteString(It first, It last): std::basic_string(first, last) {} + inline ByteString(std::basic_string const &other): std::basic_string(other) {} + inline ByteString(std::basic_string &&other): std::basic_string(std::move(other)) {} inline ByteString(ByteString const &other): std::basic_string(other) {} inline ByteString(ByteString &&other): std::basic_string(std::move(other)) {} - ByteString &operator=(ByteString const &other) { std::basic_string::operator=(other); return *this; } - ByteString &operator=(ByteString &&other) { std::basic_string::operator=(std::move(other)); return *this; } + inline ByteString &operator=(ByteString const &other) { std::basic_string::operator=(other); return *this; } + inline ByteString &operator=(ByteString &&other) { std::basic_string::operator=(std::move(other)); return *this; } + + template ByteString &operator+=(T &&other) { std::basic_string::operator+=(std::forward(other)); return *this; } + template inline ByteString operator+(T &&other) const { ByteString tmp = *this; tmp += std::forward(other); return tmp; } + template ByteString substr(Ts&&... args) const { return std::basic_string::substr(std::forward(args)...); } + template ByteString &insert(Ts&&... args) { std::basic_string::insert(std::forward(args)...); return *this; } class ConversionError : public std::runtime_error { @@ -29,8 +38,14 @@ public: String FromUtf8(bool ignoreError = true) const; inline String FromAscii() const; + + using Stream = std::basic_stringstream; }; +inline ByteString operator+(ByteString::value_type const *ch, ByteString const &str) { return ByteString(ch) + str; } +inline ByteString operator+(std::basic_string const &other, ByteString const &str) { return ByteString(other) + str; } +inline ByteString operator+(std::basic_string &&other, ByteString const &str) { return ByteString(std::move(other)) + str; } + class String : public std::basic_string { public: @@ -39,22 +54,52 @@ public: inline String(value_type const *ch, size_type count): std::basic_string(ch, count) {} inline String(value_type const *ch): std::basic_string(ch) {} template inline String(It first, It last): std::basic_string(first, last) {} + inline String(std::basic_string const &other): std::basic_string(other) {} + inline String(std::basic_string &&other): std::basic_string(std::move(other)) {} inline String(String const &other): std::basic_string(other) {} inline String(String &&other): std::basic_string(std::move(other)) {} + template inline String(ByteString::value_type const (&ch)[N]): std::basic_string(ByteString(ch, N - 1).FromAscii()) {} - String &operator=(String const &other) { std::basic_string::operator=(other); return *this; } - String &operator=(String &&other) { std::basic_string::operator=(std::move(other)); return *this; } + inline String &operator=(String const &other) { std::basic_string::operator=(other); return *this; } + inline String &operator=(String &&other) { std::basic_string::operator=(other); return *this; } + + template inline String &operator+=(T &&other) { std::basic_string::operator+=(std::forward(other)); return *this; } + template inline String &operator+=(ByteString::value_type const (&ch)[N]) { std::basic_string::operator+=(ByteString(ch, N - 1).FromAscii()); return *this; } + template inline String operator+(T &&other) const { String tmp = *this; tmp += std::forward(other); return tmp; } + template inline String substr(Ts&&... args) const { return std::basic_string::substr(std::forward(args)...); } + inline String &insert(size_t pos, String &str) { std::basic_string::insert(pos, str); return *this; } + inline String &insert(size_t pos, size_t n, value_type ch) { std::basic_string::insert(pos, n, ch); return *this; } + template inline String &insert(size_t pos, ByteString::value_type const (&ch)[N]) { std::basic_string::insert(pos, ByteString(ch, N - 1).FromAscii()); return *this; } + inline size_t find(String const &str, size_t pos = 0) { return std::basic_string::find(str, pos); } + inline size_t find(value_type ch, size_t pos = 0) { return std::basic_string::find(ch, pos); } - template inline String(ByteString::value_type const (&ch)[N]): std::basic_string(ByteString(ch, N).FromAscii()) {} + inline bool operator==(String const &other) { return std::basic_string(*this) == other; } ByteString ToUtf8() const; + ByteString ToAscii() const; + + using Stream = std::basic_stringstream; }; +inline String operator+(String::value_type const *ch, String const &str) { return String(ch) + str; } +inline String operator+(std::basic_string const &other, String const &str) { return String(other) + str; } +inline String operator+(std::basic_string &&other, String const &str) { return String(std::move(other)) + str; } +template inline String operator+(ByteString::value_type const (&ch)[N], String const &str) { return String(ch) + str; } + + inline String ByteString::FromAscii() const { String destination = String(size(), String::value_type()); for(size_t i = 0; i < size(); i++) - destination[i] = typename String::value_type(operator[](i)); + destination[i] = String::value_type(std::make_unsigned::type(operator[](i))); + return destination; +} + +inline ByteString String::ToAscii() const +{ + ByteString destination = ByteString(size(), ByteString::value_type()); + for(size_t i = 0; i < size(); i++) + destination[i] = ByteString::value_type(operator[](i)); return destination; } #endif diff --git a/src/debug/DebugLines.cpp b/src/debug/DebugLines.cpp index 69992dc66..5a42928a1 100644 --- a/src/debug/DebugLines.cpp +++ b/src/debug/DebugLines.cpp @@ -27,21 +27,21 @@ void DebugLines::Draw() g->draw_line(0, drawPoint2.Y, XRES, drawPoint2.Y, 255, 255, 255, 120); g->draw_line(drawPoint2.X, 0, drawPoint2.X, YRES, 255, 255, 255, 120); - std::stringstream info; + String::Stream info; info << drawPoint2.X << " x " << drawPoint2.Y; - g->drawtext_outline(drawPoint2.X+(drawPoint2.X>drawPoint1.X?3:-g->textwidth(info.str().c_str())-3), drawPoint2.Y+(drawPoint2.Ydrawtext_outline(drawPoint2.X+(drawPoint2.X>drawPoint1.X?3:-g->textwidth(info.str())-3), drawPoint2.Y+(drawPoint2.Ydrawtext_outline(drawPoint1.X+(drawPoint2.Xtextwidth(info.str().c_str())-2), drawPoint1.Y+(drawPoint2.Y>drawPoint1.Y?-10:3), info.str().c_str(), 255, 255, 255, 200); + g->drawtext_outline(drawPoint1.X+(drawPoint2.Xtextwidth(info.str())-2), drawPoint1.Y+(drawPoint2.Y>drawPoint1.Y?-10:3), info.str(), 255, 255, 255, 200); - info.str(""); + info.str(String()); info << std::abs(drawPoint2.X-drawPoint1.X); - g->drawtext_outline((drawPoint1.X+drawPoint2.X)/2-g->textwidth(info.str().c_str())/2, drawPoint1.Y+(drawPoint2.Y>drawPoint1.Y?-10:3), info.str().c_str(), 255, 255, 255, 200); + g->drawtext_outline((drawPoint1.X+drawPoint2.X)/2-g->textwidth(info.str())/2, drawPoint1.Y+(drawPoint2.Y>drawPoint1.Y?-10:3), info.str(), 255, 255, 255, 200); - info.str(""); + info.str(String()); info << std::abs(drawPoint2.Y-drawPoint1.Y); - g->drawtext_outline(drawPoint1.X+(drawPoint2.Xtextwidth(info.str().c_str())-2), (drawPoint1.Y+drawPoint2.Y)/2-3, info.str().c_str(), 255, 255, 255, 200); + g->drawtext_outline(drawPoint1.X+(drawPoint2.Xtextwidth(info.str())-2), (drawPoint1.Y+drawPoint2.Y)/2-3, info.str(), 255, 255, 255, 200); } } diff --git a/src/debug/DebugParts.cpp b/src/debug/DebugParts.cpp index fd14ddd2c..9c2ef55d2 100644 --- a/src/debug/DebugParts.cpp +++ b/src/debug/DebugParts.cpp @@ -1,5 +1,4 @@ #include -#include #include "DebugParts.h" #include "gui/interface/Engine.h" #include "simulation/Simulation.h" @@ -16,7 +15,7 @@ void DebugParts::Draw() Graphics * g = ui::Engine::Ref().g; int x = 0, y = 0, lpx = 0, lpy = 0; - std::stringstream info; + String::Stream info; info << sim->parts_lastActiveIndex << "/" << NPART << " (" << std::fixed << std::setprecision(2) << (float)sim->parts_lastActiveIndex/(NPART)*100.0f << "%)"; for (int i = 0; i < NPART; i++) { @@ -46,8 +45,8 @@ void DebugParts::Draw() g->addpixel(lpx, lpy+1, 255, 50, 50, 120); g->addpixel(lpx, lpy-1, 255, 50, 50, 120); - g->fillrect(7, YRES-26, g->textwidth(info.str().c_str())+5, 14, 0, 0, 0, 180); - g->drawtext(10, YRES-22, info.str().c_str(), 255, 255, 255, 255); + g->fillrect(7, YRES-26, g->textwidth(info.str())+5, 14, 0, 0, 0, 180); + g->drawtext(10, YRES-22, info.str(), 255, 255, 255, 255); } DebugParts::~DebugParts() diff --git a/src/debug/ElementPopulation.cpp b/src/debug/ElementPopulation.cpp index f2cbfb05d..3de462a11 100644 --- a/src/debug/ElementPopulation.cpp +++ b/src/debug/ElementPopulation.cpp @@ -18,8 +18,8 @@ void ElementPopulationDebug::Draw() int yBottom = YRES-10; int xStart = 10; - std::string maxValString; - std::string halfValString; + String maxValString; + String halfValString; float maxVal = 255; @@ -41,7 +41,7 @@ void ElementPopulationDebug::Draw() halfValString = format::NumberToString(maxAverage/2); - g->fillrect(xStart-5, yBottom - 263, bars+10+Graphics::textwidth(maxValString.c_str())+10, 255 + 13, 0, 0, 0, 180); + g->fillrect(xStart-5, yBottom - 263, bars+10+Graphics::textwidth(maxValString)+10, 255 + 13, 0, 0, 0, 180); bars = 0; for(int i = 0; i < PT_NUM; i++) diff --git a/src/debug/ParticleDebug.cpp b/src/debug/ParticleDebug.cpp index c838cc64d..a9fd3ebfe 100644 --- a/src/debug/ParticleDebug.cpp +++ b/src/debug/ParticleDebug.cpp @@ -1,4 +1,3 @@ -#include #include "ParticleDebug.h" #include "gui/interface/Engine.h" #include "gui/game/GameView.h" @@ -16,7 +15,7 @@ void ParticleDebug::Debug(int mode, int x, int y) { int debug_currentParticle = sim->debug_currentParticle; int i = 0; - std::stringstream logmessage; + String::Stream logmessage; if (mode == 0) { @@ -90,7 +89,7 @@ bool ParticleDebug::KeyPress(int key, Uint16 character, bool shift, bool ctrl, b { sim->UpdateParticles(sim->debug_currentParticle, NPART); sim->AfterSim(); - std::stringstream logmessage; + String::Stream logmessage; logmessage << "Updated particles from #" << sim->debug_currentParticle << " to end, updated sim"; model->Log(logmessage.str(), false); sim->debug_currentParticle = 0; diff --git a/src/graphics/DrawMethodsDef.inc b/src/graphics/DrawMethodsDef.inc index 31fbb6869..663f4bbe0 100644 --- a/src/graphics/DrawMethodsDef.inc +++ b/src/graphics/DrawMethodsDef.inc @@ -1,7 +1,6 @@ - int drawtext(int x, int y, const char *s, int r, int g, int b, int a); - int drawtext(int x, int y, std::string s, int r, int g, int b, int a); - int drawchar(int x, int y, int c, int r, int g, int b, int a); - int addchar(int x, int y, int c, int r, int g, int b, int a); + int drawtext(int x, int y, String s, int r, int g, int b, int a); + int drawchar(int x, int y, String::value_type c, int r, int g, int b, int a); + int addchar(int x, int y, String::value_type c, int r, int g, int b, int a); void xor_pixel(int x, int y); void xor_line(int x, int y, int x2, int y2); diff --git a/src/graphics/Graphics.cpp b/src/graphics/Graphics.cpp index f16b8a347..3e86925ea 100644 --- a/src/graphics/Graphics.cpp +++ b/src/graphics/Graphics.cpp @@ -1,7 +1,7 @@ #include #include #include -#include +#include "common/String.h" #include "Config.h" #include "Misc.h" #include "Graphics.h" @@ -566,9 +566,10 @@ pixel *Graphics::rescale_img(pixel *src, int sw, int sh, int *qw, int *qh, int f return q; } -int Graphics::textwidth(const char *s) +int Graphics::textwidth(String str) { int x = 0; + String::value_type const *s = str.c_str(); for (; *s; s++) { if(((char)*s)=='\b') @@ -581,19 +582,20 @@ int Graphics::textwidth(const char *s) s+=3; continue; } - x += font_data[font_ptrs[(int)(*(unsigned char *)s)]]; + x += font_data[font_ptrs[*s]]; } return x-1; } -int Graphics::CharWidth(unsigned char c) +int Graphics::CharWidth(String::value_type c) { return font_data[font_ptrs[(int)c]]; } -int Graphics::textnwidth(char *s, int n) +int Graphics::textnwidth(String str, int n) { int x = 0; + String::value_type const *s = str.c_str(); for (; *s; s++) { if (!n) @@ -608,20 +610,23 @@ int Graphics::textnwidth(char *s, int n) s+=3; continue; } - x += font_data[font_ptrs[(int)(*(unsigned char *)s)]]; + x += font_data[font_ptrs[*s]]; n--; } return x-1; } -void Graphics::textnpos(char *s, int n, int w, int *cx, int *cy) +void Graphics::textnpos(String str, int n, int w, int *cx, int *cy) { int x = 0; int y = 0; int wordlen, charspace; + String::value_type const *s = str.c_str(); while (*s&&n) { - wordlen = strcspn(s," .,!?\n"); + wordlen = 0; + while(*s && String(" .,!?\n").find(*s) != String::npos) + s++; charspace = textwidthx(s, w-x); if (charspace=w) { x = 0; @@ -646,9 +651,10 @@ void Graphics::textnpos(char *s, int n, int w, int *cx, int *cy) *cy = y; } -int Graphics::textwidthx(char *s, int w) +int Graphics::textwidthx(String str, int w) { int x=0,n=0,cw; + String::value_type const *s = str.c_str(); for (; *s; s++) { if((char)*s == '\b') @@ -662,7 +668,7 @@ int Graphics::textwidthx(char *s, int w) s+=3; continue; } - cw = font_data[font_ptrs[(int)(*(unsigned char *)s)]]; + cw = font_data[font_ptrs[*s]]; if (x+(cw/2) >= w) break; x += cw; @@ -671,9 +677,10 @@ int Graphics::textwidthx(char *s, int w) return n; } -int Graphics::PositionAtCharIndex(char *s, int charIndex, int & positionX, int & positionY) +int Graphics::PositionAtCharIndex(String str, int charIndex, int & positionX, int & positionY) { int x = 0, y = 0, lines = 1; + String::value_type const *s = str.c_str(); for (; *s; s++) { if (!charIndex) @@ -695,7 +702,7 @@ int Graphics::PositionAtCharIndex(char *s, int charIndex, int & positionX, int & charIndex-=4; continue; } - x += font_data[font_ptrs[(int)(*(unsigned char *)s)]]; + x += font_data[font_ptrs[*s]]; charIndex--; } positionX = x; @@ -703,9 +710,10 @@ int Graphics::PositionAtCharIndex(char *s, int charIndex, int & positionX, int & return lines; } -int Graphics::CharIndexAtPosition(char *s, int positionX, int positionY) +int Graphics::CharIndexAtPosition(String str, int positionX, int positionY) { int x=0, y=-2,charIndex=0,cw; + String::value_type const *s = str.c_str(); for (; *s; s++) { if(*s == '\n') { @@ -724,7 +732,7 @@ int Graphics::CharIndexAtPosition(char *s, int positionX, int positionY) charIndex+=4; continue; } - cw = font_data[font_ptrs[(int)(*(unsigned char *)s)]]; + cw = font_data[font_ptrs[*s]]; if ((x+(cw/2) >= positionX && y+FONT_H >= positionY) || y > positionY) break; x += cw; @@ -734,14 +742,17 @@ int Graphics::CharIndexAtPosition(char *s, int positionX, int positionY) } -int Graphics::textwrapheight(char *s, int width) +int Graphics::textwrapheight(String str, int width) { int x=0, height=FONT_H, cw; int wordlen; int charspace; + String::value_type const *s = str.c_str(); while (*s) { - wordlen = strcspn(s," .,!?\n"); + wordlen = 0; + while(*s && String(" .,!?\n").find(*s) != String::npos) + s++; charspace = textwidthx(s, width-x); if (charspace=width) { x = 0; @@ -780,9 +791,9 @@ int Graphics::textwrapheight(char *s, int width) return height; } -void Graphics::textsize(const char * s, int & width, int & height) +void Graphics::textsize(String str, int & width, int & height) { - if(!strlen(s)) + if(!str.size()) { width = 0; height = FONT_H-2; @@ -790,6 +801,7 @@ void Graphics::textsize(const char * s, int & width, int & height) } int cHeight = FONT_H-2, cWidth = 0, lWidth = 0; + String::value_type const *s = str.c_str(); for (; *s; s++) { if (*s == '\n') @@ -809,7 +821,7 @@ void Graphics::textsize(const char * s, int & width, int & height) } else { - cWidth += font_data[font_ptrs[(int)(*(unsigned char *)s)]]; + cWidth += font_data[font_ptrs[*s]]; if(cWidth>lWidth) lWidth = cWidth; } diff --git a/src/graphics/Graphics.h b/src/graphics/Graphics.h index 5c1e6adc9..aa961dd12 100644 --- a/src/graphics/Graphics.h +++ b/src/graphics/Graphics.h @@ -1,7 +1,7 @@ #ifndef GRAPHICS_H #define GRAPHICS_H -#include +#include "common/String.h" #include #include #include @@ -116,15 +116,15 @@ public: static pixel *render_packed_rgb(void *image, int width, int height, int cmp_size); //Font/text metrics - static int CharIndexAtPosition(char *s, int positionX, int positionY); - static int PositionAtCharIndex(char *s, int charIndex, int & positionX, int & positionY); - static int CharWidth(unsigned char c); - static int textnwidth(char *s, int n); - static void textnpos(char *s, int n, int w, int *cx, int *cy); - static int textwidthx(char *s, int w); - static int textwrapheight(char *s, int width); - static int textwidth(const char *s); - static void textsize(const char * s, int & width, int & height); + static int CharIndexAtPosition(String s, int positionX, int positionY); + static int PositionAtCharIndex(String s, int charIndex, int & positionX, int & positionY); + static int CharWidth(String::value_type c); + static int textnwidth(String s, int n); + static void textnpos(String s, int n, int w, int *cx, int *cy); + static int textwidthx(String s, int w); + static int textwrapheight(String s, int width); + static int textwidth(String s); + static void textsize(String s, int & width, int & height); VideoBuffer DumpFrame(); @@ -139,11 +139,10 @@ public: void Clear(); void Finalise(); // - int drawtext_outline(int x, int y, const char *s, int r, int g, int b, int a); - int drawtext(int x, int y, const char *s, int r, int g, int b, int a); - int drawtext(int x, int y, std::string s, int r, int g, int b, int a); - int drawchar(int x, int y, int c, int r, int g, int b, int a); - int addchar(int x, int y, int c, int r, int g, int b, int a); + int drawtext_outline(int x, int y, String s, int r, int g, int b, int a); + int drawtext(int x, int y, String s, int r, int g, int b, int a); + int drawchar(int x, int y, String::value_type c, int r, int g, int b, int a); + int addchar(int x, int y, String::value_type c, int r, int g, int b, int a); void xor_pixel(int x, int y); void xor_line(int x, int y, int x2, int y2); diff --git a/src/graphics/OpenGLDrawMethods.inl b/src/graphics/OpenGLDrawMethods.inl index 9487fcfc6..1d01c7e0e 100644 --- a/src/graphics/OpenGLDrawMethods.inl +++ b/src/graphics/OpenGLDrawMethods.inl @@ -1,7 +1,7 @@ #include "../data/font.h" #include -int PIXELMETHODS_CLASS::drawtext_outline(int x, int y, const char *s, int r, int g, int b, int a) +int PIXELMETHODS_CLASS::drawtext_outline(int x, int y, String s, int r, int g, int b, int a) { drawtext(x-1, y-1, s, 0, 0, 0, 120); drawtext(x+1, y+1, s, 0, 0, 0, 120); @@ -12,7 +12,7 @@ int PIXELMETHODS_CLASS::drawtext_outline(int x, int y, const char *s, int r, int return drawtext(x, y, s, r, g, b, a); } -int PIXELMETHODS_CLASS::drawtext(int x, int y, const char *s, int r, int g, int b, int a) +int PIXELMETHODS_CLASS::drawtext(int x, int y, String str, int r, int g, int b, int a) { bool invert = false; if(!strlen(s)) @@ -23,6 +23,7 @@ int PIXELMETHODS_CLASS::drawtext(int x, int y, const char *s, int r, int g, int VideoBuffer texture(width, height); int characterX = 0, characterY = 0; int startX = characterX; + String::value_type *s = str.c_str(); for (; *s; s++) { if (*s == '\n') @@ -98,7 +99,7 @@ int PIXELMETHODS_CLASS::drawtext(int x, int y, const char *s, int r, int g, int } else { - characterX = texture.SetCharacter(characterX, characterY, *(unsigned char *)s, r, g, b, a); + characterX = texture.SetCharacter(characterX, characterY, *s, r, g, b, a); } } glEnable(GL_TEXTURE_2D); @@ -128,12 +129,7 @@ int PIXELMETHODS_CLASS::drawtext(int x, int y, const char *s, int r, int g, int return x; } -int PIXELMETHODS_CLASS::drawtext(int x, int y, std::string s, int r, int g, int b, int a) -{ - return drawtext(x, y, s.c_str(), r, g, b, a); -} - -int PIXELMETHODS_CLASS::drawchar(int x, int y, int c, int r, int g, int b, int a) +int PIXELMETHODS_CLASS::drawchar(int x, int y, String::value_type c, int r, int g, int b, int a) { unsigned char *rp = font_data + font_ptrs[c]; int w = *(rp++); @@ -162,7 +158,7 @@ int PIXELMETHODS_CLASS::drawchar(int x, int y, int c, int r, int g, int b, int a return x + w; } -int PIXELMETHODS_CLASS::addchar(int x, int y, int c, int r, int g, int b, int a) +int PIXELMETHODS_CLASS::addchar(int x, int y, String::value_type c, int r, int g, int b, int a) { unsigned char *rp = font_data + font_ptrs[c]; int w = *(rp++); diff --git a/src/graphics/RasterDrawMethods.inl b/src/graphics/RasterDrawMethods.inl index 0cdca0e4e..4bb1469bc 100644 --- a/src/graphics/RasterDrawMethods.inl +++ b/src/graphics/RasterDrawMethods.inl @@ -1,7 +1,7 @@ #include "font.h" #include -int PIXELMETHODS_CLASS::drawtext_outline(int x, int y, const char *s, int r, int g, int b, int a) +int PIXELMETHODS_CLASS::drawtext_outline(int x, int y, String s, int r, int g, int b, int a) { drawtext(x-1, y-1, s, 0, 0, 0, 120); drawtext(x+1, y+1, s, 0, 0, 0, 120); @@ -12,15 +12,16 @@ int PIXELMETHODS_CLASS::drawtext_outline(int x, int y, const char *s, int r, int return drawtext(x, y, s, r, g, b, a); } -int PIXELMETHODS_CLASS::drawtext(int x, int y, const char *s, int r, int g, int b, int a) +int PIXELMETHODS_CLASS::drawtext(int x, int y, String str, int r, int g, int b, int a) { - if(!strlen(s)) + if(!str.size()) return 0; int invert = 0; int oR = r, oG = g, oB = b; int characterX = x, characterY = y; int startX = characterX; + String::value_type const *s = str.c_str(); for (; *s; s++) { if (*s == '\n') @@ -96,18 +97,13 @@ int PIXELMETHODS_CLASS::drawtext(int x, int y, const char *s, int r, int g, int } else { - characterX = drawchar(characterX, characterY, *(unsigned char *)s, r, g, b, a); + characterX = drawchar(characterX, characterY, *s, r, g, b, a); } } return x; } -int PIXELMETHODS_CLASS::drawtext(int x, int y, std::string s, int r, int g, int b, int a) -{ - return drawtext(x, y, s.c_str(), r, g, b, a); -} - -int PIXELMETHODS_CLASS::drawchar(int x, int y, int c, int r, int g, int b, int a) +int PIXELMETHODS_CLASS::drawchar(int x, int y, String::value_type c, int r, int g, int b, int a) { int i, j, w, bn = 0, ba = 0; unsigned char *rp = font_data + font_ptrs[c]; @@ -127,7 +123,7 @@ int PIXELMETHODS_CLASS::drawchar(int x, int y, int c, int r, int g, int b, int a return x + w; } -int PIXELMETHODS_CLASS::addchar(int x, int y, int c, int r, int g, int b, int a) +int PIXELMETHODS_CLASS::addchar(int x, int y, String::value_type c, int r, int g, int b, int a) { int i, j, w, bn = 0, ba = 0; unsigned char *rp = font_data + font_ptrs[c]; diff --git a/src/graphics/Renderer.cpp b/src/graphics/Renderer.cpp index 085b8e54d..57ffeb2cd 100644 --- a/src/graphics/Renderer.cpp +++ b/src/graphics/Renderer.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -519,17 +520,16 @@ void Renderer::RenderZoom() #endif } -int Renderer_wtypesCount; -wall_type * Renderer_wtypes = LoadWalls(Renderer_wtypesCount); +std::vector Renderer_wtypes = LoadWalls(); VideoBuffer * Renderer::WallIcon(int wallID, int width, int height) { int i, j; int wt = wallID; - if (wt<0 || wt>=Renderer_wtypesCount) + if (wt<0 || wt>=(int)Renderer_wtypes.size()) return 0; - wall_type *wtypes = Renderer_wtypes; + wall_type *wtypes = Renderer_wtypes.data(); pixel pc = wtypes[wt].colour; pixel gc = wtypes[wt].eglow; VideoBuffer * newTexture = new VideoBuffer(width, height); @@ -985,8 +985,8 @@ void Renderer::DrawSigns() for (size_t i = 0; i < signs.size(); i++) if (signs[i].text.length()) { - char type = 0; - std::string text = signs[i].getText(sim); + String::value_type type = 0; + String text = signs[i].getText(sim); sign::splitsign(signs[i].text, &type); signs[i].pos(text, x, y, w, h); clearrect(x, y, w+1, h); @@ -1496,9 +1496,9 @@ void Renderer::render_parts() if (mousePos.X>(nx-3) && mousePos.X<(nx+3) && mousePos.Y<(ny+3) && mousePos.Y>(ny-3)) //If mouse is in the head { - char buff[12]; //Buffer for HP - sprintf(buff, "%3d", sim->parts[i].life); //Show HP - drawtext(mousePos.X-8-2*(sim->parts[i].life<100)-2*(sim->parts[i].life<10), mousePos.Y-12, buff, 255, 255, 255, 255); + String::Stream hp; + hp << std::setw(3) << sim->parts[i].life; + drawtext(mousePos.X-8-2*(sim->parts[i].life<100)-2*(sim->parts[i].life<10), mousePos.Y-12, hp.str(), 255, 255, 255, 255); } if (findingElement == t) diff --git a/src/graphics/Renderer.h b/src/graphics/Renderer.h index 42afd9d07..b14143b7b 100644 --- a/src/graphics/Renderer.h +++ b/src/graphics/Renderer.h @@ -113,11 +113,10 @@ public: void draw_icon(int x, int y, Icon icon); - int drawtext_outline(int x, int y, const char *s, int r, int g, int b, int a); - int drawtext(int x, int y, const char *s, int r, int g, int b, int a); - int drawtext(int x, int y, std::string s, int r, int g, int b, int a); - int drawchar(int x, int y, int c, int r, int g, int b, int a); - int addchar(int x, int y, int c, int r, int g, int b, int a); + int drawtext_outline(int x, int y, String s, int r, int g, int b, int a); + int drawtext(int x, int y, String s, int r, int g, int b, int a); + int drawchar(int x, int y, String::value_type c, int r, int g, int b, int a); + int addchar(int x, int y, String::value_type c, int r, int g, int b, int a); void xor_pixel(int x, int y); void xor_line(int x, int y, int x2, int y2); diff --git a/src/gui/colourpicker/ColourPickerActivity.cpp b/src/gui/colourpicker/ColourPickerActivity.cpp index c83966d96..85d051030 100644 --- a/src/gui/colourpicker/ColourPickerActivity.cpp +++ b/src/gui/colourpicker/ColourPickerActivity.cpp @@ -108,8 +108,8 @@ void ColourPickerActivity::UpdateTextboxes(int r, int g, int b, int a) gValue->SetText(format::NumberToString(g)); bValue->SetText(format::NumberToString(b)); aValue->SetText(format::NumberToString(a)); - std::stringstream hex; - hex << std::hex << "0x" << std::setfill('0') << std::setw(2) << std::uppercase << a << std::setw(2) << r << std::setw(2) << g << std::setw(2) << b; + String::Stream hex; + hex << std::hex << "0x" << std::setfill(String::value_type('0')) << std::setw(2) << std::uppercase << a << std::setw(2) << r << std::setw(2) << g << std::setw(2) << b; hexValue->SetText(hex.str()); } void ColourPickerActivity::OnTryExit(ExitMethod method) diff --git a/src/gui/colourpicker/ColourPickerActivity.h b/src/gui/colourpicker/ColourPickerActivity.h index e837cc147..f8213885b 100644 --- a/src/gui/colourpicker/ColourPickerActivity.h +++ b/src/gui/colourpicker/ColourPickerActivity.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include "common/String.h" #include "Activity.h" #include "gui/interface/Window.h" #include "gui/interface/Textbox.h" diff --git a/src/gui/console/ConsoleCommand.h b/src/gui/console/ConsoleCommand.h index 31e41b05f..87e85e406 100644 --- a/src/gui/console/ConsoleCommand.h +++ b/src/gui/console/ConsoleCommand.h @@ -4,18 +4,18 @@ class ConsoleCommand { public: - ConsoleCommand(std::string command, int returnStatus, std::string returnValue): + ConsoleCommand(String command, int returnStatus, String returnValue): Command(command), ReturnStatus(returnStatus), ReturnValue(returnValue) { } - std::string Command; + String Command; int ReturnStatus; - std::string ReturnValue; + String ReturnValue; - operator std::string() const + operator ByteString() const { - return Command; + return Command.ToUtf8(); } }; diff --git a/src/gui/console/ConsoleController.cpp b/src/gui/console/ConsoleController.cpp index ed49319a1..e56968032 100644 --- a/src/gui/console/ConsoleController.cpp +++ b/src/gui/console/ConsoleController.cpp @@ -13,7 +13,7 @@ ConsoleController::ConsoleController(ControllerCallback * callback, CommandInter this->commandInterface = commandInterface; } -void ConsoleController::EvaluateCommand(std::string command) +void ConsoleController::EvaluateCommand(String command) { if(command.length()) { @@ -31,7 +31,7 @@ void ConsoleController::CloseConsole() consoleView->CloseActiveWindow(); } -std::string ConsoleController::FormatCommand(std::string command) +String ConsoleController::FormatCommand(String command) { return commandInterface->FormatCommand(command); } diff --git a/src/gui/console/ConsoleController.h b/src/gui/console/ConsoleController.h index 03c2fa78d..26f61acbe 100644 --- a/src/gui/console/ConsoleController.h +++ b/src/gui/console/ConsoleController.h @@ -1,7 +1,7 @@ #ifndef CONSOLECONTROLLER_H_ #define CONSOLECONTROLLER_H_ -#include +#include "common/String.h" #include "Controller.h" #include "ConsoleView.h" #include "ConsoleModel.h" @@ -18,8 +18,8 @@ class ConsoleController { public: bool HasDone; ConsoleController(ControllerCallback * callback, CommandInterface * commandInterface); - std::string FormatCommand(std::string command); - void EvaluateCommand(std::string command); + String FormatCommand(String command); + void EvaluateCommand(String command); void NextCommand(); void PreviousCommand(); void Exit(); diff --git a/src/gui/console/ConsoleModel.cpp b/src/gui/console/ConsoleModel.cpp index e05fe5949..bd516a84b 100644 --- a/src/gui/console/ConsoleModel.cpp +++ b/src/gui/console/ConsoleModel.cpp @@ -2,8 +2,8 @@ #include "ConsoleModel.h" ConsoleModel::ConsoleModel() { - std::vector previousHistory = Client::Ref().GetPrefStringArray("Console.History"); - for(std::vector::reverse_iterator iter = previousHistory.rbegin(), end = previousHistory.rend(); iter != end; ++iter) + std::vector previousHistory = Client::Ref().GetPrefStringArray("Console.History"); + for(std::vector::reverse_iterator iter = previousHistory.rbegin(), end = previousHistory.rend(); iter != end; ++iter) { if(previousCommands.size()<25) { diff --git a/src/gui/dialogues/ConfirmPrompt.cpp b/src/gui/dialogues/ConfirmPrompt.cpp index 0fa00ff1c..f7ea37f8b 100644 --- a/src/gui/dialogues/ConfirmPrompt.cpp +++ b/src/gui/dialogues/ConfirmPrompt.cpp @@ -6,7 +6,7 @@ #include "gui/interface/ScrollPanel.h" #include "PowderToy.h" -ConfirmPrompt::ConfirmPrompt(std::string title, std::string message, ConfirmDialogueCallback * callback_): +ConfirmPrompt::ConfirmPrompt(String title, String message, ConfirmDialogueCallback * callback_): ui::Window(ui::Point(-1, -1), ui::Point(250, 35)), callback(callback_) { @@ -68,7 +68,7 @@ ConfirmPrompt::ConfirmPrompt(std::string title, std::string message, ConfirmDial MakeActiveWindow(); } -ConfirmPrompt::ConfirmPrompt(std::string title, std::string message, std::string buttonText, ConfirmDialogueCallback * callback_): +ConfirmPrompt::ConfirmPrompt(String title, String message, String buttonText, ConfirmDialogueCallback * callback_): ui::Window(ui::Point(-1, -1), ui::Point(250, 50)), callback(callback_) { @@ -130,7 +130,7 @@ ConfirmPrompt::ConfirmPrompt(std::string title, std::string message, std::string MakeActiveWindow(); } -bool ConfirmPrompt::Blocking(std::string title, std::string message, std::string buttonText) +bool ConfirmPrompt::Blocking(String title, String message, String buttonText) { class BlockingPromptCallback: public ConfirmDialogueCallback { public: diff --git a/src/gui/dialogues/ConfirmPrompt.h b/src/gui/dialogues/ConfirmPrompt.h index 62aff7fd2..0e39f3450 100644 --- a/src/gui/dialogues/ConfirmPrompt.h +++ b/src/gui/dialogues/ConfirmPrompt.h @@ -1,16 +1,16 @@ #ifndef CONFIRMPROMPT_H_ #define CONFIRMPROMPT_H_ -#include +#include "common/String.h" #include "gui/interface/Window.h" class ConfirmDialogueCallback; class ConfirmPrompt: public ui::Window { public: enum DialogueResult { ResultCancel, ResultOkay }; - ConfirmPrompt(std::string title, std::string message, ConfirmDialogueCallback * callback_ = NULL); - ConfirmPrompt(std::string title, std::string message, std::string buttonText, ConfirmDialogueCallback * callback_ = NULL); - static bool Blocking(std::string title, std::string message, std::string buttonText = "Confirm"); + ConfirmPrompt(String title, String message, ConfirmDialogueCallback * callback_ = NULL); + ConfirmPrompt(String title, String message, String buttonText, ConfirmDialogueCallback * callback_ = NULL); + static bool Blocking(String title, String message, String buttonText = "Confirm"); virtual void OnDraw(); virtual ~ConfirmPrompt(); ConfirmDialogueCallback * callback; diff --git a/src/gui/dialogues/ErrorMessage.cpp b/src/gui/dialogues/ErrorMessage.cpp index 35b0a2dd2..394a9aa08 100644 --- a/src/gui/dialogues/ErrorMessage.cpp +++ b/src/gui/dialogues/ErrorMessage.cpp @@ -5,7 +5,7 @@ #include "gui/interface/Label.h" #include "PowderToy.h" -ErrorMessage::ErrorMessage(std::string title, std::string message, ErrorMessageCallback * callback_): +ErrorMessage::ErrorMessage(String title, String message, ErrorMessageCallback * callback_): ui::Window(ui::Point(-1, -1), ui::Point(200, 35)), callback(callback_) { @@ -50,7 +50,7 @@ ErrorMessage::ErrorMessage(std::string title, std::string message, ErrorMessage MakeActiveWindow(); } -void ErrorMessage::Blocking(std::string title, std::string message) +void ErrorMessage::Blocking(String title, String message) { class BlockingDismissCallback: public ErrorMessageCallback { public: diff --git a/src/gui/dialogues/ErrorMessage.h b/src/gui/dialogues/ErrorMessage.h index a7281b281..b5468ac27 100644 --- a/src/gui/dialogues/ErrorMessage.h +++ b/src/gui/dialogues/ErrorMessage.h @@ -7,8 +7,8 @@ class ErrorMessageCallback; class ErrorMessage: public ui::Window { ErrorMessageCallback * callback; public: - ErrorMessage(std::string title, std::string message, ErrorMessageCallback * callback_ = NULL); - static void Blocking(std::string title, std::string message); + ErrorMessage(String title, String message, ErrorMessageCallback * callback_ = NULL); + static void Blocking(String title, String message); virtual void OnDraw(); virtual ~ErrorMessage(); }; diff --git a/src/gui/dialogues/InformationMessage.cpp b/src/gui/dialogues/InformationMessage.cpp index c097c4f64..8e29d5c55 100644 --- a/src/gui/dialogues/InformationMessage.cpp +++ b/src/gui/dialogues/InformationMessage.cpp @@ -5,7 +5,7 @@ #include "gui/interface/Label.h" #include "gui/interface/ScrollPanel.h" -InformationMessage::InformationMessage(std::string title, std::string message, bool large): +InformationMessage::InformationMessage(String title, String message, bool large): ui::Window(ui::Point(-1, -1), ui::Point(200, 35)) { if (large) //Maybe also use this large mode for changelogs eventually, or have it as a customizable size? diff --git a/src/gui/dialogues/InformationMessage.h b/src/gui/dialogues/InformationMessage.h index 6a26b384a..2f13a9419 100644 --- a/src/gui/dialogues/InformationMessage.h +++ b/src/gui/dialogues/InformationMessage.h @@ -5,7 +5,7 @@ class InformationMessage: public ui::Window { public: - InformationMessage(std::string title, std::string message, bool large); + InformationMessage(String title, String message, bool large); virtual void OnDraw(); virtual ~InformationMessage(); }; diff --git a/src/gui/dialogues/LegacyDialogues.h b/src/gui/dialogues/LegacyDialogues.h index a60490500..ddde28a79 100644 --- a/src/gui/dialogues/LegacyDialogues.h +++ b/src/gui/dialogues/LegacyDialogues.h @@ -2,10 +2,10 @@ //Legacy blocking prompts //This are not implemented here, but rather in the engine bootstrapper -bool ConfirmUI(std::string title, std::string message, std::string confirmText) {} +bool ConfirmUI(String title, String message, String confirmText) {} -void ErrorUI(std::string title, std::string message) {} +void ErrorUI(String title, String message) {} -void InformationUI(std::string title, std::string message) {} +void InformationUI(String title, String message) {} -std::string MessagePromptUI(std::string title, std::string message, std::string text, std::string placeholder) {} +String MessagePromptUI(String title, String message, String text, String placeholder) {} diff --git a/src/gui/dialogues/TextPrompt.cpp b/src/gui/dialogues/TextPrompt.cpp index 4e0b5c066..24febf2ea 100644 --- a/src/gui/dialogues/TextPrompt.cpp +++ b/src/gui/dialogues/TextPrompt.cpp @@ -21,7 +21,7 @@ public: } }; -TextPrompt::TextPrompt(std::string title, std::string message, std::string text, std::string placeholder, bool multiline, TextDialogueCallback * callback_): +TextPrompt::TextPrompt(String title, String message, String text, String placeholder, bool multiline, TextDialogueCallback * callback_): ui::Window(ui::Point(-1, -1), ui::Point(200, 65)), callback(callback_) { @@ -77,15 +77,15 @@ TextPrompt::TextPrompt(std::string title, std::string message, std::string text, MakeActiveWindow(); } -std::string TextPrompt::Blocking(std::string title, std::string message, std::string text, std::string placeholder, bool multiline) +String TextPrompt::Blocking(String title, String message, String text, String placeholder, bool multiline) { - std::string returnString = ""; + String returnString = ""; class BlockingTextCallback: public TextDialogueCallback { - std::string & outputString; + String & outputString; public: - BlockingTextCallback(std::string & output) : outputString(output) {} - virtual void TextCallback(TextPrompt::DialogueResult result, std::string resultText) { + BlockingTextCallback(String & output) : outputString(output) {} + virtual void TextCallback(TextPrompt::DialogueResult result, String resultText) { if(result == ResultOkay) outputString = resultText; else diff --git a/src/gui/dialogues/TextPrompt.h b/src/gui/dialogues/TextPrompt.h index e88c977df..5b99d4ac5 100644 --- a/src/gui/dialogues/TextPrompt.h +++ b/src/gui/dialogues/TextPrompt.h @@ -11,8 +11,8 @@ protected: public: friend class CloseAction; enum DialogueResult { ResultCancel, ResultOkay }; - TextPrompt(std::string title, std::string message, std::string text, std::string placeholder, bool multiline, TextDialogueCallback * callback_); - static std::string Blocking(std::string title, std::string message, std::string text, std::string placeholder, bool multiline); + TextPrompt(String title, String message, String text, String placeholder, bool multiline, TextDialogueCallback * callback_); + static String Blocking(String title, String message, String text, String placeholder, bool multiline); virtual void OnDraw(); virtual ~TextPrompt(); TextDialogueCallback * callback; @@ -21,7 +21,7 @@ public: class TextDialogueCallback { public: - virtual void TextCallback(TextPrompt::DialogueResult result, std::string resultText) {} + virtual void TextCallback(TextPrompt::DialogueResult result, String resultText) {} virtual ~TextDialogueCallback() {} }; diff --git a/src/gui/elementsearch/ElementSearchActivity.cpp b/src/gui/elementsearch/ElementSearchActivity.cpp index 33cabfd03..9bad0fd5e 100644 --- a/src/gui/elementsearch/ElementSearchActivity.cpp +++ b/src/gui/elementsearch/ElementSearchActivity.cpp @@ -1,4 +1,5 @@ #include +#include "common/String.h" #include "ElementSearchActivity.h" #include "gui/interface/Textbox.h" #include "gui/interface/Label.h" @@ -91,7 +92,7 @@ ElementSearchActivity::ElementSearchActivity(GameController * gameController, st searchTools(""); } -void ElementSearchActivity::searchTools(std::string query) +void ElementSearchActivity::searchTools(String query) { firstResult = NULL; for(std::vector::iterator iter = toolButtons.begin(), end = toolButtons.end(); iter != end; ++iter) { @@ -103,7 +104,7 @@ void ElementSearchActivity::searchTools(std::string query) ui::Point viewPosition = searchField->Position + ui::Point(2+0, searchField->Size.Y+2+8); ui::Point current = ui::Point(0, 0); - std::string queryLower = std::string(query); + ByteString queryLower = query.ToAscii(); std::transform(queryLower.begin(), queryLower.end(), queryLower.begin(), ::tolower); std::vector matches; @@ -112,13 +113,13 @@ void ElementSearchActivity::searchTools(std::string query) for(std::vector::const_iterator iter = tools.begin(), end = tools.end(); iter != end; ++iter) { - std::string nameLower = std::string((*iter)->GetName()); + ByteString nameLower = (*iter)->GetName(); std::transform(nameLower.begin(), nameLower.end(), nameLower.begin(), ::tolower); - if(!strcmp(nameLower.c_str(), queryLower.c_str())) + if(nameLower == queryLower) exactmatches.push_back(*iter); - else if(!strncmp(nameLower.c_str(), queryLower.c_str(), queryLower.length())) + else if(!nameLower.compare(0, queryLower.length(), queryLower)) frontmatches.push_back(*iter); - else if(strstr(nameLower.c_str(), queryLower.c_str())) + else if(nameLower.find(queryLower) != String::npos) matches.push_back(*iter); } @@ -198,7 +199,7 @@ void ElementSearchActivity::OnDraw() g->drawrect(Position.X+searchField->Position.X, Position.Y+searchField->Position.Y+searchField->Size.Y+8, searchField->Size.X, Size.Y-(searchField->Position.Y+searchField->Size.Y+8)-23, 255, 255, 255, 180); if (toolTipPresence && toolTip.length()) { - g->drawtext(10, Size.Y+70, (char*)toolTip.c_str(), 255, 255, 255, toolTipPresence>51?255:toolTipPresence*5); + g->drawtext(10, Size.Y+70, toolTip, 255, 255, 255, toolTipPresence>51?255:toolTipPresence*5); } } @@ -265,7 +266,7 @@ void ElementSearchActivity::OnKeyRelease(int key, Uint16 character, bool shift, } } -void ElementSearchActivity::ToolTip(ui::Point senderPosition, std::string toolTip) +void ElementSearchActivity::ToolTip(ui::Point senderPosition, String toolTip) { this->toolTip = toolTip; this->isToolTipFadingIn = true; diff --git a/src/gui/elementsearch/ElementSearchActivity.h b/src/gui/elementsearch/ElementSearchActivity.h index bf9af235a..a4dfb46e0 100644 --- a/src/gui/elementsearch/ElementSearchActivity.h +++ b/src/gui/elementsearch/ElementSearchActivity.h @@ -2,7 +2,6 @@ #define ELEMENTSEARCHACTIVITY_H_ #include -#include #include "Activity.h" #include "gui/interface/Window.h" #include "gui/interface/Textbox.h" @@ -18,13 +17,13 @@ class ElementSearchActivity: public WindowActivity std::vector tools; ui::Textbox * searchField; std::vector toolButtons; - std::string toolTip; + String toolTip; int toolTipPresence; bool shiftPressed; bool ctrlPressed; bool altPressed; bool isToolTipFadingIn; - void searchTools(std::string query); + void searchTools(String query); public: class ToolAction; @@ -37,7 +36,7 @@ public: virtual void OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool alt); virtual void OnKeyRelease(int key, Uint16 character, bool shift, bool ctrl, bool alt); virtual void OnDraw(); - virtual void ToolTip(ui::Point senderPosition, std::string ToolTip); + virtual void ToolTip(ui::Point senderPosition, String ToolTip); }; #endif /* ELEMENTSEARCHACTIVITY_H_ */ diff --git a/src/gui/filebrowser/FileBrowserActivity.cpp b/src/gui/filebrowser/FileBrowserActivity.cpp index 4a84291dd..bfcc128fb 100644 --- a/src/gui/filebrowser/FileBrowserActivity.cpp +++ b/src/gui/filebrowser/FileBrowserActivity.cpp @@ -1,4 +1,3 @@ -#include #include #include #include "FileBrowserActivity.h" @@ -42,8 +41,8 @@ public: //Currently, reading is done on another thread, we can't render outside the main thread due to some bullshit with OpenGL class LoadFilesTask: public Task { - std::string directory; - std::string search; + ByteString directory; + ByteString search; std::vector saveFiles; virtual void before() @@ -58,15 +57,15 @@ class LoadFilesTask: public Task virtual bool doWork() { - std::vector files = Client::Ref().DirectorySearch(directory, search, ".cps"); - std::sort(files.rbegin(), files.rend(), [](std::string a, std::string b) { + std::vector files = Client::Ref().DirectorySearch(directory, search, ".cps"); + std::sort(files.rbegin(), files.rend(), [](ByteString a, ByteString b) { std::transform(a.begin(), a.end(), a.begin(), ::tolower); std::transform(b.begin(), b.end(), b.begin(), ::tolower); return a < b; }); notifyProgress(-1); - for(std::vector::iterator iter = files.begin(), end = files.end(); iter != end; ++iter) + for(std::vector::iterator iter = files.begin(), end = files.end(); iter != end; ++iter) { SaveFile * saveFile = new SaveFile(*iter); try @@ -76,18 +75,18 @@ class LoadFilesTask: public Task saveFile->SetGameSave(tempSave); saveFiles.push_back(saveFile); - std::string filename = *iter; + ByteString filename = *iter; size_t folderPos = filename.rfind(PATH_SEP); - if(folderPos!=std::string::npos && folderPos+1 < filename.size()) + if(folderPos!=ByteString::npos && folderPos+1 < filename.size()) { filename = filename.substr(folderPos+1); } size_t extPos = filename.rfind("."); - if(extPos!=std::string::npos) + if(extPos!=ByteString::npos) { filename = filename.substr(0, extPos); } - saveFile->SetDisplayName(filename); + saveFile->SetDisplayName(filename.FromUtf8()); } catch(std::exception & e) { @@ -103,7 +102,7 @@ public: return saveFiles; } - LoadFilesTask(std::string directory, std::string search): + LoadFilesTask(ByteString directory, ByteString search): directory(directory), search(search) { @@ -117,11 +116,11 @@ public: FileBrowserActivity * a; SearchAction(FileBrowserActivity * a) : a(a) {} virtual void TextChangedCallback(ui::Textbox * sender) { - a->DoSearch(sender->GetText()); + a->DoSearch(sender->GetText().ToUtf8()); } }; -FileBrowserActivity::FileBrowserActivity(std::string directory, FileSelectedCallback * callback): +FileBrowserActivity::FileBrowserActivity(ByteString directory, FileSelectedCallback * callback): WindowActivity(ui::Point(-1, -1), ui::Point(450, 300)), callback(callback), directory(directory), @@ -167,7 +166,7 @@ FileBrowserActivity::FileBrowserActivity(std::string directory, FileSelectedCall loadDirectory(directory, ""); } -void FileBrowserActivity::DoSearch(std::string search) +void FileBrowserActivity::DoSearch(ByteString search) { if(!loadFiles) { @@ -184,7 +183,7 @@ void FileBrowserActivity::SelectSave(SaveFile * file) void FileBrowserActivity::DeleteSave(SaveFile * file) { - std::string deleteMessage = "Are you sure you want to delete " + file->GetDisplayName() + ".cps?"; + String deleteMessage = "Are you sure you want to delete " + file->GetDisplayName() + ".cps?"; if (ConfirmPrompt::Blocking("Delete Save", deleteMessage)) { remove(file->GetName().c_str()); @@ -194,7 +193,7 @@ void FileBrowserActivity::DeleteSave(SaveFile * file) void FileBrowserActivity::RenameSave(SaveFile * file) { - std::string newName = TextPrompt::Blocking("Rename", "Change save name", file->GetDisplayName(), "", 0); + ByteString newName = TextPrompt::Blocking("Rename", "Change save name", file->GetDisplayName(), "", 0).ToUtf8(); if (newName.length()) { newName = directory + PATH_SEP + newName + ".cps"; @@ -208,7 +207,7 @@ void FileBrowserActivity::RenameSave(SaveFile * file) ErrorMessage::Blocking("Error", "No save name given"); } -void FileBrowserActivity::loadDirectory(std::string directory, std::string search) +void FileBrowserActivity::loadDirectory(ByteString directory, ByteString search) { for (size_t i = 0; i < components.size(); i++) { diff --git a/src/gui/filebrowser/FileBrowserActivity.h b/src/gui/filebrowser/FileBrowserActivity.h index 3696ba753..2cfe0d339 100644 --- a/src/gui/filebrowser/FileBrowserActivity.h +++ b/src/gui/filebrowser/FileBrowserActivity.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include "common/String.h" #include "Activity.h" #include "gui/interface/Window.h" #include "tasks/TaskListener.h" @@ -33,7 +33,7 @@ class FileBrowserActivity: public TaskListener, public WindowActivity std::vector files; std::vector components; std::vector componentsQueue; - std::string directory; + ByteString directory; ui::ProgressBar * progressBar; @@ -46,16 +46,16 @@ class FileBrowserActivity: public TaskListener, public WindowActivity class SearchAction; void populateList(); public: - FileBrowserActivity(std::string directory, FileSelectedCallback * callback); + FileBrowserActivity(ByteString directory, FileSelectedCallback * callback); virtual void OnDraw(); virtual void OnTick(float dt); virtual void OnTryExit(ExitMethod method); virtual void OnMouseDown(int x, int y, unsigned button); - void loadDirectory(std::string directory, std::string search); + void loadDirectory(ByteString directory, ByteString search); void SelectSave(SaveFile * file); void DeleteSave(SaveFile * file); void RenameSave(SaveFile * file); - void DoSearch(std::string search); + void DoSearch(ByteString search); virtual ~FileBrowserActivity(); virtual void NotifyDone(Task * task); diff --git a/src/gui/font/FontEditor.cpp b/src/gui/font/FontEditor.cpp index c66f85931..03c74a7e7 100644 --- a/src/gui/font/FontEditor.cpp +++ b/src/gui/font/FontEditor.cpp @@ -1,5 +1,4 @@ #include -#include #include #include #include @@ -19,7 +18,7 @@ unsigned char *font_data; short *font_ptrs; -void FontEditor::ReadHeader(std::string header) +void FontEditor::ReadHeader(ByteString header) { std::fstream file; file.open(header, std::ios_base::in); @@ -27,7 +26,7 @@ void FontEditor::ReadHeader(std::string header) throw std::runtime_error("Could not open " + header); file >> std::skipws; - std::string word; + ByteString word; while(word != "font_data[]") file >> word; @@ -82,24 +81,24 @@ void FontEditor::ReadHeader(std::string header) size_t eof = file.tellg(); file.seekg(0); - beforeFontData = std::string(startFontData, 0); + beforeFontData = ByteString(startFontData, 0); file.read(&beforeFontData[0], startFontData); file.seekg(endFontData); - afterFontData = std::string(startFontPtrs - endFontData, 0); + afterFontData = ByteString(startFontPtrs - endFontData, 0); file.read(&afterFontData[0], startFontPtrs - endFontData); file.seekg(endFontData); - afterFontData = std::string(startFontPtrs - endFontData, 0); + afterFontData = ByteString(startFontPtrs - endFontData, 0); file.read(&afterFontData[0], startFontPtrs - endFontData); file.seekg(endFontPtrs); - afterFontPtrs = std::string(eof - endFontPtrs, 0); + afterFontPtrs = ByteString(eof - endFontPtrs, 0); file.read(&afterFontPtrs[0], eof - endFontPtrs); file.close(); } -void FontEditor::WriteHeader(std::string header, std::vector const &fontData, std::vector const &fontPtrs) +void FontEditor::WriteHeader(ByteString header, std::vector const &fontData, std::vector const &fontPtrs) { std::fstream file; file.open(header, std::ios_base::out | std::ios_base::trunc); @@ -189,7 +188,7 @@ void FontEditor::PackData( } #define FONT_SCALE 16 -FontEditor::FontEditor(std::string _header): +FontEditor::FontEditor(ByteString _header): ui::Window(ui::Point(0, 0), ui::Point(WINDOWW, WINDOWH)), header(_header), currentChar(0x80), @@ -228,7 +227,7 @@ FontEditor::FontEditor(std::string _header): void TextChangedCallback(ui::Textbox *) { unsigned int number; - std::stringstream ss(v->currentCharTextbox->GetText()); + String::Stream ss(v->currentCharTextbox->GetText()); ss >> std::hex >> number; if(number < 256) v->currentChar = number; @@ -320,14 +319,14 @@ FontEditor::FontEditor(std::string _header): ColorComponentAction(int &_color): color(_color) {} void TextChangedCallback(ui::Textbox *box) { - std::stringstream ss(box->GetText()); + String::Stream ss(box->GetText()); ss >> color; } }; int *refs[6] = {&fgR, &fgG, &fgB, &bgR, &bgG, &bgB}; for(int i = 0; i < 6; i++) { - std::stringstream ss; + String::Stream ss; ss << *refs[i]; ui::Textbox *colorComponent = new ui::Textbox(ui::Point(currentX, baseline), ui::Point(27, 17), ss.str()); currentX += 28; @@ -385,8 +384,8 @@ FontEditor::FontEditor(std::string _header): PreviewAction(FontEditor *_v): v(_v) {} void TextChangedCallback(ui::Textbox *box) { - std::stringstream ss(box->GetText()); - std::string text; + String::Stream ss(box->GetText()); + String text; while(!ss.eof()) { if(ss.peek() == '\n') @@ -399,12 +398,12 @@ FontEditor::FontEditor(std::string _header): if(ss.fail()) { ss.clear(); - char ch = ss.get(); + String::value_type ch = ss.get(); if(!ss.eof()) text.push_back(ch); continue; } - text.push_back((char)ch); + text.push_back(ch); } v->outputPreview->SetText(text); } @@ -416,7 +415,7 @@ FontEditor::FontEditor(std::string _header): inputPreview->Appearance.VerticalAlign = ui::Appearance::AlignTop; inputPreview->SetActionCallback(new PreviewAction(this)); - std::stringstream input; + String::Stream input; for(unsigned int ch = 0x20; ch <= 0xFF; ch++) { if(!(ch & 0x3F)) @@ -493,7 +492,7 @@ void FontEditor::OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bo void FontEditor::UpdateCharNumber() { - std::stringstream ss; + String::Stream ss; ss << std::hex << currentChar; currentCharTextbox->SetText(ss.str()); } diff --git a/src/gui/font/FontEditor.h b/src/gui/font/FontEditor.h index bc781e01c..5353da856 100644 --- a/src/gui/font/FontEditor.h +++ b/src/gui/font/FontEditor.h @@ -13,19 +13,19 @@ class FontEditor: public ui::Window { private: - std::string header; + ByteString header; std::array fontWidths; std::array, FONT_H>, 256> fontPixels; std::vector fontData; std::vector fontPtrs; - std::string beforeFontData; - std::string afterFontData; - std::string afterFontPtrs; + ByteString beforeFontData; + ByteString afterFontData; + ByteString afterFontPtrs; - void ReadHeader(std::string header); - void WriteHeader(std::string header, std::vector const &fontData, std::vector const &fontPtrs); + void ReadHeader(ByteString header); + void WriteHeader(ByteString header, std::vector const &fontData, std::vector const &fontPtrs); static void PackData( std::array const &fontWidths, std::array, FONT_H>, 256> const &fontPixels, @@ -57,7 +57,7 @@ private: void Save(); public: - FontEditor(std::string header); + FontEditor(ByteString header); void OnDraw(); void OnMouseDown(int x, int y, unsigned button); diff --git a/src/gui/game/DecorationTool.h b/src/gui/game/DecorationTool.h index a7d5fbe2e..dbfc07e88 100644 --- a/src/gui/game/DecorationTool.h +++ b/src/gui/game/DecorationTool.h @@ -58,7 +58,7 @@ public: return newTexture; } - DecorationTool(Renderer *ren_, int decoMode, string name, string description, int r, int g, int b, std::string identifier): + DecorationTool(Renderer *ren_, int decoMode, ByteString name, String description, int r, int g, int b, ByteString identifier): Tool(decoMode, name, description, r, g, b, identifier), Red(0), Green(0), diff --git a/src/gui/game/Favorite.cpp b/src/gui/game/Favorite.cpp index 56d629075..2a721bf3b 100644 --- a/src/gui/game/Favorite.cpp +++ b/src/gui/game/Favorite.cpp @@ -4,16 +4,16 @@ #include Favorite::Favorite(): - favoritesList(std::vector()) + favoritesList(std::vector()) {} -std::vector Favorite::GetFavoritesList() +std::vector Favorite::GetFavoritesList() { return favoritesList; } -bool Favorite::IsFavorite(std::string identifier) +bool Favorite::IsFavorite(ByteString identifier) { return std::find(favoritesList.begin(), favoritesList.end(), identifier) != favoritesList.end(); } @@ -23,7 +23,7 @@ bool Favorite::AnyFavorites() return favoritesList.size() == 0; } -void Favorite::AddFavorite(std::string identifier) +void Favorite::AddFavorite(ByteString identifier) { if (!IsFavorite(identifier)) { @@ -31,7 +31,7 @@ void Favorite::AddFavorite(std::string identifier) } } -void Favorite::RemoveFavorite(std::string identifier) +void Favorite::RemoveFavorite(ByteString identifier) { favoritesList.erase(std::remove(favoritesList.begin(), favoritesList.end(), identifier), favoritesList.end()); } @@ -43,5 +43,5 @@ void Favorite::SaveFavoritesToPrefs() void Favorite::LoadFavoritesFromPrefs() { - favoritesList = Client::Ref().GetPrefStringArray("Favorites"); + favoritesList = Client::Ref().GetPrefByteStringArray("Favorites"); } diff --git a/src/gui/game/Favorite.h b/src/gui/game/Favorite.h index 1a469ed5d..1b5963160 100644 --- a/src/gui/game/Favorite.h +++ b/src/gui/game/Favorite.h @@ -1,23 +1,23 @@ #ifndef FAVORITE_H #define FAVORITE_H -#include +#include "common/String.h" #include #include "common/Singleton.h" class Favorite : public Singleton { - std::vector favoritesList; + std::vector favoritesList; public: Favorite(); - std::vector GetFavoritesList(); - bool IsFavorite(std::string identifier); + std::vector GetFavoritesList(); + bool IsFavorite(ByteString identifier); bool AnyFavorites(); - void AddFavorite(std::string identifier); - void RemoveFavorite(std::string identifier); + void AddFavorite(ByteString identifier); + void RemoveFavorite(ByteString identifier); void SaveFavoritesToPrefs(); void LoadFavoritesFromPrefs(); diff --git a/src/gui/game/GameController.cpp b/src/gui/game/GameController.cpp index 70eaad07f..6b27e065d 100644 --- a/src/gui/game/GameController.cpp +++ b/src/gui/game/GameController.cpp @@ -57,7 +57,7 @@ public: } catch(GameModelException & ex) { - new ErrorMessage("Cannot open save", ex.what()); + new ErrorMessage("Cannot open save", ByteString(ex.what()).FromUtf8()); } } } @@ -79,7 +79,7 @@ public: } catch(GameModelException & ex) { - new ErrorMessage("Cannot open save", ex.what()); + new ErrorMessage("Cannot open save", ByteString(ex.what()).FromUtf8()); } } } @@ -322,7 +322,7 @@ int GameController::GetSignAt(int x, int y) } // assumed to already be a valid sign -std::string GameController::GetSignText(int signID) +String GameController::GetSignText(int signID) { return gameModel->GetSimulation()->signs[signID].text; } @@ -573,7 +573,7 @@ void GameController::ToolClick(int toolSelection, ui::Point point) activeTool->Click(sim, cBrush, point); } -std::string GameController::StampRegion(ui::Point point1, ui::Point point2, bool includePressure) +ByteString GameController::StampRegion(ui::Point point1, ui::Point point2, bool includePressure) { bool incPressure = Client::Ref().GetPrefBool("Simulation.IncludePressure", true); if (!incPressure) @@ -583,7 +583,7 @@ std::string GameController::StampRegion(ui::Point point1, ui::Point point2, bool if(newSave) { newSave->paused = gameModel->GetPaused(); - std::string stampName = Client::Ref().AddStamp(newSave); + ByteString stampName = Client::Ref().AddStamp(newSave); delete newSave; if (stampName.length() == 0) new ErrorMessage("Could not create stamp", "Error serializing save file"); @@ -666,15 +666,15 @@ bool GameController::MouseUp(int x, int y, unsigned button, char type) if (foundSignID != -1) { sign foundSign = gameModel->GetSimulation()->signs[foundSignID]; - std::string str = foundSign.text; - char type; + String str = foundSign.text; + String::value_type type; int pos = sign::splitsign(str, &type); if (pos) { ret = false; if (type == 'c' || type == 't' || type == 's') { - std::string link = str.substr(3, pos-3); + String link = str.substr(3, pos-3); switch (type) { case 'c': @@ -687,8 +687,8 @@ bool GameController::MouseUp(int x, int y, unsigned button, char type) case 't': { // buff is already confirmed to be a number by sign::splitsign - std::stringstream uri; - uri << "http://powdertoy.co.uk/Discussions/Thread/View.html?Thread=" << link; + ByteString::Stream uri; + uri << "http://powdertoy.co.uk/Discussions/Thread/View.html?Thread=" << link.ToUtf8(); Platform::OpenURI(uri.str()); break; } @@ -1175,7 +1175,7 @@ void GameController::SetActiveTool(int toolSelection, Tool * tool) ((PropertyTool *)tool)->OpenWindow(gameModel->GetSimulation()); } -void GameController::SetActiveTool(int toolSelection, std::string identifier) +void GameController::SetActiveTool(int toolSelection, ByteString identifier) { Tool *tool = gameModel->GetToolFromIdentifier(identifier); if (!tool) @@ -1198,7 +1198,7 @@ void GameController::SetReplaceModeFlags(int flags) gameModel->GetSimulation()->replaceModeFlags = flags; } -void GameController::OpenSearch(std::string searchText) +void GameController::OpenSearch(String searchText) { if(!search) search = new SearchController(new SearchCallback(this)); @@ -1524,7 +1524,7 @@ void GameController::Vote(int direction) } catch(GameModelException & ex) { - new ErrorMessage("Error while voting", ex.what()); + new ErrorMessage("Error while voting", ByteString(ex.what()).FromUtf8()); } } } @@ -1555,14 +1555,14 @@ void GameController::ReloadSim() } } -std::string GameController::ElementResolve(int type, int ctype) +ByteString GameController::ElementResolve(int type, int ctype) { if(gameModel && gameModel->GetSimulation()) { if (type == PT_LIFE && ctype >= 0 && ctype < NGOL) return gameModel->GetSimulation()->gmenu[ctype].name; else if (type >= 0 && type < PT_NUM) - return std::string(gameModel->GetSimulation()->elements[type].Name); + return gameModel->GetSimulation()->elements[type].Name; } return ""; } @@ -1577,10 +1577,10 @@ bool GameController::IsValidElement(int type) return false; } -std::string GameController::WallName(int type) +String GameController::WallName(int type) { if(gameModel && gameModel->GetSimulation() && type >= 0 && type < UI_WALLCOUNT) - return std::string(gameModel->GetSimulation()->wtypes[type].name); + return gameModel->GetSimulation()->wtypes[type].name; else return ""; } @@ -1596,13 +1596,13 @@ void GameController::NotifyAuthUserChanged(Client * sender) gameModel->SetUser(newUser); } -void GameController::NotifyNewNotification(Client * sender, std::pair notification) +void GameController::NotifyNewNotification(Client * sender, std::pair notification) { class LinkNotification : public Notification { - std::string link; + ByteString link; public: - LinkNotification(std::string link_, std::string message) : Notification(message), link(link_) {} + LinkNotification(ByteString link_, String message) : Notification(message), link(link_) {} virtual ~LinkNotification() {} virtual void Action() @@ -1632,13 +1632,13 @@ void GameController::NotifyUpdateAvailable(Client * sender) { GameController * c; public: - UpdateNotification(GameController * c, std::string message) : Notification(message), c(c) {} + UpdateNotification(GameController * c, String message) : Notification(message), c(c) {} virtual ~UpdateNotification() {} virtual void Action() { UpdateInfo info = Client::Ref().GetUpdateInfo(); - std::stringstream updateMessage; + String::Stream updateMessage; updateMessage << "Are you sure you want to run the updater? Please save any changes before updating.\n\nCurrent version:\n "; #ifdef SNAPSHOT @@ -1674,16 +1674,16 @@ void GameController::NotifyUpdateAvailable(Client * sender) { case UpdateInfo::Snapshot: #if MOD_ID > 0 - gameModel->AddNotification(new UpdateNotification(this, std::string("A new mod update is available - click here to update"))); + gameModel->AddNotification(new UpdateNotification(this, "A new mod update is available - click here to update")); #else - gameModel->AddNotification(new UpdateNotification(this, std::string("A new snapshot is available - click here to update"))); + gameModel->AddNotification(new UpdateNotification(this, "A new snapshot is available - click here to update")); #endif break; case UpdateInfo::Stable: - gameModel->AddNotification(new UpdateNotification(this, std::string("A new version is available - click here to update"))); + gameModel->AddNotification(new UpdateNotification(this, "A new version is available - click here to update")); break; case UpdateInfo::Beta: - gameModel->AddNotification(new UpdateNotification(this, std::string("A new beta is available - click here to update"))); + gameModel->AddNotification(new UpdateNotification(this, "A new beta is available - click here to update")); break; } } diff --git a/src/gui/game/GameController.h b/src/gui/game/GameController.h index 48560190d..8449cc089 100644 --- a/src/gui/game/GameController.h +++ b/src/gui/game/GameController.h @@ -58,7 +58,7 @@ public: ~GameController(); GameView * GetView(); int GetSignAt(int x, int y); - std::string GetSignText(int signID); + String GetSignText(int signID); bool MouseMove(int x, int y, int dx, int dy); bool MouseDown(int x, int y, unsigned button); @@ -89,7 +89,7 @@ public: void DrawRect(int toolSelection, ui::Point point1, ui::Point point2); void DrawLine(int toolSelection, ui::Point point1, ui::Point point2); void DrawFill(int toolSelection, ui::Point point); - std::string StampRegion(ui::Point point1, ui::Point point2, bool includePressure); + ByteString StampRegion(ui::Point point1, ui::Point point2, bool includePressure); void CopyRegion(ui::Point point1, ui::Point point2, bool includePressure); void CutRegion(ui::Point point1, ui::Point point2, bool includePressure); void Update(); @@ -109,7 +109,7 @@ public: void RebuildFavoritesMenu(); Tool * GetActiveTool(int selection); void SetActiveTool(int toolSelection, Tool * tool); - void SetActiveTool(int toolSelection, std::string identifier); + void SetActiveTool(int toolSelection, ByteString identifier); void SetLastTool(Tool * tool); int GetReplaceModeFlags(); void SetReplaceModeFlags(int flags); @@ -119,7 +119,7 @@ public: void SetToolStrength(float value); void LoadSaveFile(SaveFile * file); void LoadSave(SaveInfo * save); - void OpenSearch(std::string searchText); + void OpenSearch(String searchText); void OpenLogin(); void OpenProfile(); void OpenTags(); @@ -147,9 +147,9 @@ public: bool MouseInZoom(ui::Point position); ui::Point PointTranslate(ui::Point point); ui::Point NormaliseBlockCoord(ui::Point point); - std::string ElementResolve(int type, int ctype); + ByteString ElementResolve(int type, int ctype); bool IsValidElement(int type); - std::string WallName(int type); + String WallName(int type); int Record(bool record); void ResetAir(); @@ -167,7 +167,7 @@ public: virtual void NotifyUpdateAvailable(Client * sender); virtual void NotifyAuthUserChanged(Client * sender); - virtual void NotifyNewNotification(Client * sender, std::pair notification); + virtual void NotifyNewNotification(Client * sender, std::pair notification); void RunUpdater(); }; diff --git a/src/gui/game/GameModel.cpp b/src/gui/game/GameModel.cpp index db00386e9..e312a10c7 100644 --- a/src/gui/game/GameModel.cpp +++ b/src/gui/game/GameModel.cpp @@ -105,7 +105,7 @@ GameModel::GameModel(): brushList.push_back(new TriangleBrush(ui::Point(4, 4))); //Load more from brushes folder - std::vector brushFiles = Client::Ref().DirectorySearch(BRUSH_DIR, "", ".ptb"); + std::vector brushFiles = Client::Ref().DirectorySearch(BRUSH_DIR, "", ".ptb"); for (size_t i = 0; i < brushFiles.size(); i++) { std::vector brushData = Client::Ref().ReadFile(brushFiles[i]); @@ -234,7 +234,7 @@ void GameModel::BuildMenus() if(activeMenu != -1) lastMenu = activeMenu; - std::string activeToolIdentifiers[4]; + ByteString activeToolIdentifiers[4]; if(regularToolset[0]) activeToolIdentifiers[0] = regularToolset[0]->GetIdentifier(); if(regularToolset[1]) @@ -264,7 +264,7 @@ void GameModel::BuildMenus() //Create menus for (int i = 0; i < SC_TOTAL; i++) { - menuList.push_back(new Menu((const char)sim->msections[i].icon[0], sim->msections[i].name, sim->msections[i].doshow)); + menuList.push_back(new Menu(sim->msections[i].icon[0], sim->msections[i].name, sim->msections[i].doshow)); } //Build menus from Simulation elements @@ -305,14 +305,14 @@ void GameModel::BuildMenus() //Build menu for GOL types for(int i = 0; i < NGOL; i++) { - Tool * tempTool = new ElementTool(PT_LIFE|PMAPID(i), sim->gmenu[i].name, std::string(sim->gmenu[i].description), PIXR(sim->gmenu[i].colour), PIXG(sim->gmenu[i].colour), PIXB(sim->gmenu[i].colour), "DEFAULT_PT_LIFE_"+std::string(sim->gmenu[i].name)); + Tool * tempTool = new ElementTool(PT_LIFE|PMAPID(i), sim->gmenu[i].name, sim->gmenu[i].description, PIXR(sim->gmenu[i].colour), PIXG(sim->gmenu[i].colour), PIXB(sim->gmenu[i].colour), "DEFAULT_PT_LIFE_"+sim->gmenu[i].name); menuList[SC_LIFE]->AddTool(tempTool); } //Build other menus from wall data for(int i = 0; i < UI_WALLCOUNT; i++) { - Tool * tempTool = new WallTool(i, "", std::string(sim->wtypes[i].descs), PIXR(sim->wtypes[i].colour), PIXG(sim->wtypes[i].colour), PIXB(sim->wtypes[i].colour), sim->wtypes[i].identifier, sim->wtypes[i].textureGen); + Tool * tempTool = new WallTool(i, "", sim->wtypes[i].descs, PIXR(sim->wtypes[i].colour), PIXG(sim->wtypes[i].colour), PIXB(sim->wtypes[i].colour), sim->wtypes[i].identifier, sim->wtypes[i].textureGen); menuList[SC_WALL]->AddTool(tempTool); //sim->wtypes[i] } @@ -386,7 +386,7 @@ void GameModel::BuildFavoritesMenu() { menuList[SC_FAVORITES]->ClearTools(); - std::vector favList = Favorite::Ref().GetFavoritesList(); + std::vector favList = Favorite::Ref().GetFavoritesList(); for (size_t i = 0; i < favList.size(); i++) { Tool *tool = GetToolFromIdentifier(favList[i]); @@ -403,7 +403,7 @@ void GameModel::BuildFavoritesMenu() notifyLastToolChanged(); } -Tool * GameModel::GetToolFromIdentifier(std::string identifier) +Tool * GameModel::GetToolFromIdentifier(ByteString identifier) { for (std::vector::iterator iter = menuList.begin(), end = menuList.end(); iter != end; ++iter) { @@ -657,8 +657,8 @@ void GameModel::SetSave(SaveInfo * newSave) saveData->authors["type"] = "save"; saveData->authors["id"] = newSave->id; saveData->authors["username"] = newSave->userName; - saveData->authors["title"] = newSave->name; - saveData->authors["description"] = newSave->Description; + saveData->authors["title"] = newSave->name.ToUtf8(); + saveData->authors["description"] = newSave->Description.ToUtf8(); saveData->authors["published"] = (int)newSave->Published; saveData->authors["date"] = newSave->updatedDate; } @@ -912,7 +912,7 @@ void GameModel::SetPaused(bool pauseState) { if (!pauseState && sim->debug_currentParticle > 0) { - std::stringstream logmessage; + String::Stream logmessage; logmessage << "Updated particles from #" << sim->debug_currentParticle << " to end due to unpause"; sim->UpdateParticles(sim->debug_currentParticle, NPART); sim->AfterSim(); @@ -1048,17 +1048,17 @@ GameSave * GameModel::GetPlaceSave() return placeSave; } -void GameModel::Log(string message, bool printToFile) +void GameModel::Log(String message, bool printToFile) { consoleLog.push_front(message); if(consoleLog.size()>100) consoleLog.pop_back(); notifyLogChanged(message); if (printToFile) - std::cout << message << std::endl; + std::cout << message.ToUtf8() << std::endl; } -deque GameModel::GetLog() +deque GameModel::GetLog() { return consoleLog; } @@ -1088,24 +1088,24 @@ void GameModel::RemoveNotification(Notification * notification) notifyNotificationsChanged(); } -void GameModel::SetToolTip(std::string text) +void GameModel::SetToolTip(String text) { toolTip = text; notifyToolTipChanged(); } -void GameModel::SetInfoTip(std::string text) +void GameModel::SetInfoTip(String text) { infoTip = text; notifyInfoTipChanged(); } -std::string GameModel::GetToolTip() +String GameModel::GetToolTip() { return toolTip; } -std::string GameModel::GetInfoTip() +String GameModel::GetInfoTip() { return infoTip; } @@ -1246,7 +1246,7 @@ void GameModel::notifyPlaceSaveChanged() } } -void GameModel::notifyLogChanged(string entry) +void GameModel::notifyLogChanged(String entry) { for (size_t i = 0; i < observers.size(); i++) { diff --git a/src/gui/game/GameModel.h b/src/gui/game/GameModel.h index f9ca40b95..0e97ed1c2 100644 --- a/src/gui/game/GameModel.h +++ b/src/gui/game/GameModel.h @@ -41,7 +41,7 @@ private: //unsigned char * clipboardData; GameSave * clipboard; GameSave * placeSave; - deque consoleLog; + deque consoleLog; vector observers; vector toolList; @@ -77,8 +77,8 @@ private: int edgeMode; - std::string infoTip; - std::string toolTip; + String infoTip; + String toolTip; //bool zoomEnabled; void notifyRendererChanged(); void notifySimulationChanged(); @@ -98,7 +98,7 @@ private: void notifyColourPresetsChanged(); void notifyColourActivePresetChanged(); void notifyNotificationsChanged(); - void notifyLogChanged(string entry); + void notifyLogChanged(String entry); void notifyInfoTipChanged(); void notifyToolTipChanged(); void notifyQuickOptionsChanged(); @@ -123,10 +123,10 @@ public: void SetColourSelectorColour(ui::Colour colour); ui::Colour GetColourSelectorColour(); - void SetToolTip(std::string text); - void SetInfoTip(std::string text); - std::string GetToolTip(); - std::string GetInfoTip(); + void SetToolTip(String text); + void SetInfoTip(String text); + String GetToolTip(); + String GetInfoTip(); void BuildMenus(); void BuildFavoritesMenu(); @@ -149,7 +149,7 @@ public: float GetToolStrength(); Tool * GetLastTool(); void SetLastTool(Tool * newTool); - Tool * GetToolFromIdentifier(std::string identifier); + Tool * GetToolFromIdentifier(ByteString identifier); Tool * GetElementTool(int elementID); vector GetToolList(); vector GetUnlistedTools(); @@ -200,8 +200,8 @@ public: ui::Point GetZoomWindowPosition(); void SetClipboard(GameSave * save); void SetPlaceSave(GameSave * save); - void Log(string message, bool printToFile); - deque GetLog(); + void Log(String message, bool printToFile); + deque GetLog(); GameSave * GetClipboard(); GameSave * GetPlaceSave(); diff --git a/src/gui/game/GameModelException.h b/src/gui/game/GameModelException.h index c95f7e60a..30961901a 100644 --- a/src/gui/game/GameModelException.h +++ b/src/gui/game/GameModelException.h @@ -1,17 +1,16 @@ #ifndef GAMEMODELEXCEPTION_H_ #define GAMEMODELEXCEPTION_H_ -#include +#include "common/String.h" #include -using namespace std; struct GameModelException: public exception { - string message; + String message; public: - GameModelException(string message_): message(message_) {} + GameModelException(String message_): message(message_) {} const char * what() const throw() { - return message.c_str(); + return message.ToUtf8().c_str(); } ~GameModelException() throw() {}; }; diff --git a/src/gui/game/GameView.cpp b/src/gui/game/GameView.cpp index c1916b9f9..0039d6c3b 100644 --- a/src/gui/game/GameView.cpp +++ b/src/gui/game/GameView.cpp @@ -1,4 +1,3 @@ -#include #include #include #include "GameView.h" @@ -40,10 +39,10 @@ private: bool leftDown; bool showSplit; int splitPosition; - std::string toolTip2; + String toolTip2; SplitButtonAction * splitActionCallback; public: - SplitButton(ui::Point position, ui::Point size, std::string buttonText, std::string toolTip, std::string toolTip2, int split) : + SplitButton(ui::Point position, ui::Point size, String buttonText, String toolTip, String toolTip2, int split) : Button(position, size, buttonText, toolTip), showSplit(true), splitPosition(split), @@ -52,7 +51,7 @@ public: { } - void SetRightToolTip(std::string tooltip) { toolTip2 = tooltip; } + void SetRightToolTip(String tooltip) { toolTip2 = tooltip; } bool GetShowSplit() { return showSplit; } void SetShowSplit(bool split) { showSplit = split; } SplitButtonAction * GetSplitActionCallback() { return splitActionCallback; } @@ -101,12 +100,12 @@ public: return; SetToolTip(x, y); } - virtual void TextPosition(std::string ButtonText) + virtual void TextPosition(String ButtonText) { ui::Button::TextPosition(ButtonText); textPosition.X += 3; } - void SetToolTips(std::string newToolTip1, std::string newToolTip2) + void SetToolTips(String newToolTip1, String newToolTip2) { toolTip = newToolTip1; toolTip2 = newToolTip2; @@ -183,7 +182,7 @@ GameView::GameView(): buttonTip(""), isButtonTipFadingIn(false), introText(2048), - introTextMessage(introTextData), + introTextMessage(ByteString(introTextData).FromAscii()), doScreenshot(false), screenshotIndex(0), @@ -610,9 +609,9 @@ void GameView::NotifyMenuListChanged(GameModel * sender) { if (menuList[i]->GetVisible()) { - std::string tempString = ""; + String tempString = ""; tempString += menuList[i]->GetIcon(); - std::string description = menuList[i]->GetDescription(); + String description = menuList[i]->GetDescription(); if (i == SC_FAVORITES && Favorite::Ref().AnyFavorites()) description += " (Use ctrl+shift+click to favorite an element)"; ui::Button * tempButton = new ui::Button(ui::Point(WINDOWW-16, currentY), ui::Point(15, 15), tempString, description); @@ -912,7 +911,7 @@ void GameView::NotifyUserChanged(GameModel * sender) } else { - loginButton->SetText(sender->GetUser().Username); + loginButton->SetText(sender->GetUser().Username.FromUtf8()); ((SplitButton*)loginButton)->SetShowSplit(true); ((SplitButton*)loginButton)->SetRightToolTip("Edit profile"); } @@ -978,15 +977,15 @@ void GameView::NotifySaveChanged(GameModel * sender) tagSimulationButton->Enabled = sender->GetSave()->GetID(); if (sender->GetSave()->GetID()) { - std::stringstream tagsStream; - std::list tags = sender->GetSave()->GetTags(); + String::Stream tagsStream; + std::list tags = sender->GetSave()->GetTags(); if (tags.size()) { - for (std::list::const_iterator iter = tags.begin(), begin = tags.begin(), end = tags.end(); iter != end; iter++) + for (std::list::const_iterator iter = tags.begin(), begin = tags.begin(), end = tags.end(); iter != end; iter++) { if (iter != begin) tagsStream << " "; - tagsStream << *iter; + tagsStream << iter->FromUtf8(); } tagSimulationButton->SetText(tagsStream.str()); } @@ -1067,7 +1066,7 @@ int GameView::Record(bool record) { time_t startTime = time(NULL); recordingFolder = startTime; - std::stringstream recordingDir; + ByteString::Stream recordingDir; recordingDir << "recordings" << PATH_SEP << recordingFolder; Client::Ref().MakeDirectory("recordings"); Client::Ref().MakeDirectory(recordingDir.str().c_str()); @@ -1327,7 +1326,7 @@ void GameView::OnMouseUp(int x, int y, unsigned button) UpdateDrawMode(); } -void GameView::ToolTip(ui::Point senderPosition, std::string toolTip) +void GameView::ToolTip(ui::Point senderPosition, String toolTip) { // buttom button tooltips if (senderPosition.Y > Size.Y-17) @@ -1342,16 +1341,16 @@ void GameView::ToolTip(ui::Point senderPosition, std::string toolTip) else if(senderPosition.X > Size.X-BARSIZE)// < Size.Y-(quickOptionButtons.size()+1)*16) { this->toolTip = toolTip; - toolTipPosition = ui::Point(Size.X-27-Graphics::textwidth((char*)toolTip.c_str()), senderPosition.Y+3); + toolTipPosition = ui::Point(Size.X-27-Graphics::textwidth(toolTip), senderPosition.Y+3); if(toolTipPosition.Y+10 > Size.Y-MENUSIZE) - toolTipPosition = ui::Point(Size.X-27-Graphics::textwidth((char*)toolTip.c_str()), Size.Y-MENUSIZE-10); + toolTipPosition = ui::Point(Size.X-27-Graphics::textwidth(toolTip), Size.Y-MENUSIZE-10); isToolTipFadingIn = true; } // element tooltips else { this->toolTip = toolTip; - toolTipPosition = ui::Point(Size.X-27-Graphics::textwidth((char*)toolTip.c_str()), Size.Y-MENUSIZE-10); + toolTipPosition = ui::Point(Size.X-27-Graphics::textwidth(toolTip), Size.Y-MENUSIZE-10); isToolTipFadingIn = true; } } @@ -1490,8 +1489,8 @@ void GameView::OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool if ((Client::Ref().GetAuthUser().UserElevation == User::ElevationModerator || Client::Ref().GetAuthUser().UserElevation == User::ElevationAdmin) && ctrl) { - std::string authorString = Client::Ref().GetAuthorInfo().toStyledString(); - new InformationMessage("Save authorship info", authorString, true); + ByteString authorString = Client::Ref().GetAuthorInfo().toStyledString(); + new InformationMessage("Save authorship info", authorString.FromUtf8(), true); } break; case 'r': @@ -1609,7 +1608,7 @@ void GameView::OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool break; case 'l': { - std::vector stampList = Client::Ref().GetStamps(0, 1); + std::vector stampList = Client::Ref().GetStamps(0, 1); if (stampList.size()) { SaveFile *saveFile = Client::Ref().GetStamp(stampList[0]); @@ -1735,13 +1734,13 @@ void GameView::OnTick(float dt) int foundSignID = c->GetSignAt(mousePosition.X, mousePosition.Y); if (foundSignID != -1) { - std::string str = c->GetSignText(foundSignID); - char type = '\0'; + String str = c->GetSignText(foundSignID); + String::value_type type = '\0'; int pos = sign::splitsign(str, &type); if (type == 'c' || type == 't' || type == 's') { - std::string linkSign = str.substr(3, pos-3); - std::stringstream tooltip; + String linkSign = str.substr(3, pos-3); + String::Stream tooltip; switch (type) { case 'c': @@ -1903,7 +1902,7 @@ void GameView::NotifyNotificationsChanged(GameModel * sender) int currentY = YRES-23; for(std::vector::iterator iter = notifications.begin(), end = notifications.end(); iter != end; ++iter) { - int width = (Graphics::textwidth((*iter)->Message.c_str()))+8; + int width = (Graphics::textwidth((*iter)->Message))+8; ui::Button * tempButton = new ui::Button(ui::Point(XRES-width-22, currentY), ui::Point(width, 15), (*iter)->Message); tempButton->SetActionCallback(new NotificationButtonAction(*iter)); tempButton->Appearance.BorderInactive = style::Colour::WarningTitle; @@ -1934,9 +1933,9 @@ void GameView::NotifyZoomChanged(GameModel * sender) zoomEnabled = sender->GetZoomEnabled(); } -void GameView::NotifyLogChanged(GameModel * sender, string entry) +void GameView::NotifyLogChanged(GameModel * sender, String entry) { - logEntries.push_front(std::pair(entry, 600)); + logEntries.push_front(std::pair(entry, 600)); if (logEntries.size() > 20) logEntries.pop_back(); } @@ -2218,7 +2217,7 @@ void GameView::OnDraw() VideoBuffer screenshot(ren->DumpFrame()); std::vector data = format::VideoBufferToPNG(screenshot); - std::stringstream filename; + ByteString::Stream filename; filename << "screenshot_"; filename << std::setfill('0') << std::setw(6) << (screenshotIndex++); filename << ".png"; @@ -2232,7 +2231,7 @@ void GameView::OnDraw() VideoBuffer screenshot(ren->DumpFrame()); std::vector data = format::VideoBufferToPPM(screenshot); - std::stringstream filename; + ByteString::Stream filename; filename << "recordings" << PATH_SEP << recordingFolder << PATH_SEP; filename << "frame_"; filename << std::setfill('0') << std::setw(6) << (recordingIndex++); @@ -2245,10 +2244,10 @@ void GameView::OnDraw() { int startX = 20; int startY = YRES-20; - deque >::iterator iter; + deque >::iterator iter; for(iter = logEntries.begin(); iter != logEntries.end(); iter++) { - string message = (*iter).first; + String message = (*iter).first; int alpha = std::min((*iter).second, 255); if (alpha <= 0) //erase this and everything older { @@ -2256,8 +2255,8 @@ void GameView::OnDraw() break; } startY -= 14; - g->fillrect(startX-3, startY-3, Graphics::textwidth((char*)message.c_str())+6, 14, 0, 0, 0, 100); - g->drawtext(startX, startY, message.c_str(), 255, 255, 255, alpha); + g->fillrect(startX-3, startY-3, Graphics::textwidth(message)+6, 14, 0, 0, 0, 100); + g->drawtext(startX, startY, message, 255, 255, 255, alpha); (*iter).second -= 3; } } @@ -2265,13 +2264,13 @@ void GameView::OnDraw() if(recording) { - std::stringstream sampleInfo; + String::Stream sampleInfo; sampleInfo << recordingIndex; sampleInfo << ". \x8E REC"; - int textWidth = Graphics::textwidth((char*)sampleInfo.str().c_str()); + int textWidth = Graphics::textwidth(sampleInfo.str()); g->fillrect(XRES-20-textWidth, 12, textWidth+8, 15, 0, 0, 0, 255*0.5); - g->drawtext(XRES-16-textWidth, 16, (const char*)sampleInfo.str().c_str(), 255, 50, 20, 255); + g->drawtext(XRES-16-textWidth, 16, sampleInfo.str(), 255, 50, 20, 255); } else if(showHud) { @@ -2281,7 +2280,7 @@ void GameView::OnDraw() alpha = 255-toolTipPresence*3; if (alpha < 50) alpha = 50; - std::stringstream sampleInfo; + String::Stream sampleInfo; sampleInfo.precision(2); int type = sample.particle.type; @@ -2295,15 +2294,15 @@ void GameView::OnDraw() if (showDebug) { if (type == PT_LAVA && c->IsValidElement(ctype)) - sampleInfo << "Molten " << c->ElementResolve(ctype, -1); + sampleInfo << "Molten " << c->ElementResolve(ctype, -1).FromAscii(); else if ((type == PT_PIPE || type == PT_PPIP) && c->IsValidElement(ctype)) - sampleInfo << c->ElementResolve(type, -1) << " with " << c->ElementResolve(ctype, (int)sample.particle.pavg[1]); + sampleInfo << c->ElementResolve(type, -1).FromAscii() << " with " << c->ElementResolve(ctype, (int)sample.particle.pavg[1]).FromAscii(); else if (type == PT_LIFE) - sampleInfo << c->ElementResolve(type, ctype); + sampleInfo << c->ElementResolve(type, ctype).FromAscii(); else if (type == PT_FILT) { - sampleInfo << c->ElementResolve(type, ctype); - const char* filtModes[] = {"set colour", "AND", "OR", "subtract colour", "red shift", "blue shift", "no effect", "XOR", "NOT", "old QRTZ scattering", "variable red shift", "variable blue shift"}; + sampleInfo << c->ElementResolve(type, ctype).FromAscii(); + String filtModes[] = {"set colour", "AND", "OR", "subtract colour", "red shift", "blue shift", "no effect", "XOR", "NOT", "old QRTZ scattering", "variable red shift", "variable blue shift"}; if (sample.particle.tmp>=0 && sample.particle.tmp<=11) sampleInfo << " (" << filtModes[sample.particle.tmp] << ")"; else @@ -2311,14 +2310,14 @@ void GameView::OnDraw() } else { - sampleInfo << c->ElementResolve(type, ctype); + sampleInfo << c->ElementResolve(type, ctype).FromAscii(); if (wavelengthGfx) sampleInfo << " (" << ctype << ")"; // Some elements store extra LIFE info in upper bits of ctype, instead of tmp/tmp2 else if (type == PT_CRAY || type == PT_DRAY || type == PT_CONV) - sampleInfo << " (" << c->ElementResolve(TYP(ctype), ID(ctype)) << ")"; + sampleInfo << " (" << c->ElementResolve(TYP(ctype), ID(ctype)).FromAscii() << ")"; else if (c->IsValidElement(ctype)) - sampleInfo << " (" << c->ElementResolve(ctype, -1) << ")"; + sampleInfo << " (" << c->ElementResolve(ctype, -1).FromAscii() << ")"; else sampleInfo << " ()"; } @@ -2336,13 +2335,13 @@ void GameView::OnDraw() else { if (type == PT_LAVA && c->IsValidElement(ctype)) - sampleInfo << "Molten " << c->ElementResolve(ctype, -1); + sampleInfo << "Molten " << c->ElementResolve(ctype, -1).FromAscii(); else if ((type == PT_PIPE || type == PT_PPIP) && c->IsValidElement(ctype)) - sampleInfo << c->ElementResolve(type, -1) << " with " << c->ElementResolve(ctype, (int)sample.particle.pavg[1]); + sampleInfo << c->ElementResolve(type, -1).FromAscii() << " with " << c->ElementResolve(ctype, (int)sample.particle.pavg[1]).FromAscii(); else if (type == PT_LIFE) - sampleInfo << c->ElementResolve(type, ctype); + sampleInfo << c->ElementResolve(type, ctype).FromAscii(); else - sampleInfo << c->ElementResolve(type, ctype); + sampleInfo << c->ElementResolve(type, ctype).FromAscii(); sampleInfo << ", Temp: " << std::fixed << sample.particle.temp - 273.15f << " C"; sampleInfo << ", Pressure: " << std::fixed << sample.AirPressure; } @@ -2361,9 +2360,9 @@ void GameView::OnDraw() sampleInfo << "Empty"; } - int textWidth = Graphics::textwidth((char*)sampleInfo.str().c_str()); + int textWidth = Graphics::textwidth(sampleInfo.str()); g->fillrect(XRES-20-textWidth, 12, textWidth+8, 15, 0, 0, 0, alpha*0.5f); - g->drawtext(XRES-16-textWidth, 16, (const char*)sampleInfo.str().c_str(), 255, 255, 255, alpha*0.75f); + g->drawtext(XRES-16-textWidth, 16, sampleInfo.str(), 255, 255, 255, alpha*0.75f); #ifndef OGLI if (wavelengthGfx) @@ -2404,7 +2403,7 @@ void GameView::OnDraw() if (showDebug) { - sampleInfo.str(std::string()); + sampleInfo.str(String()); if (type) sampleInfo << "#" << sample.ParticleID << ", "; @@ -2417,16 +2416,16 @@ void GameView::OnDraw() if (c->GetAHeatEnable()) sampleInfo << ", AHeat: " << std::fixed << sample.AirTemperature -273.15f << " C"; - textWidth = Graphics::textwidth((char*)sampleInfo.str().c_str()); + textWidth = Graphics::textwidth(sampleInfo.str()); g->fillrect(XRES-20-textWidth, 27, textWidth+8, 14, 0, 0, 0, alpha*0.5f); - g->drawtext(XRES-16-textWidth, 30, (const char*)sampleInfo.str().c_str(), 255, 255, 255, alpha*0.75f); + g->drawtext(XRES-16-textWidth, 30, sampleInfo.str(), 255, 255, 255, alpha*0.75f); } } if(showHud && introText < 51) { //FPS and some version info - std::stringstream fpsInfo; + String::Stream fpsInfo; fpsInfo.precision(2); fpsInfo << "FPS: " << std::fixed << ui::Engine::Ref().GetFps(); #ifdef DEBUG @@ -2449,37 +2448,37 @@ void GameView::OnDraw() if (ren && ren->findingElement) fpsInfo << " [FIND]"; - int textWidth = Graphics::textwidth((char*)fpsInfo.str().c_str()); + int textWidth = Graphics::textwidth(fpsInfo.str()); int alpha = 255-introText*5; g->fillrect(12, 12, textWidth+8, 15, 0, 0, 0, alpha*0.5); - g->drawtext(16, 16, (const char*)fpsInfo.str().c_str(), 32, 216, 255, alpha*0.75); + g->drawtext(16, 16, fpsInfo.str(), 32, 216, 255, alpha*0.75); } //Tooltips if(infoTipPresence) { int infoTipAlpha = (infoTipPresence>50?50:infoTipPresence)*5; - g->drawtext_outline((XRES-Graphics::textwidth((char*)infoTip.c_str()))/2, (YRES/2)-2, (char*)infoTip.c_str(), 255, 255, 255, infoTipAlpha); + g->drawtext_outline((XRES-Graphics::textwidth(infoTip))/2, (YRES/2)-2, infoTip, 255, 255, 255, infoTipAlpha); } if(toolTipPresence && toolTipPosition.X!=-1 && toolTipPosition.Y!=-1 && toolTip.length()) { if (toolTipPosition.Y == Size.Y-MENUSIZE-10) - g->drawtext_outline(toolTipPosition.X, toolTipPosition.Y, (char*)toolTip.c_str(), 255, 255, 255, toolTipPresence>51?255:toolTipPresence*5); + g->drawtext_outline(toolTipPosition.X, toolTipPosition.Y, toolTip, 255, 255, 255, toolTipPresence>51?255:toolTipPresence*5); else - g->drawtext(toolTipPosition.X, toolTipPosition.Y, (char*)toolTip.c_str(), 255, 255, 255, toolTipPresence>51?255:toolTipPresence*5); + g->drawtext(toolTipPosition.X, toolTipPosition.Y, toolTip, 255, 255, 255, toolTipPresence>51?255:toolTipPresence*5); } if(buttonTipShow > 0) { - g->drawtext(16, Size.Y-MENUSIZE-24, (char*)buttonTip.c_str(), 255, 255, 255, buttonTipShow>51?255:buttonTipShow*5); + g->drawtext(16, Size.Y-MENUSIZE-24, buttonTip, 255, 255, 255, buttonTipShow>51?255:buttonTipShow*5); } //Introduction text if(introText) { g->fillrect(0, 0, WINDOWW, WINDOWH, 0, 0, 0, introText>51?102:introText*2); - g->drawtext(16, 20, (char*)introTextMessage.c_str(), 255, 255, 255, introText>51?255:introText*5); + g->drawtext(16, 20, introTextMessage, 255, 255, 255, introText>51?255:introText*5); } // Clear menu areas, to ensure particle graphics don't overlap diff --git a/src/gui/game/GameView.h b/src/gui/game/GameView.h index d94b927cb..7c25341ba 100644 --- a/src/gui/game/GameView.h +++ b/src/gui/game/GameView.h @@ -4,7 +4,7 @@ #include #include #include -#include +#include "common/String.h" #include "GameController.h" #include "GameModel.h" #include "gui/interface/Window.h" @@ -54,16 +54,16 @@ private: int lastMenu; int toolTipPresence; - std::string toolTip; + String toolTip; bool isToolTipFadingIn; ui::Point toolTipPosition; int infoTipPresence; - std::string infoTip; + String infoTip; int buttonTipShow; - std::string buttonTip; + String buttonTip; bool isButtonTipFadingIn; int introText; - std::string introTextMessage; + String introTextMessage; bool doScreenshot; int screenshotIndex; @@ -80,7 +80,7 @@ private: vector menuButtons; vector toolButtons; vector notificationComponents; - deque > logEntries; + deque > logEntries; ui::Button * scrollBar; ui::Button * searchButton; ui::Button * reloadButton; @@ -178,14 +178,14 @@ public: void NotifyColourActivePresetChanged(GameModel * sender); void NotifyPlaceSaveChanged(GameModel * sender); void NotifyNotificationsChanged(GameModel * sender); - void NotifyLogChanged(GameModel * sender, string entry); + void NotifyLogChanged(GameModel * sender, String entry); void NotifyToolTipChanged(GameModel * sender); void NotifyInfoTipChanged(GameModel * sender); void NotifyQuickOptionsChanged(GameModel * sender); void NotifyLastToolChanged(GameModel * sender); - virtual void ToolTip(ui::Point senderPosition, std::string toolTip); + virtual void ToolTip(ui::Point senderPosition, String toolTip); virtual void OnMouseMove(int x, int y, int dx, int dy); virtual void OnMouseDown(int x, int y, unsigned button); diff --git a/src/gui/game/Menu.h b/src/gui/game/Menu.h index 0b6292bea..66543b7ef 100644 --- a/src/gui/game/Menu.h +++ b/src/gui/game/Menu.h @@ -1,19 +1,20 @@ #ifndef MENU_H_ #define MENU_H_ +#include "common/String.h" #include "Tool.h" class Menu { - char icon; - string description; - vector tools; + String::value_type icon; + String description; + std::vector tools; bool visible; public: - Menu(char icon_, string description_, int visible_): + Menu(String::value_type icon_, String description_, int visible_): icon(icon_), description(description_), - tools(vector()), + tools(std::vector()), visible(visible_ ? true : false) { @@ -28,17 +29,17 @@ public: tools.clear(); } - vector GetToolList() + std::vector GetToolList() { return tools; } - char GetIcon() + String::value_type GetIcon() { return icon; } - string GetDescription() + String GetDescription() { return description; } diff --git a/src/gui/game/Notification.h b/src/gui/game/Notification.h index b2bf6f81f..dfa21d604 100644 --- a/src/gui/game/Notification.h +++ b/src/gui/game/Notification.h @@ -1,14 +1,14 @@ #ifndef NOTIFICATION_H_ #define NOTIFICATION_H_ -#include +#include "common/String.h" class Notification { public: - Notification(std::string message) : Message(message) {} + Notification(String message) : Message(message) {} virtual ~Notification() {}; - std::string Message; + String Message; virtual void Action() { } }; diff --git a/src/gui/game/PropertyTool.cpp b/src/gui/game/PropertyTool.cpp index 5e7175e93..2491cb906 100644 --- a/src/gui/game/PropertyTool.cpp +++ b/src/gui/game/PropertyTool.cpp @@ -1,5 +1,4 @@ #include -#include #include "Tool.h" #include "client/Client.h" #include "gui/Style.h" @@ -69,7 +68,7 @@ sim(sim_) PropertyWindow * w; public: PropertyChanged(PropertyWindow * w): w(w) { } - virtual void OptionChanged(ui::DropDown * sender, std::pair option) + virtual void OptionChanged(ui::DropDown * sender, std::pair option) { w->FocusComponent(w->textField); } @@ -79,7 +78,7 @@ sim(sim_) AddComponent(property); for (size_t i = 0; i < properties.size(); i++) { - property->AddOption(std::pair(properties[i].Name, i)); + property->AddOption(std::pair(properties[i].Name.FromAscii(), i)); } property->SetOption(Client::Ref().GetPrefInteger("Prop.Type", 0)); @@ -97,7 +96,7 @@ void PropertyWindow::SetProperty() { if(property->GetOption().second!=-1 && textField->GetText().length() > 0) { - std::string value = textField->GetText(); + String value = textField->GetText(); try { switch(properties[property->GetOption().second].Type) { @@ -108,23 +107,23 @@ void PropertyWindow::SetProperty() if(value.length() > 2 && value.substr(0, 2) == "0x") { //0xC0FFEE - std::stringstream buffer; - buffer.exceptions(std::stringstream::failbit | std::stringstream::badbit); + String::Stream buffer; + buffer.exceptions(String::Stream::failbit | String::Stream::badbit); buffer << std::hex << value.substr(2); buffer >> v; } else if(value.length() > 1 && value[0] == '#') { //#C0FFEE - std::stringstream buffer; - buffer.exceptions(std::stringstream::failbit | std::stringstream::badbit); + String::Stream buffer; + buffer.exceptions(String::Stream::failbit | String::Stream::badbit); buffer << std::hex << value.substr(1); buffer >> v; } else { int type; - if (properties[property->GetOption().second].Type == StructProperty::ParticleType && (type = sim->GetParticleType(value)) != -1) + if (properties[property->GetOption().second].Type == StructProperty::ParticleType && (type = sim->GetParticleType(value.ToUtf8())) != -1) { v = type; @@ -134,8 +133,8 @@ void PropertyWindow::SetProperty() } else { - std::stringstream buffer(value); - buffer.exceptions(std::stringstream::failbit | std::stringstream::badbit); + String::Stream buffer(value); + buffer.exceptions(String::Stream::failbit | String::Stream::badbit); buffer >> v; } } @@ -159,23 +158,23 @@ void PropertyWindow::SetProperty() if(value.length() > 2 && value.substr(0, 2) == "0x") { //0xC0FFEE - std::stringstream buffer; - buffer.exceptions(std::stringstream::failbit | std::stringstream::badbit); + String::Stream buffer; + buffer.exceptions(String::Stream::failbit | String::Stream::badbit); buffer << std::hex << value.substr(2); buffer >> v; } else if(value.length() > 1 && value[0] == '#') { //#C0FFEE - std::stringstream buffer; - buffer.exceptions(std::stringstream::failbit | std::stringstream::badbit); + String::Stream buffer; + buffer.exceptions(String::Stream::failbit | String::Stream::badbit); buffer << std::hex << value.substr(1); buffer >> v; } else { - std::stringstream buffer(value); - buffer.exceptions(std::stringstream::failbit | std::stringstream::badbit); + String::Stream buffer(value); + buffer.exceptions(String::Stream::failbit | String::Stream::badbit); buffer >> v; } #ifdef DEBUG @@ -186,8 +185,8 @@ void PropertyWindow::SetProperty() } case StructProperty::Float: { - std::stringstream buffer(value); - buffer.exceptions(std::stringstream::failbit | std::stringstream::badbit); + String::Stream buffer(value); + buffer.exceptions(String::Stream::failbit | String::Stream::badbit); buffer >> tool->propValue.Float; if (properties[property->GetOption().second].Name == "temp" && value.length()) { @@ -212,7 +211,7 @@ void PropertyWindow::SetProperty() return; } Client::Ref().SetPref("Prop.Type", property->GetOption().second); - Client::Ref().SetPref("Prop.Value", textField->GetText()); + Client::Ref().SetPrefUnicode("Prop.Value", textField->GetText()); } } diff --git a/src/gui/game/QuickOption.h b/src/gui/game/QuickOption.h index fd896d6b8..688acc784 100644 --- a/src/gui/game/QuickOption.h +++ b/src/gui/game/QuickOption.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "common/String.h" #include class GameModel; @@ -23,9 +23,9 @@ protected: std::vector listeners; GameModel * m; Type type; - std::string icon; - std::string description; - QuickOption(std::string icon, std::string description, GameModel * m, Type type) : + String icon; + String description; + QuickOption(String icon, String description, GameModel * m, Type type) : m(m), type(type), icon(icon), @@ -57,10 +57,10 @@ public: virtual int GetMutli() { return 0;} virtual int GetMultiCount() { return 0;} - std::string GetIcon() { return icon; } - void SetIcon(std::string icon) { this->icon = icon; } - std::string GetDescription() { return description; } - void SetDescription(std::string description) { this->description = description; } + String GetIcon() { return icon; } + void SetIcon(String icon) { this->icon = icon; } + String GetDescription() { return description; } + void SetDescription(String description) { this->description = description; } void Perform() { perform(); diff --git a/src/gui/game/RenderPreset.h b/src/gui/game/RenderPreset.h index 91689c7ad..301d16ea5 100644 --- a/src/gui/game/RenderPreset.h +++ b/src/gui/game/RenderPreset.h @@ -3,13 +3,13 @@ class RenderPreset { public: - std::string Name; + String Name; std::vector RenderModes; std::vector DisplayModes; unsigned int ColourMode; RenderPreset(): Name(""), ColourMode(0) {} - RenderPreset(std::string name, std::vector renderModes, std::vector displayModes, unsigned int colourMode): + RenderPreset(String name, std::vector renderModes, std::vector displayModes, unsigned int colourMode): Name(name), RenderModes(renderModes), DisplayModes(displayModes), diff --git a/src/gui/game/SignTool.cpp b/src/gui/game/SignTool.cpp index 50a6de564..011923356 100644 --- a/src/gui/game/SignTool.cpp +++ b/src/gui/game/SignTool.cpp @@ -128,10 +128,10 @@ SignWindow::SignWindow(SignTool * tool_, Simulation * sim_, int signID_, ui::Poi justification = new ui::DropDown(ui::Point(52, 48), ui::Point(50, 16)); AddComponent(justification); - justification->AddOption(std::pair("\xA0 Left", (int)sign::Left)); - justification->AddOption(std::pair("\x9E Middle", (int)sign::Middle)); - justification->AddOption(std::pair("\x9F Right", (int)sign::Right)); - justification->AddOption(std::pair("\x9D None", (int)sign::None)); + justification->AddOption(std::pair("\xA0 Left", (int)sign::Left)); + justification->AddOption(std::pair("\x9E Middle", (int)sign::Middle)); + justification->AddOption(std::pair("\x9F Right", (int)sign::Right)); + justification->AddOption(std::pair("\x9D None", (int)sign::None)); justification->SetOption(1); justification->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; @@ -181,9 +181,9 @@ void SignWindow::DoDraw() { sign & currentSign = *iter; int x, y, w, h, dx, dy; - char type = 0; + String::value_type type = 0; Graphics * g = GetGraphics(); - std::string text = currentSign.getText(sim); + String text = currentSign.getText(sim); sign::splitsign(currentSign.text, &type); currentSign.pos(text, x, y, w, h); g->clearrect(x, y, w+1, h); diff --git a/src/gui/game/Tool.cpp b/src/gui/game/Tool.cpp index 399a518a6..a28d73c91 100644 --- a/src/gui/game/Tool.cpp +++ b/src/gui/game/Tool.cpp @@ -1,4 +1,4 @@ -#include +#include "common/String.h" #include "Tool.h" #include "gui/game/Brush.h" @@ -6,7 +6,7 @@ using namespace std; -Tool::Tool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int)): +Tool::Tool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int)): textureGen(textureGen), toolID(id), toolName(name), @@ -32,9 +32,9 @@ void Tool::SetTextureGen(VideoBuffer * (*textureGen)(int, int, int)) { this->textureGen = textureGen; } -std::string Tool::GetIdentifier() { return identifier; } -string Tool::GetName() { return toolName; } -string Tool::GetDescription() { return toolDescription; } +ByteString Tool::GetIdentifier() { return identifier; } +ByteString Tool::GetName() { return toolName; } +String Tool::GetDescription() { return toolDescription; } Tool::~Tool() {} void Tool::Click(Simulation * sim, Brush * brush, ui::Point position) { } @@ -50,7 +50,7 @@ void Tool::DrawRect(Simulation * sim, Brush * brush, ui::Point position1, ui::Po void Tool::DrawFill(Simulation * sim, Brush * brush, ui::Point position) {} -ElementTool::ElementTool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int)): +ElementTool::ElementTool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int)): Tool(id, name, description, r, g, b, identifier, textureGen) { } @@ -69,7 +69,7 @@ void ElementTool::DrawFill(Simulation * sim, Brush * brush, ui::Point position) } -WallTool::WallTool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int)): +WallTool::WallTool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int)): Tool(id, name, description, r, g, b, identifier, textureGen) { blocky = true; @@ -110,7 +110,7 @@ void WallTool::DrawFill(Simulation * sim, Brush * brush, ui::Point position) { sim->FloodWalls(position.X, position.Y, toolID, -1); } -WindTool::WindTool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int)): +WindTool::WindTool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int)): Tool(id, name, description, r, g, b, identifier, textureGen) { } diff --git a/src/gui/game/Tool.h b/src/gui/game/Tool.h index 84fb38e85..f0224bf87 100644 --- a/src/gui/game/Tool.h +++ b/src/gui/game/Tool.h @@ -3,8 +3,7 @@ #include -using namespace std; - +#include "common/String.h" #include "gui/interface/Point.h" #include "simulation/StructProperty.h" @@ -17,19 +16,19 @@ class Tool protected: VideoBuffer * (*textureGen)(int, int, int); int toolID; - string toolName; - string toolDescription; + ByteString toolName; + String toolDescription; float strength; bool blocky; - std::string identifier; + ByteString identifier; public: int colRed, colGreen, colBlue; - Tool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL); + Tool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL); int GetToolID() { return toolID; } - string GetName(); - string GetDescription(); - std::string GetIdentifier(); + ByteString GetName(); + String GetDescription(); + ByteString GetIdentifier(); int GetBlocky() { return blocky; } void SetStrength(float value) { strength = value; } float GetStrength() { return strength; } @@ -106,7 +105,7 @@ public: class ElementTool: public Tool { public: - ElementTool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL); + ElementTool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL); virtual ~ElementTool(); virtual void Draw(Simulation * sim, Brush * brush, ui::Point position); virtual void DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging = false); @@ -117,7 +116,7 @@ public: class Element_LIGH_Tool: public ElementTool { public: - Element_LIGH_Tool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL): + Element_LIGH_Tool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL): ElementTool(id, name, description, r, g, b, identifier, textureGen) { } virtual ~Element_LIGH_Tool() { } @@ -130,7 +129,7 @@ public: class Element_TESC_Tool: public ElementTool { public: - Element_TESC_Tool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL): + Element_TESC_Tool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL): ElementTool(id, name, description, r, g, b, identifier, textureGen) { } virtual ~Element_TESC_Tool() {} @@ -141,7 +140,7 @@ public: class PlopTool: public ElementTool { public: - PlopTool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL): + PlopTool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL): ElementTool(id, name, description, r, g, b, identifier, textureGen) { } virtual ~PlopTool() { } @@ -155,7 +154,7 @@ public: class WallTool: public Tool { public: - WallTool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL); + WallTool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL); virtual ~WallTool(); virtual void Draw(Simulation * sim, Brush * brush, ui::Point position); virtual void DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging = false); @@ -166,7 +165,7 @@ public: class WindTool: public Tool { public: - WindTool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL); + WindTool(int id, ByteString name, String description, int r, int g, int b, ByteString identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL); virtual ~WindTool() { } virtual void Draw(Simulation * sim, Brush * brush, ui::Point position) { } virtual void DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging = false); diff --git a/src/gui/game/ToolButton.cpp b/src/gui/game/ToolButton.cpp index 3557dc717..1514d7f4d 100644 --- a/src/gui/game/ToolButton.cpp +++ b/src/gui/game/ToolButton.cpp @@ -4,8 +4,8 @@ #include "gui/interface/Mouse.h" #include "Favorite.h" -ToolButton::ToolButton(ui::Point position, ui::Point size, std::string text_, std::string toolIdentifier, std::string toolTip): - ui::Button(position, size, text_, toolTip), +ToolButton::ToolButton(ui::Point position, ui::Point size, ByteString text_, ByteString toolIdentifier, String toolTip): + ui::Button(position, size, text_.FromAscii(), toolTip), toolIdentifier(toolIdentifier) { SetSelectionState(-1); diff --git a/src/gui/game/ToolButton.h b/src/gui/game/ToolButton.h index d2a8abccb..8953e1dd4 100644 --- a/src/gui/game/ToolButton.h +++ b/src/gui/game/ToolButton.h @@ -6,9 +6,9 @@ class ToolButton: public ui::Button { int currentSelection; - std::string toolIdentifier; + ByteString toolIdentifier; public: - ToolButton(ui::Point position, ui::Point size, std::string text_, std::string toolIdentifier, std::string toolTip = ""); + ToolButton(ui::Point position, ui::Point size, ByteString text_, ByteString toolIdentifier, String toolTip = ""); virtual void OnMouseUnclick(int x, int y, unsigned int button); virtual void OnMouseUp(int x, int y, unsigned int button); virtual void OnMouseClick(int x, int y, unsigned int button); diff --git a/src/gui/interface/AvatarButton.cpp b/src/gui/interface/AvatarButton.cpp index ebe1e572c..cc5da256d 100644 --- a/src/gui/interface/AvatarButton.cpp +++ b/src/gui/interface/AvatarButton.cpp @@ -12,7 +12,7 @@ namespace ui { -AvatarButton::AvatarButton(Point position, Point size, std::string username): +AvatarButton::AvatarButton(Point position, Point size, ByteString username): Component(position, size), avatar(NULL), name(username), diff --git a/src/gui/interface/AvatarButton.h b/src/gui/interface/AvatarButton.h index fcb2e7155..67edfdbbf 100644 --- a/src/gui/interface/AvatarButton.h +++ b/src/gui/interface/AvatarButton.h @@ -1,7 +1,7 @@ #ifndef AVATARBUTTON_H_ #define AVATARBUTTON_H_ -#include +#include "common/String.h" #include "Component.h" #include "graphics/Graphics.h" @@ -21,10 +21,10 @@ public: class AvatarButton : public Component, public RequestListener { VideoBuffer * avatar; - std::string name; + ByteString name; bool tried; public: - AvatarButton(Point position, Point size, std::string username); + AvatarButton(Point position, Point size, ByteString username); virtual ~AvatarButton(); virtual void OnMouseClick(int x, int y, unsigned int button); @@ -42,8 +42,8 @@ public: virtual void DoAction(); - void SetUsername(std::string username) { name = username; } - std::string GetUsername() { return name; } + void SetUsername(ByteString username) { name = username; } + ByteString GetUsername() { return name; } void SetActionCallback(AvatarButtonAction * action); protected: bool isMouseInside, isButtonDown; diff --git a/src/gui/interface/Button.cpp b/src/gui/interface/Button.cpp index 72f44777f..aa7061b25 100644 --- a/src/gui/interface/Button.cpp +++ b/src/gui/interface/Button.cpp @@ -6,7 +6,7 @@ namespace ui { -Button::Button(Point position, Point size, std::string buttonText, std::string toolTip): +Button::Button(Point position, Point size, String buttonText, String toolTip): Component(position, size), ButtonText(buttonText), toolTip(toolTip), @@ -19,14 +19,14 @@ Button::Button(Point position, Point size, std::string buttonText, std::string t TextPosition(ButtonText); } -void Button::TextPosition(std::string ButtonText) +void Button::TextPosition(String ButtonText) { buttonDisplayText = ButtonText; if(buttonDisplayText.length()) { - if(Graphics::textwidth((char *)buttonDisplayText.c_str()) > Size.X - (Appearance.icon? 22 : 0)) + if(Graphics::textwidth(buttonDisplayText) > Size.X - (Appearance.icon? 22 : 0)) { - int position = Graphics::textwidthx((char *)buttonDisplayText.c_str(), Size.X - (Appearance.icon? 38 : 22)); + int position = Graphics::textwidthx(buttonDisplayText, Size.X - (Appearance.icon? 38 : 22)); buttonDisplayText = buttonDisplayText.erase(position, buttonDisplayText.length()-position); buttonDisplayText += "..."; } @@ -41,7 +41,7 @@ void Button::SetIcon(Icon icon) TextPosition(ButtonText); } -void Button::SetText(std::string buttonText) +void Button::SetText(String buttonText) { ButtonText = buttonText; TextPosition(ButtonText); diff --git a/src/gui/interface/Button.h b/src/gui/interface/Button.h index 0cd669ebc..681d43517 100644 --- a/src/gui/interface/Button.h +++ b/src/gui/interface/Button.h @@ -1,7 +1,7 @@ #ifndef BUTTON_H_ #define BUTTON_H_ -#include +#include "common/String.h" #include "Misc.h" #include "Component.h" #include "Colour.h" @@ -21,7 +21,7 @@ public: class Button : public Component { public: - Button(Point position = Point(0, 0), Point size = Point(0, 0), std::string buttonText = "", std::string toolTip = ""); + Button(Point position = Point(0, 0), Point size = Point(0, 0), String buttonText = "", String toolTip = ""); virtual ~Button(); virtual void OnMouseClick(int x, int y, unsigned int button); @@ -34,7 +34,7 @@ public: virtual void Draw(const Point& screenPos); - virtual void TextPosition(std::string); + virtual void TextPosition(String); inline bool GetState() { return state; } virtual void DoAction(); //action of button what ever it may be virtual void DoAltAction(); //action of button what ever it may be @@ -44,15 +44,15 @@ public: void SetToggleState(bool state); void SetActionCallback(ButtonAction * action); ButtonAction * GetActionCallback() { return actionCallback; } - void SetText(std::string buttonText); + void SetText(String buttonText); void SetIcon(Icon icon); - inline std::string GetText() { return ButtonText; } - void SetToolTip(std::string newToolTip) { toolTip = newToolTip; } + inline String GetText() { return ButtonText; } + void SetToolTip(String newToolTip) { toolTip = newToolTip; } protected: - std::string ButtonText; - std::string toolTip; - std::string buttonDisplayText; + String ButtonText; + String toolTip; + String buttonDisplayText; bool isButtonDown, isAltButtonDown, state, isMouseInside, isTogglable, toggle; ButtonAction * actionCallback; diff --git a/src/gui/interface/Checkbox.cpp b/src/gui/interface/Checkbox.cpp index 8dc1737b8..36db2e90e 100644 --- a/src/gui/interface/Checkbox.cpp +++ b/src/gui/interface/Checkbox.cpp @@ -4,7 +4,7 @@ using namespace ui; -Checkbox::Checkbox(ui::Point position, ui::Point size, std::string text, std::string toolTip): +Checkbox::Checkbox(ui::Point position, ui::Point size, String text, String toolTip): Component(position, size), text(text), toolTip(toolTip), @@ -15,12 +15,12 @@ Checkbox::Checkbox(ui::Point position, ui::Point size, std::string text, std::st } -void Checkbox::SetText(std::string text) +void Checkbox::SetText(String text) { this->text = text; } -std::string Checkbox::GetText() +String Checkbox::GetText() { return text; } diff --git a/src/gui/interface/Checkbox.h b/src/gui/interface/Checkbox.h index 4877ade1b..5d016ae86 100644 --- a/src/gui/interface/Checkbox.h +++ b/src/gui/interface/Checkbox.h @@ -1,7 +1,7 @@ #ifndef CHECKBOX_H_ #define CHECKBOX_H_ -#include +#include "common/String.h" #include "Component.h" namespace ui { @@ -13,15 +13,15 @@ public: virtual ~CheckboxAction() {} }; class Checkbox: public ui::Component { - std::string text; - std::string toolTip; + String text; + String toolTip; bool checked; bool isMouseOver; CheckboxAction * actionCallback; public: - Checkbox(ui::Point position, ui::Point size, std::string text, std::string toolTip); - void SetText(std::string text); - std::string GetText(); + Checkbox(ui::Point position, ui::Point size, String text, String toolTip); + void SetText(String text); + String GetText(); void SetIcon(Icon icon); void Draw(const Point& screenPos); virtual void OnMouseEnter(int x, int y); diff --git a/src/gui/interface/Component.cpp b/src/gui/interface/Component.cpp index 2678f1b2c..e70373d70 100644 --- a/src/gui/interface/Component.cpp +++ b/src/gui/interface/Component.cpp @@ -62,13 +62,13 @@ void Component::Refresh() drawn = false; } -void Component::TextPosition(std::string displayText) +void Component::TextPosition(String displayText) { textPosition = ui::Point(0, 0); int textWidth, textHeight = 10; - Graphics::textsize((char*)displayText.c_str(), textWidth, textHeight); + Graphics::textsize(displayText, textWidth, textHeight); textSize.X = textWidth; textSize.Y = textHeight; textHeight-=3; textWidth-=1; diff --git a/src/gui/interface/Component.h b/src/gui/interface/Component.h index c33e06f29..b4848ddfc 100644 --- a/src/gui/interface/Component.h +++ b/src/gui/interface/Component.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "common/String.h" #include "common/tpt-compat.h" #include "Appearance.h" #include "Point.h" @@ -49,7 +49,7 @@ namespace ui ui::Appearance Appearance; //virtual void SetAppearance(ui::Appearance); //ui::Appearance GetAppearance(); - virtual void TextPosition(std::string); + virtual void TextPosition(String); void Refresh(); diff --git a/src/gui/interface/ContextMenu.cpp b/src/gui/interface/ContextMenu.cpp index 32faecba1..d4b89c78e 100644 --- a/src/gui/interface/ContextMenu.cpp +++ b/src/gui/interface/ContextMenu.cpp @@ -70,7 +70,7 @@ void ContextMenu::OnMouseDown(int x, int y, unsigned button) CloseActiveWindow(); } -void ContextMenu::SetItem(int id, std::string text) +void ContextMenu::SetItem(int id, String text) { for (size_t i = 0; i < items.size(); i++) { diff --git a/src/gui/interface/ContextMenu.h b/src/gui/interface/ContextMenu.h index bc6a51004..64b6d8109 100644 --- a/src/gui/interface/ContextMenu.h +++ b/src/gui/interface/ContextMenu.h @@ -12,9 +12,9 @@ class ContextMenuItem { public: int ID; - std::string Text; + String Text; bool Enabled; - ContextMenuItem(std::string text, int id, bool enabled) : ID(id), Text(text), Enabled(enabled) {} + ContextMenuItem(String text, int id, bool enabled) : ID(id), Text(text), Enabled(enabled) {} }; class ContextMenu: public ui::Window, public ButtonAction { @@ -28,7 +28,7 @@ public: virtual void ActionCallbackItem(ui::Button *sender, int item); virtual void AddItem(ContextMenuItem item); virtual void RemoveItem(int id); - virtual void SetItem(int id, std::string text); + virtual void SetItem(int id, String text); virtual void Show(ui::Point position); virtual void OnDraw(); virtual void OnMouseDown(int x, int y, unsigned button); diff --git a/src/gui/interface/CopyTextButton.cpp b/src/gui/interface/CopyTextButton.cpp index dda5f20b7..bf96d8724 100644 --- a/src/gui/interface/CopyTextButton.cpp +++ b/src/gui/interface/CopyTextButton.cpp @@ -5,7 +5,7 @@ namespace ui { - CopyTextButton::CopyTextButton(Point position, Point size, std::string buttonText, Label *copyTextLabel_): + CopyTextButton::CopyTextButton(Point position, Point size, String buttonText, Label *copyTextLabel_): Button(position, size, buttonText) { copyTextLabel = copyTextLabel_; @@ -20,7 +20,7 @@ namespace ui void CopyTextButton::OnMouseClick(int x, int y, unsigned int button) { ui::Button::OnMouseClick(x, y, button); - ClipboardPush(ButtonText); + ClipboardPush(ButtonText.ToUtf8()); copyTextLabel->SetText("Copied!"); diff --git a/src/gui/interface/CopyTextButton.h b/src/gui/interface/CopyTextButton.h index 39e42802e..4002b19ef 100644 --- a/src/gui/interface/CopyTextButton.h +++ b/src/gui/interface/CopyTextButton.h @@ -10,7 +10,7 @@ class CopyTextButton : public Button { ui::Label *copyTextLabel; public: - CopyTextButton(Point position, Point size, std::string buttonText, Label *copyTextLabel_); + CopyTextButton(Point position, Point size, String buttonText, Label *copyTextLabel_); virtual void OnMouseClick(int x, int y, unsigned int button); diff --git a/src/gui/interface/DropDown.cpp b/src/gui/interface/DropDown.cpp index 879bea8ca..f91ba5891 100644 --- a/src/gui/interface/DropDown.cpp +++ b/src/gui/interface/DropDown.cpp @@ -18,9 +18,9 @@ public: class ItemSelectedAction: public ButtonAction { DropDownWindow * window; - std::string option; + String option; public: - ItemSelectedAction(DropDownWindow * window, std::string option): window(window), option(option) { } + ItemSelectedAction(DropDownWindow * window, String option): window(window), option(option) { } virtual void ActionCallback(ui::Button *sender) { window->CloseActiveWindow(); @@ -50,7 +50,7 @@ public: Graphics * g = GetGraphics(); g->clearrect(Position.X, Position.Y, Size.X, Size.Y); } - void setOption(std::string option) + void setOption(String option) { dropDown->SetOption(option); if (dropDown->callback) @@ -129,16 +129,16 @@ void DropDown::OnMouseLeave(int x, int y) { isMouseInside = false; } - std::pair DropDown::GetOption() + std::pair DropDown::GetOption() { if(optionIndex!=-1) { return options[optionIndex]; } - return std::pair("", -1); + return std::pair("", -1); } - void DropDown::SetOption(std::string option) + void DropDown::SetOption(String option) { for (size_t i = 0; i < options.size(); i++) { @@ -162,7 +162,7 @@ void DropDown::OnMouseLeave(int x, int y) } } } - void DropDown::AddOption(std::pair option) + void DropDown::AddOption(std::pair option) { for (size_t i = 0; i < options.size(); i++) { @@ -171,7 +171,7 @@ void DropDown::OnMouseLeave(int x, int y) } options.push_back(option); } - void DropDown::RemoveOption(std::string option) + void DropDown::RemoveOption(String option) { start: for (size_t i = 0; i < options.size(); i++) @@ -185,7 +185,7 @@ void DropDown::OnMouseLeave(int x, int y) } } } - void DropDown::SetOptions(std::vector > options) + void DropDown::SetOptions(std::vector > options) { this->options = options; } diff --git a/src/gui/interface/DropDown.h b/src/gui/interface/DropDown.h index c13fdf624..8dddd0481 100644 --- a/src/gui/interface/DropDown.h +++ b/src/gui/interface/DropDown.h @@ -12,7 +12,7 @@ class DropDownWindow; class DropDownAction { public: - virtual void OptionChanged(DropDown * sender, std::pair newOption) {} + virtual void OptionChanged(DropDown * sender, std::pair newOption) {} virtual ~DropDownAction() {} }; class DropDown: public ui::Component { @@ -20,15 +20,15 @@ class DropDown: public ui::Component { bool isMouseInside; int optionIndex; DropDownAction * callback; - std::vector > options; + std::vector > options; public: DropDown(Point position, Point size); - std::pair GetOption(); + std::pair GetOption(); void SetOption(int option); - void SetOption(std::string option); - void AddOption(std::pair option); - void RemoveOption(std::string option); - void SetOptions(std::vector > options); + void SetOption(String option); + void AddOption(std::pair option); + void RemoveOption(String option); + void SetOptions(std::vector > options); void SetActionCallback(DropDownAction * action) { callback = action;} virtual void Draw(const Point& screenPos); virtual void OnMouseClick(int x, int y, unsigned int button); diff --git a/src/gui/interface/Label.cpp b/src/gui/interface/Label.cpp index e80bd77bc..a790ed718 100644 --- a/src/gui/interface/Label.cpp +++ b/src/gui/interface/Label.cpp @@ -1,4 +1,3 @@ -#include #include "Config.h" #include "Format.h" #include "Point.h" @@ -11,7 +10,7 @@ using namespace ui; -Label::Label(Point position, Point size, std::string labelText): +Label::Label(Point position, Point size, String labelText): Component(position, size), text(labelText), textColour(255, 255, 255), @@ -47,7 +46,7 @@ void Label::SetMultiline(bool status) } } -void Label::SetText(std::string text) +void Label::SetText(String text) { this->text = text; if(multiline) @@ -75,16 +74,16 @@ void Label::updateMultiline() int lines = 1; if (text.length()>0) { - char * rawText = new char[text.length()+1]; + String::value_type *rawText = new String::value_type[text.length()+1]; std::copy(text.begin(), text.end(), rawText); rawText[text.length()] = 0; - char c, pc = 0; + String::value_type c, pc = 0; int charIndex = 0; int wordWidth = 0; int lineWidth = 0; - char * wordStart = NULL; + String::value_type *wordStart = NULL; while ((c = rawText[charIndex++])) { switch(c) @@ -129,7 +128,7 @@ void Label::updateMultiline() { Size.Y = lines*12+3; } - textLines = std::string(rawText); + textLines = rawText; delete[] rawText; /*int currentWidth = 0; char * lastSpace = NULL; @@ -170,11 +169,11 @@ void Label::updateMultiline() { Size.Y = 15; } - textLines = std::string(""); + textLines = ""; } } -std::string Label::GetText() +String Label::GetText() { return this->text; } @@ -200,9 +199,9 @@ void Label::OnMouseClick(int x, int y, unsigned button) { selecting = true; if(multiline) - selectionIndex0 = Graphics::CharIndexAtPosition((char*)textLines.c_str(), x-textPosition.X, y-textPosition.Y); + selectionIndex0 = Graphics::CharIndexAtPosition(textLines, x-textPosition.X, y-textPosition.Y); else - selectionIndex0 = Graphics::CharIndexAtPosition((char*)text.c_str(), x-textPosition.X, y-textPosition.Y); + selectionIndex0 = Graphics::CharIndexAtPosition(text, x-textPosition.X, y-textPosition.Y); selectionIndex1 = selectionIndex0; updateSelection(); @@ -211,8 +210,8 @@ void Label::OnMouseClick(int x, int y, unsigned button) void Label::copySelection() { - std::string currentText = text; - std::string copyText; + String currentText = text; + String copyText; if (selectionIndex1 > selectionIndex0) copyText = currentText.substr(selectionIndex0, selectionIndex1-selectionIndex0).c_str(); @@ -222,7 +221,7 @@ void Label::copySelection() return; else copyText = currentText.c_str(); - ClipboardPush(format::CleanString(copyText, false, true, false)); + ClipboardPush(format::CleanString(copyText, false, true, false).ToUtf8()); } void Label::OnMouseUp(int x, int y, unsigned button) @@ -248,9 +247,9 @@ void Label::OnMouseMoved(int localx, int localy, int dx, int dy) if(selecting) { if(multiline) - selectionIndex1 = Graphics::CharIndexAtPosition((char*)textLines.c_str(), localx-textPosition.X, localy-textPosition.Y); + selectionIndex1 = Graphics::CharIndexAtPosition(textLines, localx-textPosition.X, localy-textPosition.Y); else - selectionIndex1 = Graphics::CharIndexAtPosition((char*)text.c_str(), localx-textPosition.X, localy-textPosition.Y); + selectionIndex1 = Graphics::CharIndexAtPosition(text, localx-textPosition.X, localy-textPosition.Y); updateSelection(); } } @@ -297,7 +296,7 @@ void Label::selectAll() void Label::updateSelection() { - std::string currentText; + String currentText; if (selectionIndex0 < 0) selectionIndex0 = 0; if (selectionIndex0 > (int)text.length()) selectionIndex0 = text.length(); @@ -309,7 +308,7 @@ void Label::updateSelection() selectionXH = -1; selectionXL = -1; - textFragments = std::string(currentText); + textFragments = currentText; return; } @@ -319,19 +318,19 @@ void Label::updateSelection() currentText = text; if(selectionIndex1 > selectionIndex0) { - selectionLineH = Graphics::PositionAtCharIndex((char*)currentText.c_str(), selectionIndex1, selectionXH, selectionYH); - selectionLineL = Graphics::PositionAtCharIndex((char*)currentText.c_str(), selectionIndex0, selectionXL, selectionYL); + selectionLineH = Graphics::PositionAtCharIndex(currentText, selectionIndex1, selectionXH, selectionYH); + selectionLineL = Graphics::PositionAtCharIndex(currentText, selectionIndex0, selectionXL, selectionYL); - textFragments = std::string(currentText); + textFragments = currentText; //textFragments.insert(selectionIndex1, "\x0E"); //textFragments.insert(selectionIndex0, "\x0F\x01\x01\x01"); textFragments.insert(selectionIndex1, "\x01"); textFragments.insert(selectionIndex0, "\x01"); } else if(selectionIndex0 > selectionIndex1) { - selectionLineH = Graphics::PositionAtCharIndex((char*)currentText.c_str(), selectionIndex0, selectionXH, selectionYH); - selectionLineL = Graphics::PositionAtCharIndex((char*)currentText.c_str(), selectionIndex1, selectionXL, selectionYL); + selectionLineH = Graphics::PositionAtCharIndex(currentText, selectionIndex0, selectionXH, selectionYH); + selectionLineL = Graphics::PositionAtCharIndex(currentText, selectionIndex1, selectionXL, selectionYL); - textFragments = std::string(currentText); + textFragments = currentText; //textFragments.insert(selectionIndex0, "\x0E"); //textFragments.insert(selectionIndex1, "\x0F\x01\x01\x01"); textFragments.insert(selectionIndex0, "\x01"); @@ -340,21 +339,21 @@ void Label::updateSelection() selectionXH = -1; selectionXL = -1; - textFragments = std::string(currentText); + textFragments = currentText; } if(displayText.length()) { displayText = tDisplayText; if(selectionIndex1 > selectionIndex0) { - int tSelectionIndex1 = Graphics::CharIndexAtPosition((char*)displayText.c_str(), selectionXH, selectionYH); - int tSelectionIndex0 = Graphics::CharIndexAtPosition((char*)displayText.c_str(), selectionXL, selectionYL); + int tSelectionIndex1 = Graphics::CharIndexAtPosition(displayText, selectionXH, selectionYH); + int tSelectionIndex0 = Graphics::CharIndexAtPosition(displayText, selectionXL, selectionYL); displayText.insert(tSelectionIndex1, "\x01"); displayText.insert(tSelectionIndex0, "\x01"); } else if(selectionIndex0 > selectionIndex1) { - int tSelectionIndex0 = Graphics::CharIndexAtPosition((char*)displayText.c_str(), selectionXH, selectionYH); - int tSelectionIndex1 = Graphics::CharIndexAtPosition((char*)displayText.c_str(), selectionXL, selectionYL); + int tSelectionIndex0 = Graphics::CharIndexAtPosition(displayText, selectionXH, selectionYH); + int tSelectionIndex1 = Graphics::CharIndexAtPosition(displayText, selectionXL, selectionYL); displayText.insert(tSelectionIndex0, "\x01"); displayText.insert(tSelectionIndex1, "\x01"); @@ -362,7 +361,7 @@ void Label::updateSelection() } } -void Label::SetDisplayText(std::string newText) +void Label::SetDisplayText(String newText) { ClearSelection(); displayText = tDisplayText = newText; @@ -384,7 +383,7 @@ void Label::Draw(const Point& screenPos) } Graphics * g = GetGraphics(); - std::string cDisplayText = displayText; + String cDisplayText = displayText; if(!cDisplayText.length()) { diff --git a/src/gui/interface/Label.h b/src/gui/interface/Label.h index db276426a..0d3338b84 100644 --- a/src/gui/interface/Label.h +++ b/src/gui/interface/Label.h @@ -1,7 +1,7 @@ #ifndef LABEL_H #define LABEL_H -#include +#include "common/String.h" #include "Component.h" #include "Colour.h" @@ -11,12 +11,12 @@ namespace ui class Label : public Component { protected: - std::string textFragments; - std::string textLines; - std::string displayText; - std::string tDisplayText; + String textFragments; + String textLines; + String displayText; + String tDisplayText; - std::string text; + String text; Colour textColour; int selectionIndex0; int selectionIndex1; @@ -40,16 +40,16 @@ namespace ui virtual void copySelection(); public: - //Label(Window* parent_state, std::string labelText); - Label(Point position, Point size, std::string labelText); - //Label(std::string labelText); + //Label(Window* parent_state, String labelText); + Label(Point position, Point size, String labelText); + //Label(String labelText); virtual ~Label(); virtual void SetMultiline(bool status); - virtual void SetText(std::string text); - virtual void SetDisplayText(std::string newText); - virtual std::string GetText(); + virtual void SetText(String text); + virtual void SetDisplayText(String newText); + virtual String GetText(); virtual bool HasSelection(); virtual void ClearSelection(); diff --git a/src/gui/interface/ProgressBar.cpp b/src/gui/interface/ProgressBar.cpp index 87cc7584a..fb55e7d4b 100644 --- a/src/gui/interface/ProgressBar.cpp +++ b/src/gui/interface/ProgressBar.cpp @@ -5,7 +5,7 @@ using namespace ui; -ProgressBar::ProgressBar(Point position, Point size, int startProgress, std::string startStatus): +ProgressBar::ProgressBar(Point position, Point size, int startProgress, String startStatus): Component(position, size), progress(0), intermediatePos(0.0f), @@ -27,12 +27,12 @@ int ProgressBar::GetProgress() return progress; } -void ProgressBar::SetStatus(std::string status) +void ProgressBar::SetStatus(String status) { progressStatus = status; } -std::string ProgressBar::GetStatus() +String ProgressBar::GetStatus() { return progressStatus; } @@ -70,9 +70,9 @@ void ProgressBar::Draw(const Point & screenPos) } } if(progress<50) - g->drawtext(screenPos.X + ((Size.X-Graphics::textwidth(progressStatus.c_str()))/2), screenPos.Y + (Size.Y-8)/2, progressStatus, 255, 255, 255, 255); + g->drawtext(screenPos.X + ((Size.X-Graphics::textwidth(progressStatus))/2), screenPos.Y + (Size.Y-8)/2, progressStatus, 255, 255, 255, 255); else - g->drawtext(screenPos.X + ((Size.X-Graphics::textwidth(progressStatus.c_str()))/2), screenPos.Y + (Size.Y-8)/2, progressStatus, 0, 0, 0, 255); + g->drawtext(screenPos.X + ((Size.X-Graphics::textwidth(progressStatus))/2), screenPos.Y + (Size.Y-8)/2, progressStatus, 0, 0, 0, 255); } void ProgressBar::Tick(float dt) diff --git a/src/gui/interface/ProgressBar.h b/src/gui/interface/ProgressBar.h index 0efd049d8..855504d77 100644 --- a/src/gui/interface/ProgressBar.h +++ b/src/gui/interface/ProgressBar.h @@ -8,13 +8,13 @@ namespace ui { int progress; float intermediatePos; - std::string progressStatus; + String progressStatus; public: - ProgressBar(Point position, Point size, int startProgress = 0, std::string startStatus = ""); + ProgressBar(Point position, Point size, int startProgress = 0, String startStatus = ""); virtual void SetProgress(int progress); virtual int GetProgress(); - virtual void SetStatus(std::string status); - virtual std::string GetStatus(); + virtual void SetStatus(String status); + virtual String GetStatus(); virtual void Draw(const Point & screenPos); virtual void Tick(float dt); }; diff --git a/src/gui/interface/RichLabel.cpp b/src/gui/interface/RichLabel.cpp index bc6914352..5f9261700 100644 --- a/src/gui/interface/RichLabel.cpp +++ b/src/gui/interface/RichLabel.cpp @@ -10,17 +10,17 @@ using namespace ui; struct RichTextParseException: public std::exception { - std::string message; + String message; public: - RichTextParseException(std::string message_ = "Parse error"): message(message_) {} + RichTextParseException(String message_ = "Parse error"): message(message_) {} const char * what() const throw() { - return message.c_str(); + return message.ToUtf8().c_str(); } ~RichTextParseException() throw() {}; }; -RichLabel::RichLabel(Point position, Point size, std::string labelText): +RichLabel::RichLabel(Point position, Point size, String labelText): Component(position, size), textSource(labelText), displayText("") @@ -45,15 +45,15 @@ void RichLabel::updateRichText() State state = ReadText; int currentDataPos = 0; - char * currentData = new char[textSource.length()+1]; + String::value_type * currentData = new String::value_type[textSource.length()+1]; std::fill(currentData, currentData+textSource.length()+1, 0); int finalTextPos = 0; - char * finalText = new char[textSource.length()+1]; + String::value_type * finalText = new String::value_type[textSource.length()+1]; std::fill(finalText, finalText+textSource.length()+1, 0); int originalTextPos = 0; - char * originalText = new char[textSource.length()+1]; + String::value_type * originalText = new String::value_type[textSource.length()+1]; std::copy(textSource.begin(), textSource.end(), originalText); originalText[textSource.length()] = 0; @@ -82,7 +82,7 @@ void RichLabel::updateRichText() if(stackPos >= 0) { currentData[currentDataPos] = 0; - regionsStack[stackPos].actionData = std::string(currentData); + regionsStack[stackPos].actionData = String(currentData); regions.push_back(regionsStack[stackPos]); stackPos--; } @@ -142,11 +142,11 @@ void RichLabel::updateRichText() throw RichTextParseException("Unclosed region"); finalText[finalTextPos] = 0; - displayText = std::string(finalText); + displayText = String(finalText); } catch (const RichTextParseException & e) { - displayText = "\br[Parse exception: " + std::string(e.what()) + "]"; + displayText = "\br[Parse exception: " + ByteString(e.what()).FromUtf8() + "]"; regions.clear(); } delete[] currentData; @@ -157,18 +157,18 @@ void RichLabel::updateRichText() TextPosition(displayText); } -void RichLabel::SetText(std::string text) +void RichLabel::SetText(String text) { textSource = text; updateRichText(); } -std::string RichLabel::GetDisplayText() +String RichLabel::GetDisplayText() { return displayText; } -std::string RichLabel::GetText() +String RichLabel::GetText() { return textSource; } @@ -182,7 +182,7 @@ void RichLabel::Draw(const Point& screenPos) void RichLabel::OnMouseClick(int x, int y, unsigned button) { - int cursorPosition = Graphics::CharIndexAtPosition((char*)displayText.c_str(), x-textPosition.X, y-textPosition.Y); + int cursorPosition = Graphics::CharIndexAtPosition(displayText, x-textPosition.X, y-textPosition.Y); for(std::vector::iterator iter = regions.begin(), end = regions.end(); iter != end; ++iter) { if((*iter).start <= cursorPosition && (*iter).finish >= cursorPosition) @@ -190,7 +190,7 @@ void RichLabel::OnMouseClick(int x, int y, unsigned button) switch((*iter).action) { case 'a': - Platform::OpenURI((*iter).actionData); + Platform::OpenURI((*iter).actionData.ToUtf8()); break; } } diff --git a/src/gui/interface/RichLabel.h b/src/gui/interface/RichLabel.h index d9682f23b..3a99adf7d 100644 --- a/src/gui/interface/RichLabel.h +++ b/src/gui/interface/RichLabel.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "common/String.h" #include "Component.h" #include "Colour.h" @@ -15,22 +15,22 @@ namespace ui int start; int finish; int action; - std::string actionData; + String actionData; }; - RichLabel(Point position, Point size, std::string richText); + RichLabel(Point position, Point size, String richText); virtual ~RichLabel(); - virtual void SetText(std::string text); - virtual std::string GetDisplayText(); - virtual std::string GetText(); + virtual void SetText(String text); + virtual String GetDisplayText(); + virtual String GetText(); virtual void Draw(const Point& screenPos); virtual void OnMouseClick(int x, int y, unsigned button); protected: - std::string textSource; - std::string displayText; + String textSource; + String displayText; std::vector regions; diff --git a/src/gui/interface/SaveButton.cpp b/src/gui/interface/SaveButton.cpp index da52369a1..813dcb53d 100644 --- a/src/gui/interface/SaveButton.cpp +++ b/src/gui/interface/SaveButton.cpp @@ -31,14 +31,14 @@ SaveButton::SaveButton(Point position, Point size, SaveInfo * save): if(save) { name = save->name; - if(Graphics::textwidth((char *)name.c_str()) > Size.X) + if(Graphics::textwidth(name) > Size.X) { - int position = Graphics::textwidthx((char *)name.c_str(), Size.X - 22); + int position = Graphics::textwidthx(name, Size.X - 22); name = name.erase(position, name.length()-position); name += "..."; } - std::string votes, icon; + String votes, icon; votes = format::NumberToString(save->GetVotesUp()-save->GetVotesDown()); icon += 0xBB; @@ -49,12 +49,12 @@ SaveButton::SaveButton(Point position, Point size, SaveInfo * save): votesBackground = icon; - for (std::string::iterator iter = icon.begin(), end = icon.end(); iter != end; ++iter) + for (String::iterator iter = icon.begin(), end = icon.end(); iter != end; ++iter) *iter -= 14; votesBackground2 = icon; - for (std::string::iterator iter = votes.begin(), end = votes.end(); iter != end; ++iter) + for (String::iterator iter = votes.begin(), end = votes.end(); iter != end; ++iter) if(*iter != '-') *iter += 127; @@ -105,9 +105,9 @@ SaveButton::SaveButton(Point position, Point size, SaveFile * file): if(file) { name = file->GetDisplayName(); - if(Graphics::textwidth((char *)name.c_str()) > Size.X) + if(Graphics::textwidth(name) > Size.X) { - int position = Graphics::textwidthx((char *)name.c_str(), Size.X - 22); + int position = Graphics::textwidthx(name, Size.X - 22); name = name.erase(position, name.length()-position); name += "..."; } @@ -217,17 +217,17 @@ void SaveButton::Draw(const Point& screenPos) } if(isMouseInside && !isMouseInsideAuthor) - g->drawtext(screenPos.X+(Size.X-Graphics::textwidth((char *)name.c_str()))/2, screenPos.Y+Size.Y - 21, name, 255, 255, 255, 255); + g->drawtext(screenPos.X+(Size.X-Graphics::textwidth(name))/2, screenPos.Y+Size.Y - 21, name, 255, 255, 255, 255); else - g->drawtext(screenPos.X+(Size.X-Graphics::textwidth((char *)name.c_str()))/2, screenPos.Y+Size.Y - 21, name, 180, 180, 180, 255); + g->drawtext(screenPos.X+(Size.X-Graphics::textwidth(name))/2, screenPos.Y+Size.Y - 21, name, 180, 180, 180, 255); if(isMouseInsideAuthor) - g->drawtext(screenPos.X+(Size.X-Graphics::textwidth((char *)save->userName.c_str()))/2, screenPos.Y+Size.Y - 10, save->userName, 200, 230, 255, 255); + g->drawtext(screenPos.X+(Size.X-Graphics::textwidth(save->userName.FromUtf8()))/2, screenPos.Y+Size.Y - 10, save->userName.FromUtf8(), 200, 230, 255, 255); else - g->drawtext(screenPos.X+(Size.X-Graphics::textwidth((char *)save->userName.c_str()))/2, screenPos.Y+Size.Y - 10, save->userName, 100, 130, 160, 255); + g->drawtext(screenPos.X+(Size.X-Graphics::textwidth(save->userName.FromUtf8()))/2, screenPos.Y+Size.Y - 10, save->userName.FromUtf8(), 100, 130, 160, 255); if (showVotes)// && !isMouseInside) { - int x = screenPos.X-7+(Size.X-thumbBoxSize.X)/2+thumbBoxSize.X-Graphics::textwidth(votesBackground.c_str()); + int x = screenPos.X-7+(Size.X-thumbBoxSize.X)/2+thumbBoxSize.X-Graphics::textwidth(votesBackground); int y = screenPos.Y-23+(Size.Y-thumbBoxSize.Y)/2+thumbBoxSize.Y; g->drawtext(x, y, votesBackground, 16, 72, 16, 255); g->drawtext(x, y, votesBackground2, 192, 192, 192, 255); @@ -259,11 +259,11 @@ void SaveButton::Draw(const Point& screenPos) if (isMouseInside) { - g->drawtext(screenPos.X+(Size.X-Graphics::textwidth((char *)name.c_str()))/2, screenPos.Y+Size.Y - 21, name, 255, 255, 255, 255); + g->drawtext(screenPos.X+(Size.X-Graphics::textwidth(name))/2, screenPos.Y+Size.Y - 21, name, 255, 255, 255, 255); } else { - g->drawtext(screenPos.X+(Size.X-Graphics::textwidth((char *)name.c_str()))/2, screenPos.Y+Size.Y - 21, name, 180, 180, 180, 255); + g->drawtext(screenPos.X+(Size.X-Graphics::textwidth(name))/2, screenPos.Y+Size.Y - 21, name, 180, 180, 180, 255); } } diff --git a/src/gui/interface/SaveButton.h b/src/gui/interface/SaveButton.h index 4b9682af2..8105ab6e3 100644 --- a/src/gui/interface/SaveButton.h +++ b/src/gui/interface/SaveButton.h @@ -1,7 +1,7 @@ #ifndef SAVEBUTTON_H_ #define SAVEBUTTON_H_ -#include +#include "common/String.h" #include "Component.h" #include "client/SaveFile.h" @@ -28,10 +28,10 @@ class SaveButton : public Component, public RequestListener SaveFile * file; SaveInfo * save; VideoBuffer * thumbnail; - std::string name; - std::string votesString; - std::string votesBackground; - std::string votesBackground2; + String name; + String votesString; + String votesBackground; + String votesBackground2; int voteBarHeightUp; int voteBarHeightDown; bool wantsDraw; diff --git a/src/gui/interface/Textbox.cpp b/src/gui/interface/Textbox.cpp index cd5bb514d..583b3eab4 100644 --- a/src/gui/interface/Textbox.cpp +++ b/src/gui/interface/Textbox.cpp @@ -1,4 +1,4 @@ -#include +#include "common/String.h" #include #include #include "Config.h" @@ -13,11 +13,11 @@ using namespace ui; -Textbox::Textbox(Point position, Point size, std::string textboxText, std::string textboxPlaceholder): +Textbox::Textbox(Point position, Point size, String textboxText, String textboxPlaceholder): Label(position, size, ""), ReadOnly(false), inputType(All), - limit(std::string::npos), + limit(String::npos), keyDown(0), characterDown(0), mouseDown(false), @@ -53,18 +53,18 @@ void Textbox::SetHidden(bool hidden) masked = hidden; } -void Textbox::SetPlaceholder(std::string text) +void Textbox::SetPlaceholder(String text) { placeHolder = text; } -void Textbox::SetText(std::string newText) +void Textbox::SetText(String newText) { backingText = newText; if(masked) { - std::string maskedText = std::string(newText); + String maskedText = newText; std::fill(maskedText.begin(), maskedText.end(), '\x8D'); Label::SetText(maskedText); } @@ -75,7 +75,7 @@ void Textbox::SetText(std::string newText) if(cursor) { - Graphics::PositionAtCharIndex(multiline?((char*)textLines.c_str()):((char*)text.c_str()), cursor, cursorPositionX, cursorPositionY); + Graphics::PositionAtCharIndex(multiline?textLines:text, cursor, cursorPositionX, cursorPositionY); } else { @@ -103,7 +103,7 @@ size_t Textbox::GetLimit() return limit; } -std::string Textbox::GetText() +String Textbox::GetText() { return backingText; } @@ -126,7 +126,7 @@ void Textbox::OnContextMenuAction(int item) void Textbox::resetCursorPosition() { - Graphics::PositionAtCharIndex(multiline?((char*)textLines.c_str()):((char*)text.c_str()), cursor, cursorPositionX, cursorPositionY); + Graphics::PositionAtCharIndex(multiline?textLines:text, cursor, cursorPositionX, cursorPositionY); } void Textbox::TabFocus() @@ -141,8 +141,8 @@ void Textbox::cutSelection() { if (getLowerSelectionBound() < 0 || getHigherSelectionBound() > (int)backingText.length()) return; - std::string toCopy = backingText.substr(getLowerSelectionBound(), getHigherSelectionBound()-getLowerSelectionBound()); - ClipboardPush(format::CleanString(toCopy, false, true, false)); + String toCopy = backingText.substr(getLowerSelectionBound(), getHigherSelectionBound()-getLowerSelectionBound()); + ClipboardPush(format::CleanString(toCopy, false, true, false).ToUtf8()); backingText.erase(backingText.begin()+getLowerSelectionBound(), backingText.begin()+getHigherSelectionBound()); cursor = getLowerSelectionBound(); } @@ -150,7 +150,7 @@ void Textbox::cutSelection() { if (!backingText.length()) return; - ClipboardPush(format::CleanString(backingText, false, true, false)); + ClipboardPush(format::CleanString(backingText, false, true, false).ToUtf8()); backingText.clear(); cursor = 0; } @@ -158,7 +158,7 @@ void Textbox::cutSelection() if(masked) { - std::string maskedText = std::string(backingText); + String maskedText = backingText; std::fill(maskedText.begin(), maskedText.end(), '\x8D'); Label::SetText(maskedText); } @@ -174,7 +174,7 @@ void Textbox::cutSelection() if(cursor) { - Graphics::PositionAtCharIndex(multiline?((char*)textLines.c_str()):((char*)text.c_str()), cursor, cursorPositionX, cursorPositionY); + Graphics::PositionAtCharIndex(multiline?textLines:text, cursor, cursorPositionX, cursorPositionY); } else { @@ -186,7 +186,7 @@ void Textbox::cutSelection() void Textbox::pasteIntoSelection() { - std::string newText = format::CleanString(ClipboardPull(), true, true, inputType != Multiline, inputType == Number || inputType == Numeric); + String newText = format::CleanString(ClipboardPull().FromUtf8(), true, true, inputType != Multiline, inputType == Number || inputType == Numeric); if (HasSelection()) { if (getLowerSelectionBound() < 0 || getHigherSelectionBound() > (int)backingText.length()) @@ -201,14 +201,14 @@ void Textbox::pasteIntoSelection() regionWidth -= Appearance.Margin.Left; regionWidth -= Appearance.Margin.Right; - if (limit != std::string::npos) + if (limit != String::npos) { newText = newText.substr(0, limit-backingText.length()); } - if (!multiline && Graphics::textwidth((char*)std::string(backingText+newText).c_str()) > regionWidth) + if (!multiline && Graphics::textwidth(backingText + newText) > regionWidth) { - int pLimit = regionWidth - Graphics::textwidth((char*)backingText.c_str()); - int cIndex = Graphics::CharIndexAtPosition((char *)newText.c_str(), pLimit, 0); + int pLimit = regionWidth - Graphics::textwidth(backingText); + int cIndex = Graphics::CharIndexAtPosition(newText, pLimit, 0); if (cIndex > 0) newText = newText.substr(0, cIndex); @@ -222,7 +222,7 @@ void Textbox::pasteIntoSelection() if(masked) { - std::string maskedText = std::string(backingText); + String maskedText = backingText; std::fill(maskedText.begin(), maskedText.end(), '\x8D'); Label::SetText(maskedText); } @@ -241,7 +241,7 @@ void Textbox::pasteIntoSelection() if(cursor) { - Graphics::PositionAtCharIndex(multiline?((char*)textLines.c_str()):((char*)text.c_str()), cursor, cursorPositionX, cursorPositionY); + Graphics::PositionAtCharIndex(multiline?textLines:text, cursor, cursorPositionX, cursorPositionY); } else { @@ -362,8 +362,8 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool if (ctrl) { size_t stopChar; - stopChar = backingText.find_first_not_of(" .,!?\n", cursor); - stopChar = backingText.find_first_of(" .,!?\n", stopChar); + stopChar = backingText.find_first_not_of(String(" .,!?\n"), cursor); + stopChar = backingText.find_first_of(String(" .,!?\n"), stopChar); backingText.erase(cursor, stopChar-cursor); } else @@ -388,11 +388,11 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool if (ctrl) { size_t stopChar; - stopChar = backingText.substr(0, cursor).find_last_not_of(" .,!?\n"); + stopChar = backingText.substr(0, cursor).find_last_not_of(String(" .,!?\n")); if (stopChar == backingText.npos) stopChar = -1; else - stopChar = backingText.substr(0, stopChar).find_last_of(" .,!?\n"); + stopChar = backingText.substr(0, stopChar).find_last_of(String(" .,!?\n")); backingText.erase(stopChar+1, cursor-(stopChar+1)); cursor = stopChar+1; } @@ -423,7 +423,7 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool regionWidth -= 13; regionWidth -= Appearance.Margin.Left; regionWidth -= Appearance.Margin.Right; - if ((limit==std::string::npos || backingText.length() < limit) && (Graphics::textwidth((char*)std::string(backingText+char(character)).c_str()) <= regionWidth || multiline)) + if ((limit==String::npos || backingText.length() < limit) && (Graphics::textwidth(backingText + character) <= regionWidth || multiline)) { if (cursor == (int)backingText.length()) { @@ -431,7 +431,7 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool } else { - backingText.insert(cursor, 1, (char)character); + backingText.insert(cursor, 1, String::value_type(character)); } cursor++; } @@ -458,7 +458,7 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool { if (masked) { - std::string maskedText = std::string(backingText); + String maskedText = backingText; std::fill(maskedText.begin(), maskedText.end(), '\x8D'); Label::SetText(maskedText); } @@ -478,7 +478,7 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool if(cursor) { - Graphics::PositionAtCharIndex(multiline?((char*)textLines.c_str()):((char*)text.c_str()), cursor, cursorPositionX, cursorPositionY); + Graphics::PositionAtCharIndex(multiline?textLines:text, cursor, cursorPositionX, cursorPositionY); } else { @@ -494,10 +494,10 @@ void Textbox::OnMouseClick(int x, int y, unsigned button) if (button != SDL_BUTTON_RIGHT) { mouseDown = true; - cursor = Graphics::CharIndexAtPosition(multiline?((char*)textLines.c_str()):((char*)text.c_str()), x-textPosition.X, y-textPosition.Y); + cursor = Graphics::CharIndexAtPosition(multiline?textLines:text, x-textPosition.X, y-textPosition.Y); if(cursor) { - Graphics::PositionAtCharIndex(multiline?((char*)textLines.c_str()):((char*)text.c_str()), cursor, cursorPositionX, cursorPositionY); + Graphics::PositionAtCharIndex(multiline?textLines:text, cursor, cursorPositionX, cursorPositionY); } else { @@ -517,10 +517,10 @@ void Textbox::OnMouseMoved(int localx, int localy, int dx, int dy) { if(mouseDown) { - cursor = Graphics::CharIndexAtPosition(multiline?((char*)textLines.c_str()):((char*)text.c_str()), localx-textPosition.X, localy-textPosition.Y); + cursor = Graphics::CharIndexAtPosition(multiline?textLines:text, localx-textPosition.X, localy-textPosition.Y); if(cursor) { - Graphics::PositionAtCharIndex(multiline?((char*)textLines.c_str()):((char*)text.c_str()), cursor, cursorPositionX, cursorPositionY); + Graphics::PositionAtCharIndex(multiline?textLines:text, cursor, cursorPositionX, cursorPositionY); } else { diff --git a/src/gui/interface/Textbox.h b/src/gui/interface/Textbox.h index f1f62aa1b..f20b8c831 100644 --- a/src/gui/interface/Textbox.h +++ b/src/gui/interface/Textbox.h @@ -1,7 +1,7 @@ #ifndef TEXTBOX_H #define TEXTBOX_H -#include +#include "common/String.h" #include "Label.h" #include "PowderToy.h" @@ -22,13 +22,13 @@ class Textbox : public Label public: bool ReadOnly; enum ValidInput { All, Multiline, Numeric, Number }; // Numeric doesn't delete trailing 0's - Textbox(Point position, Point size, std::string textboxText = "", std::string textboxPlaceholder = ""); + Textbox(Point position, Point size, String textboxText = "", String textboxPlaceholder = ""); virtual ~Textbox(); - virtual void SetText(std::string text); - virtual std::string GetText(); + virtual void SetText(String text); + virtual String GetText(); - virtual void SetPlaceholder(std::string text); + virtual void SetPlaceholder(String text); void SetBorder(bool border) { this->border = border; } void SetHidden(bool hidden); @@ -66,8 +66,8 @@ protected: bool masked, border; int cursor, cursorPositionX, cursorPositionY; TextboxAction *actionCallback; - std::string backingText; - std::string placeHolder; + String backingText; + String placeHolder; virtual void cutSelection(); virtual void pasteIntoSelection(); diff --git a/src/gui/interface/Window.h b/src/gui/interface/Window.h index bb68d438e..200aeb8dd 100644 --- a/src/gui/interface/Window.h +++ b/src/gui/interface/Window.h @@ -1,7 +1,7 @@ #ifndef WINDOW_H #define WINDOW_H -#include +#include "common/String.h" #include #include "common/tpt-compat.h" #include "gui/interface/Point.h" @@ -52,7 +52,7 @@ namespace ui // Remove a component from window. NOTE: This WILL free component from memory. void RemoveComponent(unsigned idx); - virtual void ToolTip(ui::Point senderPosition, std::string toolTip) {} + virtual void ToolTip(ui::Point senderPosition, String toolTip) {} virtual void DoInitialized(); virtual void DoExit(); diff --git a/src/gui/localbrowser/LocalBrowserController.cpp b/src/gui/localbrowser/LocalBrowserController.cpp index eca08222d..709414701 100644 --- a/src/gui/localbrowser/LocalBrowserController.cpp +++ b/src/gui/localbrowser/LocalBrowserController.cpp @@ -1,5 +1,3 @@ -#include - #include "client/Client.h" #include "LocalBrowserController.h" #include "gui/interface/Engine.h" @@ -46,7 +44,7 @@ void LocalBrowserController::RemoveSelected() virtual ~RemoveSelectedConfirmation() { } }; - std::stringstream desc; + String::Stream desc; desc << "Are you sure you want to delete " << browserModel->GetSelected().size() << " stamp"; if(browserModel->GetSelected().size()>1) desc << "s"; @@ -58,16 +56,16 @@ void LocalBrowserController::removeSelectedC() { class RemoveSavesTask : public Task { - std::vector saves; + std::vector saves; LocalBrowserController * c; public: - RemoveSavesTask(LocalBrowserController * c, std::vector saves_) : c(c) { saves = saves_; } + RemoveSavesTask(LocalBrowserController * c, std::vector saves_) : c(c) { saves = saves_; } virtual bool doWork() { for (size_t i = 0; i < saves.size(); i++) { - std::stringstream saveName; - saveName << "Deleting stamp [" << saves[i] << "] ..."; + String::Stream saveName; + saveName << "Deleting stamp [" << saves[i].FromUtf8() << "] ..."; notifyStatus(saveName.str()); Client::Ref().DeleteStamp(saves[i]); notifyProgress((float(i+1)/float(saves.size())*100)); @@ -81,7 +79,7 @@ void LocalBrowserController::removeSelectedC() } }; - std::vector selected = browserModel->GetSelected(); + std::vector selected = browserModel->GetSelected(); new TaskWindow("Removing stamps", new RemoveSavesTask(this, selected)); } @@ -98,7 +96,7 @@ void LocalBrowserController::RescanStamps() virtual ~RescanConfirmation() { } }; - std::stringstream desc; + String::Stream desc; desc << "Rescanning the stamps folder can find stamps added to the stamps folder or recover stamps when the stamps.def file has been lost or damaged. However, be warned that this will mess up the current sorting order"; new ConfirmPrompt("Rescan", desc.str(), new RescanConfirmation(this)); } @@ -146,7 +144,7 @@ void LocalBrowserController::Update() } } -void LocalBrowserController::Selected(std::string saveName, bool selected) +void LocalBrowserController::Selected(ByteString saveName, bool selected) { if(selected) browserModel->SelectSave(saveName); diff --git a/src/gui/localbrowser/LocalBrowserController.h b/src/gui/localbrowser/LocalBrowserController.h index e6f6d76f2..bacef1631 100644 --- a/src/gui/localbrowser/LocalBrowserController.h +++ b/src/gui/localbrowser/LocalBrowserController.h @@ -19,7 +19,7 @@ public: void RemoveSelected(); void removeSelectedC(); void ClearSelection(); - void Selected(std::string stampID, bool selected); + void Selected(ByteString stampID, bool selected); void RescanStamps(); void rescanStampsC(); void RefreshSavesList(); diff --git a/src/gui/localbrowser/LocalBrowserModel.cpp b/src/gui/localbrowser/LocalBrowserModel.cpp index 78955a3b8..e499bd144 100644 --- a/src/gui/localbrowser/LocalBrowserModel.cpp +++ b/src/gui/localbrowser/LocalBrowserModel.cpp @@ -100,7 +100,7 @@ int LocalBrowserModel::GetPageCount() return std::max(1, (int)(std::ceil(float(Client::Ref().GetStampsCount())/20.0f))); } -void LocalBrowserModel::SelectSave(std::string stampID) +void LocalBrowserModel::SelectSave(ByteString stampID) { for (size_t i = 0; i < selected.size(); i++) { @@ -113,7 +113,7 @@ void LocalBrowserModel::SelectSave(std::string stampID) notifySelectedChanged(); } -void LocalBrowserModel::DeselectSave(std::string stampID) +void LocalBrowserModel::DeselectSave(ByteString stampID) { bool changed = false; restart: diff --git a/src/gui/localbrowser/LocalBrowserModel.h b/src/gui/localbrowser/LocalBrowserModel.h index 75167d9ff..c52bf3941 100644 --- a/src/gui/localbrowser/LocalBrowserModel.h +++ b/src/gui/localbrowser/LocalBrowserModel.h @@ -2,16 +2,16 @@ #define STAMPSMODEL_H_ #include -#include +#include "common/String.h" #include class SaveFile; class LocalBrowserView; class LocalBrowserModel { - std::vector selected; + std::vector selected; SaveFile * stamp; - std::vector stampIDs; + std::vector stampIDs; std::vector savesList; std::vector observers; int currentPage; @@ -31,10 +31,10 @@ public: void SetSave(SaveFile * newStamp); bool GetMoveToFront(); void SetMoveToFront(bool move); - std::vector GetSelected() { return selected; } + std::vector GetSelected() { return selected; } void ClearSelected() { selected.clear(); notifySelectedChanged(); } - void SelectSave(std::string stampID); - void DeselectSave(std::string stampID); + void SelectSave(ByteString stampID); + void DeselectSave(ByteString stampID); virtual ~LocalBrowserModel(); }; diff --git a/src/gui/localbrowser/LocalBrowserModelException.h b/src/gui/localbrowser/LocalBrowserModelException.h index 5146c533d..705173b00 100644 --- a/src/gui/localbrowser/LocalBrowserModelException.h +++ b/src/gui/localbrowser/LocalBrowserModelException.h @@ -1,15 +1,14 @@ #ifndef STAMPSMODELEXCEPTION_H_ #define STAMPSMODELEXCEPTION_H_ -#include +#include "common/String.h" #include -using namespace std; class LocalBrowserModelException { - string message; + String message; public: - LocalBrowserModelException(string message_): message(message_) {}; - const char * what() const throw() { return message.c_str(); }; + LocalBrowserModelException(String message_): message(message_) {}; + const char * what() const throw() { return message.ToUtf8().c_str(); }; ~LocalBrowserModelException() throw() {}; }; diff --git a/src/gui/localbrowser/LocalBrowserView.cpp b/src/gui/localbrowser/LocalBrowserView.cpp index 950598603..4f8bef3c1 100644 --- a/src/gui/localbrowser/LocalBrowserView.cpp +++ b/src/gui/localbrowser/LocalBrowserView.cpp @@ -1,4 +1,3 @@ -#include #include "client/Client.h" #include "Format.h" #include "LocalBrowserView.h" @@ -141,7 +140,7 @@ void LocalBrowserView::NotifyPageChanged(LocalBrowserModel * sender) } else { - std::stringstream pageInfo; + String::Stream pageInfo; pageInfo << "of " << pageCount; pageCountLabel->SetText(pageInfo.str()); int width = Graphics::textwidth(pageInfo.str().c_str()); @@ -152,7 +151,7 @@ void LocalBrowserView::NotifyPageChanged(LocalBrowserModel * sender) //pageCountLabel->Position.X = WINDOWW/2+6; pageLabel->Visible = pageCountLabel->Visible = pageTextbox->Visible = true; - pageInfo.str(""); + pageInfo.str(String()); pageInfo << sender->GetPageNum(); pageTextbox->SetText(pageInfo.str()); } @@ -180,7 +179,7 @@ void LocalBrowserView::NotifySavesListChanged(LocalBrowserModel * sender) int buttonWidth, buttonHeight, saveX = 0, saveY = 0, savesX = 5, savesY = 4, buttonPadding = 2; int buttonAreaWidth, buttonAreaHeight, buttonXOffset, buttonYOffset; - vector saves = sender->GetSavesList(); + std::vector saves = sender->GetSavesList(); for (size_t i = 0; i < stampButtons.size(); i++) { RemoveComponent(stampButtons[i]); @@ -236,7 +235,7 @@ void LocalBrowserView::NotifySavesListChanged(LocalBrowserModel * sender) void LocalBrowserView::NotifySelectedChanged(LocalBrowserModel * sender) { - vector selected = sender->GetSelected(); + std::vector selected = sender->GetSelected(); for (size_t j = 0; j < stampButtons.size(); j++) { stampButtons[j]->SetSelected(false); diff --git a/src/gui/login/LoginController.cpp b/src/gui/login/LoginController.cpp index 5e3ae7713..f58e7c1f8 100644 --- a/src/gui/login/LoginController.cpp +++ b/src/gui/login/LoginController.cpp @@ -15,7 +15,7 @@ LoginController::LoginController(ControllerCallback * callback): } -void LoginController::Login(string username, string password) +void LoginController::Login(ByteString username, ByteString password) { loginModel->Login(username, password); } diff --git a/src/gui/login/LoginController.h b/src/gui/login/LoginController.h index b723cb9f7..fbf5236d2 100644 --- a/src/gui/login/LoginController.h +++ b/src/gui/login/LoginController.h @@ -1,7 +1,7 @@ #ifndef LOGINCONTROLLER_H_ #define LOGINCONTROLLER_H_ -#include +#include "common/String.h" #include "LoginView.h" #include "LoginModel.h" #include "Controller.h" @@ -18,7 +18,7 @@ class LoginController { public: bool HasExited; LoginController(ControllerCallback * callback = NULL); - void Login(string username, string password); + void Login(ByteString username, ByteString password); void Exit(); LoginView * GetView() { return loginView; } User GetUser(); diff --git a/src/gui/login/LoginModel.cpp b/src/gui/login/LoginModel.cpp index b14a69cc3..bcfe90531 100644 --- a/src/gui/login/LoginModel.cpp +++ b/src/gui/login/LoginModel.cpp @@ -6,7 +6,7 @@ LoginModel::LoginModel(): } -void LoginModel::Login(string username, string password) +void LoginModel::Login(ByteString username, ByteString password) { if (username.find('@') != username.npos) { @@ -37,7 +37,7 @@ void LoginModel::AddObserver(LoginView * observer) observers.push_back(observer); } -string LoginModel::GetStatusText() +String LoginModel::GetStatusText() { return statusText; } diff --git a/src/gui/login/LoginModel.h b/src/gui/login/LoginModel.h index 8149797e5..d21450678 100644 --- a/src/gui/login/LoginModel.h +++ b/src/gui/login/LoginModel.h @@ -2,7 +2,7 @@ #define LOGINMODEL_H_ #include -#include +#include "common/String.h" #include "LoginView.h" #include "client/Client.h" @@ -11,15 +11,15 @@ using namespace std; class LoginView; class LoginModel { vector observers; - string statusText; + String statusText; bool loginStatus; void notifyStatusChanged(); User currentUser; public: LoginModel(); - void Login(string username, string password); + void Login(ByteString username, ByteString password); void AddObserver(LoginView * observer); - string GetStatusText(); + String GetStatusText(); bool GetStatus(); User GetUser(); virtual ~LoginModel(); diff --git a/src/gui/login/LoginView.cpp b/src/gui/login/LoginView.cpp index 22b74fe1d..e6646ddf0 100644 --- a/src/gui/login/LoginView.cpp +++ b/src/gui/login/LoginView.cpp @@ -14,7 +14,7 @@ public: LoginAction(LoginView * _v) { v = _v; } void ActionCallback(ui::Button * sender) { - v->c->Login(v->usernameField->GetText(), v->passwordField->GetText()); + v->c->Login(v->usernameField->GetText().ToUtf8(), v->passwordField->GetText().ToUtf8()); } }; @@ -35,7 +35,7 @@ LoginView::LoginView(): cancelButton(new ui::Button(ui::Point(0, 87-17), ui::Point(101, 17), "Sign Out")), titleLabel(new ui::Label(ui::Point(4, 5), ui::Point(200-16, 16), "Server login")), infoLabel(new ui::Label(ui::Point(8, 67), ui::Point(200-16, 16), "")), - usernameField(new ui::Textbox(ui::Point(8, 25), ui::Point(200-16, 17), Client::Ref().GetAuthUser().Username, "[username]")), + usernameField(new ui::Textbox(ui::Point(8, 25), ui::Point(200-16, 17), Client::Ref().GetAuthUser().Username.FromUtf8(), "[username]")), passwordField(new ui::Textbox(ui::Point(8, 46), ui::Point(200-16, 17), "", "[password]")), targetSize(0, 0) { diff --git a/src/gui/options/OptionsView.cpp b/src/gui/options/OptionsView.cpp index 477f9d2ac..a40794023 100644 --- a/src/gui/options/OptionsView.cpp +++ b/src/gui/options/OptionsView.cpp @@ -89,15 +89,15 @@ OptionsView::OptionsView(): OptionsView * v; public: AirModeChanged(OptionsView * v): v(v) { } - virtual void OptionChanged(ui::DropDown * sender, std::pair option) { v->c->SetAirMode(option.second); } + virtual void OptionChanged(ui::DropDown * sender, std::pair option) { v->c->SetAirMode(option.second); } }; airMode = new ui::DropDown(ui::Point(Size.X-88, 146), ui::Point(80, 16)); AddComponent(airMode); - airMode->AddOption(std::pair("On", 0)); - airMode->AddOption(std::pair("Pressure off", 1)); - airMode->AddOption(std::pair("Velocity off", 2)); - airMode->AddOption(std::pair("Off", 3)); - airMode->AddOption(std::pair("No Update", 4)); + airMode->AddOption(std::pair("On", 0)); + airMode->AddOption(std::pair("Pressure off", 1)); + airMode->AddOption(std::pair("Velocity off", 2)); + airMode->AddOption(std::pair("Off", 3)); + airMode->AddOption(std::pair("No Update", 4)); airMode->SetActionCallback(new AirModeChanged(this)); tempLabel = new ui::Label(ui::Point(8, 146), ui::Point(Size.X-96, 16), "Air Simulation Mode"); @@ -109,14 +109,14 @@ OptionsView::OptionsView(): OptionsView * v; public: GravityModeChanged(OptionsView * v): v(v) { } - virtual void OptionChanged(ui::DropDown * sender, std::pair option) { v->c->SetGravityMode(option.second); } + virtual void OptionChanged(ui::DropDown * sender, std::pair option) { v->c->SetGravityMode(option.second); } }; gravityMode = new ui::DropDown(ui::Point(Size.X-88, 166), ui::Point(80, 16)); AddComponent(gravityMode); - gravityMode->AddOption(std::pair("Vertical", 0)); - gravityMode->AddOption(std::pair("Off", 1)); - gravityMode->AddOption(std::pair("Radial", 2)); + gravityMode->AddOption(std::pair("Vertical", 0)); + gravityMode->AddOption(std::pair("Off", 1)); + gravityMode->AddOption(std::pair("Radial", 2)); gravityMode->SetActionCallback(new GravityModeChanged(this)); tempLabel = new ui::Label(ui::Point(8, 166), ui::Point(Size.X-96, 16), "Gravity Simulation Mode"); @@ -128,14 +128,14 @@ OptionsView::OptionsView(): OptionsView * v; public: EdgeModeChanged(OptionsView * v): v(v) { } - virtual void OptionChanged(ui::DropDown * sender, std::pair option) { v->c->SetEdgeMode(option.second); } + virtual void OptionChanged(ui::DropDown * sender, std::pair option) { v->c->SetEdgeMode(option.second); } }; edgeMode = new ui::DropDown(ui::Point(Size.X-88, 186), ui::Point(80, 16)); AddComponent(edgeMode); - edgeMode->AddOption(std::pair("Void", 0)); - edgeMode->AddOption(std::pair("Solid", 1)); - edgeMode->AddOption(std::pair("Loop", 2)); + edgeMode->AddOption(std::pair("Void", 0)); + edgeMode->AddOption(std::pair("Solid", 1)); + edgeMode->AddOption(std::pair("Loop", 2)); edgeMode->SetActionCallback(new EdgeModeChanged(this)); tempLabel = new ui::Label(ui::Point(8, 186), ui::Point(Size.X-96, 16), "Edge Mode"); @@ -147,7 +147,7 @@ OptionsView::OptionsView(): OptionsView * v; public: ScaleAction(OptionsView * v): v(v) { } - virtual void OptionChanged(ui::DropDown * sender, std::pair option) { v->c->SetScale(option.second); } + virtual void OptionChanged(ui::DropDown * sender, std::pair option) { v->c->SetScale(option.second); } }; scale = new ui::DropDown(ui::Point(8, 210), ui::Point(40, 16)); { @@ -158,12 +158,12 @@ OptionsView::OptionsView(): { if (current_scale == ix_scale) current_scale_valid = true; - scale->AddOption(std::pair(format::NumberToString(ix_scale), ix_scale)); + scale->AddOption(std::pair(format::NumberToString(ix_scale), ix_scale)); ix_scale += 1; } while (ui::Engine::Ref().GetMaxWidth() >= ui::Engine::Ref().GetWidth() * ix_scale && ui::Engine::Ref().GetMaxHeight() >= ui::Engine::Ref().GetHeight() * ix_scale); if (!current_scale_valid) - scale->AddOption(std::pair("current", current_scale)); + scale->AddOption(std::pair("current", current_scale)); } scale->SetActionCallback(new ScaleAction(this)); AddComponent(scale); diff --git a/src/gui/preview/Comment.h b/src/gui/preview/Comment.h index 1d84042d0..197a0da00 100644 --- a/src/gui/preview/Comment.h +++ b/src/gui/preview/Comment.h @@ -1,16 +1,16 @@ #ifndef COMMENT_H_ #define COMMENT_H_ -#include +#include "common/String.h" class SaveComment { public: int authorID; - std::string authorName; - std::string authorNameFormatted; - std::string comment; - SaveComment(int userID, std::string username, std::string usernameFormatted, std::string commentText): + ByteString authorName; + ByteString authorNameFormatted; + String comment; + SaveComment(int userID, ByteString username, ByteString usernameFormatted, String commentText): authorID(userID), authorName(username), authorNameFormatted(usernameFormatted), comment(commentText) { } diff --git a/src/gui/preview/PreviewController.cpp b/src/gui/preview/PreviewController.cpp index 7ecc8d7a7..44870f9d2 100644 --- a/src/gui/preview/PreviewController.cpp +++ b/src/gui/preview/PreviewController.cpp @@ -1,4 +1,3 @@ -#include #include "client/Client.h" #include "PreviewController.h" #include "PreviewView.h" @@ -73,7 +72,7 @@ void PreviewController::Update() } } -bool PreviewController::SubmitComment(std::string comment) +bool PreviewController::SubmitComment(String comment) { if(comment.length() < 4) { @@ -123,7 +122,7 @@ void PreviewController::DoOpen() previewModel->SetDoOpen(true); } -void PreviewController::Report(std::string message) +void PreviewController::Report(String message) { if(Client::Ref().ReportSave(saveId, message) == RequestOkay) { @@ -147,14 +146,14 @@ void PreviewController::FavouriteSave() } catch (PreviewModelException & e) { - new ErrorMessage("Error", e.what()); + new ErrorMessage("Error", ByteString(e.what()).FromUtf8()); } } } void PreviewController::OpenInBrowser() { - std::stringstream uriStream; + ByteString::Stream uriStream; uriStream << "http://" << SERVER << "/Browse/View.html?ID=" << saveId; Platform::OpenURI(uriStream.str()); } diff --git a/src/gui/preview/PreviewController.h b/src/gui/preview/PreviewController.h index 8e148cb1f..2b64157e4 100644 --- a/src/gui/preview/PreviewController.h +++ b/src/gui/preview/PreviewController.h @@ -27,14 +27,14 @@ public: void Exit(); void DoOpen(); void OpenInBrowser(); - void Report(std::string message); + void Report(String message); void ShowLogin(); bool GetDoOpen(); SaveInfo * GetSaveInfo(); PreviewView * GetView() { return previewView; } void Update(); void FavouriteSave(); - bool SubmitComment(std::string comment); + bool SubmitComment(String comment); bool NextCommentPage(); bool PrevCommentPage(); diff --git a/src/gui/preview/PreviewModel.cpp b/src/gui/preview/PreviewModel.cpp index 888dace14..5cc503e15 100644 --- a/src/gui/preview/PreviewModel.cpp +++ b/src/gui/preview/PreviewModel.cpp @@ -70,7 +70,7 @@ void PreviewModel::UpdateSave(int saveID, int saveDate) notifySaveChanged(); notifySaveCommentsChanged(); - std::stringstream urlStream; + ByteString::Stream urlStream; if (saveDate) urlStream << "http://" << STATICSERVER << "/" << saveID << "_" << saveDate << ".cps"; else @@ -83,7 +83,7 @@ void PreviewModel::UpdateSave(int saveID, int saveDate) if (saveDate) urlStream << "&Date=" << saveDate; saveInfoDownload = new Download(urlStream.str()); - saveInfoDownload->AuthHeaders(format::NumberToString(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID); + saveInfoDownload->AuthHeaders(format::NumberToByteString(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID); saveInfoDownload->Start(); if (!GetDoOpen()) @@ -93,7 +93,7 @@ void PreviewModel::UpdateSave(int saveID, int saveDate) urlStream.str(""); urlStream << "http://" << SERVER << "/Browse/Comments.json?ID=" << saveID << "&Start=" << (commentsPageNumber-1)*20 << "&Count=20"; commentsDownload = new Download(urlStream.str()); - commentsDownload->AuthHeaders(format::NumberToString(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID); + commentsDownload->AuthHeaders(format::NumberToByteString(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID); commentsDownload->Start(); } } @@ -143,10 +143,10 @@ void PreviewModel::UpdateComments(int pageNumber) commentsPageNumber = pageNumber; if (!GetDoOpen()) { - std::stringstream urlStream; + ByteString::Stream urlStream; urlStream << "http://" << SERVER << "/Browse/Comments.json?ID=" << saveID << "&Start=" << (commentsPageNumber-1)*20 << "&Count=20"; commentsDownload = new Download(urlStream.str()); - commentsDownload->AuthHeaders(format::NumberToString(Client::Ref().GetAuthUser().UserID).c_str(), Client::Ref().GetAuthUser().SessionID.c_str()); + commentsDownload->AuthHeaders(format::NumberToByteString(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID); commentsDownload->Start(); } @@ -174,7 +174,7 @@ void PreviewModel::OnSaveReady() } catch(ParseException &e) { - new ErrorMessage("Error", e.what()); + new ErrorMessage("Error", ByteString(e.what()).FromUtf8()); canOpen = false; } notifySaveChanged(); @@ -210,9 +210,9 @@ bool PreviewModel::ParseSaveInfo(char * saveInfoResponse) int tempScoreUp = objDocument["ScoreUp"].asInt(); int tempScoreDown = objDocument["ScoreDown"].asInt(); int tempMyScore = objDocument["ScoreMine"].asInt(); - std::string tempUsername = objDocument["Username"].asString(); - std::string tempName = objDocument["Name"].asString(); - std::string tempDescription = objDocument["Description"].asString(); + ByteString tempUsername = objDocument["Username"].asString(); + String tempName = ByteString(objDocument["Name"].asString()).FromUtf8(); + String tempDescription = ByteString(objDocument["Description"].asString()).FromUtf8(); int tempCreatedDate = objDocument["DateCreated"].asInt(); int tempUpdatedDate = objDocument["Date"].asInt(); bool tempPublished = objDocument["Published"].asBool(); @@ -222,7 +222,7 @@ bool PreviewModel::ParseSaveInfo(char * saveInfoResponse) int tempVersion = objDocument["Version"].asInt(); Json::Value tagsArray = objDocument["Tags"]; - std::list tempTags; + std::list tempTags; for (Json::UInt j = 0; j < tagsArray.size(); j++) tempTags.push_back(tagsArray[j].asString()); @@ -242,7 +242,7 @@ bool PreviewModel::ParseSaveInfo(char * saveInfoResponse) saveDataDownload->Cancel(); delete saveData; saveData = NULL; - std::stringstream urlStream; + ByteString::Stream urlStream; urlStream << "http://" << STATICSERVER << "/2157797.cps"; saveDataDownload = new Download(urlStream.str()); saveDataDownload->Start(); @@ -268,12 +268,12 @@ bool PreviewModel::ParseComments(char *commentsResponse) for (Json::UInt j = 0; j < commentsArray.size(); j++) { - int userID = format::StringToNumber(commentsArray[j]["UserID"].asString()); - std::string username = commentsArray[j]["Username"].asString(); - std::string formattedUsername = commentsArray[j]["FormattedUsername"].asString(); + int userID = format::ByteStringToNumber(commentsArray[j]["UserID"].asString()); + ByteString username = commentsArray[j]["Username"].asString(); + ByteString formattedUsername = commentsArray[j]["FormattedUsername"].asString(); if (formattedUsername == "jacobot") formattedUsername = "\bt" + formattedUsername; - std::string comment = commentsArray[j]["Text"].asString(); + String comment = ByteString(commentsArray[j]["Text"].asString()).FromUtf8(); saveComments->push_back(new SaveComment(userID, username, formattedUsername, comment)); } return true; diff --git a/src/gui/preview/PreviewModelException.h b/src/gui/preview/PreviewModelException.h index 85dce1d18..c84894a26 100644 --- a/src/gui/preview/PreviewModelException.h +++ b/src/gui/preview/PreviewModelException.h @@ -1,17 +1,17 @@ #ifndef PREVIEWMODELEXCEPTION_H_ #define PREVIEWMODELEXCEPTION_H_ -#include +#include "common/String.h" #include using namespace std; struct PreviewModelException: public exception { - string message; + String message; public: - PreviewModelException(string message_): message(message_) {} + PreviewModelException(String message_): message(message_) {} const char * what() const throw() { - return message.c_str(); + return message.ToUtf8().c_str(); } ~PreviewModelException() throw() {}; }; diff --git a/src/gui/preview/PreviewView.cpp b/src/gui/preview/PreviewView.cpp index 425e729b5..e58b27e92 100644 --- a/src/gui/preview/PreviewView.cpp +++ b/src/gui/preview/PreviewView.cpp @@ -1,4 +1,3 @@ -#include #include #include #include @@ -105,7 +104,7 @@ PreviewView::PreviewView(): public: PreviewView * v; ReportPromptCallback(PreviewView * v_) { v = v_; } - virtual void TextCallback(TextPrompt::DialogueResult result, std::string resultText) { + virtual void TextCallback(TextPrompt::DialogueResult result, String resultText) { if (result == TextPrompt::ResultOkay) v->c->Report(resultText); } @@ -278,9 +277,9 @@ void PreviewView::commentBoxAutoHeight() } } -bool PreviewView::CheckSwearing(std::string text) +bool PreviewView::CheckSwearing(String text) { - for (std::set::iterator iter = swearWords.begin(), end = swearWords.end(); iter != end; iter++) + for (std::set::iterator iter = swearWords.begin(), end = swearWords.end(); iter != end; iter++) { if (text.find(*iter) != text.npos) return true; @@ -292,9 +291,9 @@ void PreviewView::CheckComment() { if (!commentWarningLabel) return; - std::string text = addCommentBox->GetText(); + String text = addCommentBox->GetText(); std::transform(text.begin(), text.end(), text.begin(), ::tolower); - if (!userIsAuthor && (text.find("stolen") != text.npos || text.find("copied") != text.npos)) + if (!userIsAuthor && (text.find("stolen") != String::npos || text.find("copied") != String::npos)) { if (!commentHelpText) { @@ -499,7 +498,7 @@ void PreviewView::NotifySaveChanged(PreviewModel * sender) votesUp = save->votesUp; votesDown = save->votesDown; saveNameLabel->SetText(save->name); - std::string dateType; + String dateType; if (save->updatedDate == save->createdDate) dateType = "Created:"; else @@ -507,11 +506,11 @@ void PreviewView::NotifySaveChanged(PreviewModel * sender) if (showAvatars) { avatarButton->SetUsername(save->userName); - authorDateLabel->SetText("\bw" + save->userName + " \bg" + dateType + " \bw" + format::UnixtimeToDateMini(save->updatedDate)); + authorDateLabel->SetText("\bw" + save->userName.FromUtf8() + " \bg" + dateType + " \bw" + format::UnixtimeToDateMini(save->updatedDate).FromAscii()); } else { - authorDateLabel->SetText("\bgAuthor:\bw " + save->userName + " \bg" + dateType + " \bw" + format::UnixtimeToDateMini(save->updatedDate)); + authorDateLabel->SetText("\bgAuthor:\bw " + save->userName.FromUtf8() + " \bg" + dateType + " \bw" + format::UnixtimeToDateMini(save->updatedDate).FromAscii()); } if (Client::Ref().GetAuthUser().UserID && save->userName == Client::Ref().GetAuthUser().Username) userIsAuthor = true; @@ -571,7 +570,7 @@ void PreviewView::submitComment() { if(addCommentBox) { - std::string comment = std::string(addCommentBox->GetText()); + String comment = addCommentBox->GetText(); submitCommentButton->Enabled = false; addCommentBox->SetText(""); addCommentBox->SetPlaceholder("Submitting comment"); //This doesn't appear to ever show since no separate thread is created @@ -632,7 +631,7 @@ void PreviewView::NotifyCommentBoxEnabledChanged(PreviewModel * sender) } } -void PreviewView::SaveLoadingError(std::string errorMessage) +void PreviewView::SaveLoadingError(String errorMessage) { doError = true; doErrorMessage = errorMessage; @@ -640,7 +639,7 @@ void PreviewView::SaveLoadingError(std::string errorMessage) void PreviewView::NotifyCommentsPageChanged(PreviewModel * sender) { - std::stringstream pageInfoStream; + String::Stream pageInfoStream; pageInfoStream << "Page " << sender->GetCommentsPageNum() << " of " << sender->GetCommentsPageCount(); pageInfo->SetText(pageInfoStream.str()); } @@ -683,9 +682,9 @@ void PreviewView::NotifyCommentsChanged(PreviewModel * sender) } if (showAvatars) - tempUsername = new ui::Label(ui::Point(31, currentY+3), ui::Point(Size.X-((XRES/2) + 13 + 26), 16), comments->at(i)->authorNameFormatted); + tempUsername = new ui::Label(ui::Point(31, currentY+3), ui::Point(Size.X-((XRES/2) + 13 + 26), 16), comments->at(i)->authorNameFormatted.FromUtf8()); else - tempUsername = new ui::Label(ui::Point(5, currentY+3), ui::Point(Size.X-((XRES/2) + 13), 16), comments->at(i)->authorNameFormatted); + tempUsername = new ui::Label(ui::Point(5, currentY+3), ui::Point(Size.X-((XRES/2) + 13), 16), comments->at(i)->authorNameFormatted.FromUtf8()); tempUsername->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; tempUsername->Appearance.VerticalAlign = ui::Appearance::AlignBottom; if (Client::Ref().GetAuthUser().UserID && Client::Ref().GetAuthUser().Username == comments->at(i)->authorName) diff --git a/src/gui/preview/PreviewView.h b/src/gui/preview/PreviewView.h index 3581e86cc..fcf6fc1a7 100644 --- a/src/gui/preview/PreviewView.h +++ b/src/gui/preview/PreviewView.h @@ -3,7 +3,7 @@ #include #include -#include +#include "common/String.h" #include "Comment.h" #include "gui/interface/Window.h" #include "gui/preview/PreviewController.h" @@ -53,7 +53,7 @@ class PreviewView: public ui::Window { bool userIsAuthor; bool doOpen; bool doError; - std::string doErrorMessage; + String doErrorMessage; bool showAvatars; bool prevPage; @@ -64,12 +64,12 @@ class PreviewView: public ui::Window { float commentBoxSizeY; bool commentHelpText; - std::set swearWords; + std::set swearWords; void displayComments(); void commentBoxAutoHeight(); void submitComment(); - bool CheckSwearing(std::string text); + bool CheckSwearing(String text); void CheckComment(); public: void AttachController(PreviewController * controller); @@ -78,7 +78,7 @@ public: void NotifyCommentsChanged(PreviewModel * sender); void NotifyCommentsPageChanged(PreviewModel * sender); void NotifyCommentBoxEnabledChanged(PreviewModel * sender); - void SaveLoadingError(std::string errorMessage); + void SaveLoadingError(String errorMessage); virtual void OnDraw(); virtual void DoDraw(); virtual void OnTick(float dt); diff --git a/src/gui/profile/ProfileActivity.cpp b/src/gui/profile/ProfileActivity.cpp index 60327e246..e012e833a 100644 --- a/src/gui/profile/ProfileActivity.cpp +++ b/src/gui/profile/ProfileActivity.cpp @@ -14,7 +14,7 @@ #include "Format.h" #include "Platform.h" -ProfileActivity::ProfileActivity(std::string username) : +ProfileActivity::ProfileActivity(ByteString username) : WindowActivity(ui::Point(-1, -1), ui::Point(236, 300)), loading(false), saving(false), @@ -98,7 +98,7 @@ void ProfileActivity::setUserInfo(UserInfo newInfo) int currentY = 5; // username label - ui::Label * title = new ui::Label(ui::Point(4, currentY), ui::Point(Size.X-8-(40+8+75), 15), info.username); + ui::Label * title = new ui::Label(ui::Point(4, currentY), ui::Point(Size.X-8-(40+8+75), 15), info.username.FromUtf8()); title->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; scrollPanel->AddChild(title); @@ -147,7 +147,7 @@ void ProfileActivity::setUserInfo(UserInfo newInfo) websiteTitle->SetTextColour(ui::Colour(180, 180, 180)); scrollPanel->AddChild(websiteTitle); - ui::Label *website = new ui::Label(ui::Point(8+websiteTitle->Size.X, currentY), ui::Point(Size.X-websiteTitle->Size.X-16, 15), info.website); + ui::Label *website = new ui::Label(ui::Point(8+websiteTitle->Size.X, currentY), ui::Point(Size.X-websiteTitle->Size.X-16, 15), info.website.FromUtf8()); website->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; scrollPanel->AddChild(website); currentY += 2+website->Size.Y; diff --git a/src/gui/profile/ProfileActivity.h b/src/gui/profile/ProfileActivity.h index 48e766324..8e9c72c14 100644 --- a/src/gui/profile/ProfileActivity.h +++ b/src/gui/profile/ProfileActivity.h @@ -1,7 +1,7 @@ #ifndef PROFILEACTIVITY_H_ #define PROFILEACTIVITY_H_ -#include +#include "common/String.h" #include "Activity.h" #include "client/requestbroker/RequestListener.h" #include "client/UserInfo.h" @@ -21,10 +21,10 @@ class ProfileActivity: public WindowActivity, public RequestListener { bool loading; bool saving; bool doError; - std::string doErrorMessage; + String doErrorMessage; void setUserInfo(UserInfo newInfo); public: - ProfileActivity(std::string username); + ProfileActivity(ByteString username); virtual ~ProfileActivity(); virtual void OnResponseReady(void * userDataPtr, int identifier); virtual void OnResponseFailed(int identifier); diff --git a/src/gui/render/RenderView.cpp b/src/gui/render/RenderView.cpp index 8165837c9..fd486b2d2 100644 --- a/src/gui/render/RenderView.cpp +++ b/src/gui/render/RenderView.cpp @@ -381,7 +381,7 @@ void RenderView::OnDraw() g->draw_line(XRES, 0, XRES, WINDOWH, 255, 255, 255, 255); if(toolTipPresence && toolTip.length()) { - g->drawtext(6, Size.Y-MENUSIZE-12, (char*)toolTip.c_str(), 255, 255, 255, toolTipPresence>51?255:toolTipPresence*5); + g->drawtext(6, Size.Y-MENUSIZE-12, toolTip, 255, 255, 255, toolTipPresence>51?255:toolTipPresence*5); } } @@ -415,7 +415,7 @@ void RenderView::OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bo } } -void RenderView::ToolTip(ui::Point senderPosition, std::string toolTip) +void RenderView::ToolTip(ui::Point senderPosition, String toolTip) { this->toolTip = toolTip; this->isToolTipFadingIn = true; diff --git a/src/gui/render/RenderView.h b/src/gui/render/RenderView.h index 83f5207e5..8220b91b8 100644 --- a/src/gui/render/RenderView.h +++ b/src/gui/render/RenderView.h @@ -18,7 +18,7 @@ class RenderView: public ui::Window { std::vector renderModes; std::vector displayModes; std::vector colourModes; - std::string toolTip; + String toolTip; int toolTipPresence; bool isToolTipFadingIn; int line1, line2, line3, line4; @@ -38,7 +38,7 @@ public: virtual void OnDraw(); virtual void OnTick(float dt); virtual void OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool alt); - virtual void ToolTip(ui::Point senderPosition, std::string toolTip); + virtual void ToolTip(ui::Point senderPosition, String toolTip); virtual ~RenderView(); }; diff --git a/src/gui/save/LocalSaveActivity.cpp b/src/gui/save/LocalSaveActivity.cpp index 61cdff6d6..09b17011d 100644 --- a/src/gui/save/LocalSaveActivity.cpp +++ b/src/gui/save/LocalSaveActivity.cpp @@ -76,8 +76,8 @@ void LocalSaveActivity::Save() class FileOverwriteConfirmation: public ConfirmDialogueCallback { public: LocalSaveActivity * a; - std::string filename; - FileOverwriteConfirmation(LocalSaveActivity * a, std::string finalFilename) : a(a), filename(finalFilename) {} + ByteString filename; + FileOverwriteConfirmation(LocalSaveActivity * a, ByteString finalFilename) : a(a), filename(finalFilename) {} virtual void ConfirmCallback(ConfirmPrompt::DialogueResult result) { if (result == ConfirmPrompt::ResultOkay) { @@ -89,12 +89,12 @@ void LocalSaveActivity::Save() if(filenameField->GetText().length()) { - std::string finalFilename = std::string(LOCAL_SAVE_DIR) + std::string(PATH_SEP) + filenameField->GetText() + ".cps"; + ByteString finalFilename = ByteString(LOCAL_SAVE_DIR) + ByteString(PATH_SEP) + filenameField->GetText().ToUtf8() + ".cps"; save.SetDisplayName(filenameField->GetText()); save.SetFileName(finalFilename); if(Client::Ref().FileExists(finalFilename)) { - new ConfirmPrompt("Overwrite file", "Are you sure you wish to overwrite\n"+finalFilename, new FileOverwriteConfirmation(this, finalFilename)); + new ConfirmPrompt("Overwrite file", "Are you sure you wish to overwrite\n"+finalFilename.FromUtf8(), new FileOverwriteConfirmation(this, finalFilename)); } else { @@ -107,7 +107,7 @@ void LocalSaveActivity::Save() } } -void LocalSaveActivity::saveWrite(std::string finalFilename) +void LocalSaveActivity::saveWrite(ByteString finalFilename) { Client::Ref().MakeDirectory(LOCAL_SAVE_DIR); GameSave *gameSave = save.GetGameSave(); diff --git a/src/gui/save/LocalSaveActivity.h b/src/gui/save/LocalSaveActivity.h index 47d3938d1..00801bbae 100644 --- a/src/gui/save/LocalSaveActivity.h +++ b/src/gui/save/LocalSaveActivity.h @@ -31,7 +31,7 @@ class LocalSaveActivity: public WindowActivity, public RequestListener FileSavedCallback * callback; public: LocalSaveActivity(SaveFile save, FileSavedCallback * callback); - void saveWrite(std::string finalFilename); + void saveWrite(ByteString finalFilename); virtual void Save(); virtual void OnDraw(); virtual void OnResponseReady(void * imagePtr, int identifier); diff --git a/src/gui/save/ServerSaveActivity.cpp b/src/gui/save/ServerSaveActivity.cpp index d39d2734e..ac8bb1aba 100644 --- a/src/gui/save/ServerSaveActivity.cpp +++ b/src/gui/save/ServerSaveActivity.cpp @@ -244,7 +244,7 @@ void ServerSaveActivity::Save() { if(Client::Ref().GetAuthUser().Username != save.GetUserName() && publishedCheckbox->GetChecked()) { - new ConfirmPrompt("Publish", "This save was created by " + save.GetUserName() + ", you're about to publish this under your own name; If you haven't been given permission by the author to do so, please uncheck the publish box, otherwise continue", new PublishConfirmation(this)); + new ConfirmPrompt("Publish", "This save was created by " + save.GetUserName().FromUtf8() + ", you're about to publish this under your own name; If you haven't been given permission by the author to do so, please uncheck the publish box, otherwise continue", new PublishConfirmation(this)); } else { @@ -264,8 +264,8 @@ void ServerSaveActivity::AddAuthorInfo() serverSaveInfo["type"] = "save"; serverSaveInfo["id"] = save.GetID(); serverSaveInfo["username"] = Client::Ref().GetAuthUser().Username; - serverSaveInfo["title"] = save.GetName(); - serverSaveInfo["description"] = save.GetDescription(); + serverSaveInfo["title"] = save.GetName().ToUtf8(); + serverSaveInfo["description"] = save.GetDescription().ToUtf8(); serverSaveInfo["published"] = (int)save.GetPublished(); serverSaveInfo["date"] = (Json::Value::UInt64)time(NULL); Client::Ref().SaveAuthorInfo(&serverSaveInfo); @@ -300,7 +300,7 @@ void ServerSaveActivity::Exit() void ServerSaveActivity::ShowPublishingInfo() { - const char *info = + String info = "In The Powder Toy, one can save simulations to their account in two privacy levels: Published and unpublished. You can choose which one by checking or unchecking the 'publish' checkbox. Saves are unpublished by default, so if you do not check publish nobody will be able to see your saves.\n" "\n" "\btPublished saves\bw will appear on the 'By Date' feed and will be seen by many people. These saves also contribute to your Average Score, which is displayed publicly on your profile page on the website. Publish saves that you want people to see so they can comment and vote on.\n" @@ -317,7 +317,7 @@ void ServerSaveActivity::ShowPublishingInfo() void ServerSaveActivity::ShowRules() { - const char *rules = + String rules = "These are the rules you should follow when uploading saves to avoid having them deleted or otherwise hidden from public view. If you fail to follow them, don't be surprised if your saves get lousy votes, unpublished, or removed from the front page should they make it there. These rules may change at any time as new problems arise, and how each rule is handled changes depending on the situation.\n" "\n" "\bt1. No image plotting.\bw If you use a program to draw out pixels from an image outside of TPT without drawing it by hand, don't be surprised when the save gets deleted and you get banned.\n" @@ -343,7 +343,7 @@ void ServerSaveActivity::ShowRules() new InformationMessage("Save Uploading Rules", rules, true); } -void ServerSaveActivity::CheckName(std::string newname) +void ServerSaveActivity::CheckName(String newname) { if (newname.length() && newname == save.GetName() && save.GetUserName() == Client::Ref().GetAuthUser().Username) titleLabel->SetText("Modify simulation properties:"); diff --git a/src/gui/save/ServerSaveActivity.h b/src/gui/save/ServerSaveActivity.h index 6ce8ed4a9..bd0ca1300 100644 --- a/src/gui/save/ServerSaveActivity.h +++ b/src/gui/save/ServerSaveActivity.h @@ -32,7 +32,7 @@ public: virtual void Exit(); virtual void ShowPublishingInfo(); virtual void ShowRules(); - virtual void CheckName(std::string newname); + virtual void CheckName(String newname); virtual void OnDraw(); virtual void OnResponseReady(void * imagePtr, int identifier); virtual void OnTick(float dt); diff --git a/src/gui/search/SearchController.cpp b/src/gui/search/SearchController.cpp index 56282dc7c..196a6d0c9 100644 --- a/src/gui/search/SearchController.cpp +++ b/src/gui/search/SearchController.cpp @@ -1,5 +1,4 @@ -#include -#include +#include "common/String.h" #include "SearchController.h" #include "SearchModel.h" #include "SearchView.h" @@ -104,7 +103,7 @@ SearchController::~SearchController() delete callback; } -void SearchController::DoSearch(std::string query, bool now) +void SearchController::DoSearch(String query, bool now) { nextQuery = query; if (!now) @@ -118,7 +117,7 @@ void SearchController::DoSearch(std::string query, bool now) } } -void SearchController::DoSearch2(std::string query) +void SearchController::DoSearch2(String query) { // calls SearchView function to set textbox text, then calls DoSearch searchView->Search(query); @@ -236,7 +235,7 @@ void SearchController::RemoveSelected() virtual ~RemoveSelectedConfirmation() { } }; - std::stringstream desc; + String::Stream desc; desc << "Are you sure you want to delete " << searchModel->GetSelected().size() << " save"; if(searchModel->GetSelected().size()>1) desc << "s"; @@ -256,12 +255,12 @@ void SearchController::removeSelectedC() { for (size_t i = 0; i < saves.size(); i++) { - std::stringstream saveID; + String::Stream saveID; saveID << "Deleting save [" << saves[i] << "] ..."; notifyStatus(saveID.str()); if (Client::Ref().DeleteSave(saves[i])!=RequestOkay) { - std::stringstream saveIDF; + String::Stream saveIDF; saveIDF << "Failed to delete [" << saves[i] << "]: " << Client::Ref().GetLastError(); notifyError(saveIDF.str()); c->Refresh(); @@ -294,12 +293,12 @@ void SearchController::UnpublishSelected(bool publish) virtual ~UnpublishSelectedConfirmation() { } }; - std::stringstream desc; + String::Stream desc; desc << "Are you sure you want to " << (publish ? "publish " : "unpublish ") << searchModel->GetSelected().size() << " save"; if (searchModel->GetSelected().size() > 1) desc << "s"; desc << "?"; - new ConfirmPrompt((publish ? "Publish Saves" : "Unpublish Saves"), desc.str(), new UnpublishSelectedConfirmation(this, publish)); + new ConfirmPrompt(publish ? String("Publish Saves") : String("Unpublish Saves"), desc.str(), new UnpublishSelectedConfirmation(this, publish)); } void SearchController::unpublishSelectedC(bool publish) @@ -314,7 +313,7 @@ void SearchController::unpublishSelectedC(bool publish) bool PublishSave(int saveID) { - std::stringstream message; + String::Stream message; message << "Publishing save [" << saveID << "]"; notifyStatus(message.str()); if (Client::Ref().PublishSave(saveID) != RequestOkay) @@ -324,7 +323,7 @@ void SearchController::unpublishSelectedC(bool publish) bool UnpublishSave(int saveID) { - std::stringstream message; + String::Stream message; message << "Unpublishing save [" << saveID << "]"; notifyStatus(message.str()); if (Client::Ref().UnpublishSave(saveID) != RequestOkay) @@ -343,7 +342,7 @@ void SearchController::unpublishSelectedC(bool publish) ret = UnpublishSave(saves[i]); if (!ret) { - std::stringstream error; + String::Stream error; if (publish) // uses html page so error message will be spam error << "Failed to publish [" << saves[i] << "], is this save yours?"; else @@ -360,7 +359,7 @@ void SearchController::unpublishSelectedC(bool publish) }; std::vector selected = searchModel->GetSelected(); - new TaskWindow((publish ? "Publishing Saves" : "Unpublishing Saves"), new UnpublishSavesTask(selected, this, publish)); + new TaskWindow(publish ? String("Publishing Saves") : String("Unpublishing Saves"), new UnpublishSavesTask(selected, this, publish)); } void SearchController::FavouriteSelected() @@ -374,12 +373,12 @@ void SearchController::FavouriteSelected() { for (size_t i = 0; i < saves.size(); i++) { - std::stringstream saveID; + String::Stream saveID; saveID << "Favouring save [" << saves[i] << "]"; notifyStatus(saveID.str()); if (Client::Ref().FavouriteSave(saves[i], true)!=RequestOkay) { - std::stringstream saveIDF; + String::Stream saveIDF; saveIDF << "Failed to favourite [" << saves[i] << "]: " + Client::Ref().GetLastError(); notifyError(saveIDF.str()); return false; @@ -399,12 +398,12 @@ void SearchController::FavouriteSelected() { for (size_t i = 0; i < saves.size(); i++) { - std::stringstream saveID; + String::Stream saveID; saveID << "Unfavouring save [" << saves[i] << "]"; notifyStatus(saveID.str()); if (Client::Ref().FavouriteSave(saves[i], false)!=RequestOkay) { - std::stringstream saveIDF; + String::Stream saveIDF; saveIDF << "Failed to unfavourite [" << saves[i] << "]: " + Client::Ref().GetLastError(); notifyError(saveIDF.str()); return false; diff --git a/src/gui/search/SearchController.h b/src/gui/search/SearchController.h index 094100e70..a52236920 100644 --- a/src/gui/search/SearchController.h +++ b/src/gui/search/SearchController.h @@ -19,7 +19,7 @@ private: ControllerCallback * callback; double nextQueryTime; - std::string nextQuery; + String nextQuery; bool nextQueryDone; bool instantOpen; bool doRefresh; @@ -32,8 +32,8 @@ public: ~SearchController(); SearchView * GetView() { return searchView; } void Exit(); - void DoSearch(std::string query, bool now = false); - void DoSearch2(std::string query); + void DoSearch(String query, bool now = false); + void DoSearch2(String query); void Refresh(); void NextPage(); void PrevPage(); diff --git a/src/gui/search/SearchModel.cpp b/src/gui/search/SearchModel.cpp index 620257e93..436112e3f 100644 --- a/src/gui/search/SearchModel.cpp +++ b/src/gui/search/SearchModel.cpp @@ -36,7 +36,7 @@ TH_ENTRY_POINT void * SearchModel::updateSaveListTHelper(void * obj) void * SearchModel::updateSaveListT() { - std::string category = ""; + ByteString category = ""; if(showFavourite) category = "Favourites"; if(showOwn && Client::Ref().GetAuthUser().UserID) @@ -55,13 +55,13 @@ TH_ENTRY_POINT void * SearchModel::updateTagListTHelper(void * obj) void * SearchModel::updateTagListT() { int tagResultCount; - std::vector > * tagList = Client::Ref().GetTags(0, 24, "", tagResultCount); + std::vector > * tagList = Client::Ref().GetTags(0, 24, "", tagResultCount); updateTagListFinished = true; return tagList; } -bool SearchModel::UpdateSaveList(int pageNumber, std::string query) +bool SearchModel::UpdateSaveList(int pageNumber, String query) { //Threading if (!updateSaveListWorking) @@ -122,7 +122,7 @@ vector SearchModel::GetSaveList() return saveList; } -vector > SearchModel::GetTagList() +vector > SearchModel::GetTagList() { return tagList; } @@ -164,7 +164,7 @@ void SearchModel::Update() { updateTagListWorking = false; - vector > * tempTagList; + vector > * tempTagList; pthread_join(updateTagListThread, (void**)&tempTagList); if(tempTagList) diff --git a/src/gui/search/SearchModel.h b/src/gui/search/SearchModel.h index 52dc6b0da..c1ed5673e 100644 --- a/src/gui/search/SearchModel.h +++ b/src/gui/search/SearchModel.h @@ -2,7 +2,7 @@ #define SEARCHMODEL_H #include -#include +#include "common/String.h" #include "common/tpt-minmax.h" #include "common/tpt-thread.h" #include @@ -16,13 +16,13 @@ class SearchModel { private: SaveInfo * loadedSave; - string currentSort; - string lastQuery; - string lastError; + ByteString currentSort; + String lastQuery; + String lastError; vector selected; vector observers; vector saveList; - vector > tagList; + vector > tagList; int currentPage; int resultCount; int thResultCount; @@ -57,10 +57,10 @@ public: void SetShowTags(bool show); bool GetShowTags(); void AddObserver(SearchView * observer); - bool UpdateSaveList(int pageNumber, std::string query); + bool UpdateSaveList(int pageNumber, String query); vector GetSaveList(); - vector > GetTagList(); - string GetLastError() { return lastError; } + vector > GetTagList(); + String GetLastError() { return lastError; } int GetPageCount() { if (!showOwn && !showFavourite && currentSort == "best" && lastQuery == "") @@ -69,9 +69,9 @@ public: return std::max(1, (int)(ceil(resultCount/20.0f))); } int GetPageNum() { return currentPage; } - std::string GetLastQuery() { return lastQuery; } - void SetSort(string sort) { if(!updateSaveListWorking) { currentSort = sort; } notifySortChanged(); } - string GetSort() { return currentSort; } + String GetLastQuery() { return lastQuery; } + void SetSort(ByteString sort) { if(!updateSaveListWorking) { currentSort = sort; } notifySortChanged(); } + ByteString GetSort() { return currentSort; } void SetShowOwn(bool show) { if(!updateSaveListWorking) { if(show!=showOwn) { showOwn = show; } } notifyShowOwnChanged(); } bool GetShowOwn() { return showOwn; } void SetShowFavourite(bool show) { if(show!=showFavourite && !updateSaveListWorking) { showFavourite = show; } notifyShowFavouriteChanged(); } diff --git a/src/gui/search/SearchView.cpp b/src/gui/search/SearchView.cpp index efebe51f2..f6e4dd0a4 100644 --- a/src/gui/search/SearchView.cpp +++ b/src/gui/search/SearchView.cpp @@ -1,5 +1,3 @@ -#include - #include "SearchView.h" #include "client/Client.h" #include "gui/interface/Keys.h" @@ -310,7 +308,7 @@ SearchView::~SearchView() saveButtons.clear(); } -void SearchView::Search(std::string query) +void SearchView::Search(String query) { searchField->SetText(query); c->DoSearch(query, true); @@ -376,7 +374,7 @@ void SearchView::NotifyPageChanged(SearchModel * sender) } else { - std::stringstream pageInfo; + String::Stream pageInfo; pageInfo << "of " << pageCount; pageCountLabel->SetText(pageInfo.str()); int width = Graphics::textwidth(pageInfo.str().c_str()); @@ -387,7 +385,7 @@ void SearchView::NotifyPageChanged(SearchModel * sender) //pageCountLabel->Position.X = WINDOWW/2+6; pageLabel->Visible = pageCountLabel->Visible = pageTextbox->Visible = true; - pageInfo.str(""); + pageInfo.str(String()); pageInfo << sender->GetPageNum(); pageTextbox->SetText(pageInfo.str()); } @@ -469,7 +467,7 @@ void SearchView::NotifyTagListChanged(SearchModel * sender) int tagWidth = 0, tagHeight = 0, tagX = 0, tagY = 0, tagsX = 6, tagsY = 4, tagPadding = 1; int tagAreaWidth, tagAreaHeight, tagXOffset = 0, tagYOffset = 0; - vector > tags = sender->GetTagList(); + vector > tags = sender->GetTagList(); RemoveComponent(motdLabel); motdLabel->SetParentWindow(NULL); @@ -510,12 +508,12 @@ void SearchView::NotifyTagListChanged(SearchModel * sender) class TagAction: public ui::ButtonAction { SearchView * v; - std::string tag; + ByteString tag; public: - TagAction(SearchView * v, std::string tag) : v(v), tag(tag) {} + TagAction(SearchView * v, ByteString tag) : v(v), tag(tag) {} virtual void ActionCallback(ui::Button * sender) { - v->Search(tag); + v->Search(tag.FromUtf8()); } }; if (sender->GetShowTags()) @@ -524,7 +522,7 @@ void SearchView::NotifyTagListChanged(SearchModel * sender) { int maxTagVotes = tags[0].second; - pair tag = tags[i]; + pair tag = tags[i]; if (tagX == tagsX) { @@ -545,7 +543,7 @@ void SearchView::NotifyTagListChanged(SearchModel * sender) tagYOffset + tagPadding + tagY*(tagHeight+tagPadding*2) ), ui::Point(tagWidth, tagHeight), - tag.first + tag.first.FromUtf8() ); tagButton->SetActionCallback(new TagAction(this, tag.first)); tagButton->Appearance.BorderInactive = ui::Colour(0, 0, 0); @@ -673,13 +671,13 @@ void SearchView::NotifySaveListChanged(SearchModel * sender) } virtual void AltActionCallback(ui::SaveButton * sender) { - stringstream search; + String::Stream search; search << "history:" << sender->GetSave()->GetID(); v->Search(search.str()); } virtual void AltActionCallback2(ui::SaveButton * sender) { - v->Search("user:"+sender->GetSave()->GetUserName()); + v->Search("user:"+sender->GetSave()->GetUserName().FromUtf8()); } }; for (size_t i = 0; i < saves.size(); i++) diff --git a/src/gui/search/SearchView.h b/src/gui/search/SearchView.h index 8c32aebb6..93f7a94ff 100644 --- a/src/gui/search/SearchView.h +++ b/src/gui/search/SearchView.h @@ -66,7 +66,7 @@ public: SearchView(); virtual ~SearchView(); void AttachController(SearchController * _c) { c = _c; } - virtual void Search(std::string); + virtual void Search(String); virtual void OnTick(float dt); virtual void OnMouseWheel(int x, int y, int d); virtual void OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool alt); diff --git a/src/gui/tags/TagsController.cpp b/src/gui/tags/TagsController.cpp index 49715aaae..da9cce04f 100644 --- a/src/gui/tags/TagsController.cpp +++ b/src/gui/tags/TagsController.cpp @@ -22,13 +22,13 @@ SaveInfo * TagsController::GetSave() return tagsModel->GetSave(); } -void TagsController::RemoveTag(std::string tag) +void TagsController::RemoveTag(ByteString tag) { tagsModel->RemoveTag(tag); } -void TagsController::AddTag(std::string tag) +void TagsController::AddTag(ByteString tag) { tagsModel->AddTag(tag); } diff --git a/src/gui/tags/TagsController.h b/src/gui/tags/TagsController.h index 8a510983f..788b1532c 100644 --- a/src/gui/tags/TagsController.h +++ b/src/gui/tags/TagsController.h @@ -16,8 +16,8 @@ public: TagsController(ControllerCallback * callback, SaveInfo * save); TagsView * GetView() {return tagsView;} SaveInfo * GetSave(); - void RemoveTag(std::string tag); - void AddTag(std::string tag); + void RemoveTag(ByteString tag); + void AddTag(ByteString tag); void Exit(); virtual ~TagsController(); }; diff --git a/src/gui/tags/TagsModel.cpp b/src/gui/tags/TagsModel.cpp index 8588afb43..2ccbaa531 100644 --- a/src/gui/tags/TagsModel.cpp +++ b/src/gui/tags/TagsModel.cpp @@ -21,14 +21,14 @@ SaveInfo * TagsModel::GetSave() return save; } -void TagsModel::RemoveTag(std::string tag) +void TagsModel::RemoveTag(ByteString tag) { if(save) { - std::list * tags = Client::Ref().RemoveTag(save->GetID(), tag); + std::list * tags = Client::Ref().RemoveTag(save->GetID(), tag); if(tags) { - save->SetTags(std::list(*tags)); + save->SetTags(std::list(*tags)); notifyTagsChanged(); delete tags; } @@ -39,14 +39,14 @@ void TagsModel::RemoveTag(std::string tag) } } -void TagsModel::AddTag(std::string tag) +void TagsModel::AddTag(ByteString tag) { if(save) { - std::list * tags = Client::Ref().AddTag(save->GetID(), tag); + std::list * tags = Client::Ref().AddTag(save->GetID(), tag); if(tags) { - save->SetTags(std::list(*tags)); + save->SetTags(std::list(*tags)); notifyTagsChanged(); delete tags; } diff --git a/src/gui/tags/TagsModel.h b/src/gui/tags/TagsModel.h index 8afe84106..9e66a0757 100644 --- a/src/gui/tags/TagsModel.h +++ b/src/gui/tags/TagsModel.h @@ -2,7 +2,7 @@ #define TAGSMODEL_H_ #include -#include +#include "common/String.h" class SaveInfo; @@ -15,8 +15,8 @@ public: TagsModel(); void AddObserver(TagsView * observer); void SetSave(SaveInfo * save); - void RemoveTag(std::string tag); - void AddTag(std::string tag); + void RemoveTag(ByteString tag); + void AddTag(ByteString tag); SaveInfo * GetSave(); virtual ~TagsModel(); }; diff --git a/src/gui/tags/TagsModelException.h b/src/gui/tags/TagsModelException.h index 671bf3b30..350f6974e 100644 --- a/src/gui/tags/TagsModelException.h +++ b/src/gui/tags/TagsModelException.h @@ -1,14 +1,14 @@ #ifndef TAGSMODELEXCEPTION_H_ #define TAGSMODELEXCEPTION_H_ -#include +#include "common/String.h" #include class TagsModelException { - std::string message; + String message; public: - TagsModelException(std::string message_): message(message_) {}; - const char * what() const throw() { return message.c_str(); }; + TagsModelException(String message_): message(message_) {}; + const char * what() const throw() { return message.ToUtf8().c_str(); }; ~TagsModelException() throw() {}; }; diff --git a/src/gui/tags/TagsView.cpp b/src/gui/tags/TagsView.cpp index 774c3488b..9aca4934d 100644 --- a/src/gui/tags/TagsView.cpp +++ b/src/gui/tags/TagsView.cpp @@ -87,9 +87,9 @@ void TagsView::NotifyTagsChanged(TagsModel * sender) class DeleteTagAction : public ui::ButtonAction { TagsView * v; - std::string tag; + ByteString tag; public: - DeleteTagAction(TagsView * _v, std::string tag) { v = _v; this->tag = tag; } + DeleteTagAction(TagsView * _v, ByteString tag) { v = _v; this->tag = tag; } void ActionCallback(ui::Button * sender) { try @@ -98,18 +98,18 @@ void TagsView::NotifyTagsChanged(TagsModel * sender) } catch(TagsModelException & ex) { - new ErrorMessage("Could not remove tag", ex.what()); + new ErrorMessage("Could not remove tag", ByteString(ex.what()).FromUtf8()); } } }; if(sender->GetSave()) { - std::list Tags = sender->GetSave()->GetTags(); + std::list Tags = sender->GetSave()->GetTags(); int i = 0; - for(std::list::const_iterator iter = Tags.begin(), end = Tags.end(); iter != end; iter++) + for(std::list::const_iterator iter = Tags.begin(), end = Tags.end(); iter != end; iter++) { - ui::Label * tempLabel = new ui::Label(ui::Point(35, 35+(16*i)), ui::Point(120, 16), *iter); + ui::Label * tempLabel = new ui::Label(ui::Point(35, 35+(16*i)), ui::Point(120, 16), (*iter).FromUtf8()); tempLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; tempLabel->Appearance.VerticalAlign = ui::Appearance::AlignMiddle; tags.push_back(tempLabel); AddComponent(tempLabel); @@ -154,11 +154,11 @@ void TagsView::addTag() } try { - c->AddTag(tagInput->GetText()); + c->AddTag(tagInput->GetText().ToUtf8()); } catch(TagsModelException & ex) { - new ErrorMessage("Could not add tag", ex.what()); + new ErrorMessage("Could not add tag", ByteString(ex.what()).FromUtf8()); } tagInput->SetText(""); } diff --git a/src/gui/update/UpdateActivity.cpp b/src/gui/update/UpdateActivity.cpp index c5b759638..5c1bd32c8 100644 --- a/src/gui/update/UpdateActivity.cpp +++ b/src/gui/update/UpdateActivity.cpp @@ -1,5 +1,4 @@ #include -#include #include "gui/dialogues/ConfirmPrompt.h" #include "gui/interface/Engine.h" #include "UpdateActivity.h" @@ -13,10 +12,10 @@ class UpdateDownloadTask : public Task { public: - UpdateDownloadTask(std::string updateName, UpdateActivity * a) : a(a), updateName(updateName) {} + UpdateDownloadTask(ByteString updateName, UpdateActivity * a) : a(a), updateName(updateName) {} private: UpdateActivity * a; - std::string updateName; + ByteString updateName; virtual void notifyDoneMain(){ a->NotifyDone(this); } @@ -26,7 +25,7 @@ private: } virtual bool doWork() { - std::stringstream errorStream; + String::Stream errorStream; void * request = http_async_req_start(NULL, (char*)updateName.c_str(), NULL, 0, 0); notifyStatus("Downloading update"); notifyProgress(-1); @@ -117,7 +116,7 @@ private: }; UpdateActivity::UpdateActivity() { - std::stringstream file; + ByteString::Stream file; #ifdef UPDATESERVER file << "http://" << UPDATESERVER << Client::Ref().GetUpdateInfo().File; #else diff --git a/src/lua/CommandInterface.cpp b/src/lua/CommandInterface.cpp index 0e455f96b..13d7d1e4c 100644 --- a/src/lua/CommandInterface.cpp +++ b/src/lua/CommandInterface.cpp @@ -1,5 +1,4 @@ #include -#include #include #if !defined(WIN) || defined(__GNUC__) #include @@ -18,23 +17,23 @@ CommandInterface::CommandInterface(GameController * c, GameModel * m) { this->m = m; }*/ -int CommandInterface::Command(std::string command) +int CommandInterface::Command(String command) { lastError = "No interpreter"; return -1; } -std::string CommandInterface::FormatCommand(std::string command) +String CommandInterface::FormatCommand(String command) { return command; } -void CommandInterface::Log(LogType type, std::string message) +void CommandInterface::Log(LogType type, String message) { m->Log(message, type == LogError || type == LogNotice); } -int CommandInterface::GetPropertyOffset(std::string key, FormatType & format) +int CommandInterface::GetPropertyOffset(ByteString key, FormatType & format) { int offset = -1; if (!key.compare("type")) @@ -105,7 +104,7 @@ int CommandInterface::GetPropertyOffset(std::string key, FormatType & format) return offset; } -std::string CommandInterface::GetLastError() +String CommandInterface::GetLastError() { return lastError; } diff --git a/src/lua/CommandInterface.h b/src/lua/CommandInterface.h index 78fdbf8fb..52ca21bd2 100644 --- a/src/lua/CommandInterface.h +++ b/src/lua/CommandInterface.h @@ -1,7 +1,7 @@ #ifndef COMMANDINTERFACE_H_ #define COMMANDINTERFACE_H_ -#include +#include "common/String.h" #include "gui/interface/Engine.h" //#include "game/GameModel.h" @@ -10,15 +10,15 @@ class GameController; class Tool; class CommandInterface { protected: - std::string lastError; + String lastError; GameModel * m; GameController * c; public: enum LogType { LogError, LogWarning, LogNotice }; enum FormatType { FormatInt, FormatString, FormatChar, FormatFloat, FormatElement }; CommandInterface(GameController * c, GameModel * m); - int GetPropertyOffset(std::string key, FormatType & format); - void Log(LogType type, std::string message); + int GetPropertyOffset(ByteString key, FormatType & format); + void Log(LogType type, String message); //void AttachGameModel(GameModel * m); virtual bool OnActiveToolChanged(int toolSelection, Tool * tool) {return true;} virtual bool OnMouseMove(int x, int y, int dx, int dy) {return true;} @@ -29,9 +29,9 @@ public: virtual bool OnKeyRelease(int key, Uint16 character, bool shift, bool ctrl, bool alt) {return true;} virtual bool OnMouseTick() { return true; } virtual void OnTick() { } - virtual int Command(std::string command); - virtual std::string FormatCommand(std::string command); - std::string GetLastError(); + virtual int Command(String command); + virtual String FormatCommand(String command); + String GetLastError(); virtual ~CommandInterface(); }; diff --git a/src/lua/LegacyLuaAPI.cpp b/src/lua/LegacyLuaAPI.cpp index 93ec42734..b72c5a6d5 100644 --- a/src/lua/LegacyLuaAPI.cpp +++ b/src/lua/LegacyLuaAPI.cpp @@ -1,5 +1,4 @@ #ifdef LUACONSOLE -#include #include #include #include @@ -26,7 +25,7 @@ int luacon_partread(lua_State* l) { int tempinteger, i = cIndex; float tempfloat; - std::string key = luaL_optstring(l, 2, ""); + ByteString key = luaL_optstring(l, 2, ""); CommandInterface::FormatType format; int offset = luacon_ci->GetPropertyOffset(key, format); @@ -62,7 +61,7 @@ int luacon_partread(lua_State* l) int luacon_partwrite(lua_State* l) { int i = cIndex; - std::string key = luaL_optstring(l, 2, ""); + ByteString key = luaL_optstring(l, 2, ""); CommandInterface::FormatType format; int offset = luacon_ci->GetPropertyOffset(key, format); @@ -473,7 +472,7 @@ int luacon_keyevent(int key, Uint16 character, int modifier, int event) int callret = lua_pcall(l, 4, 1, 0); if (callret) { - if (!strcmp(luacon_geterror(), "Error: Script not responding")) + if (luacon_geterror() == "Error: Script not responding") { ui::Engine::Ref().LastTick(Platform::GetTime()); for (int j = i; j <= len-1; j++) @@ -527,7 +526,7 @@ int luacon_mouseevent(int mx, int my, int mb, int event, int mouse_wheel) int callret = lua_pcall(l, 5, 1, 0); if (callret) { - if (!strcmp(luacon_geterror(), "Error: Script not responding")) + if (luacon_geterror() == "Error: Script not responding") { ui::Engine::Ref().LastTick(Platform::GetTime()); for (int j = i; j <= len-1; j++) @@ -579,7 +578,7 @@ int luacon_step(int mx, int my) int callret = lua_pcall(l, 0, 0, 0); if (callret) { - if (!strcmp(luacon_geterror(), "Error: Script not responding")) + if (luacon_geterror() == "Error: Script not responding") { ui::Engine::Ref().LastTick(Platform::GetTime()); for (int j = i; j <= len-1; j++) @@ -641,10 +640,10 @@ int luaL_tostring (lua_State *L, int n) return 1; } -const char *luacon_geterror() +String luacon_geterror() { luaL_tostring(luacon_ci->l, -1); - const char* err = luaL_optstring(luacon_ci->l, -1, "failed to execute"); + String err = ByteString(luaL_optstring(luacon_ci->l, -1, "failed to execute")).FromUtf8(); lua_pop(luacon_ci->l, 1); return err; } @@ -666,7 +665,7 @@ int luatpt_getelement(lua_State *l) t = luaL_optint(l, 1, 1); if (t<0 || t>=PT_NUM) return luaL_error(l, "Unrecognised element number '%d'", t); - lua_pushstring(l, luacon_sim->elements[t].Name); + lua_pushstring(l, luacon_sim->elements[t].Name.c_str()); } else { @@ -815,7 +814,7 @@ int luatpt_graphics_func(lua_State *l) int luatpt_error(lua_State* l) { - std::string errorMessage = std::string(luaL_optstring(l, 1, "Error text")); + String errorMessage = ByteString(luaL_optstring(l, 1, "Error text")).FromUtf8(); ErrorMessage::Blocking("Error", errorMessage); return 0; } @@ -842,7 +841,7 @@ int luatpt_drawtext(lua_State* l) if (textalpha<0) textalpha = 0; if (textalpha>255) textalpha = 255; - luacon_g->drawtext(textx, texty, string, textred, textgreen, textblue, textalpha); + luacon_g->drawtext(textx, texty, ByteString(string).FromUtf8(), textred, textgreen, textblue, textalpha); return 0; } @@ -860,7 +859,7 @@ int luatpt_create(lua_State* l) return luaL_error(l, "Unrecognised element number '%d'", t); } else { const char* name = luaL_optstring(l, 3, "dust"); - if ((t = luacon_sim->GetParticleType(std::string(name))) == -1) + if ((t = luacon_sim->GetParticleType(ByteString(name))) == -1) return luaL_error(l,"Unrecognised element '%s'", name); } retid = luacon_sim->create_part(-1, x, y, t); @@ -915,14 +914,14 @@ int luatpt_setconsole(lua_State* l) int luatpt_log(lua_State* l) { int args = lua_gettop(l); - std::string text = ""; + String text = ""; for(int i = 1; i <= args; i++) { luaL_tostring(l, -1); if(text.length()) - text=std::string(luaL_optstring(l, -1, "")) + ", " + text; + text=ByteString(luaL_optstring(l, -1, "")).FromUtf8() + ", " + text; else - text=std::string(luaL_optstring(l, -1, "")); + text=ByteString(luaL_optstring(l, -1, "")).FromUtf8(); lua_pop(l, 2); } if((*luacon_currentCommand)) @@ -1073,7 +1072,7 @@ int luatpt_set_property(lua_State* l) if(!lua_isnumber(l, acount) && lua_isstring(l, acount)) { name = luaL_optstring(l, acount, "none"); - if ((partsel = luacon_sim->GetParticleType(std::string(name))) == -1) + if ((partsel = luacon_sim->GetParticleType(ByteString(name))) == -1) return luaL_error(l, "Unrecognised element '%s'", name); } } @@ -1090,7 +1089,7 @@ int luatpt_set_property(lua_State* l) else { name = luaL_checklstring(l, 2, NULL); - if ((t = luacon_sim->GetParticleType(std::string(name)))==-1) + if ((t = luacon_sim->GetParticleType(ByteString(name)))==-1) return luaL_error(l, "Unrecognised element '%s'", name); } if (!lua_isnumber(l, 3) || acount >= 6) @@ -1276,7 +1275,7 @@ int luatpt_get_elecmap(lua_State* l) int luatpt_get_property(lua_State* l) { - std::string prop = luaL_optstring(l, 1, ""); + ByteString prop = luaL_optstring(l, 1, ""); int i = luaL_optint(l, 2, 0); //x coord or particle index, depending on arguments int y = luaL_optint(l, 3, -1); if (y!=-1 && y=0 && i < XRES && i>=0) @@ -1456,7 +1455,7 @@ int luatpt_textwidth(lua_State* l) { int strwidth = 0; const char* string = luaL_optstring(l, 1, ""); - strwidth = Graphics::textwidth(string); + strwidth = Graphics::textwidth(ByteString(string).FromUtf8()); lua_pushinteger(l, strwidth); return 1; } @@ -1671,22 +1670,22 @@ int luatpt_unregister_mouseclick(lua_State* l) int luatpt_input(lua_State* l) { - std::string prompt, title, result, shadow, text; - title = std::string(luaL_optstring(l, 1, "Title")); - prompt = std::string(luaL_optstring(l, 2, "Enter some text:")); - text = std::string(luaL_optstring(l, 3, "")); - shadow = std::string(luaL_optstring(l, 4, "")); + String prompt, title, result, shadow, text; + title = ByteString(luaL_optstring(l, 1, "Title")).FromUtf8(); + prompt = ByteString(luaL_optstring(l, 2, "Enter some text:")).FromUtf8(); + text = ByteString(luaL_optstring(l, 3, "")).FromUtf8(); + shadow = ByteString(luaL_optstring(l, 4, "")).FromUtf8(); result = TextPrompt::Blocking(title, prompt, text, shadow, false); - lua_pushstring(l, result.c_str()); + lua_pushstring(l, result.ToUtf8().c_str()); return 1; } int luatpt_message_box(lua_State* l) { - std::string title = std::string(luaL_optstring(l, 1, "Title")); - std::string message = std::string(luaL_optstring(l, 2, "Message")); + String title = ByteString(luaL_optstring(l, 1, "Title")).FromUtf8(); + String message = ByteString(luaL_optstring(l, 2, "Message")).FromUtf8(); int large = lua_toboolean(l, 3); new InformationMessage(title, message, large); return 0; @@ -1694,9 +1693,9 @@ int luatpt_message_box(lua_State* l) int luatpt_confirm(lua_State *l) { - std::string title = std::string(luaL_optstring(l, 1, "Title")); - std::string message = std::string(luaL_optstring(l, 2, "Message")); - std::string buttonText = std::string(luaL_optstring(l, 3, "Confirm")); + String title = ByteString(luaL_optstring(l, 1, "Title")).FromUtf8(); + String message = ByteString(luaL_optstring(l, 2, "Message")).FromUtf8(); + String buttonText = ByteString(luaL_optstring(l, 3, "Confirm")).FromUtf8(); bool ret = ConfirmPrompt::Blocking(title, message, buttonText); lua_pushboolean(l, ret ? 1 : 0); return 1; @@ -1915,9 +1914,9 @@ int luatpt_getscript(lua_State* l) int runScript = luaL_optint(l, 3, 0); int confirmPrompt = luaL_optint(l, 4, 1); - std::stringstream url; + ByteString::Stream url; url << "http://starcatcher.us/scripts/main.lua?get=" << scriptID; - if (confirmPrompt && !ConfirmPrompt::Blocking("Do you want to install script?", url.str(), "Install")) + if (confirmPrompt && !ConfirmPrompt::Blocking("Do you want to install script?", ByteString(url.str()).FromUtf8(), "Install")) return 0; int ret, len; @@ -1944,7 +1943,7 @@ int luatpt_getscript(lua_State* l) { fclose(outputfile); outputfile = NULL; - if (!confirmPrompt || ConfirmPrompt::Blocking("File already exists, overwrite?", filename, "Overwrite")) + if (!confirmPrompt || ConfirmPrompt::Blocking("File already exists, overwrite?", ByteString(filename).FromUtf8(), "Overwrite")) { outputfile = fopen(filename, "wb"); } @@ -1969,7 +1968,7 @@ int luatpt_getscript(lua_State* l) outputfile = NULL; if (runScript) { - std::stringstream luaCommand; + ByteString::Stream luaCommand; luaCommand << "dofile('" << filename << "')"; luaL_dostring(l, luaCommand.str().c_str()); } @@ -2019,7 +2018,7 @@ int luatpt_screenshot(lua_State* l) data = format::VideoBufferToPNG(screenshot); } } - std::stringstream filename; + ByteString::Stream filename; filename << "screenshot_"; filename << std::setfill('0') << std::setw(6) << (screenshotIndex++); if(fileType == 1) { diff --git a/src/lua/LuaButton.cpp b/src/lua/LuaButton.cpp index b4adf3b86..e13e83f32 100644 --- a/src/lua/LuaButton.cpp +++ b/src/lua/LuaButton.cpp @@ -26,8 +26,8 @@ LuaButton::LuaButton(lua_State * l) : int posY = luaL_optinteger(l, 2, 0); int sizeX = luaL_optinteger(l, 3, 10); int sizeY = luaL_optinteger(l, 4, 10); - std::string text = luaL_optstring(l, 5, ""); - std::string toolTip = luaL_optstring(l, 6, ""); + String text = ByteString(luaL_optstring(l, 5, "")).FromUtf8(); + String toolTip = ByteString(luaL_optstring(l, 6, "")).FromUtf8(); button = new ui::Button(ui::Point(posX, posY), ui::Point(sizeX, sizeY), text, toolTip); component = button; @@ -81,12 +81,12 @@ int LuaButton::text(lua_State * l) if(args) { luaL_checktype(l, 1, LUA_TSTRING); - button->SetText(lua_tostring(l, 1)); + button->SetText(ByteString(lua_tostring(l, 1)).FromUtf8()); return 0; } else { - lua_pushstring(l, button->GetText().c_str()); + lua_pushstring(l, button->GetText().ToUtf8().c_str()); return 1; } } @@ -99,7 +99,7 @@ void LuaButton::triggerAction() lua_rawgeti(l, LUA_REGISTRYINDEX, UserData); if (lua_pcall(l, 1, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } diff --git a/src/lua/LuaCheckbox.cpp b/src/lua/LuaCheckbox.cpp index 24883e916..6e9453468 100644 --- a/src/lua/LuaCheckbox.cpp +++ b/src/lua/LuaCheckbox.cpp @@ -26,7 +26,7 @@ LuaCheckbox::LuaCheckbox(lua_State * l) : int posY = luaL_optinteger(l, 2, 0); int sizeX = luaL_optinteger(l, 3, 10); int sizeY = luaL_optinteger(l, 4, 10); - std::string text = luaL_optstring(l, 5, ""); + String text = ByteString(luaL_optstring(l, 5, "")).FromUtf8(); checkbox = new ui::Checkbox(ui::Point(posX, posY), ui::Point(sizeX, sizeY), text, ""); component = checkbox; @@ -78,12 +78,12 @@ int LuaCheckbox::text(lua_State * l) int args = lua_gettop(l); if(args) { - checkbox->SetText(lua_tostring(l, 1)); + checkbox->SetText(ByteString(lua_tostring(l, 1)).FromUtf8()); return 0; } else { - lua_pushstring(l, checkbox->GetText().c_str()); + lua_pushstring(l, checkbox->GetText().ToUtf8().c_str()); return 1; } } @@ -97,7 +97,7 @@ void LuaCheckbox::triggerAction() lua_pushboolean(l, checkbox->GetChecked()); if (lua_pcall(l, 2, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } diff --git a/src/lua/LuaLabel.cpp b/src/lua/LuaLabel.cpp index 07ad636ac..53318a147 100644 --- a/src/lua/LuaLabel.cpp +++ b/src/lua/LuaLabel.cpp @@ -24,7 +24,7 @@ LuaLabel::LuaLabel(lua_State * l) : int posY = luaL_optinteger(l, 2, 0); int sizeX = luaL_optinteger(l, 3, 10); int sizeY = luaL_optinteger(l, 4, 10); - std::string text = luaL_optstring(l, 5, ""); + String text = ByteString(luaL_optstring(l, 5, "")).FromUtf8(); label = new ui::Label(ui::Point(posX, posY), ui::Point(sizeX, sizeY), text); component = label; @@ -35,12 +35,12 @@ int LuaLabel::text(lua_State * l) int args = lua_gettop(l); if(args) { - label->SetText(std::string(lua_tostring(l, 1))); + label->SetText(ByteString(lua_tostring(l, 1)).FromUtf8()); return 0; } else { - lua_pushstring(l, label->GetText().c_str()); + lua_pushstring(l, label->GetText().ToUtf8().c_str()); return 1; } } diff --git a/src/lua/LuaProgressBar.cpp b/src/lua/LuaProgressBar.cpp index cb6a9faaa..7a70e608a 100644 --- a/src/lua/LuaProgressBar.cpp +++ b/src/lua/LuaProgressBar.cpp @@ -25,7 +25,7 @@ LuaProgressBar::LuaProgressBar(lua_State * l) : int sizeX = luaL_optinteger(l, 3, 10); int sizeY = luaL_optinteger(l, 4, 10); int value = luaL_optinteger(l, 5, 0); - std::string status = luaL_optstring(l, 6, ""); + String status = ByteString(luaL_optstring(l, 6, "")).FromUtf8(); progressBar = new ui::ProgressBar(ui::Point(posX, posY), ui::Point(sizeX, sizeY), value, status); component = progressBar; @@ -51,12 +51,12 @@ int LuaProgressBar::status(lua_State * l) int args = lua_gettop(l); if(args) { - progressBar->SetStatus(std::string(lua_tostring(l, 1))); + progressBar->SetStatus(ByteString(lua_tostring(l, 1)).FromUtf8()); return 0; } else { - lua_pushstring(l, progressBar->GetStatus().c_str()); + lua_pushstring(l, progressBar->GetStatus().ToUtf8().c_str()); return 1; } } diff --git a/src/lua/LuaScriptHelper.h b/src/lua/LuaScriptHelper.h index 85e3730cd..db2790794 100644 --- a/src/lua/LuaScriptHelper.h +++ b/src/lua/LuaScriptHelper.h @@ -10,7 +10,7 @@ extern Renderer * luacon_ren; extern bool *luacon_currentCommand; extern int luaL_tostring(lua_State* l, int n); -extern std::string *luacon_lastError; +extern String *luacon_lastError; extern int *lua_el_func, *lua_el_mode, *lua_gr_func; @@ -25,7 +25,7 @@ int luacon_step(int mx, int my); int luacon_mouseevent(int mx, int my, int mb, int event, int mouse_wheel); int luacon_keyevent(int key, Uint16 character, int modifier, int event); int luacon_eval(const char *command); -const char *luacon_geterror(); +String luacon_geterror(); void luacon_close(); int luacon_partsread(lua_State* l); int luacon_partswrite(lua_State* l); diff --git a/src/lua/LuaScriptInterface.cpp b/src/lua/LuaScriptInterface.cpp index a89e775ae..6052f83c1 100644 --- a/src/lua/LuaScriptInterface.cpp +++ b/src/lua/LuaScriptInterface.cpp @@ -1,5 +1,4 @@ #ifdef LUACONSOLE -#include #include #include #include @@ -61,8 +60,8 @@ Graphics * luacon_g; Renderer * luacon_ren; bool *luacon_currentCommand; -std::string *luacon_lastError; -std::string lastCode; +String *luacon_lastError; +String lastCode; int *lua_el_func, *lua_el_mode, *lua_gr_func; @@ -74,7 +73,7 @@ int tptParts, tptPartsMeta, tptElementTransitions, tptPartsCData, tptPartMeta, t int atPanic(lua_State *l) { - throw std::runtime_error("Unprotected lua panic: " + std::string(lua_tostring(l, -1))); + throw std::runtime_error("Unprotected lua panic: " + ByteString(lua_tostring(l, -1))); } int TptIndexClosure(lua_State *l) @@ -296,9 +295,9 @@ tpt.partsdata = nil"); tptElements = lua_gettop(l); for (int i = 1; i < PT_NUM; i++) { - for (size_t j = 0; j < strlen(luacon_sim->elements[i].Name); j++) + for (size_t j = 0; j < luacon_sim->elements[i].Name.size(); j++) tmpname[j] = tolower(luacon_sim->elements[i].Name[j]); - tmpname[strlen(luacon_sim->elements[i].Name)] = 0; + tmpname[luacon_sim->elements[i].Name.size()] = 0; lua_newtable(l); currentElement = lua_gettop(l); @@ -321,9 +320,9 @@ tpt.partsdata = nil"); tptElementTransitions = lua_gettop(l); for (int i = 1; i < PT_NUM; i++) { - for (size_t j = 0; j < strlen(luacon_sim->elements[i].Name); j++) + for (size_t j = 0; j < luacon_sim->elements[i].Name.size(); j++) tmpname[j] = tolower(luacon_sim->elements[i].Name[j]); - tmpname[strlen(luacon_sim->elements[i].Name)] = 0; + tmpname[luacon_sim->elements[i].Name.size()] = 0; lua_newtable(l); currentElement = lua_gettop(l); @@ -381,7 +380,7 @@ void LuaScriptInterface::SetWindow(ui::Window * window) int LuaScriptInterface::tpt_index(lua_State *l) { - std::string key = luaL_checkstring(l, 2); + ByteString key = luaL_checkstring(l, 2); if (!key.compare("selectedl")) return lua_pushstring(l, luacon_selectedl.c_str()), 1; if (!key.compare("selectedr")) @@ -403,7 +402,7 @@ int LuaScriptInterface::tpt_index(lua_State *l) int LuaScriptInterface::tpt_newIndex(lua_State *l) { - std::string key = luaL_checkstring(l, 2); + ByteString key = luaL_checkstring(l, 2); if (!key.compare("selectedl")) { Tool *t = m->GetToolFromIdentifier(luaL_checkstring(l, 3)); @@ -543,7 +542,7 @@ int LuaScriptInterface::interface_closeWindow(lua_State * l) int LuaScriptInterface::simulation_signIndex(lua_State *l) { - std::string key = luaL_checkstring(l, 2); + ByteString key = luaL_checkstring(l, 2); //Get Raw Index value for element. Maybe there is a way to get the sign index some other way? lua_pushstring(l, "id"); @@ -561,9 +560,9 @@ int LuaScriptInterface::simulation_signIndex(lua_State *l) } if (!key.compare("text")) - return lua_pushstring(l, luacon_sim->signs[id].text.c_str()), 1; + return lua_pushstring(l, luacon_sim->signs[id].text.ToUtf8().c_str()), 1; else if (!key.compare("displayText")) - return lua_pushstring(l, luacon_sim->signs[id].getText(luacon_sim).c_str()), 1; + return lua_pushstring(l, luacon_sim->signs[id].getText(luacon_sim).ToUtf8().c_str()), 1; else if (!key.compare("justification")) return lua_pushnumber(l, (int)luacon_sim->signs[id].ju), 1; else if (!key.compare("x")) @@ -604,7 +603,7 @@ int LuaScriptInterface::simulation_signIndex(lua_State *l) int LuaScriptInterface::simulation_signNewIndex(lua_State *l) { - std::string key = luaL_checkstring(l, 2); + ByteString key = luaL_checkstring(l, 2); //Get Raw Index value for element. Maybe there is a way to get the sign index some other way? lua_pushstring(l, "id"); @@ -624,7 +623,7 @@ int LuaScriptInterface::simulation_signNewIndex(lua_State *l) if (!key.compare("text")) { const char *temp = luaL_checkstring(l, 3); - std::string cleaned = format::CleanString(temp, false, true, true).substr(0, 45); + String cleaned = format::CleanString(ByteString(temp).FromUtf8(), false, true, true).substr(0, 45); if (!cleaned.empty()) luacon_sim->signs[id].text = cleaned; else @@ -671,7 +670,7 @@ int LuaScriptInterface::simulation_newsign(lua_State *l) if (luacon_sim->signs.size() >= MAXSIGNS) return lua_pushnil(l), 1; - std::string text = format::CleanString(luaL_checkstring(l, 1), false, true, true).substr(0, 45); + String text = format::CleanString(ByteString(luaL_checkstring(l, 1)).FromUtf8(), false, true, true).substr(0, 45); int x = luaL_checkinteger(l, 2); int y = luaL_checkinteger(l, 3); int ju = luaL_optinteger(l, 4, 1); @@ -810,7 +809,7 @@ void LuaScriptInterface::initSimulationAPI() particleProperties = new StructProperty[particlePropertiesV.size()]; for(std::vector::iterator iter = particlePropertiesV.begin(), end = particlePropertiesV.end(); iter != end; ++iter) { - std::string propertyName = (*iter).Name; + ByteString propertyName = (*iter).Name; std::transform(propertyName.begin(), propertyName.end(), propertyName.begin(), ::toupper); lua_pushinteger(l, particlePropertiesCount); lua_setfield(l, -2, ("FIELD_"+propertyName).c_str()); @@ -1018,7 +1017,7 @@ int LuaScriptInterface::simulation_partProperty(lua_State * l) return luaL_error(l, "Invalid field ID (%d)", fieldID); property = &particleProperties[fieldID]; } else if(lua_type(l, 2) == LUA_TSTRING) { - std::string fieldName = lua_tostring(l, 2); + ByteString fieldName = lua_tostring(l, 2); for(int i = particlePropertiesCount-1; i >= 0; i--) { if(particleProperties[i].Name == fieldName) @@ -1687,7 +1686,7 @@ int LuaScriptInterface::simulation_saveStamp(lua_State * l) int w = luaL_optint(l,3,XRES-1); int h = luaL_optint(l,4,YRES-1); int includePressure = luaL_optint(l,5,1); - std::string name = luacon_controller->StampRegion(ui::Point(x, y), ui::Point(x+w, y+h), includePressure); + ByteString name = luacon_controller->StampRegion(ui::Point(x, y), ui::Point(x+w, y+h), includePressure); lua_pushstring(l, name.c_str()); return 1; } @@ -1738,12 +1737,12 @@ int LuaScriptInterface::simulation_loadStamp(lua_State * l) int LuaScriptInterface::simulation_deleteStamp(lua_State * l) { int stampCount = Client::Ref().GetStampsCount(); - std::vector stamps = Client::Ref().GetStamps(0, stampCount); + std::vector stamps = Client::Ref().GetStamps(0, stampCount); if (lua_isstring(l, 1)) //note: lua_isstring returns true on numbers too { const char * filename = luaL_optstring(l, 1, ""); - for (std::vector::const_iterator iterator = stamps.begin(), end = stamps.end(); iterator != end; ++iterator) + for (std::vector::const_iterator iterator = stamps.begin(), end = stamps.end(); iterator != end; ++iterator) { if (*iterator == filename) { @@ -2440,10 +2439,10 @@ void LuaScriptInterface::initElementsAPI() if(luacon_sim->elements[i].Enabled) { lua_pushinteger(l, i); - lua_setfield(l, -2, luacon_sim->elements[i].Identifier); + lua_setfield(l, -2, luacon_sim->elements[i].Identifier.c_str()); char realIdentifier[20]; - sprintf(realIdentifier, "DEFAULT_PT_%s", luacon_sim->elements[i].Name); - if (i != 0 && i != PT_NBHL && i != PT_NWHL && strcmp(luacon_sim->elements[i].Identifier, realIdentifier)) + sprintf(realIdentifier, "DEFAULT_PT_%s", luacon_sim->elements[i].Name.c_str()); + if (i != 0 && i != PT_NBHL && i != PT_NWHL && luacon_sim->elements[i].Identifier != realIdentifier) { lua_pushinteger(l, i); lua_setfield(l, -2, realIdentifier); @@ -2464,7 +2463,7 @@ int LuaScriptInterface::elements_loadDefault(lua_State * l) lua_getglobal(l, "elements"); lua_pushnil(l); - lua_setfield(l, -2, luacon_sim->elements[id].Identifier); + lua_setfield(l, -2, luacon_sim->elements[id].Identifier.c_str()); std::vector elementList = GetElements(); if (id < (int)elementList.size()) @@ -2473,7 +2472,7 @@ int LuaScriptInterface::elements_loadDefault(lua_State * l) luacon_sim->elements[id] = Element(); lua_pushinteger(l, id); - lua_setfield(l, -2, luacon_sim->elements[id].Identifier); + lua_setfield(l, -2, luacon_sim->elements[id].Identifier.c_str()); lua_pop(l, 1); } else @@ -2507,12 +2506,12 @@ int LuaScriptInterface::elements_loadDefault(lua_State * l) int LuaScriptInterface::elements_allocate(lua_State * l) { - std::string group, id, identifier; + ByteString group, id, identifier; luaL_checktype(l, 1, LUA_TSTRING); luaL_checktype(l, 2, LUA_TSTRING); - group = std::string(lua_tostring(l, 1)); + group = ByteString(lua_tostring(l, 1)); std::transform(group.begin(), group.end(), group.begin(), ::toupper); - id = std::string(lua_tostring(l, 2)); + id = ByteString(lua_tostring(l, 2)); std::transform(id.begin(), id.end(), id.begin(), ::toupper); if(group == "DEFAULT") @@ -2522,7 +2521,7 @@ int LuaScriptInterface::elements_allocate(lua_State * l) for(int i = 0; i < PT_NUM; i++) { - if(luacon_sim->elements[i].Enabled && std::string(luacon_sim->elements[i].Identifier) == identifier) + if(luacon_sim->elements[i].Enabled && ByteString(luacon_sim->elements[i].Identifier) == identifier) return luaL_error(l, "Element identifier already in use"); } @@ -2699,7 +2698,7 @@ int LuaScriptInterface::elements_element(lua_State * l) } lua_setfield(l, -2, (*iter).Name.c_str()); } - lua_pushstring(l, luacon_sim->elements[id].Identifier); + lua_pushstring(l, luacon_sim->elements[id].Identifier.c_str()); lua_setfield(l, -2, "Identifier"); return 1; } @@ -2709,11 +2708,11 @@ int LuaScriptInterface::elements_property(lua_State * l) { int args = lua_gettop(l); int id; - std::string propertyName; + ByteString propertyName; luaL_checktype(l, 1, LUA_TNUMBER); id = lua_tointeger(l, 1); luaL_checktype(l, 2, LUA_TSTRING); - propertyName = std::string(lua_tostring(l, 2)); + propertyName = ByteString(lua_tostring(l, 2)); if(id < 0 || id >= PT_NUM || !luacon_sim->elements[id].Enabled) return luaL_error(l, "Invalid element"); @@ -2877,7 +2876,7 @@ int LuaScriptInterface::elements_property(lua_State * l) } else if(propertyName == "Identifier") { - lua_pushstring(l, luacon_sim->elements[id].Identifier); + lua_pushstring(l, luacon_sim->elements[id].Identifier.c_str()); return 1; } else @@ -2894,7 +2893,7 @@ int LuaScriptInterface::elements_free(lua_State * l) if(id < 0 || id >= PT_NUM || !luacon_sim->elements[id].Enabled) return luaL_error(l, "Invalid element"); - std::string identifier = luacon_sim->elements[id].Identifier; + ByteString identifier = luacon_sim->elements[id].Identifier; if(identifier.length()>7 && identifier.substr(0, 7) == "DEFAULT") return luaL_error(l, "Cannot free default elements"); @@ -2937,7 +2936,7 @@ int LuaScriptInterface::graphics_textSize(lua_State * l) { int width, height; const char* text = luaL_optstring(l, 1, ""); - Graphics::textsize(text, width, height); + Graphics::textsize(ByteString(text).FromUtf8(), width, height); lua_pushinteger(l, width); lua_pushinteger(l, height); @@ -2963,7 +2962,7 @@ int LuaScriptInterface::graphics_drawText(lua_State * l) if (a<0) a = 0; else if (a>255) a = 255; - luacon_g->drawtext(x, y, text, r, g, b, a); + luacon_g->drawtext(x, y, ByteString(text).FromUtf8(), r, g, b, a); return 0; } @@ -3379,7 +3378,7 @@ int LuaScriptInterface::platform_releaseType(lua_State * l) int LuaScriptInterface::platform_exeName(lua_State * l) { - std::string name = Platform::ExecutableName(); + ByteString name = Platform::ExecutableName(); if (name.length()) lua_pushstring(l, name.c_str()); else @@ -3415,7 +3414,7 @@ int LuaScriptInterface::platform_clipboardPaste(lua_State * l) bool LuaScriptInterface::OnActiveToolChanged(int toolSelection, Tool * tool) { - std::string identifier; + ByteString identifier; if (tool) identifier = tool->GetIdentifier(); else @@ -3520,7 +3519,7 @@ void LuaScriptInterface::OnTick() luacon_step(luacon_mousex, luacon_mousey); } -int LuaScriptInterface::Command(std::string command) +int LuaScriptInterface::Command(String command) { if (command[0] == '!') { @@ -3532,24 +3531,24 @@ int LuaScriptInterface::Command(std::string command) else { int level = lua_gettop(l), ret = -1; - std::string text = ""; + String text = ""; lastError = ""; currentCommand = true; if (lastCode.length()) lastCode += "\n"; lastCode += command; - std::string tmp = "return " + lastCode; + String tmp = "return " + lastCode; ui::Engine::Ref().LastTick(Platform::GetTime()); - luaL_loadbuffer(l, tmp.c_str(), tmp.length(), "@console"); + luaL_loadbuffer(l, tmp.ToUtf8().c_str(), tmp.length(), "@console"); if (lua_type(l, -1) != LUA_TFUNCTION) { lua_pop(l, 1); - luaL_loadbuffer(l, lastCode.c_str(), lastCode.length(), "@console"); + luaL_loadbuffer(l, lastCode.ToUtf8().c_str(), lastCode.length(), "@console"); } if (lua_type(l, -1) != LUA_TFUNCTION) { lastError = luacon_geterror(); - std::string err = lastError; + String err = lastError; if (err.find("near ''") != err.npos) //the idea stolen from lua-5.1.5/lua.c lastError = "..."; else @@ -3567,9 +3566,9 @@ int LuaScriptInterface::Command(std::string command) { luaL_tostring(l, level); if (text.length()) - text += ", " + std::string(luaL_optstring(l, -1, "")); + text += ", " + ByteString(luaL_optstring(l, -1, "")).FromUtf8(); else - text = std::string(luaL_optstring(l, -1, "")); + text = ByteString(luaL_optstring(l, -1, "")).FromUtf8(); lua_pop(l, 1); } if (text.length()) @@ -3606,39 +3605,39 @@ int strlcmp(const char* a, const char* b, int len) return -1; } -std::string highlight(std::string command) +String highlight(String command) { -#define CMP(X) (!strlcmp(wstart, X, len)) - std::stringstream result; +#define CMP(X) (String(wstart, len) == X) + String::Stream result; int pos = 0; - const char *raw = command.c_str(); - char c; + String::value_type const*raw = command.c_str(); + String::value_type c; while ((c = raw[pos])) { if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_') { int len = 0; - char w; - const char* wstart = raw+pos; + String::value_type w; + String::value_type const* wstart = raw+pos; while((w = wstart[len]) && ((w >= 'A' && w <= 'Z') || (w >= 'a' && w <= 'z') || (w >= '0' && w <= '9') || w == '_')) len++; if(CMP("and") || CMP("break") || CMP("do") || CMP("else") || CMP("elseif") || CMP("end") || CMP("for") || CMP("function") || CMP("if") || CMP("in") || CMP("local") || CMP("not") || CMP("or") || CMP("repeat") || CMP("return") || CMP("then") || CMP("until") || CMP("while")) { - result << "\x0F\xB5\x89\x01"; + result << String("\x0F\xB5\x89\x01"); result.write(wstart, len); - result << "\bw"; + result << String("\bw"); } else if(CMP("false") || CMP("nil") || CMP("true")) { - result << "\x0F\xCB\x4B\x16"; + result << String("\x0F\xCB\x4B\x16"); result.write(wstart, len); - result << "\bw"; + result << String("\bw"); } else { - result << "\x0F\x2A\xA1\x98"; + result << String("\x0F\x2A\xA1\x98"); result.write(wstart, len); - result << "\bw"; + result << String("\bw"); } pos += len; } @@ -3647,20 +3646,20 @@ std::string highlight(std::string command) if(c == '0' && raw[pos + 1] == 'x') { int len = 2; - char w; - const char *wstart = raw + pos; + String::value_type w; + String::value_type const* wstart = raw+pos; while((w = wstart[len]) && ((w >= '0' && w <= '9') || (w >= 'A' && w <= 'F') || (w >= 'a' && w <= 'f'))) len++; - result << "\x0F\xD3\x36\x82"; + result << String("\x0F\xD3\x36\x82"); result.write(wstart, len); - result << "\bw"; + result << String("\bw"); pos += len; } else { int len = 0; - char w; - const char *wstart = raw+pos; + String::value_type w; + String::value_type const* wstart = raw+pos; bool seendot = false; while((w = wstart[len]) && ((w >= '0' && w <= '9') || w == '.')) { @@ -3682,9 +3681,9 @@ std::string highlight(std::string command) while((w = wstart[len]) && (w >= '0' && w <= '9')) len++; } - result << "\x0F\xD3\x36\x82"; + result << String("\x0F\xD3\x36\x82"); result.write(wstart, len); - result << "\bw"; + result << String("\bw"); pos += len; } } @@ -3693,8 +3692,8 @@ std::string highlight(std::string command) if(c == '[') { int len = 1, eqs=0; - char w; - const char *wstart = raw + pos; + String::value_type w; + String::value_type const* wstart = raw + pos; while((w = wstart[len]) && (w == '=')) { eqs++; @@ -3705,7 +3704,7 @@ std::string highlight(std::string command) if(w == ']') { int nlen = 1; - const char *cstart = wstart + len; + String::value_type const* cstart = wstart + len; while((w = cstart[nlen]) && (w == '=')) nlen++; if(w == ']' && nlen == eqs+1) @@ -3716,16 +3715,16 @@ std::string highlight(std::string command) } len++; } - result << "\x0F\xDC\x32\x2F"; + result << String("\x0F\xDC\x32\x2F"); result.write(wstart, len); - result << "\bw"; + result << String("\bw"); pos += len; } else { int len = 1; - char w; - const char *wstart = raw+pos; + String::value_type w; + String::value_type const* wstart = raw+pos; while((w = wstart[len]) && (w != c)) { if(w == '\\' && wstart[len + 1]) @@ -3734,9 +3733,9 @@ std::string highlight(std::string command) } if(w == c) len++; - result << "\x0F\xDC\x32\x2F"; + result << String("\x0F\xDC\x32\x2F"); result.write(wstart, len); - result << "\bw"; + result << String("\bw"); pos += len; } } @@ -3745,8 +3744,8 @@ std::string highlight(std::string command) if(raw[pos + 2] == '[') { int len = 3, eqs = 0; - char w; - const char *wstart = raw + pos; + String::value_type w; + String::value_type const* wstart = raw + pos; while((w = wstart[len]) && (w == '=')) { eqs++; @@ -3757,7 +3756,7 @@ std::string highlight(std::string command) if(w == ']') { int nlen = 1; - const char *cstart = wstart + len; + String::value_type const* cstart = wstart + len; while((w = cstart[nlen]) && (w == '=')) nlen++; if(w == ']' && nlen == eqs + 1) @@ -3768,32 +3767,32 @@ std::string highlight(std::string command) } len++; } - result << "\x0F\x85\x99\x01"; + result << String("\x0F\x85\x99\x01"); result.write(wstart, len); - result << "\bw"; + result << String("\bw"); pos += len; } else { int len = 2; - char w; - const char *wstart = raw + pos; + String::value_type w; + String::value_type const* wstart = raw + pos; while((w = wstart[len]) && (w != '\n')) len++; - result << "\x0F\x85\x99\x01"; + result << String("\x0F\x85\x99\x01"); result.write(wstart, len); - result << "\bw"; + result << String("\bw"); pos += len; } } else if(c == '{' || c == '}') { - result << "\x0F\xCB\x4B\x16" << c; + result << String("\x0F\xCB\x4B\x16") << c; pos++; } else if(c == '.' && raw[pos + 1] == '.' && raw[pos + 2] == '.') { - result << "\x0F\x2A\xA1\x98..."; + result << String("\x0F\x2A\xA1\x98..."); pos += 3; } else @@ -3805,9 +3804,9 @@ std::string highlight(std::string command) return result.str(); } -std::string LuaScriptInterface::FormatCommand(std::string command) +String LuaScriptInterface::FormatCommand(String command) { - if(command != "" && command[0] == '!') + if(command.size() && command[0] == '!') { return "!"+legacy->FormatCommand(command.substr(1)); } diff --git a/src/lua/LuaScriptInterface.h b/src/lua/LuaScriptInterface.h index 175bd3dba..24492731b 100644 --- a/src/lua/LuaScriptInterface.h +++ b/src/lua/LuaScriptInterface.h @@ -37,7 +37,7 @@ class TPTScriptInterface; class LuaScriptInterface: public CommandInterface { int luacon_mousex, luacon_mousey, luacon_mousebutton; - std::string luacon_selectedl, luacon_selectedr, luacon_selectedalt, luacon_selectedreplace; + ByteString luacon_selectedl, luacon_selectedr, luacon_selectedalt, luacon_selectedreplace; bool luacon_mousedown; bool currentCommand; TPTScriptInterface * legacy; @@ -185,8 +185,8 @@ public: virtual void OnTick(); virtual void Init(); virtual void SetWindow(ui::Window * window); - virtual int Command(std::string command); - virtual std::string FormatCommand(std::string command); + virtual int Command(String command); + virtual String FormatCommand(String command); virtual ~LuaScriptInterface(); }; diff --git a/src/lua/LuaSlider.cpp b/src/lua/LuaSlider.cpp index 28b847bfa..1034f9346 100644 --- a/src/lua/LuaSlider.cpp +++ b/src/lua/LuaSlider.cpp @@ -97,7 +97,7 @@ void LuaSlider::triggerOnValueChanged() lua_pushinteger(l, slider->GetValue()); if (lua_pcall(l, 2, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } diff --git a/src/lua/LuaTextbox.cpp b/src/lua/LuaTextbox.cpp index 474c02d00..c3cd6c97a 100644 --- a/src/lua/LuaTextbox.cpp +++ b/src/lua/LuaTextbox.cpp @@ -27,8 +27,8 @@ LuaTextbox::LuaTextbox(lua_State * l) : int posY = luaL_optinteger(l, 2, 0); int sizeX = luaL_optinteger(l, 3, 10); int sizeY = luaL_optinteger(l, 4, 10); - std::string text = luaL_optstring(l, 5, ""); - std::string placeholder = luaL_optstring(l, 6, ""); + String text = ByteString(luaL_optstring(l, 5, "")).FromUtf8(); + String placeholder = ByteString(luaL_optstring(l, 6, "")).FromUtf8(); textbox = new ui::Textbox(ui::Point(posX, posY), ui::Point(sizeX, sizeY), text, placeholder); textbox->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; @@ -85,7 +85,7 @@ void LuaTextbox::triggerOnTextChanged() lua_rawgeti(l, LUA_REGISTRYINDEX, UserData); if (lua_pcall(l, 1, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -95,12 +95,12 @@ int LuaTextbox::text(lua_State * l) int args = lua_gettop(l); if(args) { - textbox->SetText(std::string(lua_tostring(l, 1))); + textbox->SetText(ByteString(lua_tostring(l, 1)).FromUtf8()); return 0; } else { - lua_pushstring(l, textbox->GetText().c_str()); + lua_pushstring(l, textbox->GetText().ToUtf8().c_str()); return 1; } } diff --git a/src/lua/LuaWindow.cpp b/src/lua/LuaWindow.cpp index 4b7204b92..b7e4c79e5 100644 --- a/src/lua/LuaWindow.cpp +++ b/src/lua/LuaWindow.cpp @@ -208,7 +208,7 @@ void LuaWindow::triggerOnInitialized() lua_rawgeti(l, LUA_REGISTRYINDEX, onInitializedFunction); if(lua_pcall(l, 0, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -220,7 +220,7 @@ void LuaWindow::triggerOnExit() lua_rawgeti(l, LUA_REGISTRYINDEX, onExitFunction); if(lua_pcall(l, 0, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -233,7 +233,7 @@ void LuaWindow::triggerOnTick(float dt) lua_pushnumber(l, dt); if(lua_pcall(l, 1, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -245,7 +245,7 @@ void LuaWindow::triggerOnDraw() lua_rawgeti(l, LUA_REGISTRYINDEX, onDrawFunction); if(lua_pcall(l, 0, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -257,7 +257,7 @@ void LuaWindow::triggerOnFocus() lua_rawgeti(l, LUA_REGISTRYINDEX, onFocusFunction); if(lua_pcall(l, 0, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -269,7 +269,7 @@ void LuaWindow::triggerOnBlur() lua_rawgeti(l, LUA_REGISTRYINDEX, onBlurFunction); if(lua_pcall(l, 0, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -281,7 +281,7 @@ void LuaWindow::triggerOnTryExit() lua_rawgeti(l, LUA_REGISTRYINDEX, onTryExitFunction); if(lua_pcall(l, 0, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -293,7 +293,7 @@ void LuaWindow::triggerOnTryOkay() lua_rawgeti(l, LUA_REGISTRYINDEX, onTryOkayFunction); if(lua_pcall(l, 0, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -309,7 +309,7 @@ void LuaWindow::triggerOnMouseMove(int x, int y, int dx, int dy) lua_pushinteger(l, dy); if(lua_pcall(l, 4, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -324,7 +324,7 @@ void LuaWindow::triggerOnMouseDown(int x, int y, unsigned button) lua_pushinteger(l, button); if(lua_pcall(l, 3, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -339,7 +339,7 @@ void LuaWindow::triggerOnMouseUp(int x, int y, unsigned button) lua_pushinteger(l, button); if(lua_pcall(l, 3, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -354,7 +354,7 @@ void LuaWindow::triggerOnMouseWheel(int x, int y, int d) lua_pushinteger(l, d); if(lua_pcall(l, 3, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -371,7 +371,7 @@ void LuaWindow::triggerOnKeyPress(int key, Uint16 character, bool shift, bool ct lua_pushboolean(l, alt); if(lua_pcall(l, 5, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } @@ -388,7 +388,7 @@ void LuaWindow::triggerOnKeyRelease(int key, Uint16 character, bool shift, bool lua_pushboolean(l, alt); if(lua_pcall(l, 5, 0, 0)) { - ci->Log(CommandInterface::LogError, lua_tostring(l, -1)); + ci->Log(CommandInterface::LogError, ByteString(lua_tostring(l, -1)).FromUtf8()); } } } diff --git a/src/lua/TPTSTypes.cpp b/src/lua/TPTSTypes.cpp index 0779e02f5..caaa6917a 100644 --- a/src/lua/TPTSTypes.cpp +++ b/src/lua/TPTSTypes.cpp @@ -1,5 +1,4 @@ #include -#include #include #include "TPTSTypes.h" @@ -19,7 +18,7 @@ AnyType::AnyType(const AnyType & v): value(v.value) { if(type == TypeString) - value.str = new std::string(*(value.str)); + value.str = new String(*(value.str)); else if(type == TypePoint) value.pt = new ui::Point(*(value.pt)); } @@ -48,7 +47,7 @@ AnyType::operator StringType() { if(type == TypeNumber) { - std::stringstream numberStream; + String::Stream numberStream; numberStream << ((NumberType *)this)->Value(); return StringType(numberStream.str()); } @@ -59,7 +58,7 @@ AnyType::operator StringType() else if (type == TypePoint && value.pt) { ui::Point thisPoint = *(value.pt); - std::stringstream pointStream; + String::Stream pointStream; pointStream << thisPoint.X << "," << thisPoint.Y; return StringType(pointStream.str()); } @@ -76,9 +75,9 @@ AnyType::operator PointType() } else if(type == TypeString) { - std::stringstream pointStream(*(value.str)); + String::Stream pointStream(*(value.str)); int x, y; - char comma; + String::value_type comma; pointStream >> x >> comma >> y; if (pointStream.fail() || comma != ',') throw InvalidConversionException(type, TypePoint); @@ -122,12 +121,12 @@ float FloatType::Value() //String type -StringType::StringType(std::string string): AnyType(TypeString, ValueValue()) +StringType::StringType(String string): AnyType(TypeString, ValueValue()) { - value.str = new std::string(string); + value.str = new String(string); } -std::string StringType::Value() +String StringType::Value() { return *value.str; } diff --git a/src/lua/TPTSTypes.h b/src/lua/TPTSTypes.h index 12f34d812..93b16fbc5 100644 --- a/src/lua/TPTSTypes.h +++ b/src/lua/TPTSTypes.h @@ -1,22 +1,22 @@ #ifndef TPTSTYPES_H_ #define TPTSTYPES_H_ -#include +#include "common/String.h" #include #include "gui/interface/Point.h" enum ValueType { TypeNumber, TypeFloat, TypePoint, TypeString, TypeNull, TypeFunction }; -typedef union { int num; float numf; std::string* str; ui::Point* pt; } ValueValue; +typedef union { int num; float numf; String* str; ui::Point* pt; } ValueValue; class GeneralException { protected: - std::string exception; + String exception; public: - GeneralException(std::string message){ + GeneralException(String message){ exception = message; } - std::string GetExceptionMessage() { + String GetExceptionMessage() { return exception; } }; @@ -40,7 +40,7 @@ public: operator StringType(); operator PointType(); ValueType GetType(); - std::string TypeName() + ByteString TypeName() { switch(type) { @@ -60,7 +60,7 @@ public: return "Unknown"; } } - static std::string TypeName(ValueType type) + static ByteString TypeName(ValueType type) { switch(type) { @@ -87,7 +87,7 @@ class InvalidConversionException: public GeneralException { public: InvalidConversionException(ValueType from_, ValueType to_): - GeneralException("Invalid conversion from " + AnyType::TypeName(from_) + " to " + AnyType::TypeName(to_)) { + GeneralException("Invalid conversion from " + AnyType::TypeName(from_).FromAscii() + " to " + AnyType::TypeName(to_).FromAscii()) { } }; @@ -108,8 +108,8 @@ public: class StringType: public AnyType { public: - StringType(std::string string); - std::string Value(); + StringType(String string); + String Value(); }; class PointType: public AnyType diff --git a/src/lua/TPTScriptInterface.cpp b/src/lua/TPTScriptInterface.cpp index 8b66d46dc..7e46d8f7b 100644 --- a/src/lua/TPTScriptInterface.cpp +++ b/src/lua/TPTScriptInterface.cpp @@ -1,6 +1,5 @@ #include #include -#include #include #include #ifdef MACOSX @@ -15,26 +14,18 @@ TPTScriptInterface::TPTScriptInterface(GameController * c, GameModel * m): Comma { } -int TPTScriptInterface::Command(std::string command) +int TPTScriptInterface::Command(String command) { lastError = ""; - std::deque words; + std::deque words; std::deque commandWords; int retCode = -1; //Split command into words, put them on the stack - char * rawCommand; - rawCommand = (char*)calloc(command.length()+1, 1); - memcpy(rawCommand, (char*)command.c_str(), command.length()); - char * currentWord = rawCommand; - char * currentCommand = rawCommand; - while((currentCommand = strchr(currentCommand, ' '))) - { - currentCommand[0] = 0; - words.push_back(std::string(currentWord)); - currentWord = ++currentCommand; - } - words.push_back(std::string(currentWord)); + String::Stream ss(command); + String word; + while(std::getline(ss, word, String::value_type(' '))) + words.push_back(word); while(!words.empty()) { try @@ -48,7 +39,6 @@ int TPTScriptInterface::Command(std::string command) break; } } - free(rawCommand); if(commandWords.size()) { retCode = 0; @@ -59,10 +49,10 @@ int TPTScriptInterface::Command(std::string command) return retCode; } -ValueType TPTScriptInterface::testType(std::string word) +ValueType TPTScriptInterface::testType(String word) { size_t i = 0; - char * rawWord = (char *)word.c_str(); + String::value_type const *rawWord = word.c_str(); //Function if (word == "set") return TypeFunction; @@ -129,8 +119,9 @@ parseString: return TypeString; } -int TPTScriptInterface::parseNumber(char * stringData) +int TPTScriptInterface::parseNumber(String str) { + String::value_type const *stringData = str.c_str(); char cc; int base = 10; int currentNumber = 0; @@ -161,17 +152,19 @@ int TPTScriptInterface::parseNumber(char * stringData) } else { - return atoi(stringData); + int number; + String::Stream ss(str); + ss >> number; + return number; } return currentNumber; } -AnyType TPTScriptInterface::eval(std::deque * words) +AnyType TPTScriptInterface::eval(std::deque * words) { if(words->size() < 1) return AnyType(TypeNull, ValueValue()); - std::string word = words->front(); words->pop_front(); - char * rawWord = (char *)word.c_str(); + String word = words->front(); words->pop_front(); ValueType wordType = testType(word); switch(wordType) { @@ -192,14 +185,16 @@ AnyType TPTScriptInterface::eval(std::deque * words) return tptS_quit(words); break; case TypeNumber: - return NumberType(parseNumber(rawWord)); + return NumberType(parseNumber(word)); case TypeFloat: - return FloatType(atof(rawWord)); + return FloatType(atof(word.ToUtf8().c_str())); case TypePoint: { - int pointX, pointY; - sscanf(rawWord, "%d,%d", &pointX, &pointY); - return PointType(pointX, pointY); + String::Stream pointStream(word); + int x, y; + String::value_type comma; + pointStream >> x >> comma >> y; + return PointType(x, y); } case TypeString: return StringType(word); @@ -209,26 +204,17 @@ AnyType TPTScriptInterface::eval(std::deque * words) return StringType(word); } -std::string TPTScriptInterface::FormatCommand(std::string command) +String TPTScriptInterface::FormatCommand(String command) { - std::deque words; + std::deque words; std::deque commandWords; - std::string outputData; + String outputData; //Split command into words, put them on the stack - char * rawCommand; - rawCommand = (char*)calloc(command.length()+1, 1); - memcpy(rawCommand, (char*)command.c_str(), command.length()); - char * currentWord = rawCommand; - char * currentCommand = rawCommand; - while((currentCommand = strchr(currentCommand, ' '))) - { - currentCommand[0] = 0; - words.push_back(std::string(currentWord)); - currentWord = ++currentCommand; - } - words.push_back(std::string(currentWord)); - free(rawCommand); + String::Stream ss(command); + String word; + while(std::getline(ss, word, String::value_type(' '))) + words.push_back(word); while(!words.empty()) { ValueType cType = testType(words.front()); @@ -254,7 +240,7 @@ std::string TPTScriptInterface::FormatCommand(std::string command) return outputData; } -AnyType TPTScriptInterface::tptS_set(std::deque * words) +AnyType TPTScriptInterface::tptS_set(std::deque * words) { //Arguments from stack StringType property = eval(words); @@ -267,7 +253,7 @@ AnyType TPTScriptInterface::tptS_set(std::deque * words) int returnValue = 0; FormatType propertyFormat; - int propertyOffset = GetPropertyOffset(property.Value(), propertyFormat); + int propertyOffset = GetPropertyOffset(property.Value().ToUtf8(), propertyFormat); if (propertyOffset == -1) throw GeneralException("Invalid property"); @@ -286,21 +272,21 @@ AnyType TPTScriptInterface::tptS_set(std::deque * words) { if (property.Value() == "temp") { - std::string newString = ((StringType)value).Value(); + String newString = ((StringType)value).Value(); if (newString.at(newString.length()-1) == 'C') - newValuef = atof(newString.substr(0, newString.length()-1).c_str())+273.15; + newValuef = atof(newString.substr(0, newString.length()-1).ToUtf8().c_str())+273.15; else if (newString.at(newString.length()-1) == 'F') - newValuef = (atof(newString.substr(0, newString.length()-1).c_str())-32.0f)*5/9+273.15f; + newValuef = (atof(newString.substr(0, newString.length()-1).ToUtf8().c_str())-32.0f)*5/9+273.15f; else throw GeneralException("Invalid value for assignment"); } else { - newValue = m->GetSimulation()->GetParticleType(((StringType)value).Value()); + newValue = m->GetSimulation()->GetParticleType(((StringType)value).Value().ToUtf8()); if (newValue < 0 || newValue >= PT_NUM) { // TODO: add element CAKE to invalidate this - if (!strcasecmp(((StringType)value).Value().c_str(),"cake")) + if (!strcasecmp(((StringType)value).Value().ToUtf8().c_str(),"cake")) throw GeneralException("Cake is a lie, not an element"); throw GeneralException("Invalid element"); } @@ -386,7 +372,7 @@ AnyType TPTScriptInterface::tptS_set(std::deque * words) if (selector.GetType() == TypeNumber) type = ((NumberType)selector).Value(); else if (selector.GetType() == TypeString) - type = m->GetSimulation()->GetParticleType(((StringType)selector).Value()); + type = m->GetSimulation()->GetParticleType(((StringType)selector).Value().ToUtf8()); if (type<0 || type>=PT_NUM) throw GeneralException("Invalid particle type"); @@ -433,7 +419,7 @@ AnyType TPTScriptInterface::tptS_set(std::deque * words) return NumberType(returnValue); } -AnyType TPTScriptInterface::tptS_create(std::deque * words) +AnyType TPTScriptInterface::tptS_create(std::deque * words) { //Arguments from stack AnyType createType = eval(words); @@ -445,7 +431,7 @@ AnyType TPTScriptInterface::tptS_create(std::deque * words) if(createType.GetType() == TypeNumber) type = ((NumberType)createType).Value(); else if(createType.GetType() == TypeString) - type = m->GetSimulation()->GetParticleType(((StringType)createType).Value()); + type = m->GetSimulation()->GetParticleType(((StringType)createType).Value().ToUtf8()); else throw GeneralException("Invalid type"); @@ -467,7 +453,7 @@ AnyType TPTScriptInterface::tptS_create(std::deque * words) return NumberType(returnValue); } -AnyType TPTScriptInterface::tptS_delete(std::deque * words) +AnyType TPTScriptInterface::tptS_delete(std::deque * words) { //Arguments from stack AnyType partRef = eval(words); @@ -494,7 +480,7 @@ AnyType TPTScriptInterface::tptS_delete(std::deque * words) return NumberType(0); } -AnyType TPTScriptInterface::tptS_load(std::deque * words) +AnyType TPTScriptInterface::tptS_load(std::deque * words) { //Arguments from stack NumberType saveID = eval(words); @@ -508,7 +494,7 @@ AnyType TPTScriptInterface::tptS_load(std::deque * words) throw GeneralException("Invalid save ID"); } -AnyType TPTScriptInterface::tptS_bubble(std::deque * words) +AnyType TPTScriptInterface::tptS_bubble(std::deque * words) { //Arguments from stack PointType bubblePosA = eval(words); @@ -543,11 +529,11 @@ AnyType TPTScriptInterface::tptS_bubble(std::deque * words) return NumberType(0); } -AnyType TPTScriptInterface::tptS_reset(std::deque * words) +AnyType TPTScriptInterface::tptS_reset(std::deque * words) { //Arguments from stack StringType reset = eval(words); - std::string resetStr = reset.Value(); + String resetStr = reset.Value(); Simulation * sim = m->GetSimulation(); @@ -590,7 +576,7 @@ AnyType TPTScriptInterface::tptS_reset(std::deque * words) return NumberType(0); } -AnyType TPTScriptInterface::tptS_quit(std::deque * words) +AnyType TPTScriptInterface::tptS_quit(std::deque * words) { ui::Engine::Ref().Exit(); diff --git a/src/lua/TPTScriptInterface.h b/src/lua/TPTScriptInterface.h index dea284e73..d8f07ff6d 100644 --- a/src/lua/TPTScriptInterface.h +++ b/src/lua/TPTScriptInterface.h @@ -6,21 +6,21 @@ class TPTScriptInterface: public CommandInterface { protected: - AnyType eval(std::deque * words); - int parseNumber(char * stringData); - AnyType tptS_set(std::deque * words); - AnyType tptS_create(std::deque * words); - AnyType tptS_delete(std::deque * words); - AnyType tptS_load(std::deque * words); - AnyType tptS_reset(std::deque * words); - AnyType tptS_bubble(std::deque * words); - AnyType tptS_quit(std::deque * words); - ValueType testType(std::string word); + AnyType eval(std::deque * words); + int parseNumber(String str); + AnyType tptS_set(std::deque * words); + AnyType tptS_create(std::deque * words); + AnyType tptS_delete(std::deque * words); + AnyType tptS_load(std::deque * words); + AnyType tptS_reset(std::deque * words); + AnyType tptS_bubble(std::deque * words); + AnyType tptS_quit(std::deque * words); + ValueType testType(String word); public: TPTScriptInterface(GameController * c, GameModel * m); virtual void Tick() {} - virtual int Command(std::string command); - virtual std::string FormatCommand(std::string command); + virtual int Command(String command); + virtual String FormatCommand(String command); virtual ~TPTScriptInterface(); }; diff --git a/src/powdertoyjava/PowderToyJava.cpp b/src/powdertoyjava/PowderToyJava.cpp index 7f332f5c5..d11f7c380 100644 --- a/src/powdertoyjava/PowderToyJava.cpp +++ b/src/powdertoyjava/PowderToyJava.cpp @@ -2,8 +2,6 @@ #include #include -#include -#include #include "Config.h" #include "PowderToyJava.h" diff --git a/src/simulation/GOLMenu.h b/src/simulation/GOLMenu.h index 905431374..ef37808e1 100644 --- a/src/simulation/GOLMenu.h +++ b/src/simulation/GOLMenu.h @@ -3,10 +3,10 @@ struct gol_menu { - const char *name; + ByteString name; pixel colour; int goltype; - const char *description; + String description; }; #endif diff --git a/src/simulation/MenuSection.h b/src/simulation/MenuSection.h index 7bd292f74..fc31ed2c3 100644 --- a/src/simulation/MenuSection.h +++ b/src/simulation/MenuSection.h @@ -3,8 +3,8 @@ struct menu_section { - const char *icon; - const char *name; + String icon; + String name; int itemcount; int doshow; }; diff --git a/src/simulation/Sign.cpp b/src/simulation/Sign.cpp index 705ea8aee..02d94ada4 100644 --- a/src/simulation/Sign.cpp +++ b/src/simulation/Sign.cpp @@ -1,10 +1,9 @@ #include -#include #include "Sign.h" #include "graphics/Graphics.h" #include "simulation/Simulation.h" -sign::sign(std::string text_, int x_, int y_, Justification justification_): +sign::sign(String text_, int x_, int y_, Justification justification_): x(x_), y(y_), ju(justification_), @@ -12,9 +11,9 @@ sign::sign(std::string text_, int x_, int y_, Justification justification_): { } -std::string sign::getText(Simulation *sim) +String sign::getText(Simulation *sim) { - std::stringstream signTextNew; + String::Stream signTextNew; if (text[0] && text[0] == '{') { if (text == "{p}") @@ -55,7 +54,7 @@ std::string sign::getText(Simulation *sim) return signTextNew.str(); } -void sign::pos(std::string signText, int & x0, int & y0, int & w, int & h) +void sign::pos(String signText, int & x0, int & y0, int & w, int & h) { w = Graphics::textwidth(signText.c_str()) + 5; h = 15; @@ -64,7 +63,7 @@ void sign::pos(std::string signText, int & x0, int & y0, int & w, int & h) y0 = (y > 18) ? y - 18 : y + 4; } -int sign::splitsign(std::string str, char * type) +int sign::splitsign(String str, String::value_type *type) { if (str[0] == '{' && (str[1] == 'c' || str[1] == 't' || str[1] == 'b' || str[1] == 's')) { diff --git a/src/simulation/Sign.h b/src/simulation/Sign.h index 98b053b58..6eb83db46 100644 --- a/src/simulation/Sign.h +++ b/src/simulation/Sign.h @@ -1,7 +1,7 @@ #ifndef SIGN_H_ #define SIGN_H_ -#include +#include "common/String.h" class Simulation; @@ -9,15 +9,15 @@ class sign { public: enum Justification { Left = 0, Middle = 1, Right = 2, None = 3 }; - sign(std::string text_, int x_, int y_, Justification justification_); + sign(String text_, int x_, int y_, Justification justification_); int x, y; Justification ju; - std::string text; + String text; - std::string getText(Simulation *sim); - void pos(std::string signText, int & x0, int & y0, int & w, int & h); + String getText(Simulation *sim); + void pos(String signText, int & x0, int & y0, int & w, int & h); - static int splitsign(std::string str, char * type = NULL); + static int splitsign(String str, String::value_type *type = NULL); }; #endif diff --git a/src/simulation/Simulation.cpp b/src/simulation/Simulation.cpp index 22f43c708..b5e306608 100644 --- a/src/simulation/Simulation.cpp +++ b/src/simulation/Simulation.cpp @@ -4894,7 +4894,7 @@ movedone: framerender--; } -int Simulation::GetParticleType(std::string type) +int Simulation::GetParticleType(ByteString type) { char * txt = (char*)type.c_str(); @@ -4907,7 +4907,7 @@ int Simulation::GetParticleType(std::string type) return PT_NONE; for (int i = 1; i < PT_NUM; i++) { - if (!strcasecmp(txt, elements[i].Name) && strlen(elements[i].Name) && elements[i].Enabled) + if (!strcasecmp(txt, elements[i].Name.c_str()) && elements[i].Name.size() && elements[i].Enabled) { return i; } @@ -5383,7 +5383,6 @@ void Simulation::AfterSim() Simulation::~Simulation() { - delete[] platent; delete grav; delete air; for (size_t i = 0; i < tools.size(); i++) @@ -5447,21 +5446,11 @@ Simulation::Simulation(): pv = air->pv; hv = air->hv; - int menuCount; - menu_section * msectionsT = LoadMenus(menuCount); - memcpy(msections, msectionsT, menuCount * sizeof(menu_section)); - free(msectionsT); + msections = LoadMenus(); - int wallCount; - wall_type * wtypesT = LoadWalls(wallCount); - memcpy(wtypes, wtypesT, wallCount * sizeof(wall_type)); - free(wtypesT); + wtypes = LoadWalls(); - platent = new unsigned[PT_NUM]; - int latentCount; - unsigned int * platentT = LoadLatent(latentCount); - memcpy(platent, platentT, latentCount * sizeof(unsigned int)); - free(platentT); + platent = LoadLatent(); std::vector elementList = GetElements(); for(int i = 0; i < PT_NUM; i++) @@ -5474,20 +5463,9 @@ Simulation::Simulation(): tools = GetTools(); - int golRulesCount; - int * golRulesT = LoadGOLRules(golRulesCount); - memcpy(grule, golRulesT, sizeof(int) * (golRulesCount*10)); - free(golRulesT); + grule = LoadGOLRules(); - int golTypesCount; - int * golTypesT = LoadGOLTypes(golTypesCount); - memcpy(goltype, golTypesT, sizeof(int) * (golTypesCount)); - free(golTypesT); - - int golMenuCount; - gol_menu * golMenuT = LoadGOLMenu(golMenuCount); - memcpy(gmenu, golMenuT, sizeof(gol_menu) * golMenuCount); - free(golMenuT); + gmenu = LoadGOLMenu(); player.comm = 0; player2.comm = 0; diff --git a/src/simulation/Simulation.h b/src/simulation/Simulation.h index 3ae09fabd..eb6f90414 100644 --- a/src/simulation/Simulation.h +++ b/src/simulation/Simulation.h @@ -41,12 +41,12 @@ public: Element elements[PT_NUM]; //Element * elements; std::vector tools; - unsigned int * platent; - wall_type wtypes[UI_WALLCOUNT]; - gol_menu gmenu[NGOL]; - int goltype[NGOL]; - int grule[NGOL+1][10]; - menu_section msections[SC_TOTAL]; + std::vector platent; + std::vector wtypes; + std::vector gmenu; + std::vector goltype; + std::vector > grule; + std::vector msections; int currentTick; int replaceModeSelected; @@ -199,7 +199,7 @@ public: void GetGravityField(int x, int y, float particleGrav, float newtonGrav, float & pGravX, float & pGravY); - int GetParticleType(std::string type); + int GetParticleType(ByteString type); void orbitalparts_get(int block1, int block2, int resblock1[], int resblock2[]); void orbitalparts_set(int *block1, int *block2, int resblock1[], int resblock2[]); diff --git a/src/simulation/SimulationData.cpp b/src/simulation/SimulationData.cpp index 5f04a2ef8..3a4ff4dd8 100644 --- a/src/simulation/SimulationData.cpp +++ b/src/simulation/SimulationData.cpp @@ -3,9 +3,9 @@ #include "ElementGraphics.h" #include "Elements.h" -gol_menu * LoadGOLMenu(int & golMenuCount) +std::vector LoadGOLMenu() { - gol_menu golMenu[NGOL] = + return { {"GOL", PIXPACK(0x0CAC00), 0, "Game Of Life: Begin 3/Stay 23"}, {"HLIF", PIXPACK(0xFF0000), 1, "High Life: B36/S23"}, @@ -32,15 +32,11 @@ gol_menu * LoadGOLMenu(int & golMenuCount) {"FROG", PIXPACK(0x00AA00), 22, "Frogs: B34/S12/3"}, {"BRAN", PIXPACK(0xCCCC00), 23, "Brian 6: B246/S6/3"} }; - golMenuCount = NGOL; - gol_menu * golMenuT = (gol_menu*)malloc(NGOL*sizeof(gol_menu)); - memcpy(golMenuT, golMenu, NGOL*sizeof(gol_menu)); - return golMenuT; } -int * LoadGOLRules(int & golRuleCount) +std::vector > LoadGOLRules() { - int golRules[NGOL+1][10] = + return { // 0,1,2,3,4,5,6,7,8,STATES live=1 spawn=2 spawn&live=3 States are kind of how long until it dies, normal ones use two states(living,dead) for others the intermediate states live but do nothing {0,0,0,0,0,0,0,0,0,2},//blank @@ -69,15 +65,11 @@ int * LoadGOLRules(int & golRuleCount) {0,1,1,2,2,0,0,0,0,3},//FROG {0,0,2,0,2,0,3,0,0,3},//BRAN }; - golRuleCount = NGOL+1; - int * golRulesT = (int*)malloc((golRuleCount*10)*sizeof(int)); - memcpy(golRulesT, golRules, (golRuleCount*10)*sizeof(int)); - return golRulesT; } -int * LoadGOLTypes(int & golTypeCount) +std::vector LoadGOLTypes() { - int golTypes[NGOL] = + return { GT_GOL, GT_HLIF, @@ -104,15 +96,11 @@ int * LoadGOLTypes(int & golTypeCount) GT_FROG, GT_BRAN, }; - golTypeCount = NGOL; - int * golTypesT = (int*)malloc((golTypeCount)*sizeof(int)); - memcpy(golTypesT, golTypes, (golTypeCount)*sizeof(int)); - return golTypesT; } -wall_type * LoadWalls(int & wallCount) +std::vector LoadWalls() { - wall_type wtypes[] = + return { {PIXPACK(0x808080), PIXPACK(0x000000), 0, Renderer::WallIcon, "ERASE", "DEFAULT_WL_ERASE", "Erases walls."}, {PIXPACK(0xC0C0C0), PIXPACK(0x101010), 0, Renderer::WallIcon, "CONDUCTIVE WALL", "DEFAULT_WL_CNDTW", "Blocks everything. Conductive."}, @@ -134,15 +122,11 @@ wall_type * LoadWalls(int & wallCount) {PIXPACK(0x808080), PIXPACK(0x000000), 0, Renderer::WallIcon, "ERASEALL", "DEFAULT_WL_ERASEA", "Erases walls, particles, and signs."}, {PIXPACK(0x800080), PIXPACK(0x000000), 0, Renderer::WallIcon, "STASIS WALL", "DEFAULT_WL_STASIS", "Freezes particles inside the wall in place until powered."}, }; - wallCount = UI_WALLCOUNT; - wall_type * wtypesT = (wall_type*)malloc(UI_WALLCOUNT*sizeof(wall_type)); - memcpy(wtypesT, wtypes, UI_WALLCOUNT*sizeof(wall_type)); - return wtypesT; } -menu_section * LoadMenus(int & menuCount) +std::vector LoadMenus() { - menu_section msections[] = //doshow does not do anything currently. + return { {"\xC1", "Walls", 0, 1}, {"\xC2", "Electronics", 0, 1}, @@ -163,15 +147,11 @@ menu_section * LoadMenus(int & menuCount) {"\xC8", "Cracker", 0, 0}, {"\xC8", "Cracker!", 0, 0}, }; - menuCount = SC_TOTAL; - menu_section * msectionsT = (menu_section*)malloc(SC_TOTAL*sizeof(menu_section)); - memcpy(msectionsT, msections, SC_TOTAL*sizeof(menu_section)); - return msectionsT; } -unsigned int * LoadLatent(int & elementCount) +std::vector LoadLatent() { - unsigned int platent[PT_NUM] = + return { /* NONE */ 0, /* DUST */ 0, @@ -335,8 +315,4 @@ unsigned int * LoadLatent(int & elementCount) /* FRAY */ 0, /* REPL */ 0, }; - elementCount = PT_NUM; - unsigned int * platentT = (unsigned int*)malloc(PT_NUM*sizeof(unsigned int)); - memcpy(platentT, platent, PT_NUM*sizeof(unsigned int)); - return platentT; } diff --git a/src/simulation/SimulationData.h b/src/simulation/SimulationData.h index 471b7d019..c823b5552 100644 --- a/src/simulation/SimulationData.h +++ b/src/simulation/SimulationData.h @@ -1,4 +1,5 @@ #include +#include #define SC_WALL 0 #define SC_ELEC 1 @@ -142,16 +143,16 @@ struct menu_section; class SimTool; class Element; -gol_menu * LoadGOLMenu(int & golMenuCount); +std::vector LoadGOLMenu(); -int * LoadGOLTypes(int & golTypeCount); +std::vector LoadGOLTypes(); -int * LoadGOLRules(int & golRuleCount); +std::vector > LoadGOLRules(); -wall_type * LoadWalls(int & wallCount); +std::vector LoadWalls(); -menu_section * LoadMenus(int & menuCount); +std::vector LoadMenus(); -unsigned int * LoadLatent(int & elementCount); +std::vector LoadLatent(); #endif /* SIMULATIONDATA_H */ diff --git a/src/simulation/StorageClasses.h b/src/simulation/StorageClasses.h index 7f60b3918..5f493075f 100644 --- a/src/simulation/StorageClasses.h +++ b/src/simulation/StorageClasses.h @@ -1,7 +1,6 @@ #ifndef STORAGECLASSES_H_ #define STORAGECLASSES_H_ -#include #include "Elements.h" class Renderer; diff --git a/src/simulation/StructProperty.h b/src/simulation/StructProperty.h index cd3002e59..59908cdb4 100644 --- a/src/simulation/StructProperty.h +++ b/src/simulation/StructProperty.h @@ -1,17 +1,17 @@ #ifndef STRUCTPROPERTY_H_ #define STRUCTPROPERTY_H_ -#include +#include "common/String.h" #include struct StructProperty { enum PropertyType { ParticleType, Colour, Integer, UInteger, Float, String, Char, UChar, Removed }; - std::string Name; + ByteString Name; PropertyType Type; intptr_t Offset; - StructProperty(std::string name, PropertyType type, intptr_t offset): + StructProperty(ByteString name, PropertyType type, intptr_t offset): Name(name), Type(type), Offset(offset) diff --git a/src/simulation/WallType.h b/src/simulation/WallType.h index b8ec53eb2..79478d5e0 100644 --- a/src/simulation/WallType.h +++ b/src/simulation/WallType.h @@ -1,6 +1,7 @@ #ifndef WALLTYPE_H_ #define WALLTYPE_H_ +#include "common/String.h" #include "graphics/Pixel.h" class VideoBuffer; @@ -10,9 +11,9 @@ struct wall_type pixel eglow; // if emap set, add this to fire glow int drawstyle; VideoBuffer * (*textureGen)(int, int, int); - const char *name; - const char *identifier; - const char *descs; + String name; + ByteString identifier; + String descs; }; #endif diff --git a/src/simulation/elements/Element.h b/src/simulation/elements/Element.h index f726d410f..2b399fb7e 100644 --- a/src/simulation/elements/Element.h +++ b/src/simulation/elements/Element.h @@ -13,8 +13,8 @@ struct Particle; class Element { public: - const char *Identifier; - const char *Name; + ByteString Identifier; + ByteString Name; pixel Colour; int MenuVisible; int MenuSection; @@ -38,7 +38,7 @@ public: int Weight; float Temperature; unsigned char HeatConduct; - const char *Description; + String Description; unsigned int Properties; float LowPressure; diff --git a/src/simulation/elements/LIFE.cpp b/src/simulation/elements/LIFE.cpp index 9ac25b287..310bcc517 100644 --- a/src/simulation/elements/LIFE.cpp +++ b/src/simulation/elements/LIFE.cpp @@ -52,13 +52,11 @@ Element_LIFE::Element_LIFE() { Element_GOL_colourInit = true; - int golMenuCount; - gol_menu * golMenuT = LoadGOLMenu(golMenuCount); - for(int i = 0; i < golMenuCount && i < NGOL; i++) + std::vector golMenuT = LoadGOLMenu(); + for(int i = 0; i < NGOL; i++) { Element_GOL_colour[i] = golMenuT[i].colour; } - free(golMenuT); } } diff --git a/src/simulation/simtools/SimTool.h b/src/simulation/simtools/SimTool.h index 4aa969d2c..66ae865b1 100644 --- a/src/simulation/simtools/SimTool.h +++ b/src/simulation/simtools/SimTool.h @@ -10,10 +10,10 @@ struct Particle; class SimTool { public: - const char *Identifier; - const char *Name; + ByteString Identifier; + ByteString Name; pixel Colour; - const char *Description; + String Description; SimTool(); virtual ~SimTool() {} diff --git a/src/tasks/Task.cpp b/src/tasks/Task.cpp index 9da5edee2..761143e9b 100644 --- a/src/tasks/Task.cpp +++ b/src/tasks/Task.cpp @@ -26,12 +26,12 @@ int Task::GetProgress() return progress; } -std::string Task::GetStatus() +String Task::GetStatus() { return status; } -std::string Task::GetError() +String Task::GetError() { return error; } @@ -53,14 +53,14 @@ void Task::Poll() int newProgress; bool newDone = false; bool newSuccess = false; - std::string newStatus; - std::string newError; + String newStatus; + String newError; pthread_mutex_lock(&taskMutex); newProgress = thProgress; newDone = thDone; newSuccess = thSuccess; - newStatus = std::string(thStatus); - newError = std::string(thError); + newStatus = thStatus; + newError = thError; pthread_mutex_unlock(&taskMutex); success = newSuccess; @@ -71,12 +71,12 @@ void Task::Poll() } if(newError!=error) { - error = std::string(newError); + error = newError; notifyErrorMain(); } if(newStatus!=status) { - status = std::string(newStatus); + status = newStatus; notifyStatusMain(); } @@ -140,17 +140,17 @@ void Task::notifyProgress(int progress) pthread_mutex_unlock(&taskMutex); } -void Task::notifyStatus(std::string status) +void Task::notifyStatus(String status) { pthread_mutex_lock(&taskMutex); - thStatus = std::string(status); + thStatus = status; pthread_mutex_unlock(&taskMutex); } -void Task::notifyError(std::string error) +void Task::notifyError(String error) { pthread_mutex_lock(&taskMutex); - thError = std::string(error); + thError = error; pthread_mutex_unlock(&taskMutex); } diff --git a/src/tasks/Task.h b/src/tasks/Task.h index 52ca39493..5913750ad 100644 --- a/src/tasks/Task.h +++ b/src/tasks/Task.h @@ -1,7 +1,7 @@ #ifndef TASK_H_ #define TASK_H_ -#include +#include "common/String.h" #include "common/tpt-thread.h" #include "TaskListener.h" #include "Config.h" @@ -14,8 +14,8 @@ public: int GetProgress(); bool GetDone(); bool GetSuccess(); - std::string GetError(); - std::string GetStatus(); + String GetError(); + String GetStatus(); void Poll(); Task() : listener(NULL) { progress = 0; thProgress = 0; } virtual ~Task(); @@ -23,14 +23,14 @@ protected: int progress; bool done; bool success; - std::string status; - std::string error; + String status; + String error; int thProgress; bool thDone; bool thSuccess; - std::string thStatus; - std::string thError; + String thStatus; + String thError; TaskListener * listener; pthread_t doWorkThread; @@ -44,8 +44,8 @@ protected: TH_ENTRY_POINT static void * doWork_helper(void * ref); virtual void notifyProgress(int progress); - virtual void notifyError(std::string error); - virtual void notifyStatus(std::string status); + virtual void notifyError(String error); + virtual void notifyStatus(String status); virtual void notifyProgressMain(); virtual void notifyErrorMain(); diff --git a/src/tasks/TaskWindow.cpp b/src/tasks/TaskWindow.cpp index a8eacc4db..3e46ecad3 100644 --- a/src/tasks/TaskWindow.cpp +++ b/src/tasks/TaskWindow.cpp @@ -1,4 +1,3 @@ -#include #include "common/tpt-minmax.h" #include "gui/interface/Label.h" #include "gui/interface/Engine.h" @@ -7,7 +6,7 @@ #include "gui/Style.h" #include "Task.h" -TaskWindow::TaskWindow(std::string title_, Task * task_, bool closeOnDone): +TaskWindow::TaskWindow(String title_, Task * task_, bool closeOnDone): ui::Window(ui::Point(-1, -1), ui::Point(240, 60)), task(task_), title(title_), @@ -63,7 +62,7 @@ void TaskWindow::Exit() void TaskWindow::NotifyProgress(Task * task) { progress = task->GetProgress(); - std::stringstream pStream; + String::Stream pStream; if(progress>-1) { pStream << progress << "%"; @@ -120,9 +119,9 @@ void TaskWindow::OnDraw() } } if(progress<50) - g->drawtext(Position.X + ((Size.X-Graphics::textwidth(progressStatus.c_str()))/2), Position.Y + Size.Y-13, progressStatus, 255, 255, 255, 255); + g->drawtext(Position.X + ((Size.X-Graphics::textwidth(progressStatus))/2), Position.Y + Size.Y-13, progressStatus, 255, 255, 255, 255); else - g->drawtext(Position.X + ((Size.X-Graphics::textwidth(progressStatus.c_str()))/2), Position.Y + Size.Y-13, progressStatus, 0, 0, 0, 255); + g->drawtext(Position.X + ((Size.X-Graphics::textwidth(progressStatus))/2), Position.Y + Size.Y-13, progressStatus, 0, 0, 0, 255); } TaskWindow::~TaskWindow() { diff --git a/src/tasks/TaskWindow.h b/src/tasks/TaskWindow.h index 44acd222e..3b3f872c7 100644 --- a/src/tasks/TaskWindow.h +++ b/src/tasks/TaskWindow.h @@ -1,7 +1,6 @@ #ifndef TASKWINDOW_H_ #define TASKWINDOW_H_ -#include #include "gui/interface/Label.h" #include "gui/interface/Window.h" #include "tasks/TaskListener.h" @@ -9,15 +8,15 @@ class Task; class TaskWindow: public ui::Window, public TaskListener { Task * task; - std::string title; + String title; int progress; float intermediatePos; bool done; bool closeOnDone; ui::Label * statusLabel; - std::string progressStatus; + String progressStatus; public: - TaskWindow(std::string title_, Task * task_, bool closeOnDone = true); + TaskWindow(String title_, Task * task_, bool closeOnDone = true); virtual void NotifyStatus(Task * task); virtual void NotifyDone(Task * task); virtual void NotifyProgress(Task * task); From 9d927cbd6f49c7340678772e0947c9f4f1e05644 Mon Sep 17 00:00:00 2001 From: mniip Date: Tue, 1 May 2018 02:21:34 +0300 Subject: [PATCH 06/27] Add an auxiliary font reader class to reduce code repetition --- src/graphics/Font.cpp | 2 + src/graphics/Font.h | 43 ++++++++++++++ src/graphics/Graphics.cpp | 90 ++++++++++-------------------- src/graphics/Graphics.h | 6 +- src/graphics/OpenGLGraphics.cpp | 2 +- src/graphics/RasterDrawMethods.inl | 46 ++++----------- 6 files changed, 88 insertions(+), 101 deletions(-) create mode 100644 src/graphics/Font.cpp create mode 100644 src/graphics/Font.h diff --git a/src/graphics/Font.cpp b/src/graphics/Font.cpp new file mode 100644 index 000000000..ee869789b --- /dev/null +++ b/src/graphics/Font.cpp @@ -0,0 +1,2 @@ +#define INCLUDE_FONTDATA +#include "font.h" diff --git a/src/graphics/Font.h b/src/graphics/Font.h new file mode 100644 index 000000000..1e29d4626 --- /dev/null +++ b/src/graphics/Font.h @@ -0,0 +1,43 @@ +#include + +#include "common/String.h" +#include "font.h" + +class FontReader +{ + unsigned char *pointer; + int width; + int pixels; + int data; + + inline FontReader(unsigned char *_pointer): + pointer(_pointer + 1), + width(*_pointer), + pixels(0), + data(0) + {} + +public: + inline FontReader(String::value_type ch): + FontReader(ch <= 0xFF ? &font_data[font_ptrs[ch]] : &font_data[0]) + { + } + + inline int GetWidth() const + { + return width; + } + + inline int NextPixel() + { + if(!pixels) + { + data = *(pointer++); + pixels = 4; + } + int old = data; + pixels--; + data >>= 2; + return old & 0x3; + } +}; diff --git a/src/graphics/Graphics.cpp b/src/graphics/Graphics.cpp index 3e86925ea..3a187021c 100644 --- a/src/graphics/Graphics.cpp +++ b/src/graphics/Graphics.cpp @@ -5,8 +5,7 @@ #include "Config.h" #include "Misc.h" #include "Graphics.h" -#define INCLUDE_FONTDATA -#include "font.h" +#include "Font.h" #ifdef HIGH_QUALITY_RESAMPLE #include "resampler/resampler.h" #endif @@ -86,64 +85,31 @@ void VideoBuffer::Resize(int width, int height, bool resample, bool fixedRatio) } } -int VideoBuffer::SetCharacter(int x, int y, int c, int r, int g, int b, int a) +int VideoBuffer::SetCharacter(int x, int y, String::value_type c, int r, int g, int b, int a) { - int i, j, w, bn = 0, ba = 0; - unsigned char *rp = font_data + font_ptrs[c]; - w = *(rp++); - for (j=-2; j>= 2; - bn -= 2; - } - return x + w; + FontReader reader(c); + for (int j = -2; j < FONT_H - 2; j++) + for (int i = 0; i < reader.GetWidth(); i++) + SetPixel(x + i, y + j, r, g, b, reader.NextPixel() * a / 3); + return x + reader.GetWidth(); } -int VideoBuffer::BlendCharacter(int x, int y, int c, int r, int g, int b, int a) +int VideoBuffer::BlendCharacter(int x, int y, String::value_type c, int r, int g, int b, int a) { - int i, j, w, bn = 0, ba = 0; - unsigned char *rp = font_data + font_ptrs[c]; - w = *(rp++); - for (j=-2; j>= 2; - bn -= 2; - } - return x + w; + FontReader reader(c); + for (int j = -2; j < FONT_H - 2; j++) + for (int i = 0; i < reader.GetWidth(); i++) + BlendPixel(x + i, y + j, r, g, b, reader.NextPixel() * a / 3); + return x + reader.GetWidth(); } -int VideoBuffer::AddCharacter(int x, int y, int c, int r, int g, int b, int a) +int VideoBuffer::AddCharacter(int x, int y, String::value_type c, int r, int g, int b, int a) { - int i, j, w, bn = 0, ba = 0; - unsigned char *rp = font_data + font_ptrs[c]; - w = *(rp++); - for (j=-2; j>= 2; - bn -= 2; - } - return x + w; + FontReader reader(c); + for (int j = -2; j < FONT_H - 2; j++) + for (int i = 0; i < reader.GetWidth(); i++) + AddPixel(x + i, y + j, r, g, b, reader.NextPixel() * a / 3); + return x + reader.GetWidth(); } VideoBuffer::~VideoBuffer() @@ -582,14 +548,14 @@ int Graphics::textwidth(String str) s+=3; continue; } - x += font_data[font_ptrs[*s]]; + x += FontReader(*s).GetWidth(); } return x-1; } int Graphics::CharWidth(String::value_type c) { - return font_data[font_ptrs[(int)c]]; + return FontReader(c).GetWidth(); } int Graphics::textnwidth(String str, int n) @@ -610,7 +576,7 @@ int Graphics::textnwidth(String str, int n) s+=3; continue; } - x += font_data[font_ptrs[*s]]; + x += FontReader(*s).GetWidth(); n--; } return x-1; @@ -638,7 +604,7 @@ void Graphics::textnpos(String str, int n, int w, int *cx, int *cy) if (!n) { break; } - x += font_data[font_ptrs[*s]]; + x += FontReader(*s).GetWidth(); if (x>=w) { x = 0; @@ -668,7 +634,7 @@ int Graphics::textwidthx(String str, int w) s+=3; continue; } - cw = font_data[font_ptrs[*s]]; + cw = FontReader(*s).GetWidth(); if (x+(cw/2) >= w) break; x += cw; @@ -702,7 +668,7 @@ int Graphics::PositionAtCharIndex(String str, int charIndex, int & positionX, in charIndex-=4; continue; } - x += font_data[font_ptrs[*s]]; + x += FontReader(*s).GetWidth(); charIndex--; } positionX = x; @@ -732,7 +698,7 @@ int Graphics::CharIndexAtPosition(String str, int positionX, int positionY) charIndex+=4; continue; } - cw = font_data[font_ptrs[*s]]; + cw = FontReader(*s).GetWidth(); if ((x+(cw/2) >= positionX && y+FONT_H >= positionY) || y > positionY) break; x += cw; @@ -778,7 +744,7 @@ int Graphics::textwrapheight(String str, int width) } else { - cw = font_data[font_ptrs[*s]]; + cw = FontReader(*s).GetWidth(); if (x+cw>=width) { x = 0; @@ -821,7 +787,7 @@ void Graphics::textsize(String str, int & width, int & height) } else { - cWidth += font_data[font_ptrs[*s]]; + cWidth += FontReader(*s).GetWidth(); if(cWidth>lWidth) lWidth = cWidth; } diff --git a/src/graphics/Graphics.h b/src/graphics/Graphics.h index aa961dd12..3ed16ece5 100644 --- a/src/graphics/Graphics.h +++ b/src/graphics/Graphics.h @@ -84,9 +84,9 @@ public: b = 255; Buffer[y*(Width)+x] = PIXRGB(r,g,b); } - int SetCharacter(int x, int y, int c, int r, int g, int b, int a); - int BlendCharacter(int x, int y, int c, int r, int g, int b, int a); - int AddCharacter(int x, int y, int c, int r, int g, int b, int a); + int SetCharacter(int x, int y, String::value_type c, int r, int g, int b, int a); + int BlendCharacter(int x, int y, String::value_type c, int r, int g, int b, int a); + int AddCharacter(int x, int y, String::value_type c, int r, int g, int b, int a); ~VideoBuffer(); }; diff --git a/src/graphics/OpenGLGraphics.cpp b/src/graphics/OpenGLGraphics.cpp index f951b0dac..2651eb941 100644 --- a/src/graphics/OpenGLGraphics.cpp +++ b/src/graphics/OpenGLGraphics.cpp @@ -1,5 +1,5 @@ #include "Graphics.h" -#include "font.h" +#include "Font.h" #include "common/tpt-thread.h" #ifdef OGLI diff --git a/src/graphics/RasterDrawMethods.inl b/src/graphics/RasterDrawMethods.inl index 4bb1469bc..bd565f367 100644 --- a/src/graphics/RasterDrawMethods.inl +++ b/src/graphics/RasterDrawMethods.inl @@ -1,5 +1,5 @@ -#include "font.h" #include +#include "Font.h" int PIXELMETHODS_CLASS::drawtext_outline(int x, int y, String s, int r, int g, int b, int a) { @@ -105,44 +105,20 @@ int PIXELMETHODS_CLASS::drawtext(int x, int y, String str, int r, int g, int b, int PIXELMETHODS_CLASS::drawchar(int x, int y, String::value_type c, int r, int g, int b, int a) { - int i, j, w, bn = 0, ba = 0; - unsigned char *rp = font_data + font_ptrs[c]; - w = *(rp++); - for (j=-2; j>= 2; - bn -= 2; - } - return x + w; + FontReader reader(c); + for (int j = -2; j < FONT_H - 2; j++) + for (int i = 0; i < reader.GetWidth(); i++) + blendpixel(x + i, y + j, r, g, b, reader.NextPixel() * a / 3); + return x + reader.GetWidth(); } int PIXELMETHODS_CLASS::addchar(int x, int y, String::value_type c, int r, int g, int b, int a) { - int i, j, w, bn = 0, ba = 0; - unsigned char *rp = font_data + font_ptrs[c]; - w = *(rp++); - for (j=-2; j>= 2; - bn -= 2; - } - return x + w; + FontReader reader(c); + for (int j = -2; j < FONT_H - 2; j++) + for (int i = 0; i < reader.GetWidth(); i++) + addpixel(x + i, y + j, r, g, b, reader.NextPixel() * a / 3); + return x + reader.GetWidth(); } TPT_INLINE void PIXELMETHODS_CLASS::xor_pixel(int x, int y) From b8c5e94a41a21d6d6a801aca3ba049423f4addfb Mon Sep 17 00:00:00 2001 From: mniip Date: Tue, 1 May 2018 05:57:03 +0300 Subject: [PATCH 07/27] Add blocks/gaps to the font format --- data/font.h | 16 +- src/graphics/Font.h | 18 +- src/gui/font/FontEditor.cpp | 334 ++++++++++++++++++++++++------------ src/gui/font/FontEditor.h | 27 +-- 4 files changed, 274 insertions(+), 121 deletions(-) diff --git a/data/font.h b/data/font.h index b2ead7614..084d64701 100644 --- a/data/font.h +++ b/data/font.h @@ -260,9 +260,10 @@ unsigned char font_data[] = { 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, 0x06, 0x00, 0x00, 0x00, 0x74, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0xDC, 0xC0, 0x0C, 0x99, 0x31, 0x30, 0x89, 0x41, 0x07, + 0x0A, 0x00, 0x00, 0x00, 0x74, 0x00, 0xD0, 0x1F, 0x40, 0x8B, 0x07, 0x3D, 0xF3, 0xF1, 0x3F, 0x3F, 0xFD, 0xF8, 0x41, 0xFF, 0x07, 0xD0, 0x1C, 0x00, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; -short font_ptrs[] = { +unsigned short font_ptrs[] = { 0x0000, 0x0010, 0x0020, 0x0030, 0x0040, 0x0050, 0x0060, 0x0070, 0x0080, 0x0090, 0x00A0, 0x00B0, 0x00C0, 0x00D0, 0x00E0, 0x00F0, 0x0100, 0x0110, 0x0120, 0x0130, 0x0140, 0x0150, 0x0160, 0x0170, @@ -295,14 +296,23 @@ short font_ptrs[] = { 0x1396, 0x13A9, 0x13BC, 0x13CF, 0x13E2, 0x13F5, 0x1408, 0x141B, 0x142E, 0x1441, 0x1454, 0x1467, 0x147A, 0x148D, 0x14A0, 0x14B3, 0x14C6, 0x14D9, 0x14EC, 0x14FF, 0x1512, 0x1525, 0x1538, 0x154B, + + 0x155E, +}; +unsigned int font_ranges[][2] = { + { 0x000000, 0x0000FF }, + { 0x00FFFD, 0x00FFFD }, + { 0, 0 }, }; #else extern unsigned char font_data[]; -extern short font_ptrs[]; +extern unsigned short font_ptrs[]; +extern unsigned int font_ranges[][2]; #endif #else extern unsigned char *font_data; -extern short *font_ptrs; +extern unsigned short *font_ptrs; +extern unsigned int (*font_ranges)[2]; #endif #endif diff --git a/src/graphics/Font.h b/src/graphics/Font.h index 1e29d4626..d7640cc9c 100644 --- a/src/graphics/Font.h +++ b/src/graphics/Font.h @@ -17,9 +17,25 @@ class FontReader data(0) {} + static inline unsigned char *lookupChar(String::value_type ch) + { + size_t offset = 0; + for(int i = 0; font_ranges[i][1]; i++) + if(font_ranges[i][0] > ch) + break; + else if(font_ranges[i][1] >= ch) + return &font_data[font_ptrs[offset + (ch - font_ranges[i][0])]]; + else + offset += font_ranges[i][1] - font_ranges[i][0] + 1; + if(ch == 0xFFFD) + return &font_data[0]; + else + return lookupChar(0xFFFD); + } + public: inline FontReader(String::value_type ch): - FontReader(ch <= 0xFF ? &font_data[font_ptrs[ch]] : &font_data[0]) + FontReader(lookupChar(ch)) { } diff --git a/src/gui/font/FontEditor.cpp b/src/gui/font/FontEditor.cpp index 03c74a7e7..37e0eb51e 100644 --- a/src/gui/font/FontEditor.cpp +++ b/src/gui/font/FontEditor.cpp @@ -16,7 +16,8 @@ #ifdef FONTEDITOR unsigned char *font_data; -short *font_ptrs; +unsigned short *font_ptrs; +unsigned int (*font_ranges)[2]; void FontEditor::ReadHeader(ByteString header) { @@ -47,15 +48,15 @@ void FontEditor::ReadHeader(ByteString header) } while(!file.fail()); file.clear(); - + size_t endFontData = file.tellg(); - + while(word != "font_ptrs[]") file >> word; file >> word >> word; - + size_t startFontPtrs = file.tellg(); - + fontPtrs.clear(); do { @@ -69,9 +70,30 @@ void FontEditor::ReadHeader(ByteString header) } while(!file.fail()); file.clear(); - + size_t endFontPtrs = file.tellg(); + while(word != "font_ranges[][2]") + file >> word; + file >> word >> word; + + size_t startFontRanges = file.tellg(); + + fontRanges.clear(); + while(true) + { + unsigned int value1, value2; + file >> word >> std::hex >> value1 >> word >> std::hex >> value2 >> word; + if(file.fail()) + break; + fontRanges.push_back({value1, value2}); + if(!value2) + break; + } + file.clear(); + + size_t endFontRanges = file.tellg(); + do { file >> word; @@ -88,17 +110,17 @@ void FontEditor::ReadHeader(ByteString header) afterFontData = ByteString(startFontPtrs - endFontData, 0); file.read(&afterFontData[0], startFontPtrs - endFontData); - file.seekg(endFontData); - afterFontData = ByteString(startFontPtrs - endFontData, 0); - file.read(&afterFontData[0], startFontPtrs - endFontData); - file.seekg(endFontPtrs); - afterFontPtrs = ByteString(eof - endFontPtrs, 0); - file.read(&afterFontPtrs[0], eof - endFontPtrs); + afterFontPtrs = ByteString(startFontRanges - endFontPtrs, 0); + file.read(&afterFontPtrs[0], startFontRanges - endFontPtrs); + + file.seekg(endFontRanges); + afterFontRanges = ByteString(eof - endFontRanges, 0); + file.read(&afterFontRanges[0], eof - endFontRanges); file.close(); } -void FontEditor::WriteHeader(ByteString header, std::vector const &fontData, std::vector const &fontPtrs) +void FontEditor::WriteHeader(ByteString header, std::vector const &fontData, std::vector const &fontPtrs, std::vector > const &fontRanges) { std::fstream file; file.open(header, std::ios_base::out | std::ios_base::trunc); @@ -107,84 +129,128 @@ void FontEditor::WriteHeader(ByteString header, std::vector const file << std::setfill('0') << std::hex << std::uppercase; file << beforeFontData << std::endl; - for(int ch = 0; ch < 256; ch++) + + size_t pos = 0; + size_t ptrpos = 0; + while(pos < fontData.size()) { - file << " " << "0x" << std::setw(2) << (unsigned int)fontData[fontPtrs[ch]] << ", "; - for(int i = fontPtrs[ch] + 1; i < (int)(ch == (int)fontPtrs.size() - 1 ? fontData.size() : fontPtrs[ch + 1]); i++) - file << " " << "0x" << std::setw(2) << (unsigned int)fontData[i] << ","; + file << " " << "0x" << std::setw(2) << (unsigned int)fontData[pos] << ", "; + for(pos++; pos < fontData.size() && (ptrpos == fontPtrs.size() - 1 || pos < (size_t)fontPtrs[ptrpos + 1]); pos++) + file << " " << "0x" << std::setw(2) << (unsigned int)fontData[pos] << ","; file << std::endl; + ptrpos++; } file << afterFontData; - for(int ch = 0; ch < 256; ch++) + + pos = 0; + for(size_t i = 0; pos < fontPtrs.size() && fontRanges[i][1]; i++) { - if(!(ch & 7)) - file << std::endl << " "; - else - file << " "; - file << "0x" << std::setw(4) << (unsigned int)fontPtrs[ch] << ","; + bool first = true; + for(String::value_type ch = fontRanges[i][0]; ch <= fontRanges[i][1]; ch++) + { + if(!(ch & 0x7) || first) + file << std::endl << " "; + else + file << " "; + first = false; + file << "0x" << std::setw(4) << (unsigned int)fontPtrs[pos++] << ","; + } + file << std::endl; } - file << std::endl << afterFontPtrs; + file << afterFontPtrs << std::endl; + for(size_t i = 0; i < fontRanges.size() - 1; i++) + file << " { 0x" << std::setw(6) << (unsigned int)fontRanges[i][0] << ", 0x" << std::setw(6) << (unsigned int)fontRanges[i][1] << " }," << std::endl; + file << " { 0, 0 },"; + file << afterFontRanges; file.close(); } void FontEditor::UnpackData( - std::array &fontWidths, - std::array, FONT_H>, 256> &fontPixels, + std::map &fontWidths, + std::map, FONT_H> > &fontPixels, std::vector const &fontData, - std::vector const &fontPtrs) + std::vector const &fontPtrs, + std::vector > const &fontRanges) { - for(int ch = 0; ch < 256; ch++) - { - unsigned char const *data = &fontData[fontPtrs[ch]]; - int bits = 0; - int pixels = 0; - int width = fontWidths[ch] = *(data++); - for(int j = 0; j < FONT_H; j++) - for(int i = 0; i < width; i++) - { - if(!bits) + fontWidths.clear(); + fontPixels.clear(); + size_t pos = 0; + for(size_t range = 0; fontRanges[range][1]; range++) + for(String::value_type ch = fontRanges[range][0]; ch <= fontRanges[range][1]; ch++) + { + unsigned char const *pointer = &fontData[fontPtrs[pos]]; + int width = fontWidths[ch] = *(pointer++); + int pixels = 0; + int data = 0; + for(int j = 0; j < FONT_H; j++) + for(int i = 0; i < width; i++) { - pixels = *(data++); - bits = 8; + if(!pixels) + { + data = *(pointer++); + pixels = 4; + } + fontPixels[ch][j][i] = data & 3; + data >>= 2; + pixels--; } - fontPixels[ch][j][i] = pixels & 3; - pixels >>= 2; - bits -= 2; - } - } + pos++; + } } void FontEditor::PackData( - std::array const &fontWidths, - std::array, FONT_H>, 256> const &fontPixels, + std::map const &fontWidths, + std::map, FONT_H> > const &fontPixels, std::vector &fontData, - std::vector &fontPtrs) + std::vector &fontPtrs, + std::vector > &fontRanges) { - fontPtrs.clear(); fontData.clear(); - for(int ch = 0; ch < 256; ch++) + fontPtrs.clear(); + fontRanges.clear(); + bool first = true; + String::value_type rangeStart; + String::value_type prev; + for(std::map::const_iterator it = fontWidths.begin(); it != fontWidths.end(); it++) { - fontPtrs.push_back(fontData.size()); - fontData.push_back(fontWidths[ch]); - - int bits = 0; - int pixels = 0; - for(int j = 0; j < FONT_H; j++) - for(int i = 0; i < fontWidths[ch]; i++) + String::value_type ch = it->first; + if(first) + { + rangeStart = ch; + first = false; + } + else + if(ch != prev + 1) { - if(bits == 8) - { - fontData.push_back(pixels); - bits = 0; - pixels = 0; - } - pixels >>= 2; - pixels |= fontPixels[ch][j][i] << 6; - bits += 2; + fontRanges.push_back({rangeStart, prev}); + rangeStart = ch; } - if(bits) - fontData.push_back(pixels); + + fontPtrs.push_back(fontData.size()); + fontData.push_back(it->second); + + int pixels = 0; + int data = 0; + for(int j = 0; j < FONT_H; j++) + for(int i = 0; i < it->second; i++) + { + if(pixels == 4) + { + fontData.push_back(data); + pixels = 0; + data = 0; + } + data >>= 2; + data |= fontPixels.at(ch)[j][i] << 6; + pixels++; + } + if(pixels) + fontData.push_back(data); + + prev = ch; } + fontRanges.push_back({rangeStart, prev}); + fontRanges.push_back({0, 0}); } #define FONT_SCALE 16 @@ -197,9 +263,10 @@ FontEditor::FontEditor(ByteString _header): rulers(1) { ReadHeader(header); - UnpackData(fontWidths, fontPixels, fontData, fontPtrs); + UnpackData(fontWidths, fontPixels, fontData, fontPtrs, fontRanges); font_data = fontData.data(); font_ptrs = fontPtrs.data(); + font_ranges = (unsigned int (*)[2])fontRanges.data(); int baseline = 8 + FONT_H * FONT_SCALE + 4 + FONT_H + 4 + 1; int currentX = 1; @@ -227,9 +294,9 @@ FontEditor::FontEditor(ByteString _header): void TextChangedCallback(ui::Textbox *) { unsigned int number; - String::Stream ss(v->currentCharTextbox->GetText()); + ByteString::Stream ss(v->currentCharTextbox->GetText().ToUtf8()); ss >> std::hex >> number; - if(number < 256) + if(number <= 0x10FFFF) v->currentChar = number; } }; @@ -284,6 +351,45 @@ FontEditor::FontEditor(ByteString _header): grow->SetActionCallback(new GrowCharAction(this)); AddComponent(grow); + class AddCharAction : public ui::ButtonAction + { + FontEditor *v; + public: + AddCharAction(FontEditor *_v): v(_v) {} + void ActionCallback(ui::Button *) + { + if(v->fontWidths.find(v->currentChar) == v->fontWidths.end()) + { + v->savedButton->SetToggleState(false); + v->fontWidths[v->currentChar] = 5; + v->fontPixels[v->currentChar]; + } + } + }; + ui::Button *add = new ui::Button(ui::Point(currentX, baseline), ui::Point(36, 17), "Add"); + currentX += 37; + add->SetActionCallback(new AddCharAction(this)); + AddComponent(add); + + class RemoveCharAction : public ui::ButtonAction + { + FontEditor *v; + public: + RemoveCharAction(FontEditor *_v): v(_v) {} + void ActionCallback(ui::Button *) + { + if(v->fontWidths.find(v->currentChar) != v->fontWidths.end()) + { + v->savedButton->SetToggleState(false); + v->fontWidths.erase(v->currentChar); + v->fontPixels.erase(v->currentChar); + } + } + }; + ui::Button *remove = new ui::Button(ui::Point(currentX, baseline), ui::Point(36, 17), "Remove"); + currentX += 37; + remove->SetActionCallback(new RemoveCharAction(this)); + AddComponent(remove); class ToggleAction : public ui::ButtonAction { @@ -295,6 +401,7 @@ FontEditor::FontEditor(ByteString _header): toggle = button->GetToggleState(); } }; + ui::Button *showGrid = new ui::Button(ui::Point(currentX, baseline), ui::Point(32, 17), "Grid"); currentX += 33; showGrid->SetTogglable(true); @@ -319,7 +426,7 @@ FontEditor::FontEditor(ByteString _header): ColorComponentAction(int &_color): color(_color) {} void TextChangedCallback(ui::Textbox *box) { - String::Stream ss(box->GetText()); + ByteString::Stream ss(box->GetText().ToUtf8()); ss >> color; } }; @@ -384,7 +491,7 @@ FontEditor::FontEditor(ByteString _header): PreviewAction(FontEditor *_v): v(_v) {} void TextChangedCallback(ui::Textbox *box) { - String::Stream ss(box->GetText()); + ByteString::Stream ss(box->GetText().ToUtf8()); // ByteString::Stream for now String text; while(!ss.eof()) { @@ -431,41 +538,54 @@ void FontEditor::OnDraw() { Graphics *g = GetGraphics(); - int areaWidth = 8 + fontWidths[currentChar] * FONT_SCALE + 8; - g->fillrect(0, 0, areaWidth, 8 + FONT_H * FONT_SCALE + 4 + FONT_H + 4, bgR, bgG, bgB, 255); - for(int j = 0; j < FONT_H; j++) - for(int i = 0; i < fontWidths[currentChar]; i++) - g->fillrect(8 + i * FONT_SCALE, 8 + j * FONT_SCALE, FONT_SCALE - grid, FONT_SCALE - grid, fgR, fgG, fgB, fontPixels[currentChar][j][i] * 255 / 3); - - for(int j = 0; j < FONT_H; j++) - for(int i = 0; i < fontWidths[currentChar]; i++) - g->blendpixel(8 + i, 8 + FONT_H * FONT_SCALE + 4 + j, fgR, fgG, fgB, fontPixels[currentChar][j][i] * 255 / 3); - - - if(rulers) + if(fontWidths.find(currentChar) != fontWidths.end()) { - g->draw_line(0, 7 + 0 * FONT_SCALE , areaWidth - 1, 7 + 0 * FONT_SCALE, 128, 128, 128, 255); - g->draw_line(0, 7 + 2 * FONT_SCALE , areaWidth - 1, 7 + 2 * FONT_SCALE, 128, 128, 128, 255); - g->draw_line(0, 7 + 4 * FONT_SCALE , areaWidth - 1, 7 + 4 * FONT_SCALE, 128, 128, 128, 255); - g->draw_line(0, 7 + 9 * FONT_SCALE , areaWidth - 1, 7 + 9 * FONT_SCALE, 128, 128, 128, 255); - g->draw_line(0, 7 + 12 * FONT_SCALE , areaWidth - 1, 7 + 12 * FONT_SCALE, 128, 128, 128, 255); + int width = fontWidths[currentChar]; + std::array, FONT_H> const &pixels = fontPixels[currentChar]; - g->draw_line(7, 8, 7, 7 + FONT_H * FONT_SCALE, 128, 128, 128, 255); - g->draw_line(7 + fontWidths[currentChar] * FONT_SCALE, 8, 7 + fontWidths[currentChar] * FONT_SCALE, 7 + FONT_H * FONT_SCALE, 128, 128, 128, 255); + int areaWidth = 8 + width * FONT_SCALE + 8; + g->fillrect(0, 0, areaWidth, 8 + FONT_H * FONT_SCALE + 4 + FONT_H + 4, bgR, bgG, bgB, 255); + for(int j = 0; j < FONT_H; j++) + for(int i = 0; i < width; i++) + g->fillrect(8 + i * FONT_SCALE, 8 + j * FONT_SCALE, FONT_SCALE - grid, FONT_SCALE - grid, fgR, fgG, fgB, pixels[j][i] * 255 / 3); + + for(int j = 0; j < FONT_H; j++) + for(int i = 0; i < width; i++) + g->blendpixel(8 + i, 8 + FONT_H * FONT_SCALE + 4 + j, fgR, fgG, fgB, pixels[j][i] * 255 / 3); + + + if(rulers) + { + g->draw_line(0, 7 + 0 * FONT_SCALE , areaWidth - 1, 7 + 0 * FONT_SCALE, 128, 128, 128, 255); + g->draw_line(0, 7 + 2 * FONT_SCALE , areaWidth - 1, 7 + 2 * FONT_SCALE, 128, 128, 128, 255); + g->draw_line(0, 7 + 4 * FONT_SCALE , areaWidth - 1, 7 + 4 * FONT_SCALE, 128, 128, 128, 255); + g->draw_line(0, 7 + 9 * FONT_SCALE , areaWidth - 1, 7 + 9 * FONT_SCALE, 128, 128, 128, 255); + g->draw_line(0, 7 + 12 * FONT_SCALE , areaWidth - 1, 7 + 12 * FONT_SCALE, 128, 128, 128, 255); + + g->draw_line(7, 8, 7, 7 + FONT_H * FONT_SCALE, 128, 128, 128, 255); + g->draw_line(7 + width * FONT_SCALE, 8, 7 + width * FONT_SCALE, 7 + FONT_H * FONT_SCALE, 128, 128, 128, 255); + } + } + else + { + g->drawtext(8, 8, "No character", 255, 0, 0, 255); } } void FontEditor::OnMouseDown(int x, int y, unsigned button) { - x = (x - 8) / FONT_SCALE; - y = (y - 8) / FONT_SCALE; - if(x >= 0 && y >= 0 && x < fontWidths[currentChar] && y < FONT_H) + if(fontWidths.find(currentChar) != fontWidths.end()) { - if(button == SDL_BUTTON_LEFT) - fontPixels[currentChar][y][x] = (fontPixels[currentChar][y][x] + 1) % 4; - else - fontPixels[currentChar][y][x] = (fontPixels[currentChar][y][x] + 3) % 4; - savedButton->SetToggleState(false); + x = (x - 8) / FONT_SCALE; + y = (y - 8) / FONT_SCALE; + if(x >= 0 && y >= 0 && x < fontWidths[currentChar] && y < FONT_H) + { + if(button == SDL_BUTTON_LEFT) + fontPixels[currentChar][y][x] = (fontPixels[currentChar][y][x] + 1) % 4; + else + fontPixels[currentChar][y][x] = (fontPixels[currentChar][y][x] + 3) % 4; + savedButton->SetToggleState(false); + } } } @@ -492,9 +612,9 @@ void FontEditor::OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bo void FontEditor::UpdateCharNumber() { - String::Stream ss; + ByteString::Stream ss; ss << std::hex << currentChar; - currentCharTextbox->SetText(ss.str()); + currentCharTextbox->SetText(ByteString(ss.str()).FromUtf8()); } void FontEditor::PrevChar() @@ -506,7 +626,7 @@ void FontEditor::PrevChar() void FontEditor::NextChar() { - if(currentChar < 255) + if(currentChar <= 0x10FFFF) currentChar++; UpdateCharNumber(); } @@ -527,17 +647,19 @@ void FontEditor::GrowChar() void FontEditor::Render() { - PackData(fontWidths, fontPixels, fontData, fontPtrs); + PackData(fontWidths, fontPixels, fontData, fontPtrs, fontRanges); font_data = fontData.data(); font_ptrs = fontPtrs.data(); + font_ranges = (unsigned int (*)[2])fontRanges.data(); } void FontEditor::Save() { std::vector tmpFontData; - std::vector tmpFontPtrs; - PackData(fontWidths, fontPixels, tmpFontData, tmpFontPtrs); - WriteHeader(header, tmpFontData, tmpFontPtrs); + std::vector tmpFontPtrs; + std::vector > tmpFontRanges; + PackData(fontWidths, fontPixels, tmpFontData, tmpFontPtrs, tmpFontRanges); + WriteHeader(header, tmpFontData, tmpFontPtrs, tmpFontRanges); savedButton->SetToggleState(true); } #endif diff --git a/src/gui/font/FontEditor.h b/src/gui/font/FontEditor.h index 5353da856..833966ae6 100644 --- a/src/gui/font/FontEditor.h +++ b/src/gui/font/FontEditor.h @@ -3,6 +3,7 @@ #include #include +#include #include "font.h" @@ -14,34 +15,38 @@ class FontEditor: public ui::Window { private: ByteString header; - std::array fontWidths; - std::array, FONT_H>, 256> fontPixels; + std::map fontWidths; + std::map, FONT_H> > fontPixels; std::vector fontData; - std::vector fontPtrs; + std::vector fontPtrs; + std::vector > fontRanges; ByteString beforeFontData; ByteString afterFontData; ByteString afterFontPtrs; + ByteString afterFontRanges; void ReadHeader(ByteString header); - void WriteHeader(ByteString header, std::vector const &fontData, std::vector const &fontPtrs); + void WriteHeader(ByteString header, std::vector const &fontData, std::vector const &fontPtrs, std::vector > const &fontRanges); static void PackData( - std::array const &fontWidths, - std::array, FONT_H>, 256> const &fontPixels, + std::map const &fontWidths, + std::map, FONT_H> > const &fontPixels, std::vector &fontData, - std::vector &fontPtrs); + std::vector &fontPtrs, + std::vector > &fontRanges); static void UnpackData( - std::array &fontWidths, - std::array, FONT_H>, 256> &fontPixels, + std::map &fontWidths, + std::map, FONT_H> > &fontPixels, std::vector const &fontData, - std::vector const &fontPtrs); + std::vector const &fontPtrs, + std::vector > const &fontRanges); ui::Textbox *currentCharTextbox; ui::Button *savedButton; ui::Label *outputPreview; - int currentChar; + String::value_type currentChar; int fgR, fgG, fgB; int bgR, bgG, bgB; From 833383b121d54e3c43bd17778496e9a576806c28 Mon Sep 17 00:00:00 2001 From: mniip Date: Tue, 1 May 2018 07:01:56 +0300 Subject: [PATCH 08/27] Move TPT's icons to the (real) Private Use Area of the unicode --- data/font.h | 4 +- src/graphics/Graphics.cpp | 178 +++++++++++----------- src/graphics/Renderer.cpp | 6 +- src/gui/font/FontEditor.cpp | 4 +- src/gui/game/GameModel.cpp | 2 +- src/gui/game/GameView.cpp | 6 +- src/gui/game/SampleTool.cpp | 2 +- src/gui/game/SignTool.cpp | 12 +- src/gui/game/ToolButton.cpp | 2 +- src/gui/interface/SaveButton.cpp | 20 +-- src/gui/interface/Textbox.cpp | 8 +- src/gui/localbrowser/LocalBrowserView.cpp | 4 +- src/gui/search/SearchView.cpp | 4 +- src/simulation/MenuSection.h | 2 +- src/simulation/SimulationData.cpp | 36 ++--- 15 files changed, 146 insertions(+), 144 deletions(-) diff --git a/data/font.h b/data/font.h index 084d64701..56e3024d3 100644 --- a/data/font.h +++ b/data/font.h @@ -280,6 +280,7 @@ unsigned short font_ptrs[] = { 0x06FE, 0x070E, 0x071B, 0x0728, 0x0738, 0x0745, 0x0758, 0x0768, 0x0778, 0x0788, 0x0798, 0x07A5, 0x07B5, 0x07C2, 0x07D2, 0x07E2, 0x07F5, 0x0805, 0x0815, 0x0825, 0x0832, 0x0839, 0x0846, 0x0859, + 0x0866, 0x087F, 0x08A4, 0x08C9, 0x08E8, 0x090D, 0x092C, 0x094B, 0x096A, 0x0989, 0x09A8, 0x09C7, 0x09E6, 0x0A0B, 0x0A1E, 0x0A3D, 0x0A5C, 0x0A7B, 0x0A9A, 0x0AB3, 0x0AD5, 0x0AF7, 0x0B1C, 0x0B41, @@ -300,7 +301,8 @@ unsigned short font_ptrs[] = { 0x155E, }; unsigned int font_ranges[][2] = { - { 0x000000, 0x0000FF }, + { 0x000000, 0x00007F }, + { 0x00E000, 0x00E07F }, { 0x00FFFD, 0x00FFFD }, { 0, 0 }, }; diff --git a/src/graphics/Graphics.cpp b/src/graphics/Graphics.cpp index 3a187021c..12b0bec29 100644 --- a/src/graphics/Graphics.cpp +++ b/src/graphics/Graphics.cpp @@ -803,262 +803,262 @@ void Graphics::draw_icon(int x, int y, Icon icon, unsigned char alpha, bool inve { case IconOpen: if(invert) - drawchar(x, y, 0x81, 0, 0, 0, alpha); + drawchar(x, y, 0xE001, 0, 0, 0, alpha); else - drawchar(x, y, 0x81, 255, 255, 255, alpha); + drawchar(x, y, 0xE001, 255, 255, 255, alpha); break; case IconReload: if(invert) - drawchar(x, y, 0x91, 0, 0, 0, alpha); + drawchar(x, y, 0xE011, 0, 0, 0, alpha); else - drawchar(x, y, 0x91, 255, 255, 255, alpha); + drawchar(x, y, 0xE011, 255, 255, 255, alpha); break; case IconSave: if(invert) - drawchar(x, y, 0x82, 0, 0, 0, alpha); + drawchar(x, y, 0xE002, 0, 0, 0, alpha); else - drawchar(x, y, 0x82, 255, 255, 255, alpha); + drawchar(x, y, 0xE002, 255, 255, 255, alpha); break; case IconVoteUp: if(invert) { - drawchar(x-11, y+1, 0xCB, 0, 100, 0, alpha); + drawchar(x-11, y+1, 0xE04B, 0, 100, 0, alpha); drawtext(x+2, y+1, "Vote", 0, 100, 0, alpha); } else { - drawchar(x-11, y+1, 0xCB, 0, 187, 18, alpha); + drawchar(x-11, y+1, 0xE04B, 0, 187, 18, alpha); drawtext(x+2, y+1, "Vote", 0, 187, 18, alpha); } break; case IconVoteDown: if(invert) - drawchar(x, y, 0xCA, 100, 10, 0, alpha); + drawchar(x, y, 0xE04A, 100, 10, 0, alpha); else - drawchar(x, y, 0xCA, 187, 40, 0, alpha); + drawchar(x, y, 0xE04A, 187, 40, 0, alpha); break; case IconTag: if(invert) - drawchar(x, y, 0x83, 0, 0, 0, alpha); + drawchar(x, y, 0xE003, 0, 0, 0, alpha); else - drawchar(x, y, 0x83, 255, 255, 255, alpha); + drawchar(x, y, 0xE003, 255, 255, 255, alpha); break; case IconNew: if(invert) - drawchar(x, y, 0x92, 0, 0, 0, alpha); + drawchar(x, y, 0xE012, 0, 0, 0, alpha); else - drawchar(x, y, 0x92, 255, 255, 255, alpha); + drawchar(x, y, 0xE012, 255, 255, 255, alpha); break; case IconLogin: if(invert) - drawchar(x, y+1, 0x84, 0, 0, 0, alpha); + drawchar(x, y+1, 0xE004, 0, 0, 0, alpha); else - drawchar(x, y+1, 0x84, 255, 255, 255, alpha); + drawchar(x, y+1, 0xE004, 255, 255, 255, alpha); break; case IconSimulationSettings: if(invert) - drawchar(x, y+1, 0xCF, 0, 0, 0, alpha); + drawchar(x, y+1, 0xE04F, 0, 0, 0, alpha); else - drawchar(x, y+1, 0xCF, 255, 255, 255, alpha); + drawchar(x, y+1, 0xE04F, 255, 255, 255, alpha); break; case IconRenderSettings: if(invert) { - drawchar(x, y+1, 0xD8, 255, 0, 0, alpha); - drawchar(x, y+1, 0xD9, 0, 255, 0, alpha); - drawchar(x, y+1, 0xDA, 0, 0, 255, alpha); + drawchar(x, y+1, 0xE058, 255, 0, 0, alpha); + drawchar(x, y+1, 0xE059, 0, 255, 0, alpha); + drawchar(x, y+1, 0xE05A, 0, 0, 255, alpha); } else { - addchar(x, y+1, 0xD8, 255, 0, 0, alpha); - addchar(x, y+1, 0xD9, 0, 255, 0, alpha); - addchar(x, y+1, 0xDA, 0, 0, 255, alpha); + addchar(x, y+1, 0xE058, 255, 0, 0, alpha); + addchar(x, y+1, 0xE059, 0, 255, 0, alpha); + addchar(x, y+1, 0xE05A, 0, 0, 255, alpha); } break; case IconPause: if(invert) - drawchar(x, y, 0x90, 0, 0, 0, alpha); + drawchar(x, y, 0xE010, 0, 0, 0, alpha); else - drawchar(x, y, 0x90, 255, 255, 255, alpha); + drawchar(x, y, 0xE010, 255, 255, 255, alpha); break; case IconFavourite: if(invert) - drawchar(x, y, 0xCC, 100, 80, 32, alpha); + drawchar(x, y, 0xE04C, 100, 80, 32, alpha); else - drawchar(x, y, 0xCC, 192, 160, 64, alpha); + drawchar(x, y, 0xE04C, 192, 160, 64, alpha); break; case IconReport: if(invert) - drawchar(x, y, 0xE3, 140, 140, 0, alpha); + drawchar(x, y, 0xE063, 140, 140, 0, alpha); else - drawchar(x, y, 0xE3, 255, 255, 0, alpha); + drawchar(x, y, 0xE063, 255, 255, 0, alpha); break; case IconUsername: if(invert) { - drawchar(x, y, 0x8B, 32, 64, 128, alpha); - drawchar(x, y, 0x8A, 0, 0, 0, alpha); + drawchar(x, y, 0xE00B, 32, 64, 128, alpha); + drawchar(x, y, 0xE00A, 0, 0, 0, alpha); } else { - drawchar(x, y, 0x8B, 32, 64, 128, alpha); - drawchar(x, y, 0x8A, 255, 255, 255, alpha); + drawchar(x, y, 0xE00B, 32, 64, 128, alpha); + drawchar(x, y, 0xE00A, 255, 255, 255, alpha); } break; case IconPassword: if(invert) { - drawchar(x, y, 0x8C, 160, 144, 32, alpha); - drawchar(x, y, 0x84, 0, 0, 0, alpha); + drawchar(x, y, 0xE00C, 160, 144, 32, alpha); + drawchar(x, y, 0xE004, 0, 0, 0, alpha); } else { - drawchar(x, y, 0x8C, 160, 144, 32, alpha); - drawchar(x, y, 0x84, 255, 255, 255, alpha); + drawchar(x, y, 0xE00C, 160, 144, 32, alpha); + drawchar(x, y, 0xE004, 255, 255, 255, alpha); } break; case IconClose: if(invert) - drawchar(x, y, 0xAA, 20, 20, 20, alpha); + drawchar(x, y, 0xE02A, 20, 20, 20, alpha); else - drawchar(x, y, 0xAA, 230, 230, 230, alpha); + drawchar(x, y, 0xE02A, 230, 230, 230, alpha); break; case IconVoteSort: if (invert) { - drawchar(x, y, 0xA9, 44, 48, 32, alpha); - drawchar(x, y, 0xA8, 32, 44, 32, alpha); - drawchar(x, y, 0xA7, 128, 128, 128, alpha); + drawchar(x, y, 0xE029, 44, 48, 32, alpha); + drawchar(x, y, 0xE028, 32, 44, 32, alpha); + drawchar(x, y, 0xE027, 128, 128, 128, alpha); } else { - drawchar(x, y, 0xA9, 144, 48, 32, alpha); - drawchar(x, y, 0xA8, 32, 144, 32, alpha); - drawchar(x, y, 0xA7, 255, 255, 255, alpha); + drawchar(x, y, 0xE029, 144, 48, 32, alpha); + drawchar(x, y, 0xE028, 32, 144, 32, alpha); + drawchar(x, y, 0xE027, 255, 255, 255, alpha); } break; case IconDateSort: if (invert) { - drawchar(x, y, 0xA6, 32, 32, 32, alpha); + drawchar(x, y, 0xE026, 32, 32, 32, alpha); } else { - drawchar(x, y, 0xA6, 255, 255, 255, alpha); + drawchar(x, y, 0xE026, 255, 255, 255, alpha); } break; case IconMyOwn: if (invert) { - drawchar(x, y, 0x94, 192, 160, 64, alpha); - drawchar(x, y, 0x93, 32, 32, 32, alpha); + drawchar(x, y, 0xE014, 192, 160, 64, alpha); + drawchar(x, y, 0xE013, 32, 32, 32, alpha); } else { - drawchar(x, y, 0x94, 192, 160, 64, alpha); - drawchar(x, y, 0x93, 255, 255, 255, alpha); + drawchar(x, y, 0xE014, 192, 160, 64, alpha); + drawchar(x, y, 0xE013, 255, 255, 255, alpha); } break; case IconSearch: - drawchar(x, y, 0x8E, 30, 30, 180, alpha); - drawchar(x, y, 0x8F, 255, 255, 255, alpha); + drawchar(x, y, 0xE00E, 30, 30, 180, alpha); + drawchar(x, y, 0xE00F, 255, 255, 255, alpha); break; case IconDelete: if(invert) { - drawchar(x, y, 0x86, 159, 47, 31, alpha); - drawchar(x, y, 0x85, 0, 0, 0, alpha); + drawchar(x, y, 0xE006, 159, 47, 31, alpha); + drawchar(x, y, 0xE005, 0, 0, 0, alpha); } else { - drawchar(x, y, 0x86, 159, 47, 31, alpha); - drawchar(x, y, 0x85, 255, 255, 255, alpha); + drawchar(x, y, 0xE006, 159, 47, 31, alpha); + drawchar(x, y, 0xE005, 255, 255, 255, alpha); } break; case IconAdd: if(invert) { - drawchar(x, y, 0x86, 32, 144, 32, alpha); - drawchar(x, y, 0x89, 0, 0, 0, alpha); + drawchar(x, y, 0xE006, 32, 144, 32, alpha); + drawchar(x, y, 0xE009, 0, 0, 0, alpha); } else { - drawchar(x, y, 0x86, 32, 144, 32, alpha); - drawchar(x, y, 0x89, 255, 255, 255, alpha); + drawchar(x, y, 0xE006, 32, 144, 32, alpha); + drawchar(x, y, 0xE009, 255, 255, 255, alpha); } break; case IconVelocity: - drawchar(x+1, y, 0x98, 128, 160, 255, alpha); + drawchar(x+1, y, 0xE018, 128, 160, 255, alpha); break; case IconPressure: if(invert) - drawchar(x+1, y+1, 0x99, 180, 160, 16, alpha); + drawchar(x+1, y+1, 0xE019, 180, 160, 16, alpha); else - drawchar(x+1, y+1, 0x99, 255, 212, 32, alpha); + drawchar(x+1, y+1, 0xE019, 255, 212, 32, alpha); break; case IconPersistant: if(invert) - drawchar(x+1, y+1, 0x9A, 20, 20, 20, alpha); + drawchar(x+1, y+1, 0xE01A, 20, 20, 20, alpha); else - drawchar(x+1, y+1, 0x9A, 212, 212, 212, alpha); + drawchar(x+1, y+1, 0xE01A, 212, 212, 212, alpha); break; case IconFire: - drawchar(x+1, y+1, 0x9B, 255, 0, 0, alpha); - drawchar(x+1, y+1, 0x9C, 255, 255, 64, alpha); + drawchar(x+1, y+1, 0xE01B, 255, 0, 0, alpha); + drawchar(x+1, y+1, 0xE01C, 255, 255, 64, alpha); break; case IconBlob: if(invert) - drawchar(x+1, y, 0xBF, 55, 180, 55, alpha); + drawchar(x+1, y, 0xE03F, 55, 180, 55, alpha); else - drawchar(x+1, y, 0xBF, 55, 255, 55, alpha); + drawchar(x+1, y, 0xE03F, 55, 255, 55, alpha); break; case IconHeat: - drawchar(x+3, y, 0xBE, 255, 0, 0, alpha); + drawchar(x+3, y, 0xE03E, 255, 0, 0, alpha); if(invert) - drawchar(x+3, y, 0xBD, 0, 0, 0, alpha); + drawchar(x+3, y, 0xE03D, 0, 0, 0, alpha); else - drawchar(x+3, y, 0xBD, 255, 255, 255, alpha); + drawchar(x+3, y, 0xE03D, 255, 255, 255, alpha); break; case IconBlur: if(invert) - drawchar(x+1, y, 0xC4, 50, 70, 180, alpha); + drawchar(x+1, y, 0xE044, 50, 70, 180, alpha); else - drawchar(x+1, y, 0xC4, 100, 150, 255, alpha); + drawchar(x+1, y, 0xE044, 100, 150, 255, alpha); break; case IconGradient: if(invert) - drawchar(x+1, y+1, 0xD3, 255, 50, 255, alpha); + drawchar(x+1, y+1, 0xE053, 255, 50, 255, alpha); else - drawchar(x+1, y+1, 0xD3, 205, 50, 205, alpha); + drawchar(x+1, y+1, 0xE053, 205, 50, 205, alpha); break; case IconLife: if(invert) - drawchar(x, y+1, 0xE0, 0, 0, 0, alpha); + drawchar(x, y+1, 0xE060, 0, 0, 0, alpha); else - drawchar(x, y+1, 0xE0, 255, 255, 255, alpha); + drawchar(x, y+1, 0xE060, 255, 255, 255, alpha); break; case IconEffect: - drawchar(x+1, y, 0xE1, 255, 255, 160, alpha); + drawchar(x+1, y, 0xE061, 255, 255, 160, alpha); break; case IconGlow: - drawchar(x+1, y, 0xDF, 200, 255, 255, alpha); + drawchar(x+1, y, 0xE05F, 200, 255, 255, alpha); break; case IconWarp: - drawchar(x+1, y, 0xDE, 255, 255, 255, alpha); + drawchar(x+1, y, 0xE05E, 255, 255, 255, alpha); break; case IconBasic: if(invert) - drawchar(x+1, y+1, 0xDB, 50, 50, 0, alpha); + drawchar(x+1, y+1, 0xE05B, 50, 50, 0, alpha); else - drawchar(x+1, y+1, 0xDB, 255, 255, 200, alpha); + drawchar(x+1, y+1, 0xE05B, 255, 255, 200, alpha); break; case IconAltAir: if(invert) { - drawchar(x+1, y+1, 0xD4, 180, 55, 55, alpha); - drawchar(x+1, y+1, 0xD5, 55, 180, 55, alpha); + drawchar(x+1, y+1, 0xE054, 180, 55, 55, alpha); + drawchar(x+1, y+1, 0xE055, 55, 180, 55, alpha); } else { - drawchar(x+1, y+1, 0xD4, 255, 55, 55, alpha); - drawchar(x+1, y+1, 0xD5, 55, 255, 55, alpha); + drawchar(x+1, y+1, 0xE054, 255, 55, 55, alpha); + drawchar(x+1, y+1, 0xE055, 55, 255, 55, alpha); } break; default: diff --git a/src/graphics/Renderer.cpp b/src/graphics/Renderer.cpp index 57ffeb2cd..161700a4e 100644 --- a/src/graphics/Renderer.cpp +++ b/src/graphics/Renderer.cpp @@ -677,7 +677,7 @@ VideoBuffer * Renderer::WallIcon(int wallID, int width, int height) newTexture->SetPixel(i, j, PIXR(pc), PIXG(pc), PIXB(pc), 255); } } - newTexture->AddCharacter(4, 2, 0x8D, 255, 255, 255, 255); + newTexture->AddCharacter(4, 2, 0xE00D, 255, 255, 255, 255); for (i=width/3; iSetPixel(i, 7+(int)(3.9f*cos(i*0.3f)), 255, 255, 255, 255); @@ -805,7 +805,7 @@ void Renderer::DrawWalls() // there is no velocity here, draw a streamline and continue if (!xVel && !yVel) { - drawtext(x*CELL, y*CELL-2, "\x8D", 255, 255, 255, 128); + drawtext(x*CELL, y*CELL-2, String(1, 0xE00D), 255, 255, 255, 128); addpixel(oldX, oldY, 255, 255, 255, 255); continue; } @@ -836,7 +836,7 @@ void Renderer::DrawWalls() xf += xVel; yf += yVel; } - drawtext(x*CELL, y*CELL-2, "\x8D", 255, 255, 255, 128); + drawtext(x*CELL, y*CELL-2, String(1, 0xE00D), 255, 255, 255, 128); } break; case 1: diff --git a/src/gui/font/FontEditor.cpp b/src/gui/font/FontEditor.cpp index 37e0eb51e..d80b1a6b9 100644 --- a/src/gui/font/FontEditor.cpp +++ b/src/gui/font/FontEditor.cpp @@ -281,7 +281,7 @@ FontEditor::FontEditor(ByteString _header): v->PrevChar(); } }; - ui::Button *prev = new ui::Button(ui::Point(currentX, baseline), ui::Point(17, 17), "\x96"); + ui::Button *prev = new ui::Button(ui::Point(currentX, baseline), ui::Point(17, 17), String(1, 0xE016)); currentX += 18; prev->SetActionCallback(new PrevCharAction(this)); AddComponent(prev); @@ -316,7 +316,7 @@ FontEditor::FontEditor(ByteString _header): v->NextChar(); } }; - ui::Button *next = new ui::Button(ui::Point(currentX, baseline), ui::Point(17, 17), "\x95"); + ui::Button *next = new ui::Button(ui::Point(currentX, baseline), ui::Point(17, 17), String(1, 0xE015)); currentX += 18; next->SetActionCallback(new NextCharAction(this)); AddComponent(next); diff --git a/src/gui/game/GameModel.cpp b/src/gui/game/GameModel.cpp index e312a10c7..14684df97 100644 --- a/src/gui/game/GameModel.cpp +++ b/src/gui/game/GameModel.cpp @@ -264,7 +264,7 @@ void GameModel::BuildMenus() //Create menus for (int i = 0; i < SC_TOTAL; i++) { - menuList.push_back(new Menu(sim->msections[i].icon[0], sim->msections[i].name, sim->msections[i].doshow)); + menuList.push_back(new Menu(sim->msections[i].icon, sim->msections[i].name, sim->msections[i].doshow)); } //Build menus from Simulation elements diff --git a/src/gui/game/GameView.cpp b/src/gui/game/GameView.cpp index 0039d6c3b..6e01e08b7 100644 --- a/src/gui/game/GameView.cpp +++ b/src/gui/game/GameView.cpp @@ -433,7 +433,7 @@ GameView::GameView(): v->c->OpenElementSearch(); } }; - ui::Button * tempButton = new ui::Button(ui::Point(WINDOWW-16, WINDOWH-32), ui::Point(15, 15), "\xE5", "Search for elements"); + ui::Button * tempButton = new ui::Button(ui::Point(WINDOWW-16, WINDOWH-32), ui::Point(15, 15), String(1, 0xE065), "Search for elements"); tempButton->Appearance.Margin = ui::Border(0, 2, 3, 2); tempButton->SetActionCallback(new ElementSearchAction(this)); AddComponent(tempButton); @@ -1912,7 +1912,7 @@ void GameView::NotifyNotificationsChanged(GameModel * sender) AddComponent(tempButton); notificationComponents.push_back(tempButton); - tempButton = new ui::Button(ui::Point(XRES-20, currentY), ui::Point(15, 15), "\xAA"); + tempButton = new ui::Button(ui::Point(XRES-20, currentY), ui::Point(15, 15), String(1, 0xE02A)); //tempButton->SetIcon(IconClose); tempButton->SetActionCallback(new CloseNotificationButtonAction(this, *iter)); tempButton->Appearance.Margin.Left -= 1; @@ -2266,7 +2266,7 @@ void GameView::OnDraw() { String::Stream sampleInfo; sampleInfo << recordingIndex; - sampleInfo << ". \x8E REC"; + sampleInfo << ". " + String(1, 0xE00E) + " REC"; int textWidth = Graphics::textwidth(sampleInfo.str()); g->fillrect(XRES-20-textWidth, 12, textWidth+8, 15, 0, 0, 0, 255*0.5); diff --git a/src/gui/game/SampleTool.cpp b/src/gui/game/SampleTool.cpp index e1c13b76d..ca58d686b 100644 --- a/src/gui/game/SampleTool.cpp +++ b/src/gui/game/SampleTool.cpp @@ -15,7 +15,7 @@ VideoBuffer * SampleTool::GetIcon(int toolID, int width, int height) newTexture->SetPixel(x, y, PIXR(pc), PIXG(pc), PIXB(pc), 255); } } - newTexture->AddCharacter((width/2)-5, (height/2)-5, 0xE6, 255, 255, 255, 255); + newTexture->AddCharacter((width/2)-5, (height/2)-5, 0xE066, 255, 255, 255, 255); newTexture->BlendPixel(10, 9, 100, 180, 255, 255); newTexture->BlendPixel(11, 8, 100, 180, 255, 255); newTexture->BlendPixel(12, 7, 100, 180, 255, 255); diff --git a/src/gui/game/SignTool.cpp b/src/gui/game/SignTool.cpp index 011923356..046a16308 100644 --- a/src/gui/game/SignTool.cpp +++ b/src/gui/game/SignTool.cpp @@ -128,10 +128,10 @@ SignWindow::SignWindow(SignTool * tool_, Simulation * sim_, int signID_, ui::Poi justification = new ui::DropDown(ui::Point(52, 48), ui::Point(50, 16)); AddComponent(justification); - justification->AddOption(std::pair("\xA0 Left", (int)sign::Left)); - justification->AddOption(std::pair("\x9E Middle", (int)sign::Middle)); - justification->AddOption(std::pair("\x9F Right", (int)sign::Right)); - justification->AddOption(std::pair("\x9D None", (int)sign::None)); + justification->AddOption(std::pair(String(1, 0xE020) + " Left", (int)sign::Left)); + justification->AddOption(std::pair(String(1, 0xE01E) + " Middle", (int)sign::Middle)); + justification->AddOption(std::pair(String(1, 0xE01F) + " Right", (int)sign::Right)); + justification->AddOption(std::pair(String(1, 0xE01D) + " None", (int)sign::None)); justification->SetOption(1); justification->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; @@ -268,8 +268,8 @@ VideoBuffer * SignTool::GetIcon(int toolID, int width, int height) newTexture->SetPixel(x, y, PIXR(pc), PIXG(pc), PIXB(pc), 255); } } - newTexture->AddCharacter((width/2)-5, (height/2)-5, 0xA1, 32, 64, 128, 255); - newTexture->BlendCharacter((width/2)-5, (height/2)-5, 0xA0, 255, 255, 255, 255); + newTexture->AddCharacter((width/2)-5, (height/2)-5, 0xE021, 32, 64, 128, 255); + newTexture->BlendCharacter((width/2)-5, (height/2)-5, 0xE020, 255, 255, 255, 255); return newTexture; } diff --git a/src/gui/game/ToolButton.cpp b/src/gui/game/ToolButton.cpp index 1514d7f4d..f2000024e 100644 --- a/src/gui/game/ToolButton.cpp +++ b/src/gui/game/ToolButton.cpp @@ -67,7 +67,7 @@ void ToolButton::Draw(const ui::Point& screenPos) } if (Favorite::Ref().IsFavorite(toolIdentifier)) { - g->drawtext(screenPos.X, screenPos.Y, "\xE8", Appearance.BorderFavorite.Red, Appearance.BorderFavorite.Green, Appearance.BorderFavorite.Blue, Appearance.BorderFavorite.Alpha); + g->drawtext(screenPos.X, screenPos.Y, String(1, 0xE068), Appearance.BorderFavorite.Red, Appearance.BorderFavorite.Green, Appearance.BorderFavorite.Blue, Appearance.BorderFavorite.Alpha); } if (totalColour<544) diff --git a/src/gui/interface/SaveButton.cpp b/src/gui/interface/SaveButton.cpp index 813dcb53d..9b7732559 100644 --- a/src/gui/interface/SaveButton.cpp +++ b/src/gui/interface/SaveButton.cpp @@ -41,22 +41,22 @@ SaveButton::SaveButton(Point position, Point size, SaveInfo * save): String votes, icon; votes = format::NumberToString(save->GetVotesUp()-save->GetVotesDown()); - icon += 0xBB; + icon += 0xE03B; for (size_t j = 1; j < votes.length(); j++) - icon += 0xBC; - icon += 0xB9; - icon += 0xBA; + icon += 0xE03C; + icon += 0xE039; + icon += 0xE03A; votesBackground = icon; for (String::iterator iter = icon.begin(), end = icon.end(); iter != end; ++iter) - *iter -= 14; + *iter -= 14; // 0xE039 -> 0xE02B votesBackground2 = icon; for (String::iterator iter = votes.begin(), end = votes.end(); iter != end; ++iter) if(*iter != '-') - *iter += 127; + *iter += 0xDFFF; // 0x30 -> 0xE02F votesString = votes; @@ -239,15 +239,15 @@ void SaveButton::Draw(const Point& screenPos) int y = screenPos.Y-15+(Size.Y-thumbBoxSize.Y)/2+thumbBoxSize.Y; g->fillrect(x+1, y+1, 7, 8, 255, 255, 255, 255); if (isMouseInsideHistory) { - g->drawtext(x, y, "\xA6", 200, 100, 80, 255); + g->drawtext(x, y, String(1, 0xE026), 200, 100, 80, 255); } else { - g->drawtext(x, y, "\xA6", 160, 70, 50, 255); + g->drawtext(x, y, String(1, 0xE026), 160, 70, 50, 255); } } if (!save->GetPublished()) { - g->drawtext(screenPos.X, screenPos.Y-2, "\xCD", 255, 255, 255, 255); - g->drawtext(screenPos.X, screenPos.Y-2, "\xCE", 212, 151, 81, 255); + g->drawtext(screenPos.X, screenPos.Y-2, String(1, 0xE04D), 255, 255, 255, 255); + g->drawtext(screenPos.X, screenPos.Y-2, String(1, 0xE04E), 212, 151, 81, 255); } } else if (file) diff --git a/src/gui/interface/Textbox.cpp b/src/gui/interface/Textbox.cpp index 583b3eab4..ce9ca014c 100644 --- a/src/gui/interface/Textbox.cpp +++ b/src/gui/interface/Textbox.cpp @@ -65,7 +65,7 @@ void Textbox::SetText(String newText) if(masked) { String maskedText = newText; - std::fill(maskedText.begin(), maskedText.end(), '\x8D'); + std::fill(maskedText.begin(), maskedText.end(), 0xE00D); Label::SetText(maskedText); } else @@ -159,7 +159,7 @@ void Textbox::cutSelection() if(masked) { String maskedText = backingText; - std::fill(maskedText.begin(), maskedText.end(), '\x8D'); + std::fill(maskedText.begin(), maskedText.end(), 0xE00D); Label::SetText(maskedText); } else @@ -223,7 +223,7 @@ void Textbox::pasteIntoSelection() if(masked) { String maskedText = backingText; - std::fill(maskedText.begin(), maskedText.end(), '\x8D'); + std::fill(maskedText.begin(), maskedText.end(), 0xE00D); Label::SetText(maskedText); } else @@ -459,7 +459,7 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool if (masked) { String maskedText = backingText; - std::fill(maskedText.begin(), maskedText.end(), '\x8D'); + std::fill(maskedText.begin(), maskedText.end(), 0xE00D); Label::SetText(maskedText); } else diff --git a/src/gui/localbrowser/LocalBrowserView.cpp b/src/gui/localbrowser/LocalBrowserView.cpp index 4f8bef3c1..dc8acd8b8 100644 --- a/src/gui/localbrowser/LocalBrowserView.cpp +++ b/src/gui/localbrowser/LocalBrowserView.cpp @@ -21,8 +21,8 @@ LocalBrowserView::LocalBrowserView(): lastChanged(0), pageCount(0) { - nextButton = new ui::Button(ui::Point(WINDOWW-52, WINDOWH-18), ui::Point(50, 16), "Next \x95"); - previousButton = new ui::Button(ui::Point(2, WINDOWH-18), ui::Point(50, 16), "\x96 Prev"); + nextButton = new ui::Button(ui::Point(WINDOWW-52, WINDOWH-18), ui::Point(50, 16), "Next " + String(1, 0xE015)); + previousButton = new ui::Button(ui::Point(2, WINDOWH-18), ui::Point(50, 16), String(1, 0xE016) + " Prev"); undeleteButton = new ui::Button(ui::Point(WINDOWW-122, WINDOWH-18), ui::Point(60, 16), "Rescan"); AddComponent(nextButton); AddComponent(previousButton); diff --git a/src/gui/search/SearchView.cpp b/src/gui/search/SearchView.cpp index f6e4dd0a4..88e712e85 100644 --- a/src/gui/search/SearchView.cpp +++ b/src/gui/search/SearchView.cpp @@ -24,8 +24,8 @@ SearchView::SearchView(): Client::Ref().AddListener(this); - nextButton = new ui::Button(ui::Point(WINDOWW-52, WINDOWH-18), ui::Point(50, 16), "Next \x95"); - previousButton = new ui::Button(ui::Point(2, WINDOWH-18), ui::Point(50, 16), "\x96 Prev"); + nextButton = new ui::Button(ui::Point(WINDOWW-52, WINDOWH-18), ui::Point(50, 16), "Next " + String(1, 0xE015)); + previousButton = new ui::Button(ui::Point(2, WINDOWH-18), ui::Point(50, 16), String(1, 0xE016) + " Prev"); tagsLabel = new ui::Label(ui::Point(270, WINDOWH-18), ui::Point(WINDOWW-540, 16), "\boPopular Tags:"); motdLabel = new ui::RichLabel(ui::Point(51, WINDOWH-18), ui::Point(WINDOWW-102, 16), Client::Ref().GetMessageOfTheDay()); diff --git a/src/simulation/MenuSection.h b/src/simulation/MenuSection.h index fc31ed2c3..23be2b53b 100644 --- a/src/simulation/MenuSection.h +++ b/src/simulation/MenuSection.h @@ -3,7 +3,7 @@ struct menu_section { - String icon; + String::value_type icon; String name; int itemcount; int doshow; diff --git a/src/simulation/SimulationData.cpp b/src/simulation/SimulationData.cpp index 3a4ff4dd8..b92069c31 100644 --- a/src/simulation/SimulationData.cpp +++ b/src/simulation/SimulationData.cpp @@ -128,24 +128,24 @@ std::vector LoadMenus() { return { - {"\xC1", "Walls", 0, 1}, - {"\xC2", "Electronics", 0, 1}, - {"\xD6", "Powered Materials", 0, 1}, - {"\x99", "Sensors", 0, 1}, - {"\xE2", "Force", 0, 1}, - {"\xC3", "Explosives", 0, 1}, - {"\xC5", "Gases", 0, 1}, - {"\xC4", "Liquids", 0, 1}, - {"\xD0", "Powders", 0, 1}, - {"\xD1", "Solids", 0, 1}, - {"\xC6", "Radioactive", 0, 1}, - {"\xCC", "Special", 0, 1}, - {"\xD2", "Game Of Life", 0, 1}, - {"\xD7", "Tools", 0, 1}, - {"\xE7", "Favorites", 0, 1}, - {"\xE4", "Decoration tools", 0, 1}, - {"\xC8", "Cracker", 0, 0}, - {"\xC8", "Cracker!", 0, 0}, + {0xE041, "Walls", 0, 1}, + {0xE042, "Electronics", 0, 1}, + {0xE056, "Powered Materials", 0, 1}, + {0xE019, "Sensors", 0, 1}, + {0xE062, "Force", 0, 1}, + {0xE043, "Explosives", 0, 1}, + {0xE045, "Gases", 0, 1}, + {0xE044, "Liquids", 0, 1}, + {0xE050, "Powders", 0, 1}, + {0xE051, "Solids", 0, 1}, + {0xE046, "Radioactive", 0, 1}, + {0xE04C, "Special", 0, 1}, + {0xE052, "Game Of Life", 0, 1}, + {0xE057, "Tools", 0, 1}, + {0xE067, "Favorites", 0, 1}, + {0xE064, "Decoration tools", 0, 1}, + {0xE048, "Cracker", 0, 0}, + {0xE048, "Cracker!", 0, 0}, }; } From a121c62c3b7fb871be93f36b2dfc2d0d7256acaa Mon Sep 17 00:00:00 2001 From: mniip Date: Wed, 2 May 2018 01:32:04 +0300 Subject: [PATCH 09/27] Add some helper methods and rewrite some of the string manipulation code --- src/PowderToySDL.cpp | 26 +- src/client/Client.cpp | 57 ++--- src/client/GameSave.cpp | 10 +- src/client/HTTP.cpp | 9 +- src/common/String.h | 233 ++++++++++++++---- src/graphics/Graphics.cpp | 4 +- src/graphics/Renderer.cpp | 4 +- src/gui/console/ConsoleController.cpp | 2 +- .../elementsearch/ElementSearchActivity.cpp | 6 +- src/gui/filebrowser/FileBrowserActivity.cpp | 13 +- src/gui/font/FontEditor.cpp | 4 +- src/gui/game/GameController.cpp | 4 +- src/gui/game/GameView.cpp | 28 +-- src/gui/game/PropertyTool.cpp | 20 +- src/gui/game/SignTool.cpp | 8 +- src/gui/game/ToolButton.cpp | 4 +- src/gui/interface/Label.cpp | 20 +- src/gui/interface/SaveButton.cpp | 8 +- src/gui/interface/Textbox.cpp | 26 +- src/gui/localbrowser/LocalBrowserView.cpp | 4 +- src/gui/login/LoginModel.cpp | 2 +- src/gui/preview/PreviewView.cpp | 8 +- src/gui/search/SearchView.cpp | 4 +- src/gui/update/UpdateActivity.cpp | 4 +- src/lua/LuaScriptInterface.cpp | 12 +- src/lua/TPTScriptInterface.cpp | 4 +- src/simulation/Sign.cpp | 2 +- src/simulation/Simulation.cpp | 2 +- 28 files changed, 314 insertions(+), 214 deletions(-) diff --git a/src/PowderToySDL.cpp b/src/PowderToySDL.cpp index 086dda513..f16fb917d 100644 --- a/src/PowderToySDL.cpp +++ b/src/PowderToySDL.cpp @@ -1166,26 +1166,22 @@ int main(int argc, char * argv[]) ByteString ptsaveArg = arguments["ptsave"]; try { - if (ptsaveArg.find("ptsave:")) - throw std::runtime_error("Invalid save link"); - - ByteString saveIdPart = ""; - int saveId; - size_t hashPos = ptsaveArg.find('#'); - if (hashPos != ByteString::npos) + ByteString saveIdPart; + if (ByteString::Split split = arguments["ptsave"].SplitBy(':')) { - saveIdPart = ptsaveArg.substr(7, hashPos-7); + if (split.Before() != "ptsave") + throw std::runtime_error("Not a ptsave link"); + saveIdPart = split.After().SplitBy('#').Before(); } else - { - saveIdPart = ptsaveArg.substr(7); - } - if (!saveIdPart.length()) + throw std::runtime_error("Invalid save link"); + + if (!saveIdPart.size()) throw std::runtime_error("No Save ID"); #ifdef DEBUG - std::cout << "Got Ptsave: id: " << saveIdPart << std::endl; + std::cout << "Got Ptsave: id: " << saveIdPart << std::endl; #endif - saveId = format::ByteStringToNumber(saveIdPart); + int saveId = format::ByteStringToNumber(saveIdPart); if (!saveId) throw std::runtime_error("Invalid Save ID"); @@ -1227,7 +1223,7 @@ int main(int argc, char * argv[]) } catch(exception& e) { - BlueScreen(e.what()); + BlueScreen(ByteString(e.what()).FromUtf8()); } #endif diff --git a/src/client/Client.cpp b/src/client/Client.cpp index 3b7eaf44b..333d7e98d 100644 --- a/src/client/Client.cpp +++ b/src/client/Client.cpp @@ -349,17 +349,9 @@ bool Client::DoInstallation() #include "icondoc.h" int success = 1; - ByteString filename = Platform::ExecutableName(), pathname = filename.substr(0, filename.rfind('/')); - for (size_t i = 0; i < filename.size(); i++) - { - if (filename[i] == '\'') - { - filename.insert(i, "'\\'"); - i += 3; - } - } - filename.insert(filename.size(), "'"); - filename.insert(0, "'"); + ByteString filename = Platform::ExecutableName(), pathname = filename.SplitFromEndBy('/').Before(); + filename.Substitute('\'', "'\\''"); + filename = '\'' + filename + '\''; FILE *f; const char *mimedata = @@ -539,18 +531,17 @@ std::vector Client::DirectorySearch(ByteString directory, ByteString bool extensionMatch = !extensions.size(); for(std::vector::iterator extIter = extensions.begin(), extEnd = extensions.end(); extIter != extEnd; ++extIter) { - size_t filenameLength = filename.length()-(*extIter).length(); - if(filename.find(*extIter, filenameLength) == filenameLength) + if(filename.EndsWith(*extIter)) { extensionMatch = true; - tempfilename = filename.substr(0, filenameLength); + tempfilename = filename.SubstrFromEnd(0, (*extIter).size()); break; } } for (ByteString::iterator iter = tempfilename.begin(); iter != tempfilename.end(); ++iter) *iter = toupper(*iter); bool searchMatch = !search.size(); - if(search.size() && tempfilename.find(search)!=ByteString::npos) + if(search.size() && tempfilename.Contains(search)) searchMatch = true; if(searchMatch && extensionMatch) @@ -1202,10 +1193,9 @@ void Client::RescanStamps() stampIDs.clear(); while ((entry = readdir(directory))) { - if(strncmp(entry->d_name, "..", 3) && strncmp(entry->d_name, ".", 2) && strstr(entry->d_name, ".stm") && strlen(entry->d_name) == 14) - { - stampIDs.push_front(ByteString(entry->d_name).substr(0, 10)); - } + ByteString name = entry->d_name; + if(name != ".." && name != "." && name.EndsWith(".stm") && name.size() == 14) + stampIDs.push_front(name.Substr(0, 10)); } closedir(directory); updateStamps(); @@ -2084,11 +2074,10 @@ Json::Value Client::GetPref(Json::Value root, ByteString prop, Json::Value defau { try { - size_t dot = prop.find('.'); - if (dot == prop.npos) - return root.get(prop, defaultValue); + if(ByteString::Split split = prop.SplitBy('.')) + return GetPref(root[split.Before()], split.After(), defaultValue); else - return GetPref(root[prop.substr(0, dot)], prop.substr(dot+1), defaultValue); + return root.get(prop, defaultValue); } catch (std::exception & e) { @@ -2277,15 +2266,14 @@ std::vector Client::GetPrefBoolArray(ByteString prop) // and return it to SetPref to do the actual setting Json::Value Client::SetPrefHelper(Json::Value root, ByteString prop, Json::Value value) { - size_t dot = prop.find("."); - if (dot == prop.npos) - root[prop] = value; - else + if(ByteString::Split split = prop.SplitBy('.')) { - Json::Value toSet = GetPref(root, prop.substr(0, dot)); - toSet = SetPrefHelper(toSet, prop.substr(dot+1), value); - root[prop.substr(0, dot)] = toSet; + Json::Value toSet = GetPref(root, split.Before()); + toSet = SetPrefHelper(toSet, split.After(), value); + root[split.Before()] = toSet; } + else + root[prop] = value; return root; } @@ -2293,13 +2281,10 @@ void Client::SetPref(ByteString prop, Json::Value value) { try { - size_t dot = prop.find("."); - if (dot == prop.npos) - preferences[prop] = value; + if(ByteString::Split split = prop.SplitBy('.')) + preferences[split.Before()] = SetPrefHelper(preferences[split.Before()], split.After(), value); else - { - preferences[prop.substr(0, dot)] = SetPrefHelper(preferences[prop.substr(0, dot)], prop.substr(dot+1), value); - } + preferences[prop] = value; } catch (std::exception & e) { diff --git a/src/client/GameSave.cpp b/src/client/GameSave.cpp index cedba9f4e..7bf4845f0 100644 --- a/src/client/GameSave.cpp +++ b/src/client/GameSave.cpp @@ -678,7 +678,7 @@ void GameSave::readOPS(char * data, int dataLength) { if (!strcmp(bson_iterator_key(&signiter), "text") && bson_iterator_type(&signiter) == BSON_STRING) { - tempSign.text = format::CleanString(ByteString(bson_iterator_string(&signiter)).FromUtf8(), true, true, true).substr(0, 45); + tempSign.text = format::CleanString(ByteString(bson_iterator_string(&signiter)).FromUtf8(), true, true, true).Substr(0, 45); } else if (!strcmp(bson_iterator_key(&signiter), "justification") && bson_iterator_type(&signiter) == BSON_INT) { @@ -1407,11 +1407,7 @@ void GameSave::readPSv(char * saveDataChar, int dataLength) int bzStatus = 0; if ((bzStatus = BZ2_bzBuffToBuffDecompress((char *)data, (unsigned *)&size, (char *)(saveData+12), dataLength-12, 0, 0))) - { - String::Stream bzStatusStr; - bzStatusStr << bzStatus; - throw ParseException(ParseException::Corrupt, "Cannot decompress: " + bzStatusStr.str()); - } + throw ParseException(ParseException::Corrupt, "Cannot decompress: " + format::NumberToString(bzStatus)); dataLength = size; #ifdef DEBUG @@ -1952,7 +1948,7 @@ void GameSave::readPSv(char * saveDataChar, int dataLength) x = 254; memcpy(tempSignText, data+p, x); tempSignText[x] = 0; - tempSign.text = format::CleanString(tempSignText, true, true, true).substr(0, 45); + tempSign.text = format::CleanString(tempSignText, true, true, true).Substr(0, 45); tempSigns.push_back(tempSign); p += x; } diff --git a/src/client/HTTP.cpp b/src/client/HTTP.cpp index afd21508b..26da8f496 100644 --- a/src/client/HTTP.cpp +++ b/src/client/HTTP.cpp @@ -947,7 +947,7 @@ ByteString FindBoundary(std::map parts, ByteString bound { // loop through every character in each part and search for the substring, adding 1 to map for every character found (character after the substring) for (ssize_t j = 0; j < (ssize_t)((*iter).second.length()-blen); j++) - if (!blen || (*iter).second.substr(j, blen) == boundary) + if (!blen || (*iter).second.Substr(j, blen) == boundary) { unsigned char ch = (*iter).second[j+blen]; if (ch >= '0' && ch <= '9') @@ -999,12 +999,11 @@ ByteString GetMultipartMessage(std::map parts, ByteStrin data << "Content-transfer-encoding: binary" << "\r\n"; // colon p - size_t colonP = name.find(':'); - if (colonP != name.npos) + if (ByteString::Split split = name.SplitBy(':')) { // used to upload files (save data) - data << "content-disposition: form-data; name=\"" << name.substr(0, colonP) << "\""; - data << "filename=\"" << name.substr(colonP+1) << "\""; + data << "content-disposition: form-data; name=\"" << split.Before() << "\""; + data << "filename=\"" << split.After() << "\""; } else { diff --git a/src/common/String.h b/src/common/String.h index 0da29b864..76825f684 100644 --- a/src/common/String.h +++ b/src/common/String.h @@ -7,26 +7,97 @@ class String; +template class SplitBase +{ + T const &parent; + size_t posBefore; + size_t posAfter; + bool reverse; + + inline SplitBase(T const &_parent, size_t _posBefore, size_t offset, bool _reverse): + parent(_parent), + posBefore(_posBefore), + posAfter(_posBefore == T::npos ? T::npos : _posBefore + offset), + reverse(_reverse) + {} +public: + inline T Before(bool includeSeparator = false) const + { + if(posBefore == T::npos) + return reverse ? T() : parent; + return parent.Substr(0, includeSeparator ? posAfter : posBefore); + } + inline T After(bool includeSeparator = false) const + { + if(posBefore == T::npos) + return reverse ? parent : T(); + return parent.Substr(includeSeparator ? posBefore : posAfter); + } + + inline size_t PositionBefore() const { return posBefore; } + inline size_t PositionAfter() const { return posAfter; } + + inline operator bool() const { return posBefore != T::npos; } + + friend T; +}; + class ByteString : public std::basic_string { + using super = std::basic_string; +public: + inline ByteString(): super() {} + inline ByteString(value_type ch): super(1, ch) {} + inline ByteString(size_type count, value_type ch): super(count, ch) {} + inline ByteString(value_type const *ch, size_type count): super(ch, count) {} + inline ByteString(value_type const *ch): super(ch) {} + template inline ByteString(It first, It last): super(first, last) {} + inline ByteString(super const &other): super(other) {} + inline ByteString(super &&other): super(std::move(other)) {} + inline ByteString(ByteString const &other): super(other) {} + inline ByteString(ByteString &&other): super(std::move(other)) {} + + inline ByteString &operator=(ByteString const &other) { super::operator=(other); return *this; } + inline ByteString &operator=(ByteString &&other) { super::operator=(other); return *this; } + + inline ByteString &operator+=(ByteString const &other) { super::operator+=(other); return *this; } + inline ByteString &operator+=(ByteString &&other) { super::operator+=(std::move(other)); return *this; } + + inline ByteString Substr(size_t pos = 0, size_t count = npos) const { return super::substr(pos, count); } + inline ByteString SubstrFromEnd(size_t rpos = 0, size_t rcount = npos) const { return super::substr(rcount == npos || rcount > rpos ? 0 : rpos - rcount, size() - rpos); } + inline ByteString Between(size_t from, size_t to) const { return from >= to ? ByteString() : super::substr(from, to - from); } + + inline bool Contains(value_type ch) const { return super::find(ch) != npos; } + inline bool Contains(ByteString const &other) { return super::find(other) != npos; } + + inline bool BeginsWith(ByteString const &other) const { return super::compare(0, other.size(), other); } + inline bool EndsWith(ByteString const &other) const { return super::compare(size() - other.size(), other.size(), other); } + + using Split = SplitBase; + inline Split SplitBy(value_type ch, size_t pos = 0) const { return Split(*this, super::find(ch, pos), 1, false); } + inline Split SplitBy(ByteString const &str, size_t pos = 0) const { return Split(*this, super::find(str, pos), str.size(), false); } + inline Split SplitByAny(ByteString const &str, size_t pos = 0) const { return Split(*this, super::find_first_of(str, pos), 1, false); } + inline Split SplitByNot(ByteString const &str, size_t pos = 0) const { return Split(*this, super::find_first_not_of(str, pos), 1, false); } + inline Split SplitFromEndBy(value_type ch, size_t pos = npos) const { return Split(*this, super::rfind(ch, pos), 1, true); } + inline Split SplitFromEndBy(ByteString const &str, size_t pos = npos) const { return Split(*this, super::find(str, pos), str.size(), true); } + inline Split SplitFromEndByAny(ByteString const &str, size_t pos = npos) const { return Split(*this, super::find_last_of(str, pos), 1, true); } + inline Split SplitFromEndByNot(ByteString const &str, size_t pos = npos) const { return Split(*this, super::find_last_not_of(str, pos), 1, true); } + + inline ByteString &Substitute(ByteString const &needle, ByteString const &replacement) + { + size_t needleSize = needle.size(); + size_t replacementSize = replacement.size(); + size_t at = super::find(needle); + while(at != npos) + { + super::replace(at, needleSize, replacement); + at += replacementSize + !needleSize; + at = super::find(needle, at); + } + return *this; + } + public: - inline ByteString(): std::basic_string() {} - inline ByteString(size_type count, value_type ch): std::basic_string(count, ch) {} - inline ByteString(value_type const *ch, size_type count): std::basic_string(ch, count) {} - inline ByteString(value_type const *ch): std::basic_string(ch) {} - template inline ByteString(It first, It last): std::basic_string(first, last) {} - inline ByteString(std::basic_string const &other): std::basic_string(other) {} - inline ByteString(std::basic_string &&other): std::basic_string(std::move(other)) {} - inline ByteString(ByteString const &other): std::basic_string(other) {} - inline ByteString(ByteString &&other): std::basic_string(std::move(other)) {} - - inline ByteString &operator=(ByteString const &other) { std::basic_string::operator=(other); return *this; } - inline ByteString &operator=(ByteString &&other) { std::basic_string::operator=(std::move(other)); return *this; } - - template ByteString &operator+=(T &&other) { std::basic_string::operator+=(std::forward(other)); return *this; } - template inline ByteString operator+(T &&other) const { ByteString tmp = *this; tmp += std::forward(other); return tmp; } - template ByteString substr(Ts&&... args) const { return std::basic_string::substr(std::forward(args)...); } - template ByteString &insert(Ts&&... args) { std::basic_string::insert(std::forward(args)...); return *this; } class ConversionError : public std::runtime_error { @@ -42,38 +113,89 @@ public: using Stream = std::basic_stringstream; }; -inline ByteString operator+(ByteString::value_type const *ch, ByteString const &str) { return ByteString(ch) + str; } -inline ByteString operator+(std::basic_string const &other, ByteString const &str) { return ByteString(other) + str; } -inline ByteString operator+(std::basic_string &&other, ByteString const &str) { return ByteString(std::move(other)) + str; } +inline ByteString operator+(ByteString const &lhs, ByteString const &rhs) { return static_cast const &>(lhs) + static_cast const &>(rhs); } +inline ByteString operator+(ByteString const &lhs, ByteString &&rhs) { return static_cast const &>(lhs) + static_cast &&>(rhs); } +inline ByteString operator+(ByteString &&lhs, ByteString const &rhs) { return static_cast &&>(lhs) + static_cast const &>(rhs); } +inline ByteString operator+(ByteString &&lhs, ByteString &&rhs) { return static_cast &&>(lhs) + static_cast &&>(rhs); } +inline ByteString operator+(ByteString const &lhs, std::basic_string const &rhs) { return static_cast const &>(lhs) + rhs; } +inline ByteString operator+(ByteString const &lhs, std::basic_string &&rhs) { return static_cast const &>(lhs) + std::move(rhs); } +inline ByteString operator+(ByteString &&lhs, std::basic_string const &rhs) { return static_cast &&>(lhs) + rhs; } +inline ByteString operator+(ByteString &&lhs, std::basic_string &&rhs) { return static_cast &&>(lhs) + std::move(rhs); } +inline ByteString operator+(ByteString const &lhs, ByteString::value_type rhs) { return static_cast const &>(lhs) + rhs; } +inline ByteString operator+(ByteString &&lhs, ByteString::value_type rhs) { return static_cast &&>(lhs) + rhs; } +inline ByteString operator+(ByteString const &lhs, ByteString::value_type const *rhs) { return static_cast const &>(lhs) + rhs; } +inline ByteString operator+(ByteString &&lhs, ByteString::value_type const *rhs) { return static_cast &&>(lhs) + rhs; } +inline ByteString operator+(std::basic_string const &lhs, ByteString const &rhs) { return lhs + static_cast const &>(rhs); } +inline ByteString operator+(std::basic_string const &lhs, ByteString &&rhs) { return lhs + static_cast &&>(rhs); } +inline ByteString operator+(std::basic_string &&lhs, ByteString const &rhs) { return std::move(lhs) + static_cast const &>(rhs); } +inline ByteString operator+(std::basic_string &&lhs, ByteString &&rhs) { return std::move(lhs) + static_cast &&>(rhs); } +inline ByteString operator+(ByteString::value_type lhs, ByteString const &rhs) { return lhs + static_cast const &>(rhs); } +inline ByteString operator+(ByteString::value_type lhs, ByteString &&rhs) { return lhs + static_cast &&>(rhs); } +inline ByteString operator+(ByteString::value_type const *lhs, ByteString const &rhs) { return lhs + static_cast const &>(rhs); } +inline ByteString operator+(ByteString::value_type const *lhs, ByteString &&rhs) { return lhs + static_cast &&>(rhs); } class String : public std::basic_string { + using super = std::basic_string; public: - inline String(): std::basic_string() {} - inline String(size_type count, value_type ch): std::basic_string(count, ch) {} - inline String(value_type const *ch, size_type count): std::basic_string(ch, count) {} - inline String(value_type const *ch): std::basic_string(ch) {} - template inline String(It first, It last): std::basic_string(first, last) {} - inline String(std::basic_string const &other): std::basic_string(other) {} - inline String(std::basic_string &&other): std::basic_string(std::move(other)) {} - inline String(String const &other): std::basic_string(other) {} - inline String(String &&other): std::basic_string(std::move(other)) {} - template inline String(ByteString::value_type const (&ch)[N]): std::basic_string(ByteString(ch, N - 1).FromAscii()) {} + inline String(): super() {} + inline String(value_type ch): super(1, ch) {} + inline String(size_type count, value_type ch): super(count, ch) {} + inline String(value_type const *ch, size_type count): super(ch, count) {} + inline String(value_type const *ch): super(ch) {} + template inline String(It first, It last): super(first, last) {} + inline String(super const &other): super(other) {} + inline String(super &&other): super(std::move(other)) {} + inline String(String const &other): super(other) {} + inline String(String &&other): super(std::move(other)) {} + template inline String(ByteString::value_type const (&ch)[N]): super(ByteString(ch, N - 1).FromAscii()) {} - inline String &operator=(String const &other) { std::basic_string::operator=(other); return *this; } - inline String &operator=(String &&other) { std::basic_string::operator=(other); return *this; } + inline String &operator=(String const &other) { super::operator=(other); return *this; } + inline String &operator=(String &&other) { super::operator=(other); return *this; } + + inline String &operator+=(String const &other) { super::operator+=(other); return *this; } + inline String &operator+=(String &&other) { super::operator+=(std::move(other)); return *this; } + + inline String Substr(size_t pos = 0, size_t count = npos) const { return super::substr(pos, count); } + inline String SubstrFromEnd(size_t rpos = 0, size_t rcount = npos) const { return super::substr(rcount == npos || rcount > rpos ? 0 : rpos - rcount, size() - rpos); } + inline String Between(size_t from, size_t to) const { return from >= to ? String() : super::substr(from, to - from); } + + inline bool Contains(value_type ch) const { return super::find(ch) != npos; } + inline bool Contains(String const &other) const { return super::find(other) != npos; } + + inline bool BeginsWith(String const &other) const { return super::compare(0, other.size(), other); } + inline bool EndsWith(String const &other) const { return super::compare(size() - other.size(), other.size(), other); } + + using Split = SplitBase; + inline Split SplitBy(value_type ch, size_t pos = 0) const { return Split(*this, super::find(ch, pos), 1, false); } + inline Split SplitBy(String const &str, size_t pos = 0) const { return Split(*this, super::find(str, pos), str.size(), false); } + inline Split SplitByAny(String const &str, size_t pos = 0) const { return Split(*this, super::find_first_of(str, pos), 1, false); } + inline Split SplitByNot(String const &str, size_t pos = 0) const { return Split(*this, super::find_first_not_of(str, pos), 1, false); } + inline Split SplitFromEndBy(value_type ch, size_t pos = npos) const { return Split(*this, super::rfind(ch, pos), 1, true); } + inline Split SplitFromEndBy(String const &str, size_t pos = npos) const { return Split(*this, super::find(str, pos), str.size(), true); } + inline Split SplitFromEndByAny(String const &str, size_t pos = npos) const { return Split(*this, super::find_last_of(str, pos), 1, true); } + inline Split SplitFromEndByNot(String const &str, size_t pos = npos) const { return Split(*this, super::find_last_not_of(str, pos), 1, true); } + + inline String &Substitute(String const &needle, String const &replacement) + { + size_t needleSize = needle.size(); + size_t replacementSize = replacement.size(); + size_t at = super::find(needle); + while(at != npos) + { + super::replace(at, needleSize, replacement); + at += replacementSize + !needleSize; + at = super::find(needle, at); + } + return *this; + } - template inline String &operator+=(T &&other) { std::basic_string::operator+=(std::forward(other)); return *this; } - template inline String &operator+=(ByteString::value_type const (&ch)[N]) { std::basic_string::operator+=(ByteString(ch, N - 1).FromAscii()); return *this; } - template inline String operator+(T &&other) const { String tmp = *this; tmp += std::forward(other); return tmp; } - template inline String substr(Ts&&... args) const { return std::basic_string::substr(std::forward(args)...); } - inline String &insert(size_t pos, String &str) { std::basic_string::insert(pos, str); return *this; } - inline String &insert(size_t pos, size_t n, value_type ch) { std::basic_string::insert(pos, n, ch); return *this; } - template inline String &insert(size_t pos, ByteString::value_type const (&ch)[N]) { std::basic_string::insert(pos, ByteString(ch, N - 1).FromAscii()); return *this; } - inline size_t find(String const &str, size_t pos = 0) { return std::basic_string::find(str, pos); } - inline size_t find(value_type ch, size_t pos = 0) { return std::basic_string::find(ch, pos); } + inline String &Insert(size_t pos, String const &str) { super::insert(pos, str); return *this; } + inline String &Erase(size_t pos, size_t count) { super::erase(pos, count); return *this; } + inline String &EraseBetween(size_t from, size_t to) { if(from < to) super::erase(from, to - from); return *this; } inline bool operator==(String const &other) { return std::basic_string(*this) == other; } + inline bool operator!=(String const &other) { return std::basic_string(*this) != other; } ByteString ToUtf8() const; ByteString ToAscii() const; @@ -81,11 +203,30 @@ public: using Stream = std::basic_stringstream; }; -inline String operator+(String::value_type const *ch, String const &str) { return String(ch) + str; } -inline String operator+(std::basic_string const &other, String const &str) { return String(other) + str; } -inline String operator+(std::basic_string &&other, String const &str) { return String(std::move(other)) + str; } -template inline String operator+(ByteString::value_type const (&ch)[N], String const &str) { return String(ch) + str; } - +inline String operator+(String const &lhs, String const &rhs) { return static_cast const &>(lhs) + static_cast const &>(rhs); } +inline String operator+(String const &lhs, String &&rhs) { return static_cast const &>(lhs) + static_cast &&>(rhs); } +inline String operator+(String &&lhs, String const &rhs) { return static_cast &&>(lhs) + static_cast const &>(rhs); } +inline String operator+(String &&lhs, String &&rhs) { return static_cast &&>(lhs) + static_cast &&>(rhs); } +inline String operator+(String const &lhs, std::basic_string const &rhs) { return static_cast const &>(lhs) + rhs; } +inline String operator+(String const &lhs, std::basic_string &&rhs) { return static_cast const &>(lhs) + std::move(rhs); } +inline String operator+(String &&lhs, std::basic_string const &rhs) { return static_cast &&>(lhs) + rhs; } +inline String operator+(String &&lhs, std::basic_string &&rhs) { return static_cast &&>(lhs) + std::move(rhs); } +inline String operator+(String const &lhs, String::value_type rhs) { return static_cast const &>(lhs) + rhs; } +inline String operator+(String &&lhs, String::value_type rhs) { return static_cast &&>(lhs) + rhs; } +inline String operator+(String const &lhs, String::value_type const *rhs) { return static_cast const &>(lhs) + rhs; } +inline String operator+(String &&lhs, String::value_type const *rhs) { return static_cast &&>(lhs) + rhs; } +template inline String operator+(String const &lhs, ByteString::value_type const (&rhs)[N]) { return static_cast const &>(lhs) + std::move(ByteString(rhs).FromAscii()); } +template inline String operator+(String &&lhs, ByteString::value_type const (&rhs)[N]) { return static_cast &&>(lhs) + std::move(ByteString(rhs).FromAscii()); } +inline String operator+(std::basic_string const &lhs, String const &rhs) { return lhs + static_cast const &>(rhs); } +inline String operator+(std::basic_string const &lhs, String &&rhs) { return lhs + static_cast &&>(rhs); } +inline String operator+(std::basic_string &&lhs, String const &rhs) { return std::move(lhs) + static_cast const &>(rhs); } +inline String operator+(std::basic_string &&lhs, String &&rhs) { return std::move(lhs) + static_cast &&>(rhs); } +inline String operator+(String::value_type lhs, String const &rhs) { return lhs + static_cast const &>(rhs); } +inline String operator+(String::value_type lhs, String &&rhs) { return lhs + static_cast &&>(rhs); } +inline String operator+(String::value_type const *lhs, String const &rhs) { return lhs + static_cast const &>(rhs); } +inline String operator+(String::value_type const *lhs, String &&rhs) { return lhs + static_cast &&>(rhs); } +template inline String operator+(ByteString::value_type const (&lhs)[N], String const &rhs) { return std::move(ByteString(lhs).FromAscii()) + static_cast const &>(rhs); } +template inline String operator+(ByteString::value_type const (&lhs)[N], String &&rhs) { return std::move(ByteString(lhs).FromAscii()) + static_cast &&>(rhs); } inline String ByteString::FromAscii() const { diff --git a/src/graphics/Graphics.cpp b/src/graphics/Graphics.cpp index 12b0bec29..7d5700033 100644 --- a/src/graphics/Graphics.cpp +++ b/src/graphics/Graphics.cpp @@ -591,7 +591,7 @@ void Graphics::textnpos(String str, int n, int w, int *cx, int *cy) while (*s&&n) { wordlen = 0; - while(*s && String(" .,!?\n").find(*s) != String::npos) + while(*s && String(" .,!?\n").Contains(*s)) s++; charspace = textwidthx(s, w-x); if (charspaceCommand(command); consoleModel->AddLastCommand(ConsoleCommand(command, returnCode, commandInterface->GetLastError())); diff --git a/src/gui/elementsearch/ElementSearchActivity.cpp b/src/gui/elementsearch/ElementSearchActivity.cpp index 9bad0fd5e..3ffc2c8f8 100644 --- a/src/gui/elementsearch/ElementSearchActivity.cpp +++ b/src/gui/elementsearch/ElementSearchActivity.cpp @@ -117,9 +117,9 @@ void ElementSearchActivity::searchTools(String query) std::transform(nameLower.begin(), nameLower.end(), nameLower.begin(), ::tolower); if(nameLower == queryLower) exactmatches.push_back(*iter); - else if(!nameLower.compare(0, queryLower.length(), queryLower)) + else if(!nameLower.BeginsWith(queryLower)) frontmatches.push_back(*iter); - else if(nameLower.find(queryLower) != String::npos) + else if(nameLower.Contains(queryLower)) matches.push_back(*iter); } @@ -181,7 +181,7 @@ void ElementSearchActivity::SetActiveTool(int selectionState, Tool * tool) gameController->RebuildFavoritesMenu(); } else if (ctrlPressed && altPressed && !shiftPressed && - tool->GetIdentifier().find("DEFAULT_PT_") != tool->GetIdentifier().npos) + tool->GetIdentifier().Contains("DEFAULT_PT_")) { gameController->SetActiveTool(3, tool); } diff --git a/src/gui/filebrowser/FileBrowserActivity.cpp b/src/gui/filebrowser/FileBrowserActivity.cpp index bfcc128fb..e130e9960 100644 --- a/src/gui/filebrowser/FileBrowserActivity.cpp +++ b/src/gui/filebrowser/FileBrowserActivity.cpp @@ -75,17 +75,8 @@ class LoadFilesTask: public Task saveFile->SetGameSave(tempSave); saveFiles.push_back(saveFile); - ByteString filename = *iter; - size_t folderPos = filename.rfind(PATH_SEP); - if(folderPos!=ByteString::npos && folderPos+1 < filename.size()) - { - filename = filename.substr(folderPos+1); - } - size_t extPos = filename.rfind("."); - if(extPos!=ByteString::npos) - { - filename = filename.substr(0, extPos); - } + ByteString filename = (*iter).SplitFromEndBy(PATH_SEP).After(); + filename = filename.SplitBy('.').Before(); saveFile->SetDisplayName(filename.FromUtf8()); } catch(std::exception & e) diff --git a/src/gui/font/FontEditor.cpp b/src/gui/font/FontEditor.cpp index d80b1a6b9..b322c4bad 100644 --- a/src/gui/font/FontEditor.cpp +++ b/src/gui/font/FontEditor.cpp @@ -281,7 +281,7 @@ FontEditor::FontEditor(ByteString _header): v->PrevChar(); } }; - ui::Button *prev = new ui::Button(ui::Point(currentX, baseline), ui::Point(17, 17), String(1, 0xE016)); + ui::Button *prev = new ui::Button(ui::Point(currentX, baseline), ui::Point(17, 17), 0xE016); currentX += 18; prev->SetActionCallback(new PrevCharAction(this)); AddComponent(prev); @@ -316,7 +316,7 @@ FontEditor::FontEditor(ByteString _header): v->NextChar(); } }; - ui::Button *next = new ui::Button(ui::Point(currentX, baseline), ui::Point(17, 17), String(1, 0xE015)); + ui::Button *next = new ui::Button(ui::Point(currentX, baseline), ui::Point(17, 17), 0xE015); currentX += 18; next->SetActionCallback(new NextCharAction(this)); AddComponent(next); diff --git a/src/gui/game/GameController.cpp b/src/gui/game/GameController.cpp index 6b27e065d..f7b1079ac 100644 --- a/src/gui/game/GameController.cpp +++ b/src/gui/game/GameController.cpp @@ -674,7 +674,7 @@ bool GameController::MouseUp(int x, int y, unsigned button, char type) ret = false; if (type == 'c' || type == 't' || type == 's') { - String link = str.substr(3, pos-3); + String link = str.Substr(3, pos-3); switch (type) { case 'c': @@ -983,7 +983,7 @@ void GameController::Update() { int rightSelected = PT_DUST; Tool * activeTool = gameModel->GetActiveTool(1); - if (activeTool->GetIdentifier().find("DEFAULT_PT_") != activeTool->GetIdentifier().npos) + if (activeTool->GetIdentifier().BeginsWith("DEFAULT_PT_")) { int sr = activeTool->GetToolID(); if (sr && sim->IsValidElement(sr)) diff --git a/src/gui/game/GameView.cpp b/src/gui/game/GameView.cpp index 6e01e08b7..75c1ac8a5 100644 --- a/src/gui/game/GameView.cpp +++ b/src/gui/game/GameView.cpp @@ -433,7 +433,7 @@ GameView::GameView(): v->c->OpenElementSearch(); } }; - ui::Button * tempButton = new ui::Button(ui::Point(WINDOWW-16, WINDOWH-32), ui::Point(15, 15), String(1, 0xE065), "Search for elements"); + ui::Button * tempButton = new ui::Button(ui::Point(WINDOWW-16, WINDOWH-32), ui::Point(15, 15), 0xE065, "Search for elements"); tempButton->Appearance.Margin = ui::Border(0, 2, 3, 2); tempButton->SetActionCallback(new ElementSearchAction(this)); AddComponent(tempButton); @@ -555,7 +555,7 @@ public: else { if (v->CtrlBehaviour() && v->AltBehaviour() && !v->ShiftBehaviour()) - if (tool->GetIdentifier().find("DEFAULT_PT_") != tool->GetIdentifier().npos) + if (tool->GetIdentifier().BeginsWith("DEFAULT_PT_")) sender->SetSelectionState(3); if (sender->GetSelectionState() >= 0 && sender->GetSelectionState() <= 3) @@ -676,18 +676,15 @@ void GameView::NotifyActiveToolsChanged(GameModel * sender) if(sender->GetActiveTool(0) == tool) { toolButtons[i]->SetSelectionState(0); //Primary - if (tool->GetIdentifier().find("DEFAULT_UI_WIND") != tool->GetIdentifier().npos) - windTool = true; - else - windTool = false; + windTool = tool->GetIdentifier() == "DEFAULT_UI_WIND"; - if (sender->GetActiveTool(0)->GetIdentifier().find("DEFAULT_DECOR_") != sender->GetActiveTool(0)->GetIdentifier().npos) + if (sender->GetActiveTool(0)->GetIdentifier().BeginsWith("DEFAULT_DECOR_")) decoBrush = true; } else if(sender->GetActiveTool(1) == tool) { toolButtons[i]->SetSelectionState(1); //Secondary - if (sender->GetActiveTool(1)->GetIdentifier().find("DEFAULT_DECOR_") != sender->GetActiveTool(1)->GetIdentifier().npos) + if (sender->GetActiveTool(1)->GetIdentifier().BeginsWith("DEFAULT_DECOR_")) decoBrush = true; } else if(sender->GetActiveTool(2) == tool) @@ -708,7 +705,7 @@ void GameView::NotifyActiveToolsChanged(GameModel * sender) if (sender->GetRenderer()->findingElement) { Tool *active = sender->GetActiveTool(0); - if (active->GetIdentifier().find("_PT_") == active->GetIdentifier().npos) + if (active->GetIdentifier().Contains("_PT_")) ren->findingElement = 0; else ren->findingElement = sender->GetActiveTool(0)->GetToolID()%256; @@ -723,10 +720,7 @@ void GameView::NotifyLastToolChanged(GameModel * sender) if (sender->GetLastTool()) { wallBrush = sender->GetLastTool()->GetBlocky(); - if (sender->GetLastTool()->GetIdentifier().find("DEFAULT_TOOL_") != sender->GetLastTool()->GetIdentifier().npos) - toolBrush = true; - else - toolBrush = false; + toolBrush = sender->GetLastTool()->GetIdentifier().BeginsWith("DEFAULT_TOOL_"); } } @@ -1504,7 +1498,7 @@ void GameView::OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool if (ctrl) { Tool *active = c->GetActiveTool(0); - if (active->GetIdentifier().find("_PT_") == active->GetIdentifier().npos || ren->findingElement == active->GetToolID()%256) + if (!active->GetIdentifier().Contains("_PT_") || ren->findingElement == active->GetToolID()%256) ren->findingElement = 0; else ren->findingElement = active->GetToolID()%256; @@ -1739,7 +1733,7 @@ void GameView::OnTick(float dt) int pos = sign::splitsign(str, &type); if (type == 'c' || type == 't' || type == 's') { - String linkSign = str.substr(3, pos-3); + String linkSign = str.Substr(3, pos-3); String::Stream tooltip; switch (type) { @@ -1912,7 +1906,7 @@ void GameView::NotifyNotificationsChanged(GameModel * sender) AddComponent(tempButton); notificationComponents.push_back(tempButton); - tempButton = new ui::Button(ui::Point(XRES-20, currentY), ui::Point(15, 15), String(1, 0xE02A)); + tempButton = new ui::Button(ui::Point(XRES-20, currentY), ui::Point(15, 15), 0xE02A); //tempButton->SetIcon(IconClose); tempButton->SetActionCallback(new CloseNotificationButtonAction(this, *iter)); tempButton->Appearance.Margin.Left -= 1; @@ -2266,7 +2260,7 @@ void GameView::OnDraw() { String::Stream sampleInfo; sampleInfo << recordingIndex; - sampleInfo << ". " + String(1, 0xE00E) + " REC"; + sampleInfo << ". " + String(0xE00E) + " REC"; int textWidth = Graphics::textwidth(sampleInfo.str()); g->fillrect(XRES-20-textWidth, 12, textWidth+8, 15, 0, 0, 0, 255*0.5); diff --git a/src/gui/game/PropertyTool.cpp b/src/gui/game/PropertyTool.cpp index 2491cb906..487ab3528 100644 --- a/src/gui/game/PropertyTool.cpp +++ b/src/gui/game/PropertyTool.cpp @@ -104,20 +104,20 @@ void PropertyWindow::SetProperty() case StructProperty::ParticleType: { int v; - if(value.length() > 2 && value.substr(0, 2) == "0x") + if(value.length() > 2 && value.BeginsWith("0x")) { //0xC0FFEE String::Stream buffer; buffer.exceptions(String::Stream::failbit | String::Stream::badbit); - buffer << std::hex << value.substr(2); + buffer << std::hex << value.Substr(2); buffer >> v; } - else if(value.length() > 1 && value[0] == '#') + else if(value.length() > 1 && value.BeginsWith("0")) { //#C0FFEE String::Stream buffer; buffer.exceptions(String::Stream::failbit | String::Stream::badbit); - buffer << std::hex << value.substr(1); + buffer << std::hex << value.Substr(1); buffer >> v; } else @@ -155,20 +155,20 @@ void PropertyWindow::SetProperty() case StructProperty::UInteger: { unsigned int v; - if(value.length() > 2 && value.substr(0, 2) == "0x") + if(value.length() > 2 && value.BeginsWith("0x")) { //0xC0FFEE String::Stream buffer; buffer.exceptions(String::Stream::failbit | String::Stream::badbit); - buffer << std::hex << value.substr(2); + buffer << std::hex << value.Substr(2); buffer >> v; } - else if(value.length() > 1 && value[0] == '#') + else if(value.length() > 1 && value.BeginsWith("#")) { //#C0FFEE String::Stream buffer; buffer.exceptions(String::Stream::failbit | String::Stream::badbit); - buffer << std::hex << value.substr(1); + buffer << std::hex << value.Substr(1); buffer >> v; } else @@ -190,9 +190,9 @@ void PropertyWindow::SetProperty() buffer >> tool->propValue.Float; if (properties[property->GetOption().second].Name == "temp" && value.length()) { - if (value.substr(value.length()-1) == "C") + if (value.EndsWith("C")) tool->propValue.Float += 273.15; - else if (value.substr(value.length()-1) == "F") + else if (value.EndsWith("F")) tool->propValue.Float = (tool->propValue.Float-32.0f)*5/9+273.15f; } #ifdef DEBUG diff --git a/src/gui/game/SignTool.cpp b/src/gui/game/SignTool.cpp index 046a16308..5302d48b8 100644 --- a/src/gui/game/SignTool.cpp +++ b/src/gui/game/SignTool.cpp @@ -128,10 +128,10 @@ SignWindow::SignWindow(SignTool * tool_, Simulation * sim_, int signID_, ui::Poi justification = new ui::DropDown(ui::Point(52, 48), ui::Point(50, 16)); AddComponent(justification); - justification->AddOption(std::pair(String(1, 0xE020) + " Left", (int)sign::Left)); - justification->AddOption(std::pair(String(1, 0xE01E) + " Middle", (int)sign::Middle)); - justification->AddOption(std::pair(String(1, 0xE01F) + " Right", (int)sign::Right)); - justification->AddOption(std::pair(String(1, 0xE01D) + " None", (int)sign::None)); + justification->AddOption(std::pair(0xE020 + String(" Left"), (int)sign::Left)); + justification->AddOption(std::pair(0xE01E + String(" Middle"), (int)sign::Middle)); + justification->AddOption(std::pair(0xE01F + String(" Right"), (int)sign::Right)); + justification->AddOption(std::pair(0xE01D + String(" None"), (int)sign::None)); justification->SetOption(1); justification->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; diff --git a/src/gui/game/ToolButton.cpp b/src/gui/game/ToolButton.cpp index f2000024e..751cfd6f6 100644 --- a/src/gui/game/ToolButton.cpp +++ b/src/gui/game/ToolButton.cpp @@ -13,7 +13,7 @@ ToolButton::ToolButton(ui::Point position, ui::Point size, ByteString text_, Byt Appearance.BorderFavorite = ui::Colour(255, 255, 0); //don't use "..." on elements that have long names - buttonDisplayText = ButtonText.substr(0, 7); + buttonDisplayText = ButtonText.Substr(0, 7); Component::TextPosition(buttonDisplayText); } @@ -67,7 +67,7 @@ void ToolButton::Draw(const ui::Point& screenPos) } if (Favorite::Ref().IsFavorite(toolIdentifier)) { - g->drawtext(screenPos.X, screenPos.Y, String(1, 0xE068), Appearance.BorderFavorite.Red, Appearance.BorderFavorite.Green, Appearance.BorderFavorite.Blue, Appearance.BorderFavorite.Alpha); + g->drawtext(screenPos.X, screenPos.Y, 0xE068, Appearance.BorderFavorite.Red, Appearance.BorderFavorite.Green, Appearance.BorderFavorite.Blue, Appearance.BorderFavorite.Alpha); } if (totalColour<544) diff --git a/src/gui/interface/Label.cpp b/src/gui/interface/Label.cpp index a790ed718..ce4b66f5b 100644 --- a/src/gui/interface/Label.cpp +++ b/src/gui/interface/Label.cpp @@ -214,9 +214,9 @@ void Label::copySelection() String copyText; if (selectionIndex1 > selectionIndex0) - copyText = currentText.substr(selectionIndex0, selectionIndex1-selectionIndex0).c_str(); + copyText = currentText.Between(selectionIndex0, selectionIndex1).c_str(); else if(selectionIndex0 > selectionIndex1) - copyText = currentText.substr(selectionIndex1, selectionIndex0-selectionIndex1).c_str(); + copyText = currentText.Between(selectionIndex1, selectionIndex0).c_str(); else if (!currentText.length()) return; else @@ -324,8 +324,8 @@ void Label::updateSelection() textFragments = currentText; //textFragments.insert(selectionIndex1, "\x0E"); //textFragments.insert(selectionIndex0, "\x0F\x01\x01\x01"); - textFragments.insert(selectionIndex1, "\x01"); - textFragments.insert(selectionIndex0, "\x01"); + textFragments.Insert(selectionIndex1, "\x01"); + textFragments.Insert(selectionIndex0, "\x01"); } else if(selectionIndex0 > selectionIndex1) { selectionLineH = Graphics::PositionAtCharIndex(currentText, selectionIndex0, selectionXH, selectionYH); selectionLineL = Graphics::PositionAtCharIndex(currentText, selectionIndex1, selectionXL, selectionYL); @@ -333,8 +333,8 @@ void Label::updateSelection() textFragments = currentText; //textFragments.insert(selectionIndex0, "\x0E"); //textFragments.insert(selectionIndex1, "\x0F\x01\x01\x01"); - textFragments.insert(selectionIndex0, "\x01"); - textFragments.insert(selectionIndex1, "\x01"); + textFragments.Insert(selectionIndex0, "\x01"); + textFragments.Insert(selectionIndex1, "\x01"); } else { selectionXH = -1; selectionXL = -1; @@ -349,14 +349,14 @@ void Label::updateSelection() int tSelectionIndex1 = Graphics::CharIndexAtPosition(displayText, selectionXH, selectionYH); int tSelectionIndex0 = Graphics::CharIndexAtPosition(displayText, selectionXL, selectionYL); - displayText.insert(tSelectionIndex1, "\x01"); - displayText.insert(tSelectionIndex0, "\x01"); + displayText.Insert(tSelectionIndex1, "\x01"); + displayText.Insert(tSelectionIndex0, "\x01"); } else if(selectionIndex0 > selectionIndex1) { int tSelectionIndex0 = Graphics::CharIndexAtPosition(displayText, selectionXH, selectionYH); int tSelectionIndex1 = Graphics::CharIndexAtPosition(displayText, selectionXL, selectionYL); - displayText.insert(tSelectionIndex0, "\x01"); - displayText.insert(tSelectionIndex1, "\x01"); + displayText.Insert(tSelectionIndex0, "\x01"); + displayText.Insert(tSelectionIndex1, "\x01"); } } } diff --git a/src/gui/interface/SaveButton.cpp b/src/gui/interface/SaveButton.cpp index 9b7732559..8fd9aef2c 100644 --- a/src/gui/interface/SaveButton.cpp +++ b/src/gui/interface/SaveButton.cpp @@ -239,15 +239,15 @@ void SaveButton::Draw(const Point& screenPos) int y = screenPos.Y-15+(Size.Y-thumbBoxSize.Y)/2+thumbBoxSize.Y; g->fillrect(x+1, y+1, 7, 8, 255, 255, 255, 255); if (isMouseInsideHistory) { - g->drawtext(x, y, String(1, 0xE026), 200, 100, 80, 255); + g->drawtext(x, y, 0xE026, 200, 100, 80, 255); } else { - g->drawtext(x, y, String(1, 0xE026), 160, 70, 50, 255); + g->drawtext(x, y, 0xE026, 160, 70, 50, 255); } } if (!save->GetPublished()) { - g->drawtext(screenPos.X, screenPos.Y-2, String(1, 0xE04D), 255, 255, 255, 255); - g->drawtext(screenPos.X, screenPos.Y-2, String(1, 0xE04E), 212, 151, 81, 255); + g->drawtext(screenPos.X, screenPos.Y-2, 0xE04D, 255, 255, 255, 255); + g->drawtext(screenPos.X, screenPos.Y-2, 0xE04E, 212, 151, 81, 255); } } else if (file) diff --git a/src/gui/interface/Textbox.cpp b/src/gui/interface/Textbox.cpp index ce9ca014c..659f909c5 100644 --- a/src/gui/interface/Textbox.cpp +++ b/src/gui/interface/Textbox.cpp @@ -141,7 +141,7 @@ void Textbox::cutSelection() { if (getLowerSelectionBound() < 0 || getHigherSelectionBound() > (int)backingText.length()) return; - String toCopy = backingText.substr(getLowerSelectionBound(), getHigherSelectionBound()-getLowerSelectionBound()); + String toCopy = backingText.Between(getLowerSelectionBound(), getHigherSelectionBound()); ClipboardPush(format::CleanString(toCopy, false, true, false).ToUtf8()); backingText.erase(backingText.begin()+getLowerSelectionBound(), backingText.begin()+getHigherSelectionBound()); cursor = getLowerSelectionBound(); @@ -191,7 +191,7 @@ void Textbox::pasteIntoSelection() { if (getLowerSelectionBound() < 0 || getHigherSelectionBound() > (int)backingText.length()) return; - backingText.erase(backingText.begin()+getLowerSelectionBound(), backingText.begin()+getHigherSelectionBound()); + backingText.EraseBetween(getLowerSelectionBound(), getHigherSelectionBound()); cursor = getLowerSelectionBound(); } @@ -203,7 +203,7 @@ void Textbox::pasteIntoSelection() if (limit != String::npos) { - newText = newText.substr(0, limit-backingText.length()); + newText = newText.Substr(0, limit-backingText.length()); } if (!multiline && Graphics::textwidth(backingText + newText) > regionWidth) { @@ -211,12 +211,12 @@ void Textbox::pasteIntoSelection() int cIndex = Graphics::CharIndexAtPosition(newText, pLimit, 0); if (cIndex > 0) - newText = newText.substr(0, cIndex); + newText = newText.Substr(0, cIndex); else newText = ""; } - backingText.insert(cursor, newText); + backingText.Insert(cursor, newText); cursor = cursor+newText.length(); ClearSelection(); @@ -353,7 +353,7 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool { if (getLowerSelectionBound() < 0 || getHigherSelectionBound() > (int)backingText.length()) return; - backingText.erase(backingText.begin()+getLowerSelectionBound(), backingText.begin()+getHigherSelectionBound()); + backingText.Erase(getLowerSelectionBound(), getHigherSelectionBound()); cursor = getLowerSelectionBound(); changed = true; } @@ -362,9 +362,9 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool if (ctrl) { size_t stopChar; - stopChar = backingText.find_first_not_of(String(" .,!?\n"), cursor); - stopChar = backingText.find_first_of(String(" .,!?\n"), stopChar); - backingText.erase(cursor, stopChar-cursor); + stopChar = backingText.SplitByNot(" .,!?\n", cursor).PositionBefore(); + stopChar = backingText.SplitByAny(" .,!?\n", stopChar).PositionBefore(); + backingText.EraseBetween(cursor, stopChar); } else backingText.erase(cursor, 1); @@ -388,12 +388,12 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool if (ctrl) { size_t stopChar; - stopChar = backingText.substr(0, cursor).find_last_not_of(String(" .,!?\n")); + stopChar = backingText.SplitFromEndByNot(" .,!?\n", cursor).PositionBefore(); if (stopChar == backingText.npos) stopChar = -1; else - stopChar = backingText.substr(0, stopChar).find_last_of(String(" .,!?\n")); - backingText.erase(stopChar+1, cursor-(stopChar+1)); + stopChar = backingText.SplitFromEndByAny(" .,!?\n", stopChar).PositionBefore(); + backingText.EraseBetween(stopChar+1, cursor); cursor = stopChar+1; } else @@ -431,7 +431,7 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool } else { - backingText.insert(cursor, 1, String::value_type(character)); + backingText.Insert(cursor, character); } cursor++; } diff --git a/src/gui/localbrowser/LocalBrowserView.cpp b/src/gui/localbrowser/LocalBrowserView.cpp index dc8acd8b8..d0c1f175b 100644 --- a/src/gui/localbrowser/LocalBrowserView.cpp +++ b/src/gui/localbrowser/LocalBrowserView.cpp @@ -21,8 +21,8 @@ LocalBrowserView::LocalBrowserView(): lastChanged(0), pageCount(0) { - nextButton = new ui::Button(ui::Point(WINDOWW-52, WINDOWH-18), ui::Point(50, 16), "Next " + String(1, 0xE015)); - previousButton = new ui::Button(ui::Point(2, WINDOWH-18), ui::Point(50, 16), String(1, 0xE016) + " Prev"); + nextButton = new ui::Button(ui::Point(WINDOWW-52, WINDOWH-18), ui::Point(50, 16), String("Next ") + 0xE015); + previousButton = new ui::Button(ui::Point(2, WINDOWH-18), ui::Point(50, 16), 0xE016 + String(" Prev")); undeleteButton = new ui::Button(ui::Point(WINDOWW-122, WINDOWH-18), ui::Point(60, 16), "Rescan"); AddComponent(nextButton); AddComponent(previousButton); diff --git a/src/gui/login/LoginModel.cpp b/src/gui/login/LoginModel.cpp index bcfe90531..fed7ddc15 100644 --- a/src/gui/login/LoginModel.cpp +++ b/src/gui/login/LoginModel.cpp @@ -8,7 +8,7 @@ LoginModel::LoginModel(): void LoginModel::Login(ByteString username, ByteString password) { - if (username.find('@') != username.npos) + if (username.Contains("@")) { statusText = "Use your Powder Toy account to log in, not your email. If you don't have a Powder Toy account, you can create one at https://powdertoy.co.uk/Register.html"; loginStatus = false; diff --git a/src/gui/preview/PreviewView.cpp b/src/gui/preview/PreviewView.cpp index e58b27e92..df0eea955 100644 --- a/src/gui/preview/PreviewView.cpp +++ b/src/gui/preview/PreviewView.cpp @@ -280,10 +280,8 @@ void PreviewView::commentBoxAutoHeight() bool PreviewView::CheckSwearing(String text) { for (std::set::iterator iter = swearWords.begin(), end = swearWords.end(); iter != end; iter++) - { - if (text.find(*iter) != text.npos) + if (text.Contains(*iter)) return true; - } return false; } @@ -293,7 +291,7 @@ void PreviewView::CheckComment() return; String text = addCommentBox->GetText(); std::transform(text.begin(), text.end(), text.begin(), ::tolower); - if (!userIsAuthor && (text.find("stolen") != String::npos || text.find("copied") != String::npos)) + if (!userIsAuthor && (text.Contains("stolen") || text.Contains("copied"))) { if (!commentHelpText) { @@ -304,7 +302,7 @@ void PreviewView::CheckComment() commentHelpText = true; } } - else if (userIsAuthor && text.find("vote") != text.npos) + else if (userIsAuthor && text.Contains("vote")) { commentWarningLabel->SetText("Do not ask for votes"); commentHelpText = true; diff --git a/src/gui/search/SearchView.cpp b/src/gui/search/SearchView.cpp index 88e712e85..117e5544d 100644 --- a/src/gui/search/SearchView.cpp +++ b/src/gui/search/SearchView.cpp @@ -24,8 +24,8 @@ SearchView::SearchView(): Client::Ref().AddListener(this); - nextButton = new ui::Button(ui::Point(WINDOWW-52, WINDOWH-18), ui::Point(50, 16), "Next " + String(1, 0xE015)); - previousButton = new ui::Button(ui::Point(2, WINDOWH-18), ui::Point(50, 16), String(1, 0xE016) + " Prev"); + nextButton = new ui::Button(ui::Point(WINDOWW-52, WINDOWH-18), ui::Point(50, 16), String("Next ") + 0xE015); + previousButton = new ui::Button(ui::Point(2, WINDOWH-18), ui::Point(50, 16), 0xE016 + String(" Prev")); tagsLabel = new ui::Label(ui::Point(270, WINDOWH-18), ui::Point(WINDOWW-540, 16), "\boPopular Tags:"); motdLabel = new ui::RichLabel(ui::Point(51, WINDOWH-18), ui::Point(WINDOWW-102, 16), Client::Ref().GetMessageOfTheDay()); diff --git a/src/gui/update/UpdateActivity.cpp b/src/gui/update/UpdateActivity.cpp index 5c1bd32c8..9cf228633 100644 --- a/src/gui/update/UpdateActivity.cpp +++ b/src/gui/update/UpdateActivity.cpp @@ -43,7 +43,7 @@ private: { free(data); errorStream << "Server responded with Status " << status; - notifyError("Could not download update: " + errorStream.str()); + notifyError("Could not download update: " + String(errorStream.str())); return false; } if (!data) @@ -109,7 +109,7 @@ private: return true; corrupt: - notifyError("Downloaded update is corrupted\n" + errorStream.str()); + notifyError("Downloaded update is corrupted\n" + String(errorStream.str())); free(data); return false; } diff --git a/src/lua/LuaScriptInterface.cpp b/src/lua/LuaScriptInterface.cpp index 6052f83c1..013f1596e 100644 --- a/src/lua/LuaScriptInterface.cpp +++ b/src/lua/LuaScriptInterface.cpp @@ -623,7 +623,7 @@ int LuaScriptInterface::simulation_signNewIndex(lua_State *l) if (!key.compare("text")) { const char *temp = luaL_checkstring(l, 3); - String cleaned = format::CleanString(ByteString(temp).FromUtf8(), false, true, true).substr(0, 45); + String cleaned = format::CleanString(ByteString(temp).FromUtf8(), false, true, true).Substr(0, 45); if (!cleaned.empty()) luacon_sim->signs[id].text = cleaned; else @@ -670,7 +670,7 @@ int LuaScriptInterface::simulation_newsign(lua_State *l) if (luacon_sim->signs.size() >= MAXSIGNS) return lua_pushnil(l), 1; - String text = format::CleanString(ByteString(luaL_checkstring(l, 1)).FromUtf8(), false, true, true).substr(0, 45); + String text = format::CleanString(ByteString(luaL_checkstring(l, 1)).FromUtf8(), false, true, true).Substr(0, 45); int x = luaL_checkinteger(l, 2); int y = luaL_checkinteger(l, 3); int ju = luaL_optinteger(l, 4, 1); @@ -2894,7 +2894,7 @@ int LuaScriptInterface::elements_free(lua_State * l) return luaL_error(l, "Invalid element"); ByteString identifier = luacon_sim->elements[id].Identifier; - if(identifier.length()>7 && identifier.substr(0, 7) == "DEFAULT") + if(identifier.BeginsWith("DEFAULT")) return luaL_error(l, "Cannot free default elements"); luacon_sim->elements[id].Enabled = false; @@ -3524,7 +3524,7 @@ int LuaScriptInterface::Command(String command) if (command[0] == '!') { lastError = ""; - int ret = legacy->Command(command.substr(1)); + int ret = legacy->Command(command.Substr(1)); lastError = legacy->GetLastError(); return ret; } @@ -3549,7 +3549,7 @@ int LuaScriptInterface::Command(String command) { lastError = luacon_geterror(); String err = lastError; - if (err.find("near ''") != err.npos) //the idea stolen from lua-5.1.5/lua.c + if (err.Contains("near ''")) //the idea stolen from lua-5.1.5/lua.c lastError = "..."; else lastCode = ""; @@ -3808,7 +3808,7 @@ String LuaScriptInterface::FormatCommand(String command) { if(command.size() && command[0] == '!') { - return "!"+legacy->FormatCommand(command.substr(1)); + return "!"+legacy->FormatCommand(command.Substr(1)); } else return highlight(command); diff --git a/src/lua/TPTScriptInterface.cpp b/src/lua/TPTScriptInterface.cpp index 7e46d8f7b..22ee72d2d 100644 --- a/src/lua/TPTScriptInterface.cpp +++ b/src/lua/TPTScriptInterface.cpp @@ -274,9 +274,9 @@ AnyType TPTScriptInterface::tptS_set(std::deque * words) { String newString = ((StringType)value).Value(); if (newString.at(newString.length()-1) == 'C') - newValuef = atof(newString.substr(0, newString.length()-1).ToUtf8().c_str())+273.15; + newValuef = atof(newString.SubstrFromEnd(1).ToUtf8().c_str())+273.15; else if (newString.at(newString.length()-1) == 'F') - newValuef = (atof(newString.substr(0, newString.length()-1).ToUtf8().c_str())-32.0f)*5/9+273.15f; + newValuef = (atof(newString.SubstrFromEnd(1).ToUtf8().c_str())-32.0f)*5/9+273.15f; else throw GeneralException("Invalid value for assignment"); } diff --git a/src/simulation/Sign.cpp b/src/simulation/Sign.cpp index 02d94ada4..01bbf40ac 100644 --- a/src/simulation/Sign.cpp +++ b/src/simulation/Sign.cpp @@ -41,7 +41,7 @@ String sign::getText(Simulation *sim) { int pos = splitsign(text); if (pos) - signTextNew << text.substr(pos+1, text.length()-pos-2); + signTextNew << text.Between(pos + 1, text.size() - 1); else signTextNew << text; } diff --git a/src/simulation/Simulation.cpp b/src/simulation/Simulation.cpp index b5e306608..0a1791eec 100644 --- a/src/simulation/Simulation.cpp +++ b/src/simulation/Simulation.cpp @@ -76,7 +76,7 @@ int Simulation::Load(int fullX, int fullY, GameSave * save, bool includePressure // if this is a custom element, set the ID to the ID we found when comparing identifiers in the palette map // set type to 0 if we couldn't find an element with that identifier present when loading, // unless this is a default element, in which case keep the current ID, because otherwise when an element is renamed it wouldn't show up anymore in older saves - if (myId != 0 || pi.first.find("DEFAULT_PT_") != 0) + if (myId != 0 || pi.first.BeginsWith("DEFAULT_PT_")) partMap[pi.second] = myId; } } From ced7b0c993aa7683b04d20460abca01e81828c87 Mon Sep 17 00:00:00 2001 From: mniip Date: Wed, 2 May 2018 02:22:10 +0300 Subject: [PATCH 10/27] Move the ConversionError class --- src/common/String.cpp | 4 ++-- src/common/String.h | 17 +++++++++-------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/common/String.cpp b/src/common/String.cpp index a197d17a6..41bbe0136 100644 --- a/src/common/String.cpp +++ b/src/common/String.cpp @@ -5,7 +5,7 @@ #include "String.h" -std::string ByteString::ConversionError::formatError(ByteString::value_type const *at, ByteString::value_type const *upto) +ByteString ConversionError::formatError(ByteString::value_type const *at, ByteString::value_type const *upto) { std::stringstream ss; ss << "Could not convert sequence to UTF-8:"; @@ -77,7 +77,7 @@ ByteString String::ToUtf8() const } else if(result == std::codecvt_base::error) { - throw ByteString::ConversionError(true); + throw ConversionError(true); } else if(result == std::codecvt_base::partial) { diff --git a/src/common/String.h b/src/common/String.h index 76825f684..706f270e0 100644 --- a/src/common/String.h +++ b/src/common/String.h @@ -99,14 +99,6 @@ public: public: - class ConversionError : public std::runtime_error - { - static std::string formatError(value_type const *at, value_type const *upto); - public: - inline ConversionError(value_type const *at, value_type const *upto): std::runtime_error(formatError(at, upto)) {} - inline ConversionError(bool to): std::runtime_error(to ? "Could not convert to UTF-8" : "Could not convert from UTF-8") {} - }; - String FromUtf8(bool ignoreError = true) const; inline String FromAscii() const; @@ -243,4 +235,13 @@ inline ByteString String::ToAscii() const destination[i] = ByteString::value_type(operator[](i)); return destination; } + +class ConversionError : public std::runtime_error +{ + static ByteString formatError(ByteString::value_type const *at, ByteString::value_type const *upto); +public: + inline ConversionError(ByteString::value_type const *at, ByteString::value_type const *upto): std::runtime_error(formatError(at, upto)) {} + inline ConversionError(bool to): std::runtime_error(to ? "Could not convert to UTF-8" : "Could not convert from UTF-8") {} +}; + #endif From f864f81a7617bdd0a2355eb400aaf8c96ccf363d Mon Sep 17 00:00:00 2001 From: mniip Date: Wed, 2 May 2018 05:38:08 +0300 Subject: [PATCH 11/27] StringBuilder mockup --- src/common/String.cpp | 159 ++++++++++++++++++++++++++++++++++++++++++ src/common/String.h | 41 +++++++++++ 2 files changed, 200 insertions(+) diff --git a/src/common/String.cpp b/src/common/String.cpp index 41bbe0136..87f133327 100644 --- a/src/common/String.cpp +++ b/src/common/String.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include "String.h" @@ -88,6 +89,164 @@ ByteString String::ToUtf8() const } } +inline String::value_type widen_wchar(wchar_t ch) +{ + return std::make_unsigned::type(ch); +} + +inline bool representable_wchar(String::value_type ch) +{ + return ch < String::value_type(std::make_unsigned::type(std::numeric_limits::max())); +} + +inline wchar_t narrow_wchar(String::value_type ch) +{ + return wchar_t(ch); +} + +static thread_local struct LocaleImpl +{ + std::basic_stringstream stream; + std::basic_stringstream wstream; + + LocaleImpl() + { + stream.imbue(std::locale::classic()); + wstream.imbue(std::locale::classic()); + } + + inline void PrepareWStream(StringBuilder &b) + { + wstream.flags(b.flags); + wstream.width(b.width); + wstream.precision(b.precision); + wstream.fill(b.fill); + } + + inline void FlushWStream(StringBuilder &b) + { + std::basic_string wstr = wstream.str(); + std::vector chars; // operator new? + chars.reserve(wstr.size()); + for(wchar_t ch : wstream.str()) + chars.push_back(widen_wchar(ch)); + b.AddChars(chars.data(), chars.size()); + wstream.str(std::basic_string()); + } +} +LocaleImpl; + +String StringBuilder::Build() const +{ + return String(buffer.begin(), buffer.end()); +} + +void StringBuilder::AddChars(String::value_type const *data, size_t count) +{ + buffer.reserve(buffer.size() + count); + buffer.insert(buffer.end(), data, data + count); +} + +StringBuilder &operator<<(StringBuilder &b, short int data) +{ + LocaleImpl.PrepareWStream(b); + LocaleImpl.wstream << data; + LocaleImpl.FlushWStream(b); + return b; +} + +StringBuilder &operator<<(StringBuilder &b, int data) +{ + LocaleImpl.PrepareWStream(b); + LocaleImpl.wstream << data; + LocaleImpl.FlushWStream(b); + return b; +} + +StringBuilder &operator<<(StringBuilder &b, long int data) +{ + LocaleImpl.PrepareWStream(b); + LocaleImpl.wstream << data; + LocaleImpl.FlushWStream(b); + return b; +} + +StringBuilder &operator<<(StringBuilder &b, long long int data) +{ + LocaleImpl.PrepareWStream(b); + LocaleImpl.wstream << data; + LocaleImpl.FlushWStream(b); + return b; +} + +StringBuilder &operator<<(StringBuilder &b, unsigned short int data) +{ + LocaleImpl.PrepareWStream(b); + LocaleImpl.wstream << data; + LocaleImpl.FlushWStream(b); + return b; +} + +StringBuilder &operator<<(StringBuilder &b, unsigned int data) +{ + LocaleImpl.PrepareWStream(b); + LocaleImpl.wstream << data; + LocaleImpl.FlushWStream(b); + return b; +} + +StringBuilder &operator<<(StringBuilder &b, unsigned long int data) +{ + LocaleImpl.PrepareWStream(b); + LocaleImpl.wstream << data; + LocaleImpl.FlushWStream(b); + return b; +} + +StringBuilder &operator<<(StringBuilder &b, unsigned long long int data) +{ + LocaleImpl.PrepareWStream(b); + LocaleImpl.wstream << data; + LocaleImpl.FlushWStream(b); + return b; +} + +StringBuilder &operator<<(StringBuilder &b, ByteString::value_type data) +{ + String::value_type ch = data; + b.AddChars(&ch, 1); + return b; +} + +StringBuilder &operator<<(StringBuilder &b, String::value_type data) +{ + b.AddChars(&data, 1); + return b; +} + +StringBuilder &operator<<(StringBuilder &b, String const &data) +{ + b.AddChars(data.data(), data.size()); + return b; +} + +StringBuilder &operator<<(StringBuilder &b, float data) +{ + LocaleImpl.PrepareWStream(b); + LocaleImpl.wstream << data; + LocaleImpl.FlushWStream(b); + return b; +} + +StringBuilder &operator<<(StringBuilder &b, double data) +{ + LocaleImpl.PrepareWStream(b); + LocaleImpl.wstream << data; + LocaleImpl.FlushWStream(b); + return b; +} + + template<> std::ctype::~ctype() { } diff --git a/src/common/String.h b/src/common/String.h index 706f270e0..9b6eb2696 100644 --- a/src/common/String.h +++ b/src/common/String.h @@ -3,9 +3,13 @@ #include #include +#include #include +#include +class ByteStringBuilder; class String; +class StringBuilder; template class SplitBase { @@ -244,4 +248,41 @@ public: inline ConversionError(bool to): std::runtime_error(to ? "Could not convert to UTF-8" : "Could not convert from UTF-8") {} }; +class StringBuilder +{ + std::vector buffer; // TODO: std::list > ? +public: + std::ios_base::fmtflags flags; + String::value_type fill; + size_t width, precision; + inline StringBuilder(): flags(std::ios_base::skipws | std::ios_base::dec), fill(' '), width(0), precision(6) {} + + void AddChars(String::value_type const *, size_t); + size_t Size() const { return buffer.size(); } + String Build() const; + + template StringBuilder &operator<<(T) = delete; + + template StringBuilder &Add(T &&arg, Ts&&... args) + { + return (*this << std::forward(arg)).Add(std::forward(args)...); + } + StringBuilder &Add() { return *this; } +}; + +StringBuilder &operator<<(StringBuilder &, short int); +StringBuilder &operator<<(StringBuilder &, int); +StringBuilder &operator<<(StringBuilder &, long int); +StringBuilder &operator<<(StringBuilder &, long long int); +StringBuilder &operator<<(StringBuilder &, unsigned short int); +StringBuilder &operator<<(StringBuilder &, unsigned int); +StringBuilder &operator<<(StringBuilder &, unsigned long int); +StringBuilder &operator<<(StringBuilder &, unsigned long long int); +StringBuilder &operator<<(StringBuilder &, ByteString::value_type); +StringBuilder &operator<<(StringBuilder &, String::value_type); +StringBuilder &operator<<(StringBuilder &, String const &); +StringBuilder &operator<<(StringBuilder &, float); +StringBuilder &operator<<(StringBuilder &, double); +template StringBuilder &operator<<(StringBuilder &b, ByteString::value_type const (&data)[N]) { return b << ByteString(data).FromUtf8(); } + #endif From eeacc90fc57734aa542e082c7bcc755df0e52caf Mon Sep 17 00:00:00 2001 From: mniip Date: Wed, 2 May 2018 06:54:28 +0300 Subject: [PATCH 12/27] Add StringBuilder formatters --- src/common/Format.h | 90 +++++++++++++++++++++++++++++++++++++++++++++ src/common/String.h | 5 +-- 2 files changed, 92 insertions(+), 3 deletions(-) create mode 100644 src/common/Format.h diff --git a/src/common/Format.h b/src/common/Format.h new file mode 100644 index 000000000..1cec0408e --- /dev/null +++ b/src/common/Format.h @@ -0,0 +1,90 @@ +#pragma once + +#include +#include + +#include "common/String.h" + +template class FormatProxy +{ + T const &value; + inline FormatProxy(T const &_value): value(_value) {} +public: + inline void Write(StringBuilder &b) { b << value; } +}; + +class Format +{ + std::function writer; +public: + template inline Format(T const &value, Ts... args): + writer([value, args...](StringBuilder &b) { FormatProxy(value, args...).Write(b); }) + {} + + friend StringBuilder &operator<<(StringBuilder &, Format const &); + + enum Base { Dec, Oct, Hex }; + enum Float { Default, Fixed, Scientific }; +}; + +inline StringBuilder &operator<<(StringBuilder &b, Format const &f) +{ + f.writer(b); + return b; +} + +template class IntegralFormatProxy +{ + T value; + Format::Base base; + size_t width; +public: + inline IntegralFormatProxy(T _value, Format::Base _base = Format::Dec, size_t _width = 0): value(_value), base(_base), width(_width) {} + inline void Write(StringBuilder &b) + { + std::ios_base::fmtflags oldflags = b.flags; + b.flags &= ~std::ios_base::basefield; + b.flags |= base == Format::Hex ? std::ios_base::hex : base == Format::Oct ? std::ios_base::oct : std::ios_base::dec; + size_t oldwidth = b.width; + b.width = width; + b << value; + b.flags = oldflags; + b.width = oldwidth; + } +}; + +template<> class FormatProxy: public IntegralFormatProxy { using IntegralFormatProxy::IntegralFormatProxy; }; +template<> class FormatProxy: public IntegralFormatProxy { using IntegralFormatProxy::IntegralFormatProxy; }; +template<> class FormatProxy: public IntegralFormatProxy { using IntegralFormatProxy::IntegralFormatProxy; }; +template<> class FormatProxy: public IntegralFormatProxy { using IntegralFormatProxy::IntegralFormatProxy; }; +template<> class FormatProxy: public IntegralFormatProxy { using IntegralFormatProxy::IntegralFormatProxy; }; +template<> class FormatProxy: public IntegralFormatProxy { using IntegralFormatProxy::IntegralFormatProxy; }; +template<> class FormatProxy: public IntegralFormatProxy { using IntegralFormatProxy::IntegralFormatProxy; }; +template<> class FormatProxy: public IntegralFormatProxy { using IntegralFormatProxy::IntegralFormatProxy; }; + +template class FloatingFormatProxy +{ + T value; + size_t precision; + Format::Float style; + size_t width; +public: + inline FloatingFormatProxy(T _value, size_t _precision, Format::Float _style = Format::Default, size_t _width = 0): value(_value), precision(_precision), style(_style), width(_width) {} + inline void Write(StringBuilder &b) + { + std::ios_base::fmtflags oldflags = b.flags; + b.flags &= ~std::ios_base::floatfield; + b.flags |= style == Format::Fixed ? std::ios_base::fixed : style == Format::Scientific ? std::ios_base::scientific : std::ios_base::fmtflags(); + size_t oldwidth = b.width; + b.width = width; + size_t oldprecision = b.precision; + b.precision = precision; + b << value; + b.flags = oldflags; + b.width = oldwidth; + b.precision = oldprecision; + } +}; + +template<> class FormatProxy: public FloatingFormatProxy { using FloatingFormatProxy::FloatingFormatProxy; }; +template<> class FormatProxy: public FloatingFormatProxy { using FloatingFormatProxy::FloatingFormatProxy; }; diff --git a/src/common/String.h b/src/common/String.h index 9b6eb2696..1f6011b47 100644 --- a/src/common/String.h +++ b/src/common/String.h @@ -1,5 +1,4 @@ -#ifndef TPT_STRING -#define TPT_STRING +#pragma once #include #include @@ -285,4 +284,4 @@ StringBuilder &operator<<(StringBuilder &, float); StringBuilder &operator<<(StringBuilder &, double); template StringBuilder &operator<<(StringBuilder &b, ByteString::value_type const (&data)[N]) { return b << ByteString(data).FromUtf8(); } -#endif +#include "common/Format.h" From 7523c14252f0d99b5537612728584636cf1a71e3 Mon Sep 17 00:00:00 2001 From: mniip Date: Wed, 2 May 2018 08:45:50 +0300 Subject: [PATCH 13/27] Reword the Format interface --- src/common/Format.h | 154 ++++++++++++++++++++++++++------------------ src/common/String.h | 8 +++ 2 files changed, 99 insertions(+), 63 deletions(-) diff --git a/src/common/Format.h b/src/common/Format.h index 1cec0408e..1c7fdf975 100644 --- a/src/common/Format.h +++ b/src/common/Format.h @@ -13,78 +13,106 @@ public: inline void Write(StringBuilder &b) { b << value; } }; -class Format +namespace Format { - std::function writer; -public: - template inline Format(T const &value, Ts... args): - writer([value, args...](StringBuilder &b) { FormatProxy(value, args...).Write(b); }) - {} + template struct FlagsOverride + { + T value; + inline FlagsOverride(T _value): value(_value) {} + }; + template struct FlagsOverride + { + inline FlagsOverride() {} + }; - friend StringBuilder &operator<<(StringBuilder &, Format const &); + template struct WidthOverride + { + T value; + size_t width; + inline WidthOverride(T _value, size_t _width): value(_value), width(_width) {} + }; + template<> struct WidthOverride + { + size_t width; + inline WidthOverride(size_t _width): width(_width) {} + }; - enum Base { Dec, Oct, Hex }; - enum Float { Default, Fixed, Scientific }; + template struct PrecisionOverride + { + T value; + size_t precision; + inline PrecisionOverride(T _value, size_t _precision): value(_value), precision(_precision) {} + }; + template<> struct PrecisionOverride + { + size_t precision; + inline PrecisionOverride(size_t _precision): precision(_precision) {} + }; + + template inline FlagsOverride Oct(T value) { return FlagsOverride(value); } + template inline FlagsOverride Dec(T value) { return FlagsOverride(value); } + template inline FlagsOverride Hex(T value) { return FlagsOverride(value); } + inline FlagsOverride Oct() { return FlagsOverride(); } + inline FlagsOverride Dec() { return FlagsOverride(); } + inline FlagsOverride Hex() { return FlagsOverride(); } + + template inline FlagsOverride Fixed(T value) { return FlagsOverride(value); } + template inline FlagsOverride Scientific(T value) { return FlagsOverride(value); } + template inline FlagsOverride FloatDefault(T value) { return FlagsOverride(value); } + inline FlagsOverride Fixed() { return FlagsOverride(); } + inline FlagsOverride Scientific() { return FlagsOverride(); } + inline FlagsOverride FloatDefault() { return FlagsOverride(); } + + template inline WidthOverride Width(T value, size_t width) { return WidthOverride(value, width); } + template inline PrecisionOverride Precision(T value, size_t precision) { return PrecisionOverride(value, precision); } + inline WidthOverride Width(size_t width) { return WidthOverride(width); } + inline PrecisionOverride Precision(size_t precision) { return PrecisionOverride(precision); } }; -inline StringBuilder &operator<<(StringBuilder &b, Format const &f) +template inline StringBuilder &operator<<(StringBuilder &b, Format::FlagsOverride data) { - f.writer(b); + std::ios_base::fmtflags oldflags = b.flags; + b.flags = (b.flags & ~reset) | set; + b << data.value; + b.flags = oldflags; + return b; +} +template inline StringBuilder &operator<<(StringBuilder &b, Format::FlagsOverride data) +{ + b.flags = (b.flags & ~reset) | set; return b; } -template class IntegralFormatProxy +template inline StringBuilder &operator<<(StringBuilder &b, Format::WidthOverride data) { - T value; - Format::Base base; - size_t width; -public: - inline IntegralFormatProxy(T _value, Format::Base _base = Format::Dec, size_t _width = 0): value(_value), base(_base), width(_width) {} - inline void Write(StringBuilder &b) - { - std::ios_base::fmtflags oldflags = b.flags; - b.flags &= ~std::ios_base::basefield; - b.flags |= base == Format::Hex ? std::ios_base::hex : base == Format::Oct ? std::ios_base::oct : std::ios_base::dec; - size_t oldwidth = b.width; - b.width = width; - b << value; - b.flags = oldflags; - b.width = oldwidth; - } -}; - -template<> class FormatProxy: public IntegralFormatProxy { using IntegralFormatProxy::IntegralFormatProxy; }; -template<> class FormatProxy: public IntegralFormatProxy { using IntegralFormatProxy::IntegralFormatProxy; }; -template<> class FormatProxy: public IntegralFormatProxy { using IntegralFormatProxy::IntegralFormatProxy; }; -template<> class FormatProxy: public IntegralFormatProxy { using IntegralFormatProxy::IntegralFormatProxy; }; -template<> class FormatProxy: public IntegralFormatProxy { using IntegralFormatProxy::IntegralFormatProxy; }; -template<> class FormatProxy: public IntegralFormatProxy { using IntegralFormatProxy::IntegralFormatProxy; }; -template<> class FormatProxy: public IntegralFormatProxy { using IntegralFormatProxy::IntegralFormatProxy; }; -template<> class FormatProxy: public IntegralFormatProxy { using IntegralFormatProxy::IntegralFormatProxy; }; - -template class FloatingFormatProxy + size_t oldwidth = b.width; + b.width = data.width; + b << data.value; + b.width = oldwidth; + return b; +} +inline StringBuilder &operator<<(StringBuilder &b, Format::WidthOverride data) { - T value; - size_t precision; - Format::Float style; - size_t width; -public: - inline FloatingFormatProxy(T _value, size_t _precision, Format::Float _style = Format::Default, size_t _width = 0): value(_value), precision(_precision), style(_style), width(_width) {} - inline void Write(StringBuilder &b) - { - std::ios_base::fmtflags oldflags = b.flags; - b.flags &= ~std::ios_base::floatfield; - b.flags |= style == Format::Fixed ? std::ios_base::fixed : style == Format::Scientific ? std::ios_base::scientific : std::ios_base::fmtflags(); - size_t oldwidth = b.width; - b.width = width; - size_t oldprecision = b.precision; - b.precision = precision; - b << value; - b.flags = oldflags; - b.width = oldwidth; - b.precision = oldprecision; - } -}; + b.width = data.width; + return b; +} -template<> class FormatProxy: public FloatingFormatProxy { using FloatingFormatProxy::FloatingFormatProxy; }; -template<> class FormatProxy: public FloatingFormatProxy { using FloatingFormatProxy::FloatingFormatProxy; }; +template inline StringBuilder &operator<<(StringBuilder &b, Format::PrecisionOverride data) +{ + std::ios_base::fmtflags oldflags = b.flags; + if(!(oldflags & std::ios_base::floatfield)) + b.flags |= std::ios_base::fixed; + size_t oldprecision = b.precision; + b.precision = data.precision; + b << data.value; + b.precision = oldprecision; + b.flags = oldflags; + return b; +} +inline StringBuilder &operator<<(StringBuilder &b, Format::PrecisionOverride data) +{ + if(!(b.flags & std::ios_base::floatfield)) + b.flags |= std::ios_base::fixed; + b.precision = data.precision; + return b; +} diff --git a/src/common/String.h b/src/common/String.h index 1f6011b47..79eb3d145 100644 --- a/src/common/String.h +++ b/src/common/String.h @@ -194,6 +194,7 @@ public: ByteString ToUtf8() const; ByteString ToAscii() const; + template static String Build(Ts&&... args); using Stream = std::basic_stringstream; }; @@ -284,4 +285,11 @@ StringBuilder &operator<<(StringBuilder &, float); StringBuilder &operator<<(StringBuilder &, double); template StringBuilder &operator<<(StringBuilder &b, ByteString::value_type const (&data)[N]) { return b << ByteString(data).FromUtf8(); } +template String String::Build(Ts&&... args) +{ + StringBuilder b; + b.Add(std::forward(args)...); + return b.Build(); +} + #include "common/Format.h" From 6c9cb174fb2598d11762cde62d1808a10653a1b0 Mon Sep 17 00:00:00 2001 From: mniip Date: Wed, 2 May 2018 22:08:52 +0300 Subject: [PATCH 14/27] Change some uses of String::Stream to StringBuilder --- src/PowderToySDL.cpp | 4 +- src/client/Client.cpp | 8 +-- src/client/GameSave.cpp | 7 +-- src/common/Format.h | 9 +++ src/debug/DebugLines.cpp | 21 +++---- src/debug/DebugParts.cpp | 7 +-- src/debug/ParticleDebug.cpp | 17 +++--- src/graphics/Renderer.cpp | 5 +- src/gui/colourpicker/ColourPickerActivity.cpp | 4 +- src/gui/font/FontEditor.cpp | 13 ++--- src/gui/game/GameController.cpp | 4 +- src/gui/game/GameModel.cpp | 5 +- src/gui/game/GameView.cpp | 56 +++++++++---------- .../localbrowser/LocalBrowserController.cpp | 15 ++--- src/gui/localbrowser/LocalBrowserView.cpp | 12 ++-- src/gui/preview/PreviewView.cpp | 4 +- src/gui/search/SearchController.cpp | 48 +++++----------- src/gui/search/SearchView.cpp | 18 +++--- src/gui/update/UpdateActivity.cpp | 18 +++--- src/lua/LuaScriptInterface.cpp | 50 +++++------------ src/lua/TPTSTypes.cpp | 8 +-- src/simulation/Sign.cpp | 17 +++--- src/tasks/TaskWindow.cpp | 10 +--- 23 files changed, 143 insertions(+), 217 deletions(-) diff --git a/src/PowderToySDL.cpp b/src/PowderToySDL.cpp index f16fb917d..4fd0bb32e 100644 --- a/src/PowderToySDL.cpp +++ b/src/PowderToySDL.cpp @@ -753,11 +753,11 @@ void EventProcess(SDL_Event event) void DoubleScreenDialog() { - String::Stream message; + StringBuilder message; message << "Switching to double size mode since your screen was determined to be large enough: "; message << desktopWidth << "x" << desktopHeight << " detected, " << WINDOWW*2 << "x" << WINDOWH*2 << " required"; message << "\nTo undo this, hit Cancel. You can toggle double size mode in settings at any time."; - if (!ConfirmPrompt::Blocking("Large screen detected", message.str())) + if (!ConfirmPrompt::Blocking("Large screen detected", message.Build())) { Client::Ref().SetPref("Scale", 1); engine->SetScale(1); diff --git a/src/client/Client.cpp b/src/client/Client.cpp index 333d7e98d..4741c896a 100644 --- a/src/client/Client.cpp +++ b/src/client/Client.cpp @@ -695,9 +695,7 @@ RequestStatus Client::ParseServerReturn(char *result, int status, bool json) return RequestOkay; if (status != 200) { - String::Stream httperror; - httperror << "HTTP Error " << status << ": " << http_ret_text(status); - lastError = httperror.str(); + lastError = String::Build("HTTP Error ", status, ": ", ByteString(http_ret_text(status)).FromUtf8()); return RequestFailure; } @@ -727,9 +725,7 @@ RequestStatus Client::ParseServerReturn(char *result, int status, bool json) if (!strncmp((const char *)result, "Error: ", 7)) { status = atoi(result+7); - String::Stream httperror; - httperror << "HTTP Error " << status << ": " << http_ret_text(status); - lastError = httperror.str(); + lastError = String::Build("HTTP Error ", status, ": ", ByteString(http_ret_text(status)).FromUtf8()); return RequestFailure; } lastError = "Could not read response: " + ByteString(e.what()).FromUtf8(); diff --git a/src/client/GameSave.cpp b/src/client/GameSave.cpp index 7bf4845f0..3b7f16f23 100644 --- a/src/client/GameSave.cpp +++ b/src/client/GameSave.cpp @@ -805,13 +805,12 @@ void GameSave::readOPS(char * data, int dataLength) if (major > SAVE_VERSION || (major == SAVE_VERSION && minor > MINOR_VERSION)) #endif { - String::Stream errorMessage; #ifdef RENDERER - errorMessage << "Save from a newer version: Requires render version " << renderMajor << "." << renderMinor; + String errorMessage = String::Build("Save from a newer version: Requires render version ", renderMajor, ".", renderMinor); #else - errorMessage << "Save from a newer version: Requires version " << major << "." << minor; + String errorMessage = String::Build("Save from a newer version: Requires version ", major, ".", minor); #endif - throw ParseException(ParseException::WrongVersion, errorMessage.str()); + throw ParseException(ParseException::WrongVersion, errorMessage); } #if defined(SNAPSHOT) || defined(DEBUG) else if (major > SAVE_VERSION || (major == SAVE_VERSION && minor > MINOR_VERSION)) diff --git a/src/common/Format.h b/src/common/Format.h index 1c7fdf975..cd454b362 100644 --- a/src/common/Format.h +++ b/src/common/Format.h @@ -56,6 +56,15 @@ namespace Format inline FlagsOverride Dec() { return FlagsOverride(); } inline FlagsOverride Hex() { return FlagsOverride(); } + template inline FlagsOverride Uppercase(T value) { return FlagsOverride(value); } + template inline FlagsOverride ShowPoint(T value) { return FlagsOverride(value); } + template inline FlagsOverride NoUppercase(T value) { return FlagsOverride(value); } + template inline FlagsOverride NoShowPoint(T value) { return FlagsOverride(value); } + inline FlagsOverride Uppercase() { return FlagsOverride(); } + inline FlagsOverride ShowPoint() { return FlagsOverride(); } + inline FlagsOverride NoUppercase() { return FlagsOverride(); } + inline FlagsOverride NoShowPoint() { return FlagsOverride(); } + template inline FlagsOverride Fixed(T value) { return FlagsOverride(value); } template inline FlagsOverride Scientific(T value) { return FlagsOverride(value); } template inline FlagsOverride FloatDefault(T value) { return FlagsOverride(value); } diff --git a/src/debug/DebugLines.cpp b/src/debug/DebugLines.cpp index 5a42928a1..7de5665b4 100644 --- a/src/debug/DebugLines.cpp +++ b/src/debug/DebugLines.cpp @@ -27,21 +27,18 @@ void DebugLines::Draw() g->draw_line(0, drawPoint2.Y, XRES, drawPoint2.Y, 255, 255, 255, 120); g->draw_line(drawPoint2.X, 0, drawPoint2.X, YRES, 255, 255, 255, 120); - String::Stream info; - info << drawPoint2.X << " x " << drawPoint2.Y; - g->drawtext_outline(drawPoint2.X+(drawPoint2.X>drawPoint1.X?3:-g->textwidth(info.str())-3), drawPoint2.Y+(drawPoint2.Ydrawtext_outline(drawPoint2.X+(drawPoint2.X>drawPoint1.X?3:-g->textwidth(info)-3), drawPoint2.Y+(drawPoint2.Ydrawtext_outline(drawPoint1.X+(drawPoint2.Xtextwidth(info.str())-2), drawPoint1.Y+(drawPoint2.Y>drawPoint1.Y?-10:3), info.str(), 255, 255, 255, 200); + info = String::Build(drawPoint1.X, " x ", drawPoint1.Y); + g->drawtext_outline(drawPoint1.X+(drawPoint2.Xtextwidth(info)-2), drawPoint1.Y+(drawPoint2.Y>drawPoint1.Y?-10:3), info, 255, 255, 255, 200); - info.str(String()); - info << std::abs(drawPoint2.X-drawPoint1.X); - g->drawtext_outline((drawPoint1.X+drawPoint2.X)/2-g->textwidth(info.str())/2, drawPoint1.Y+(drawPoint2.Y>drawPoint1.Y?-10:3), info.str(), 255, 255, 255, 200); + info = String::Build(std::abs(drawPoint2.X-drawPoint1.X)); + g->drawtext_outline((drawPoint1.X+drawPoint2.X)/2-g->textwidth(info)/2, drawPoint1.Y+(drawPoint2.Y>drawPoint1.Y?-10:3), info, 255, 255, 255, 200); - info.str(String()); - info << std::abs(drawPoint2.Y-drawPoint1.Y); - g->drawtext_outline(drawPoint1.X+(drawPoint2.Xtextwidth(info.str())-2), (drawPoint1.Y+drawPoint2.Y)/2-3, info.str(), 255, 255, 255, 200); + info = String::Build(std::abs(drawPoint2.Y-drawPoint1.Y)); + g->drawtext_outline(drawPoint1.X+(drawPoint2.Xtextwidth(info)-2), (drawPoint1.Y+drawPoint2.Y)/2-3, info, 255, 255, 255, 200); } } diff --git a/src/debug/DebugParts.cpp b/src/debug/DebugParts.cpp index 9c2ef55d2..ffab84228 100644 --- a/src/debug/DebugParts.cpp +++ b/src/debug/DebugParts.cpp @@ -15,8 +15,7 @@ void DebugParts::Draw() Graphics * g = ui::Engine::Ref().g; int x = 0, y = 0, lpx = 0, lpy = 0; - String::Stream info; - info << sim->parts_lastActiveIndex << "/" << NPART << " (" << std::fixed << std::setprecision(2) << (float)sim->parts_lastActiveIndex/(NPART)*100.0f << "%)"; + String info = String::Build(sim->parts_lastActiveIndex, "/", NPART, " (", Format::Precision((float)sim->parts_lastActiveIndex/(NPART)*100.0f, 2), "%)"); for (int i = 0; i < NPART; i++) { if (sim->parts[i].type) @@ -45,8 +44,8 @@ void DebugParts::Draw() g->addpixel(lpx, lpy+1, 255, 50, 50, 120); g->addpixel(lpx, lpy-1, 255, 50, 50, 120); - g->fillrect(7, YRES-26, g->textwidth(info.str())+5, 14, 0, 0, 0, 180); - g->drawtext(10, YRES-22, info.str(), 255, 255, 255, 255); + g->fillrect(7, YRES-26, g->textwidth(info)+5, 14, 0, 0, 0, 180); + g->drawtext(10, YRES-22, info, 255, 255, 255, 255); } DebugParts::~DebugParts() diff --git a/src/debug/ParticleDebug.cpp b/src/debug/ParticleDebug.cpp index a9fd3ebfe..d50ed7a9f 100644 --- a/src/debug/ParticleDebug.cpp +++ b/src/debug/ParticleDebug.cpp @@ -15,7 +15,7 @@ void ParticleDebug::Debug(int mode, int x, int y) { int debug_currentParticle = sim->debug_currentParticle; int i = 0; - String::Stream logmessage; + String logmessage; if (mode == 0) { @@ -25,21 +25,21 @@ void ParticleDebug::Debug(int mode, int x, int y) while (i < NPART && !sim->parts[i].type) i++; if (i == NPART) - logmessage << "End of particles reached, updated sim"; + logmessage = "End of particles reached, updated sim"; else - logmessage << "Updated particle #" << i; + logmessage = String::Build("Updated particle #", i); } else if (mode == 1) { if (x < 0 || x >= XRES || y < 0 || y >= YRES || !sim->pmap[y][x] || (i = ID(sim->pmap[y][x])) < debug_currentParticle) { i = NPART; - logmessage << "Updated particles from #" << debug_currentParticle << " to end, updated sim"; + logmessage = String::Build("Updated particles from #", debug_currentParticle, " to end, updated sim"); } else - logmessage << "Updated particles #" << debug_currentParticle << " through #" << i; + logmessage = String::Build("Updated particles #", debug_currentParticle, " through #", i); } - model->Log(logmessage.str(), false); + model->Log(logmessage, false); if (sim->debug_currentParticle == 0) { @@ -89,9 +89,8 @@ bool ParticleDebug::KeyPress(int key, Uint16 character, bool shift, bool ctrl, b { sim->UpdateParticles(sim->debug_currentParticle, NPART); sim->AfterSim(); - String::Stream logmessage; - logmessage << "Updated particles from #" << sim->debug_currentParticle << " to end, updated sim"; - model->Log(logmessage.str(), false); + String logmessage = String::Build("Updated particles from #", sim->debug_currentParticle, " to end, updated sim"); + model->Log(logmessage, false); sim->debug_currentParticle = 0; } else diff --git a/src/graphics/Renderer.cpp b/src/graphics/Renderer.cpp index 575a7e156..d937986f1 100644 --- a/src/graphics/Renderer.cpp +++ b/src/graphics/Renderer.cpp @@ -1496,9 +1496,8 @@ void Renderer::render_parts() if (mousePos.X>(nx-3) && mousePos.X<(nx+3) && mousePos.Y<(ny+3) && mousePos.Y>(ny-3)) //If mouse is in the head { - String::Stream hp; - hp << std::setw(3) << sim->parts[i].life; - drawtext(mousePos.X-8-2*(sim->parts[i].life<100)-2*(sim->parts[i].life<10), mousePos.Y-12, hp.str(), 255, 255, 255, 255); + String hp = String::Build(Format::Width(sim->parts[i].life, 3)); + drawtext(mousePos.X-8-2*(sim->parts[i].life<100)-2*(sim->parts[i].life<10), mousePos.Y-12, hp, 255, 255, 255, 255); } if (findingElement == t) diff --git a/src/gui/colourpicker/ColourPickerActivity.cpp b/src/gui/colourpicker/ColourPickerActivity.cpp index 85d051030..a3bef8f23 100644 --- a/src/gui/colourpicker/ColourPickerActivity.cpp +++ b/src/gui/colourpicker/ColourPickerActivity.cpp @@ -108,9 +108,7 @@ void ColourPickerActivity::UpdateTextboxes(int r, int g, int b, int a) gValue->SetText(format::NumberToString(g)); bValue->SetText(format::NumberToString(b)); aValue->SetText(format::NumberToString(a)); - String::Stream hex; - hex << std::hex << "0x" << std::setfill(String::value_type('0')) << std::setw(2) << std::uppercase << a << std::setw(2) << r << std::setw(2) << g << std::setw(2) << b; - hexValue->SetText(hex.str()); + hexValue->SetText(String::Build(Format::Hex(), Format::Uppercase(), Format::Width(2), a, r, g, b)); } void ColourPickerActivity::OnTryExit(ExitMethod method) { diff --git a/src/gui/font/FontEditor.cpp b/src/gui/font/FontEditor.cpp index b322c4bad..82a761f60 100644 --- a/src/gui/font/FontEditor.cpp +++ b/src/gui/font/FontEditor.cpp @@ -433,9 +433,7 @@ FontEditor::FontEditor(ByteString _header): int *refs[6] = {&fgR, &fgG, &fgB, &bgR, &bgG, &bgB}; for(int i = 0; i < 6; i++) { - String::Stream ss; - ss << *refs[i]; - ui::Textbox *colorComponent = new ui::Textbox(ui::Point(currentX, baseline), ui::Point(27, 17), ss.str()); + ui::Textbox *colorComponent = new ui::Textbox(ui::Point(currentX, baseline), ui::Point(27, 17), format::NumberToString(*refs[i])); currentX += 28; colorComponent->SetActionCallback(new ColorComponentAction(*refs[i])); AddComponent(colorComponent); @@ -522,14 +520,15 @@ FontEditor::FontEditor(ByteString _header): inputPreview->Appearance.VerticalAlign = ui::Appearance::AlignTop; inputPreview->SetActionCallback(new PreviewAction(this)); - String::Stream input; + StringBuilder input; + input << Format::Hex() << Format::Width(2); for(unsigned int ch = 0x20; ch <= 0xFF; ch++) { if(!(ch & 0x3F)) - input << "20 "; - input << std::hex << std::setw(2) << ch << " "; + input << 0x20 << " "; + input << ch << " "; } - inputPreview->SetText(input.str()); + inputPreview->SetText(input.Build()); PreviewAction(this).TextChangedCallback(inputPreview); AddComponent(inputPreview); } diff --git a/src/gui/game/GameController.cpp b/src/gui/game/GameController.cpp index f7b1079ac..f82dc4a5d 100644 --- a/src/gui/game/GameController.cpp +++ b/src/gui/game/GameController.cpp @@ -1638,7 +1638,7 @@ void GameController::NotifyUpdateAvailable(Client * sender) virtual void Action() { UpdateInfo info = Client::Ref().GetUpdateInfo(); - String::Stream updateMessage; + StringBuilder updateMessage; updateMessage << "Are you sure you want to run the updater? Please save any changes before updating.\n\nCurrent version:\n "; #ifdef SNAPSHOT @@ -1666,7 +1666,7 @@ void GameController::NotifyUpdateAvailable(Client * sender) if (info.Changelog.length()) updateMessage << "\n\nChangelog:\n" << info.Changelog; - new ConfirmPrompt("Run Updater", updateMessage.str(), new UpdateConfirmation(c)); + new ConfirmPrompt("Run Updater", updateMessage.Build(), new UpdateConfirmation(c)); } }; diff --git a/src/gui/game/GameModel.cpp b/src/gui/game/GameModel.cpp index 14684df97..e5d953cb2 100644 --- a/src/gui/game/GameModel.cpp +++ b/src/gui/game/GameModel.cpp @@ -912,12 +912,11 @@ void GameModel::SetPaused(bool pauseState) { if (!pauseState && sim->debug_currentParticle > 0) { - String::Stream logmessage; - logmessage << "Updated particles from #" << sim->debug_currentParticle << " to end due to unpause"; + String logmessage = String::Build("Updated particles from #", sim->debug_currentParticle, " to end due to unpause"); sim->UpdateParticles(sim->debug_currentParticle, NPART); sim->AfterSim(); sim->debug_currentParticle = 0; - Log(logmessage.str(), false); + Log(logmessage, false); } sim->sys_pause = pauseState?1:0; diff --git a/src/gui/game/GameView.cpp b/src/gui/game/GameView.cpp index 75c1ac8a5..37b95e3c9 100644 --- a/src/gui/game/GameView.cpp +++ b/src/gui/game/GameView.cpp @@ -971,7 +971,7 @@ void GameView::NotifySaveChanged(GameModel * sender) tagSimulationButton->Enabled = sender->GetSave()->GetID(); if (sender->GetSave()->GetID()) { - String::Stream tagsStream; + StringBuilder tagsStream; std::list tags = sender->GetSave()->GetTags(); if (tags.size()) { @@ -981,7 +981,7 @@ void GameView::NotifySaveChanged(GameModel * sender) tagsStream << " "; tagsStream << iter->FromUtf8(); } - tagSimulationButton->SetText(tagsStream.str()); + tagSimulationButton->SetText(tagsStream.Build()); } else { @@ -1734,7 +1734,7 @@ void GameView::OnTick(float dt) if (type == 'c' || type == 't' || type == 's') { String linkSign = str.Substr(3, pos-3); - String::Stream tooltip; + StringBuilder tooltip; switch (type) { case 'c': @@ -1747,7 +1747,7 @@ void GameView::OnTick(float dt) tooltip << "Search for " << linkSign; break; } - ToolTip(ui::Point(0, Size.Y), tooltip.str()); + ToolTip(ui::Point(0, Size.Y), tooltip.Build()); } } @@ -2258,13 +2258,11 @@ void GameView::OnDraw() if(recording) { - String::Stream sampleInfo; - sampleInfo << recordingIndex; - sampleInfo << ". " + String(0xE00E) + " REC"; + String sampleInfo = String::Build(recordingIndex, ". ", String(0xE00E), " REC"); - int textWidth = Graphics::textwidth(sampleInfo.str()); + int textWidth = Graphics::textwidth(sampleInfo); g->fillrect(XRES-20-textWidth, 12, textWidth+8, 15, 0, 0, 0, 255*0.5); - g->drawtext(XRES-16-textWidth, 16, sampleInfo.str(), 255, 50, 20, 255); + g->drawtext(XRES-16-textWidth, 16, sampleInfo, 255, 50, 20, 255); } else if(showHud) { @@ -2274,8 +2272,8 @@ void GameView::OnDraw() alpha = 255-toolTipPresence*3; if (alpha < 50) alpha = 50; - String::Stream sampleInfo; - sampleInfo.precision(2); + StringBuilder sampleInfo; + sampleInfo << Format::Precision(2); int type = sample.particle.type; if (type) @@ -2315,7 +2313,7 @@ void GameView::OnDraw() else sampleInfo << " ()"; } - sampleInfo << ", Temp: " << std::fixed << sample.particle.temp -273.15f << " C"; + sampleInfo << ", Temp: " << (sample.particle.temp - 273.15f) << " C"; sampleInfo << ", Life: " << sample.particle.life; if (sample.particle.type != PT_RFRG && sample.particle.type != PT_RFGL) sampleInfo << ", Tmp: " << sample.particle.tmp; @@ -2324,7 +2322,7 @@ void GameView::OnDraw() if (type == PT_CRAY || type == PT_DRAY || type == PT_EXOT || type == PT_LIGH || type == PT_SOAP || type == PT_TRON || type == PT_VIBR || type == PT_VIRS || type == PT_WARP || type == PT_LCRY || type == PT_CBNW || type == PT_TSNS || type == PT_DTEC || type == PT_LSNS || type == PT_PSTN) sampleInfo << ", Tmp2: " << sample.particle.tmp2; - sampleInfo << ", Pressure: " << std::fixed << sample.AirPressure; + sampleInfo << ", Pressure: " << sample.AirPressure; } else { @@ -2336,27 +2334,27 @@ void GameView::OnDraw() sampleInfo << c->ElementResolve(type, ctype).FromAscii(); else sampleInfo << c->ElementResolve(type, ctype).FromAscii(); - sampleInfo << ", Temp: " << std::fixed << sample.particle.temp - 273.15f << " C"; - sampleInfo << ", Pressure: " << std::fixed << sample.AirPressure; + sampleInfo << ", Temp: " << sample.particle.temp - 273.15f << " C"; + sampleInfo << ", Pressure: " << sample.AirPressure; } } else if (sample.WallType) { sampleInfo << c->WallName(sample.WallType); - sampleInfo << ", Pressure: " << std::fixed << sample.AirPressure; + sampleInfo << ", Pressure: " << sample.AirPressure; } else if (sample.isMouseInSim) { - sampleInfo << "Empty, Pressure: " << std::fixed << sample.AirPressure; + sampleInfo << "Empty, Pressure: " << sample.AirPressure; } else { sampleInfo << "Empty"; } - int textWidth = Graphics::textwidth(sampleInfo.str()); + int textWidth = Graphics::textwidth(sampleInfo.Build()); g->fillrect(XRES-20-textWidth, 12, textWidth+8, 15, 0, 0, 0, alpha*0.5f); - g->drawtext(XRES-16-textWidth, 16, sampleInfo.str(), 255, 255, 255, alpha*0.75f); + g->drawtext(XRES-16-textWidth, 16, sampleInfo.Build(), 255, 255, 255, alpha*0.75f); #ifndef OGLI if (wavelengthGfx) @@ -2397,7 +2395,8 @@ void GameView::OnDraw() if (showDebug) { - sampleInfo.str(String()); + StringBuilder sampleInfo; + sampleInfo << Format::Precision(2); if (type) sampleInfo << "#" << sample.ParticleID << ", "; @@ -2408,22 +2407,21 @@ void GameView::OnDraw() sampleInfo << ", GX: " << sample.GravityVelocityX << " GY: " << sample.GravityVelocityY; if (c->GetAHeatEnable()) - sampleInfo << ", AHeat: " << std::fixed << sample.AirTemperature -273.15f << " C"; + sampleInfo << ", AHeat: " << sample.AirTemperature - 273.15f << " C"; - textWidth = Graphics::textwidth(sampleInfo.str()); + textWidth = Graphics::textwidth(sampleInfo.Build()); g->fillrect(XRES-20-textWidth, 27, textWidth+8, 14, 0, 0, 0, alpha*0.5f); - g->drawtext(XRES-16-textWidth, 30, sampleInfo.str(), 255, 255, 255, alpha*0.75f); + g->drawtext(XRES-16-textWidth, 30, sampleInfo.Build(), 255, 255, 255, alpha*0.75f); } } if(showHud && introText < 51) { //FPS and some version info - String::Stream fpsInfo; - fpsInfo.precision(2); - fpsInfo << "FPS: " << std::fixed << ui::Engine::Ref().GetFps(); + StringBuilder fpsInfo; + fpsInfo << Format::Precision(2) << "FPS: " << ui::Engine::Ref().GetFps(); #ifdef DEBUG - fpsInfo << " Delta: " << std::fixed << ui::Engine::Ref().GetDelta(); + fpsInfo << " Delta: " << ui::Engine::Ref().GetDelta(); #endif if (showDebug) @@ -2442,10 +2440,10 @@ void GameView::OnDraw() if (ren && ren->findingElement) fpsInfo << " [FIND]"; - int textWidth = Graphics::textwidth(fpsInfo.str()); + int textWidth = Graphics::textwidth(fpsInfo.Build()); int alpha = 255-introText*5; g->fillrect(12, 12, textWidth+8, 15, 0, 0, 0, alpha*0.5); - g->drawtext(16, 16, fpsInfo.str(), 32, 216, 255, alpha*0.75); + g->drawtext(16, 16, fpsInfo.Build(), 32, 216, 255, alpha*0.75); } //Tooltips diff --git a/src/gui/localbrowser/LocalBrowserController.cpp b/src/gui/localbrowser/LocalBrowserController.cpp index 709414701..1675c68fc 100644 --- a/src/gui/localbrowser/LocalBrowserController.cpp +++ b/src/gui/localbrowser/LocalBrowserController.cpp @@ -44,12 +44,12 @@ void LocalBrowserController::RemoveSelected() virtual ~RemoveSelectedConfirmation() { } }; - String::Stream desc; + StringBuilder desc; desc << "Are you sure you want to delete " << browserModel->GetSelected().size() << " stamp"; if(browserModel->GetSelected().size()>1) desc << "s"; desc << "?"; - new ConfirmPrompt("Delete stamps", desc.str(), new RemoveSelectedConfirmation(this)); + new ConfirmPrompt("Delete stamps", desc.Build(), new RemoveSelectedConfirmation(this)); } void LocalBrowserController::removeSelectedC() @@ -64,10 +64,8 @@ void LocalBrowserController::removeSelectedC() { for (size_t i = 0; i < saves.size(); i++) { - String::Stream saveName; - saveName << "Deleting stamp [" << saves[i].FromUtf8() << "] ..."; - notifyStatus(saveName.str()); - Client::Ref().DeleteStamp(saves[i]); + notifyStatus(String::Build("Deleting stamp [", saves[i].FromUtf8(), "] ...")); + Client::Ref().DeleteStamp(saves[i]); notifyProgress((float(i+1)/float(saves.size())*100)); } return true; @@ -96,9 +94,8 @@ void LocalBrowserController::RescanStamps() virtual ~RescanConfirmation() { } }; - String::Stream desc; - desc << "Rescanning the stamps folder can find stamps added to the stamps folder or recover stamps when the stamps.def file has been lost or damaged. However, be warned that this will mess up the current sorting order"; - new ConfirmPrompt("Rescan", desc.str(), new RescanConfirmation(this)); + String desc = "Rescanning the stamps folder can find stamps added to the stamps folder or recover stamps when the stamps.def file has been lost or damaged. However, be warned that this will mess up the current sorting order"; + new ConfirmPrompt("Rescan", desc, new RescanConfirmation(this)); } void LocalBrowserController::rescanStampsC() diff --git a/src/gui/localbrowser/LocalBrowserView.cpp b/src/gui/localbrowser/LocalBrowserView.cpp index d0c1f175b..1a87a42e1 100644 --- a/src/gui/localbrowser/LocalBrowserView.cpp +++ b/src/gui/localbrowser/LocalBrowserView.cpp @@ -140,10 +140,9 @@ void LocalBrowserView::NotifyPageChanged(LocalBrowserModel * sender) } else { - String::Stream pageInfo; - pageInfo << "of " << pageCount; - pageCountLabel->SetText(pageInfo.str()); - int width = Graphics::textwidth(pageInfo.str().c_str()); + String pageInfo = String::Build("of ", pageCount); + pageCountLabel->SetText(pageInfo); + int width = Graphics::textwidth(pageInfo); pageLabel->Position.X = WINDOWW/2-width-20; pageTextbox->Position.X = WINDOWW/2-width+11; @@ -151,9 +150,8 @@ void LocalBrowserView::NotifyPageChanged(LocalBrowserModel * sender) //pageCountLabel->Position.X = WINDOWW/2+6; pageLabel->Visible = pageCountLabel->Visible = pageTextbox->Visible = true; - pageInfo.str(String()); - pageInfo << sender->GetPageNum(); - pageTextbox->SetText(pageInfo.str()); + pageInfo = String::Build(sender->GetPageNum()); + pageTextbox->SetText(pageInfo); } if(sender->GetPageNum() == 1) diff --git a/src/gui/preview/PreviewView.cpp b/src/gui/preview/PreviewView.cpp index df0eea955..d1565471b 100644 --- a/src/gui/preview/PreviewView.cpp +++ b/src/gui/preview/PreviewView.cpp @@ -637,9 +637,7 @@ void PreviewView::SaveLoadingError(String errorMessage) void PreviewView::NotifyCommentsPageChanged(PreviewModel * sender) { - String::Stream pageInfoStream; - pageInfoStream << "Page " << sender->GetCommentsPageNum() << " of " << sender->GetCommentsPageCount(); - pageInfo->SetText(pageInfoStream.str()); + pageInfo->SetText(String::Build("Page ", sender->GetCommentsPageNum(), " of ", sender->GetCommentsPageCount())); } void PreviewView::NotifyCommentsChanged(PreviewModel * sender) diff --git a/src/gui/search/SearchController.cpp b/src/gui/search/SearchController.cpp index 196a6d0c9..ce461b97a 100644 --- a/src/gui/search/SearchController.cpp +++ b/src/gui/search/SearchController.cpp @@ -235,12 +235,12 @@ void SearchController::RemoveSelected() virtual ~RemoveSelectedConfirmation() { } }; - String::Stream desc; + StringBuilder desc; desc << "Are you sure you want to delete " << searchModel->GetSelected().size() << " save"; if(searchModel->GetSelected().size()>1) desc << "s"; desc << "?"; - new ConfirmPrompt("Delete saves", desc.str(), new RemoveSelectedConfirmation(this)); + new ConfirmPrompt("Delete saves", desc.Build(), new RemoveSelectedConfirmation(this)); } void SearchController::removeSelectedC() @@ -255,14 +255,10 @@ void SearchController::removeSelectedC() { for (size_t i = 0; i < saves.size(); i++) { - String::Stream saveID; - saveID << "Deleting save [" << saves[i] << "] ..."; - notifyStatus(saveID.str()); + notifyStatus(String::Build("Deleting save [", saves[i], "] ...")); if (Client::Ref().DeleteSave(saves[i])!=RequestOkay) { - String::Stream saveIDF; - saveIDF << "Failed to delete [" << saves[i] << "]: " << Client::Ref().GetLastError(); - notifyError(saveIDF.str()); + notifyError(String::Build("Failed to delete [", saves[i], "]: ", Client::Ref().GetLastError())); c->Refresh(); return false; } @@ -293,12 +289,12 @@ void SearchController::UnpublishSelected(bool publish) virtual ~UnpublishSelectedConfirmation() { } }; - String::Stream desc; - desc << "Are you sure you want to " << (publish ? "publish " : "unpublish ") << searchModel->GetSelected().size() << " save"; + StringBuilder desc; + desc << "Are you sure you want to " << (publish ? String("publish ") : String("unpublish ")) << searchModel->GetSelected().size() << " save"; if (searchModel->GetSelected().size() > 1) desc << "s"; desc << "?"; - new ConfirmPrompt(publish ? String("Publish Saves") : String("Unpublish Saves"), desc.str(), new UnpublishSelectedConfirmation(this, publish)); + new ConfirmPrompt(publish ? String("Publish Saves") : String("Unpublish Saves"), desc.Build(), new UnpublishSelectedConfirmation(this, publish)); } void SearchController::unpublishSelectedC(bool publish) @@ -313,9 +309,7 @@ void SearchController::unpublishSelectedC(bool publish) bool PublishSave(int saveID) { - String::Stream message; - message << "Publishing save [" << saveID << "]"; - notifyStatus(message.str()); + notifyStatus(String::Build("Publishing save [", saveID, "]")); if (Client::Ref().PublishSave(saveID) != RequestOkay) return false; return true; @@ -323,9 +317,7 @@ void SearchController::unpublishSelectedC(bool publish) bool UnpublishSave(int saveID) { - String::Stream message; - message << "Unpublishing save [" << saveID << "]"; - notifyStatus(message.str()); + notifyStatus(String::Build("Unpublishing save [", saveID, "]")); if (Client::Ref().UnpublishSave(saveID) != RequestOkay) return false; return true; @@ -342,12 +334,10 @@ void SearchController::unpublishSelectedC(bool publish) ret = UnpublishSave(saves[i]); if (!ret) { - String::Stream error; if (publish) // uses html page so error message will be spam - error << "Failed to publish [" << saves[i] << "], is this save yours?"; + notifyError(String::Build("Failed to publish [", saves[i], "], is this save yours?")); else - error << "Failed to unpublish [" << saves[i] << "]: " + Client::Ref().GetLastError(); - notifyError(error.str()); + notifyError(String::Build("Failed to unpublish [", saves[i], "]: " + Client::Ref().GetLastError())); c->Refresh(); return false; } @@ -373,14 +363,10 @@ void SearchController::FavouriteSelected() { for (size_t i = 0; i < saves.size(); i++) { - String::Stream saveID; - saveID << "Favouring save [" << saves[i] << "]"; - notifyStatus(saveID.str()); + notifyStatus(String::Build("Favouring save [", saves[i], "]")); if (Client::Ref().FavouriteSave(saves[i], true)!=RequestOkay) { - String::Stream saveIDF; - saveIDF << "Failed to favourite [" << saves[i] << "]: " + Client::Ref().GetLastError(); - notifyError(saveIDF.str()); + notifyError(String::Build("Failed to favourite [", saves[i], "]: " + Client::Ref().GetLastError())); return false; } notifyProgress((float(i+1)/float(saves.size())*100)); @@ -398,14 +384,10 @@ void SearchController::FavouriteSelected() { for (size_t i = 0; i < saves.size(); i++) { - String::Stream saveID; - saveID << "Unfavouring save [" << saves[i] << "]"; - notifyStatus(saveID.str()); + notifyStatus(String::Build("Unfavouring save [", saves[i], "]")); if (Client::Ref().FavouriteSave(saves[i], false)!=RequestOkay) { - String::Stream saveIDF; - saveIDF << "Failed to unfavourite [" << saves[i] << "]: " + Client::Ref().GetLastError(); - notifyError(saveIDF.str()); + notifyError(String::Build("Failed to unfavourite [", saves[i], "]: " + Client::Ref().GetLastError())); return false; } notifyProgress((float(i+1)/float(saves.size())*100)); diff --git a/src/gui/search/SearchView.cpp b/src/gui/search/SearchView.cpp index 117e5544d..14fe3798f 100644 --- a/src/gui/search/SearchView.cpp +++ b/src/gui/search/SearchView.cpp @@ -374,10 +374,9 @@ void SearchView::NotifyPageChanged(SearchModel * sender) } else { - String::Stream pageInfo; - pageInfo << "of " << pageCount; - pageCountLabel->SetText(pageInfo.str()); - int width = Graphics::textwidth(pageInfo.str().c_str()); + String pageInfo = String::Build("of ", pageCount); + pageCountLabel->SetText(pageInfo); + int width = Graphics::textwidth(pageInfo); pageLabel->Position.X = WINDOWW/2-width-20; pageTextbox->Position.X = WINDOWW/2-width+11; @@ -385,9 +384,8 @@ void SearchView::NotifyPageChanged(SearchModel * sender) //pageCountLabel->Position.X = WINDOWW/2+6; pageLabel->Visible = pageCountLabel->Visible = pageTextbox->Visible = true; - pageInfo.str(String()); - pageInfo << sender->GetPageNum(); - pageTextbox->SetText(pageInfo.str()); + pageInfo = String::Build(sender->GetPageNum()); + pageTextbox->SetText(pageInfo); } if(sender->GetPageNum() == 1) { @@ -671,13 +669,11 @@ void SearchView::NotifySaveListChanged(SearchModel * sender) } virtual void AltActionCallback(ui::SaveButton * sender) { - String::Stream search; - search << "history:" << sender->GetSave()->GetID(); - v->Search(search.str()); + v->Search(String::Build("history:", sender->GetSave()->GetID())); } virtual void AltActionCallback2(ui::SaveButton * sender) { - v->Search("user:"+sender->GetSave()->GetUserName().FromUtf8()); + v->Search(String::Build("user:", sender->GetSave()->GetUserName().FromUtf8())); } }; for (size_t i = 0; i < saves.size(); i++) diff --git a/src/gui/update/UpdateActivity.cpp b/src/gui/update/UpdateActivity.cpp index 9cf228633..3f9ddcb8b 100644 --- a/src/gui/update/UpdateActivity.cpp +++ b/src/gui/update/UpdateActivity.cpp @@ -25,7 +25,7 @@ private: } virtual bool doWork() { - String::Stream errorStream; + String error; void * request = http_async_req_start(NULL, (char*)updateName.c_str(), NULL, 0, 0); notifyStatus("Downloading update"); notifyProgress(-1); @@ -42,13 +42,13 @@ private: if (status!=200) { free(data); - errorStream << "Server responded with Status " << status; - notifyError("Could not download update: " + String(errorStream.str())); + error = String::Build("Server responded with Status ", status); + notifyError("Could not download update: " + error); return false; } if (!data) { - errorStream << "Server responded with nothing"; + error = "Server responded with nothing"; notifyError("Server did not return any data"); return false; } @@ -60,12 +60,12 @@ private: if(dataLength<16) { - errorStream << "Unsufficient data, got " << dataLength << " bytes"; + error = String::Build("Unsufficient data, got ", dataLength, " bytes"); goto corrupt; } if (data[0]!=0x42 || data[1]!=0x75 || data[2]!=0x54 || data[3]!=0x54) { - errorStream << "Invalid update format"; + error = "Invalid update format"; goto corrupt; } @@ -78,7 +78,7 @@ private: res = (char *)malloc(uncompressedLength); if (!res) { - errorStream << "Unable to allocate " << uncompressedLength << " bytes of memory for decompression"; + error = String::Build("Unable to allocate ", uncompressedLength, " bytes of memory for decompression"); goto corrupt; } @@ -86,7 +86,7 @@ private: dstate = BZ2_bzBuffToBuffDecompress((char *)res, (unsigned *)&uncompressedLength, (char *)(data+8), dataLength-8, 0, 0); if (dstate) { - errorStream << "Unable to decompress update: " << dstate; + error = String::Build("Unable to decompress update: ", dstate); free(res); goto corrupt; } @@ -109,7 +109,7 @@ private: return true; corrupt: - notifyError("Downloaded update is corrupted\n" + String(errorStream.str())); + notifyError("Downloaded update is corrupted\n" + error); free(data); return false; } diff --git a/src/lua/LuaScriptInterface.cpp b/src/lua/LuaScriptInterface.cpp index 013f1596e..cdcf4910c 100644 --- a/src/lua/LuaScriptInterface.cpp +++ b/src/lua/LuaScriptInterface.cpp @@ -3608,7 +3608,7 @@ int strlcmp(const char* a, const char* b, int len) String highlight(String command) { #define CMP(X) (String(wstart, len) == X) - String::Stream result; + StringBuilder result; int pos = 0; String::value_type const*raw = command.c_str(); String::value_type c; @@ -3622,23 +3622,11 @@ String highlight(String command) while((w = wstart[len]) && ((w >= 'A' && w <= 'Z') || (w >= 'a' && w <= 'z') || (w >= '0' && w <= '9') || w == '_')) len++; if(CMP("and") || CMP("break") || CMP("do") || CMP("else") || CMP("elseif") || CMP("end") || CMP("for") || CMP("function") || CMP("if") || CMP("in") || CMP("local") || CMP("not") || CMP("or") || CMP("repeat") || CMP("return") || CMP("then") || CMP("until") || CMP("while")) - { - result << String("\x0F\xB5\x89\x01"); - result.write(wstart, len); - result << String("\bw"); - } + result << "\x0F\xB5\x89\x01" << String(wstart, len) << "\bw"; else if(CMP("false") || CMP("nil") || CMP("true")) - { - result << String("\x0F\xCB\x4B\x16"); - result.write(wstart, len); - result << String("\bw"); - } + result << "\x0F\xCB\x4B\x16" << String(wstart, len) << "\bw"; else - { - result << String("\x0F\x2A\xA1\x98"); - result.write(wstart, len); - result << String("\bw"); - } + result << "\x0F\x2A\xA1\x98" << String(wstart, len) << "\bw"; pos += len; } else if((c >= '0' && c <= '9') || (c == '.' && raw[pos + 1] >= '0' && raw[pos + 1] <= '9')) @@ -3650,9 +3638,7 @@ String highlight(String command) String::value_type const* wstart = raw+pos; while((w = wstart[len]) && ((w >= '0' && w <= '9') || (w >= 'A' && w <= 'F') || (w >= 'a' && w <= 'f'))) len++; - result << String("\x0F\xD3\x36\x82"); - result.write(wstart, len); - result << String("\bw"); + result << "\x0F\xD3\x36\x82" << String(wstart, len) << "\bw"; pos += len; } else @@ -3681,9 +3667,7 @@ String highlight(String command) while((w = wstart[len]) && (w >= '0' && w <= '9')) len++; } - result << String("\x0F\xD3\x36\x82"); - result.write(wstart, len); - result << String("\bw"); + result << "\x0F\xD3\x36\x82" << String(wstart, len) << "\bw"; pos += len; } } @@ -3715,9 +3699,7 @@ String highlight(String command) } len++; } - result << String("\x0F\xDC\x32\x2F"); - result.write(wstart, len); - result << String("\bw"); + result << "\x0F\xDC\x32\x2F" << String(wstart, len) << "\bw"; pos += len; } else @@ -3733,9 +3715,7 @@ String highlight(String command) } if(w == c) len++; - result << String("\x0F\xDC\x32\x2F"); - result.write(wstart, len); - result << String("\bw"); + result << "\x0F\xDC\x32\x2F" << String(wstart, len) << "\bw"; pos += len; } } @@ -3767,9 +3747,7 @@ String highlight(String command) } len++; } - result << String("\x0F\x85\x99\x01"); - result.write(wstart, len); - result << String("\bw"); + result << "\x0F\x85\x99\x01" << String(wstart, len) << "\bw"; pos += len; } else @@ -3779,20 +3757,18 @@ String highlight(String command) String::value_type const* wstart = raw + pos; while((w = wstart[len]) && (w != '\n')) len++; - result << String("\x0F\x85\x99\x01"); - result.write(wstart, len); - result << String("\bw"); + result << "\x0F\x85\x99\x01" << String(wstart, len) << "\bw"; pos += len; } } else if(c == '{' || c == '}') { - result << String("\x0F\xCB\x4B\x16") << c; + result << "\x0F\xCB\x4B\x16" << c << "\bw"; pos++; } else if(c == '.' && raw[pos + 1] == '.' && raw[pos + 2] == '.') { - result << String("\x0F\x2A\xA1\x98..."); + result << "\x0F\x2A\xA1\x98...\bw"; pos += 3; } else @@ -3801,7 +3777,7 @@ String highlight(String command) pos++; } } - return result.str(); + return result.Build(); } String LuaScriptInterface::FormatCommand(String command) diff --git a/src/lua/TPTSTypes.cpp b/src/lua/TPTSTypes.cpp index caaa6917a..0d77293c7 100644 --- a/src/lua/TPTSTypes.cpp +++ b/src/lua/TPTSTypes.cpp @@ -47,9 +47,7 @@ AnyType::operator StringType() { if(type == TypeNumber) { - String::Stream numberStream; - numberStream << ((NumberType *)this)->Value(); - return StringType(numberStream.str()); + return StringType(String::Build(((NumberType *)this)->Value())); } else if(type == TypeString && value.str) { @@ -58,9 +56,7 @@ AnyType::operator StringType() else if (type == TypePoint && value.pt) { ui::Point thisPoint = *(value.pt); - String::Stream pointStream; - pointStream << thisPoint.X << "," << thisPoint.Y; - return StringType(pointStream.str()); + return StringType(String::Build(thisPoint.X, ",", thisPoint.Y)); } else throw InvalidConversionException(type, TypeString); diff --git a/src/simulation/Sign.cpp b/src/simulation/Sign.cpp index 01bbf40ac..11cb273f3 100644 --- a/src/simulation/Sign.cpp +++ b/src/simulation/Sign.cpp @@ -13,7 +13,6 @@ sign::sign(String text_, int x_, int y_, Justification justification_): String sign::getText(Simulation *sim) { - String::Stream signTextNew; if (text[0] && text[0] == '{') { if (text == "{p}") @@ -21,37 +20,35 @@ String sign::getText(Simulation *sim) float pressure = 0.0f; if (x >= 0 && x < XRES && y >= 0 && y < YRES) pressure = sim->pv[y/CELL][x/CELL]; - signTextNew << std::fixed << std::showpoint << std::setprecision(2) << "Pressure: " << pressure; + return String::Build("Pressure: ", Format::Precision(Format::ShowPoint(pressure), 2)); } else if (text == "{aheat}") { float aheat = 0.0f; if (x >= 0 && x < XRES && y >= 0 && y < YRES) aheat = sim->hv[y/CELL][x/CELL]; - signTextNew << std::fixed << std::showpoint << std::setprecision(2) << aheat-273.15f; + return String::Build(Format::Precision(Format::ShowPoint(aheat - 273.15f), 2)); } else if (text == "{t}") { if (x >= 0 && x < XRES && y >= 0 && y < YRES && sim->pmap[y][x]) - signTextNew << std::fixed << std::showpoint << std::setprecision(2) << "Temp: " << sim->parts[ID(sim->pmap[y][x])].temp-273.15f; + return String::Build("Temp: ", Format::Precision(Format::ShowPoint(sim->parts[ID(sim->pmap[y][x])].temp - 273.15f), 2)); else - signTextNew << "Temp: 0.00"; + return String::Build("Temp: ", Format::Precision(Format::ShowPoint(0), 2)); } else { int pos = splitsign(text); if (pos) - signTextNew << text.Between(pos + 1, text.size() - 1); + return text.Between(pos + 1, text.size() - 1); else - signTextNew << text; + return text; } } else { - signTextNew << text; + return text; } - - return signTextNew.str(); } void sign::pos(String signText, int & x0, int & y0, int & w, int & h) diff --git a/src/tasks/TaskWindow.cpp b/src/tasks/TaskWindow.cpp index 3e46ecad3..c742ad298 100644 --- a/src/tasks/TaskWindow.cpp +++ b/src/tasks/TaskWindow.cpp @@ -62,16 +62,10 @@ void TaskWindow::Exit() void TaskWindow::NotifyProgress(Task * task) { progress = task->GetProgress(); - String::Stream pStream; if(progress>-1) - { - pStream << progress << "%"; - } + progressStatus = String::Build(progress, "%"); else - { - pStream << "Please wait..."; - } - progressStatus = pStream.str(); + progressStatus = "Please wait..."; } void TaskWindow::OnTick(float dt) From d1610c512797a037a389bb2bdcf4f965435f8eb5 Mon Sep 17 00:00:00 2001 From: mniip Date: Wed, 2 May 2018 23:42:34 +0300 Subject: [PATCH 15/27] Add string partitioning methods --- src/common/String.h | 51 ++++++++++++++++++++++++++++++++++ src/lua/TPTScriptInterface.cpp | 8 ++---- 2 files changed, 53 insertions(+), 6 deletions(-) diff --git a/src/common/String.h b/src/common/String.h index 79eb3d145..ee3206b8b 100644 --- a/src/common/String.h +++ b/src/common/String.h @@ -171,6 +171,57 @@ public: inline Split SplitFromEndByAny(String const &str, size_t pos = npos) const { return Split(*this, super::find_last_of(str, pos), 1, true); } inline Split SplitFromEndByNot(String const &str, size_t pos = npos) const { return Split(*this, super::find_last_not_of(str, pos), 1, true); } + inline std::vector PartitionBy(value_type ch, bool includeEmpty = false) const + { + std::vector result; + size_t at = 0; + while(true) + { + Split split = SplitBy(ch, at); + String part = split.Before(); + if(includeEmpty || part.size()) + result.push_back(part); + at = split.PositionAfter(); + if(!split) + break; + } + return result; + } + + inline std::vector PartitionBy(String const &str, bool includeEmpty = false) const + { + std::vector result; + size_t at = 0; + while(true) + { + Split split = SplitBy(str, at); + String part = split.Before(); + if(includeEmpty || part.size()) + result.push_back(part); + at = split.PositionAfter(); + if(!split) + break; + } + return result; + } + + inline std::vector PartitionByAny(String const &str, bool includeEmpty = false) const + { + std::vector result; + size_t at = 0; + while(true) + { + Split split = SplitByAny(str, at); + String part = split.Before(); + if(includeEmpty || part.size()) + result.push_back(part); + at = split.PositionAfter(); + if(!split) + break; + } + return result; + } + inline String &Substitute(String const &needle, String const &replacement) { size_t needleSize = needle.size(); diff --git a/src/lua/TPTScriptInterface.cpp b/src/lua/TPTScriptInterface.cpp index 22ee72d2d..aa5f9de6f 100644 --- a/src/lua/TPTScriptInterface.cpp +++ b/src/lua/TPTScriptInterface.cpp @@ -22,9 +22,7 @@ int TPTScriptInterface::Command(String command) int retCode = -1; //Split command into words, put them on the stack - String::Stream ss(command); - String word; - while(std::getline(ss, word, String::value_type(' '))) + for(String word : command.PartitionBy(' ')) words.push_back(word); while(!words.empty()) { @@ -211,9 +209,7 @@ String TPTScriptInterface::FormatCommand(String command) String outputData; //Split command into words, put them on the stack - String::Stream ss(command); - String word; - while(std::getline(ss, word, String::value_type(' '))) + for(String word : command.PartitionBy(' ')) words.push_back(word); while(!words.empty()) { From 2f9cab7e54216a9f7fceb0d870a98da92db90e43 Mon Sep 17 00:00:00 2001 From: mniip Date: Thu, 3 May 2018 00:34:47 +0300 Subject: [PATCH 16/27] Move "big" methods out of the header. Also fix Partition --- src/common/String.cpp | 140 +++++++++++++++++++++++++++++++++-- src/common/String.h | 165 ++++++++++++++++-------------------------- 2 files changed, 199 insertions(+), 106 deletions(-) diff --git a/src/common/String.cpp b/src/common/String.cpp index 87f133327..efa4fea49 100644 --- a/src/common/String.cpp +++ b/src/common/String.cpp @@ -16,19 +16,84 @@ ByteString ConversionError::formatError(ByteString::value_type const *at, ByteSt } -std::codecvt_utf8 convert(1); +static std::codecvt_utf8 convert(1); + +std::vector ByteString::PartitionBy(value_type ch, bool includeEmpty) const +{ + std::vector result; + size_t at = 0; + while(true) + { + Split split = SplitBy(ch, at); + ByteString part = split.Before(); + if(includeEmpty || part.size()) + result.push_back(part); + at = split.PositionAfter(); + if(!split) + break; + } + return result; +} + +std::vector ByteString::PartitionBy(ByteString const &str, bool includeEmpty) const +{ + std::vector result; + size_t at = 0; + while(true) + { + Split split = SplitBy(str, at); + ByteString part = split.Before(); + if(includeEmpty || part.size()) + result.push_back(part); + at = split.PositionAfter(); + if(!split) + break; + } + return result; +} + +std::vector ByteString::PartitionByAny(ByteString const &str, bool includeEmpty) const +{ + std::vector result; + size_t at = 0; + while(true) + { + Split split = SplitByAny(str, at); + ByteString part = split.Before(); + if(includeEmpty || part.size()) + result.push_back(part); + at = split.PositionAfter(); + if(!split) + break; + } + return result; +} + +ByteString &ByteString::Substitute(ByteString const &needle, ByteString const &replacement) +{ + size_t needleSize = needle.size(); + size_t replacementSize = replacement.size(); + size_t at = super::find(needle); + while(at != npos) + { + super::replace(at, needleSize, replacement); + at += replacementSize + !needleSize; + at = super::find(needle, at); + } + return *this; +} String ByteString::FromUtf8(bool ignoreError) const { std::vector destination = std::vector(size(), String::value_type()); - std::codecvt_utf8::state_type state; + std::codecvt_utf8::state_type state; ByteString::value_type const *from = data(), *from_next; String::value_type *to = destination.data(), *to_next; while(true) { - std::codecvt_utf8::result result = convert.in(state, from, data() + size(), from_next, to, destination.data() + destination.size(), to_next); + std::codecvt_utf8::result result = convert.in(state, from, data() + size(), from_next, to, destination.data() + destination.size(), to_next); from = from_next; to = to_next; if(result == std::codecvt_base::ok || result == std::codecvt_base::noconv) @@ -58,17 +123,82 @@ String ByteString::FromUtf8(bool ignoreError) const } } +std::vector String::PartitionBy(value_type ch, bool includeEmpty) const +{ + std::vector result; + size_t at = 0; + while(true) + { + Split split = SplitBy(ch, at); + String part = split.Before(); + if(includeEmpty || part.size()) + result.push_back(part); + at = split.PositionAfter(); + if(!split) + break; + } + return result; +} + +std::vector String::PartitionBy(String const &str, bool includeEmpty) const +{ + std::vector result; + size_t at = 0; + while(true) + { + Split split = SplitBy(str, at); + String part = split.Before(); + if(includeEmpty || part.size()) + result.push_back(part); + at = split.PositionAfter(); + if(!split) + break; + } + return result; +} + +std::vector String::PartitionByAny(String const &str, bool includeEmpty) const +{ + std::vector result; + size_t at = 0; + while(true) + { + Split split = SplitByAny(str, at); + String part = split.Before(); + if(includeEmpty || part.size()) + result.push_back(part); + at = split.PositionAfter(); + if(!split) + break; + } + return result; +} + +String &String::Substitute(String const &needle, String const &replacement) +{ + size_t needleSize = needle.size(); + size_t replacementSize = replacement.size(); + size_t at = super::find(needle); + while(at != npos) + { + super::replace(at, needleSize, replacement); + at += replacementSize + !needleSize; + at = super::find(needle, at); + } + return *this; +} + ByteString String::ToUtf8() const { std::vector destination = std::vector(size(), ByteString::value_type()); - std::codecvt_utf8::state_type state; + std::codecvt_utf8::state_type state; String::value_type const *from = data(), *from_next; ByteString::value_type *to = destination.data(), *to_next; while(true) { - std::codecvt_utf8::result result = convert.out(state, from, data() + size(), from_next, to, destination.data() + destination.size(), to_next); + std::codecvt_utf8::result result = convert.out(state, from, data() + size(), from_next, to, destination.data() + destination.size(), to_next); from = from_next; to = to_next; if(result == std::codecvt_base::ok || result == std::codecvt_base::noconv) diff --git a/src/common/String.h b/src/common/String.h index ee3206b8b..663eb03ae 100644 --- a/src/common/String.h +++ b/src/common/String.h @@ -13,12 +13,14 @@ class StringBuilder; template class SplitBase { T const &parent; + size_t posFrom; size_t posBefore; size_t posAfter; bool reverse; - inline SplitBase(T const &_parent, size_t _posBefore, size_t offset, bool _reverse): + inline SplitBase(T const &_parent, size_t _posFrom, size_t _posBefore, size_t offset, bool _reverse): parent(_parent), + posFrom(_posFrom), posBefore(_posBefore), posAfter(_posBefore == T::npos ? T::npos : _posBefore + offset), reverse(_reverse) @@ -27,16 +29,17 @@ public: inline T Before(bool includeSeparator = false) const { if(posBefore == T::npos) - return reverse ? T() : parent; - return parent.Substr(0, includeSeparator ? posAfter : posBefore); + return reverse ? T() : parent.Substr(posFrom); + return parent.Substr(reverse ? 0 : posFrom, includeSeparator ? posAfter : posBefore); } inline T After(bool includeSeparator = false) const { if(posBefore == T::npos) - return reverse ? parent : T(); - return parent.Substr(includeSeparator ? posBefore : posAfter); + return reverse ? parent.Substr(0, posFrom) : T(); + return parent.Substr(includeSeparator ? posBefore : posAfter, reverse ? posFrom : T::npos); } + inline size_t PositionFrom() const { return posFrom; } inline size_t PositionBefore() const { return posBefore; } inline size_t PositionAfter() const { return posAfter; } @@ -77,30 +80,24 @@ public: inline bool EndsWith(ByteString const &other) const { return super::compare(size() - other.size(), other.size(), other); } using Split = SplitBase; - inline Split SplitBy(value_type ch, size_t pos = 0) const { return Split(*this, super::find(ch, pos), 1, false); } - inline Split SplitBy(ByteString const &str, size_t pos = 0) const { return Split(*this, super::find(str, pos), str.size(), false); } - inline Split SplitByAny(ByteString const &str, size_t pos = 0) const { return Split(*this, super::find_first_of(str, pos), 1, false); } - inline Split SplitByNot(ByteString const &str, size_t pos = 0) const { return Split(*this, super::find_first_not_of(str, pos), 1, false); } - inline Split SplitFromEndBy(value_type ch, size_t pos = npos) const { return Split(*this, super::rfind(ch, pos), 1, true); } - inline Split SplitFromEndBy(ByteString const &str, size_t pos = npos) const { return Split(*this, super::find(str, pos), str.size(), true); } - inline Split SplitFromEndByAny(ByteString const &str, size_t pos = npos) const { return Split(*this, super::find_last_of(str, pos), 1, true); } - inline Split SplitFromEndByNot(ByteString const &str, size_t pos = npos) const { return Split(*this, super::find_last_not_of(str, pos), 1, true); } + inline Split SplitBy(value_type ch, size_t pos = 0) const { return Split(*this, pos, super::find(ch, pos), 1, false); } + inline Split SplitBy(ByteString const &str, size_t pos = 0) const { return Split(*this, pos, super::find(str, pos), str.size(), false); } + inline Split SplitByAny(ByteString const &str, size_t pos = 0) const { return Split(*this, pos, super::find_first_of(str, pos), 1, false); } + inline Split SplitByNot(ByteString const &str, size_t pos = 0) const { return Split(*this, pos, super::find_first_not_of(str, pos), 1, false); } + inline Split SplitFromEndBy(value_type ch, size_t pos = npos) const { return Split(*this, pos, super::rfind(ch, pos), 1, true); } + inline Split SplitFromEndBy(ByteString const &str, size_t pos = npos) const { return Split(*this, pos, super::find(str, pos), str.size(), true); } + inline Split SplitFromEndByAny(ByteString const &str, size_t pos = npos) const { return Split(*this, pos, super::find_last_of(str, pos), 1, true); } + inline Split SplitFromEndByNot(ByteString const &str, size_t pos = npos) const { return Split(*this, pos, super::find_last_not_of(str, pos), 1, true); } - inline ByteString &Substitute(ByteString const &needle, ByteString const &replacement) - { - size_t needleSize = needle.size(); - size_t replacementSize = replacement.size(); - size_t at = super::find(needle); - while(at != npos) - { - super::replace(at, needleSize, replacement); - at += replacementSize + !needleSize; - at = super::find(needle, at); - } - return *this; - } + std::vector PartitionBy(value_type ch, bool includeEmpty = false) const; + std::vector PartitionBy(ByteString const &str, bool includeEmpty = false) const; + std::vector PartitionByAny(ByteString const &str, bool includeEmpty = false) const; -public: + ByteString &Substitute(ByteString const &needle, ByteString const &replacement); + + inline ByteString &Insert(size_t pos, ByteString const &str) { super::insert(pos, str); return *this; } + inline ByteString &Erase(size_t pos, size_t count) { super::erase(pos, count); return *this; } + inline ByteString &EraseBetween(size_t from, size_t to) { if(from < to) super::erase(from, to - from); return *this; } String FromUtf8(bool ignoreError = true) const; inline String FromAscii() const; @@ -129,6 +126,18 @@ inline ByteString operator+(ByteString::value_type lhs, ByteString &&rhs) { retu inline ByteString operator+(ByteString::value_type const *lhs, ByteString const &rhs) { return lhs + static_cast const &>(rhs); } inline ByteString operator+(ByteString::value_type const *lhs, ByteString &&rhs) { return lhs + static_cast &&>(rhs); } +inline bool operator==(ByteString const &lhs, ByteString const &rhs) { return static_cast const &>(lhs) == static_cast const &>(rhs); } +inline bool operator==(ByteString const &lhs, std::basic_string const &rhs) { return static_cast const &>(lhs) == rhs; } +inline bool operator==(ByteString const &lhs, ByteString::value_type const *rhs) { return static_cast const &>(lhs) == rhs; } +inline bool operator==(std::basic_string const &lhs, ByteString const &rhs) { return lhs == static_cast const &>(rhs); } +inline bool operator==(ByteString::value_type const *lhs, ByteString const &rhs) { return lhs == static_cast const &>(rhs); } + +inline bool operator!=(ByteString const &lhs, ByteString const &rhs) { return static_cast const &>(lhs) != static_cast const &>(rhs); } +inline bool operator!=(ByteString const &lhs, std::basic_string const &rhs) { return static_cast const &>(lhs) != rhs; } +inline bool operator!=(ByteString const &lhs, ByteString::value_type const *rhs) { return static_cast const &>(lhs) != rhs; } +inline bool operator!=(std::basic_string const &lhs, ByteString const &rhs) { return lhs != static_cast const &>(rhs); } +inline bool operator!=(ByteString::value_type const *lhs, ByteString const &rhs) { return lhs != static_cast const &>(rhs); } + class String : public std::basic_string { using super = std::basic_string; @@ -162,87 +171,25 @@ public: inline bool EndsWith(String const &other) const { return super::compare(size() - other.size(), other.size(), other); } using Split = SplitBase; - inline Split SplitBy(value_type ch, size_t pos = 0) const { return Split(*this, super::find(ch, pos), 1, false); } - inline Split SplitBy(String const &str, size_t pos = 0) const { return Split(*this, super::find(str, pos), str.size(), false); } - inline Split SplitByAny(String const &str, size_t pos = 0) const { return Split(*this, super::find_first_of(str, pos), 1, false); } - inline Split SplitByNot(String const &str, size_t pos = 0) const { return Split(*this, super::find_first_not_of(str, pos), 1, false); } - inline Split SplitFromEndBy(value_type ch, size_t pos = npos) const { return Split(*this, super::rfind(ch, pos), 1, true); } - inline Split SplitFromEndBy(String const &str, size_t pos = npos) const { return Split(*this, super::find(str, pos), str.size(), true); } - inline Split SplitFromEndByAny(String const &str, size_t pos = npos) const { return Split(*this, super::find_last_of(str, pos), 1, true); } - inline Split SplitFromEndByNot(String const &str, size_t pos = npos) const { return Split(*this, super::find_last_not_of(str, pos), 1, true); } + inline Split SplitBy(value_type ch, size_t pos = 0) const { return Split(*this, pos, super::find(ch, pos), 1, false); } + inline Split SplitBy(String const &str, size_t pos = 0) const { return Split(*this, pos, super::find(str, pos), str.size(), false); } + inline Split SplitByAny(String const &str, size_t pos = 0) const { return Split(*this, pos, super::find_first_of(str, pos), 1, false); } + inline Split SplitByNot(String const &str, size_t pos = 0) const { return Split(*this, pos, super::find_first_not_of(str, pos), 1, false); } + inline Split SplitFromEndBy(value_type ch, size_t pos = npos) const { return Split(*this, pos, super::rfind(ch, pos), 1, true); } + inline Split SplitFromEndBy(String const &str, size_t pos = npos) const { return Split(*this, pos,super::find(str, pos), str.size(), true); } + inline Split SplitFromEndByAny(String const &str, size_t pos = npos) const { return Split(*this, pos, super::find_last_of(str, pos), 1, true); } + inline Split SplitFromEndByNot(String const &str, size_t pos = npos) const { return Split(*this, pos, super::find_last_not_of(str, pos), 1, true); } - inline std::vector PartitionBy(value_type ch, bool includeEmpty = false) const - { - std::vector result; - size_t at = 0; - while(true) - { - Split split = SplitBy(ch, at); - String part = split.Before(); - if(includeEmpty || part.size()) - result.push_back(part); - at = split.PositionAfter(); - if(!split) - break; - } - return result; - } + std::vector PartitionBy(value_type ch, bool includeEmpty = false) const; + std::vector PartitionBy(String const &str, bool includeEmpty = false) const; + std::vector PartitionByAny(String const &str, bool includeEmpty = false) const; - inline std::vector PartitionBy(String const &str, bool includeEmpty = false) const - { - std::vector result; - size_t at = 0; - while(true) - { - Split split = SplitBy(str, at); - String part = split.Before(); - if(includeEmpty || part.size()) - result.push_back(part); - at = split.PositionAfter(); - if(!split) - break; - } - return result; - } - - inline std::vector PartitionByAny(String const &str, bool includeEmpty = false) const - { - std::vector result; - size_t at = 0; - while(true) - { - Split split = SplitByAny(str, at); - String part = split.Before(); - if(includeEmpty || part.size()) - result.push_back(part); - at = split.PositionAfter(); - if(!split) - break; - } - return result; - } - - inline String &Substitute(String const &needle, String const &replacement) - { - size_t needleSize = needle.size(); - size_t replacementSize = replacement.size(); - size_t at = super::find(needle); - while(at != npos) - { - super::replace(at, needleSize, replacement); - at += replacementSize + !needleSize; - at = super::find(needle, at); - } - return *this; - } + String &Substitute(String const &needle, String const &replacement); inline String &Insert(size_t pos, String const &str) { super::insert(pos, str); return *this; } inline String &Erase(size_t pos, size_t count) { super::erase(pos, count); return *this; } inline String &EraseBetween(size_t from, size_t to) { if(from < to) super::erase(from, to - from); return *this; } - inline bool operator==(String const &other) { return std::basic_string(*this) == other; } - inline bool operator!=(String const &other) { return std::basic_string(*this) != other; } - ByteString ToUtf8() const; ByteString ToAscii() const; template static String Build(Ts&&... args); @@ -275,6 +222,22 @@ inline String operator+(String::value_type const *lhs, String &&rhs) { return lh template inline String operator+(ByteString::value_type const (&lhs)[N], String const &rhs) { return std::move(ByteString(lhs).FromAscii()) + static_cast const &>(rhs); } template inline String operator+(ByteString::value_type const (&lhs)[N], String &&rhs) { return std::move(ByteString(lhs).FromAscii()) + static_cast &&>(rhs); } +inline bool operator==(String const &lhs, String const &rhs) { return static_cast const &>(lhs) == static_cast const &>(rhs); } +inline bool operator==(String const &lhs, std::basic_string const &rhs) { return static_cast const &>(lhs) == rhs; } +inline bool operator==(String const &lhs, String::value_type const *rhs) { return static_cast const &>(lhs) == rhs; } +template inline bool operator==(String const &lhs, ByteString::value_type const (&rhs)[N]) { return static_cast const &>(lhs) == std::move(ByteString(rhs).FromAscii()); } +inline bool operator==(std::basic_string const &lhs, String const &rhs) { return lhs == static_cast const &>(rhs); } +inline bool operator==(String::value_type const *lhs, String const &rhs) { return lhs == static_cast const &>(rhs); } +template inline bool operator==(ByteString::value_type const (&lhs)[N], String const &rhs) { return std::move(ByteString(lhs).FromAscii()) == static_cast const &>(rhs); } + +inline bool operator!=(String const &lhs, String const &rhs) { return static_cast const &>(lhs) != static_cast const &>(rhs); } +inline bool operator!=(String const &lhs, std::basic_string const &rhs) { return static_cast const &>(lhs) != rhs; } +inline bool operator!=(String const &lhs, String::value_type const *rhs) { return static_cast const &>(lhs) != rhs; } +template inline bool operator!=(String const &lhs, ByteString::value_type const (&rhs)[N]) { return static_cast const &>(lhs) != std::move(ByteString(rhs).FromAscii()); } +inline bool operator!=(std::basic_string const &lhs, String const &rhs) { return lhs != static_cast const &>(rhs); } +inline bool operator!=(String::value_type const *lhs, String const &rhs) { return lhs != static_cast const &>(rhs); } +template inline bool operator!=(ByteString::value_type const (&lhs)[N], String const &rhs) { return std::move(ByteString(lhs).FromAscii()) != static_cast const &>(rhs); } + inline String ByteString::FromAscii() const { String destination = String(size(), String::value_type()); From 4b92926f0d0b2774c5e928b50d2d5dc24a7f0932 Mon Sep 17 00:00:00 2001 From: mniip Date: Thu, 3 May 2018 00:45:22 +0300 Subject: [PATCH 17/27] Fix partition again --- src/common/String.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/common/String.h b/src/common/String.h index 663eb03ae..306bc9313 100644 --- a/src/common/String.h +++ b/src/common/String.h @@ -30,13 +30,13 @@ public: { if(posBefore == T::npos) return reverse ? T() : parent.Substr(posFrom); - return parent.Substr(reverse ? 0 : posFrom, includeSeparator ? posAfter : posBefore); + return parent.Between(reverse ? 0 : posFrom, includeSeparator ? posAfter : posBefore); } inline T After(bool includeSeparator = false) const { if(posBefore == T::npos) return reverse ? parent.Substr(0, posFrom) : T(); - return parent.Substr(includeSeparator ? posBefore : posAfter, reverse ? posFrom : T::npos); + return parent.Between(includeSeparator ? posBefore : posAfter, reverse ? posFrom : T::npos); } inline size_t PositionFrom() const { return posFrom; } From 1ea7a035d1c7e23180f992c16a8fc29ed450c916 Mon Sep 17 00:00:00 2001 From: mniip Date: Thu, 3 May 2018 02:48:05 +0300 Subject: [PATCH 18/27] Add Number parsing facilities --- src/common/Format.h | 2 ++ src/common/String.cpp | 61 +++++++++++++++++++++++++++++++++++++++ src/common/String.h | 66 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 129 insertions(+) diff --git a/src/common/Format.h b/src/common/Format.h index cd454b362..c2db70752 100644 --- a/src/common/Format.h +++ b/src/common/Format.h @@ -62,8 +62,10 @@ namespace Format template inline FlagsOverride NoShowPoint(T value) { return FlagsOverride(value); } inline FlagsOverride Uppercase() { return FlagsOverride(); } inline FlagsOverride ShowPoint() { return FlagsOverride(); } + inline FlagsOverride SkipWS() { return FlagsOverride(); } inline FlagsOverride NoUppercase() { return FlagsOverride(); } inline FlagsOverride NoShowPoint() { return FlagsOverride(); } + inline FlagsOverride NoSkipWS() { return FlagsOverride(); } template inline FlagsOverride Fixed(T value) { return FlagsOverride(value); } template inline FlagsOverride Scientific(T value) { return FlagsOverride(value); } diff --git a/src/common/String.cpp b/src/common/String.cpp index efa4fea49..a3e1788d9 100644 --- a/src/common/String.cpp +++ b/src/common/String.cpp @@ -234,6 +234,8 @@ inline wchar_t narrow_wchar(String::value_type ch) return wchar_t(ch); } +String numberChars = "-.+0123456789ABCDEFXabcdefx"; + static thread_local struct LocaleImpl { std::basic_stringstream stream; @@ -253,6 +255,16 @@ static thread_local struct LocaleImpl wstream.fill(b.fill); } + inline void PrepareWStream(String const &str, size_t pos, std::ios_base::fmtflags set, std::ios_base::fmtflags reset) + { + wstream.flags((std::ios_base::dec & ~ reset) | set); + std::basic_string wstr; + while(pos < str.size() && representable_wchar(str[pos]) && numberChars.Contains(str[pos])) + wstr.push_back(narrow_wchar(str[pos++])); + wstream.str(wstr); + wstream.clear(); + } + inline void FlushWStream(StringBuilder &b) { std::basic_string wstr = wstream.str(); @@ -263,6 +275,11 @@ static thread_local struct LocaleImpl b.AddChars(chars.data(), chars.size()); wstream.str(std::basic_string()); } + + inline void FlushWStream() + { + wstream.str(std::basic_string()); + } } LocaleImpl; @@ -376,6 +393,50 @@ StringBuilder &operator<<(StringBuilder &b, double data) return b; } +String::Split String::SplitSigned(long long int &value, size_t pos, std::ios_base::fmtflags set, std::ios_base::fmtflags reset) const +{ + LocaleImpl.PrepareWStream(*this, pos, set, reset); + LocaleImpl.wstream >> value; + if(LocaleImpl.wstream.fail()) + { + LocaleImpl.FlushWStream(); + return Split(*this, pos, npos, 0, false); + } + LocaleImpl.wstream.clear(); + Split split(*this, pos, pos + LocaleImpl.wstream.tellg(), 0, false); + LocaleImpl.FlushWStream(); + return split; +} + +String::Split String::SplitUnsigned(unsigned long long int &value, size_t pos, std::ios_base::fmtflags set, std::ios_base::fmtflags reset) const +{ + LocaleImpl.PrepareWStream(*this, pos, set, reset); + LocaleImpl.wstream >> value; + if(LocaleImpl.wstream.fail()) + { + LocaleImpl.FlushWStream(); + return Split(*this, pos, npos, 0, false); + } + LocaleImpl.wstream.clear(); + Split split(*this, pos, pos + LocaleImpl.wstream.tellg(), 0, false); + LocaleImpl.FlushWStream(); + return split; +} + +String::Split String::SplitFloat(double &value, size_t pos, std::ios_base::fmtflags set, std::ios_base::fmtflags reset) const +{ + LocaleImpl.PrepareWStream(*this, pos, set, reset); + LocaleImpl.wstream >> value; + if(LocaleImpl.wstream.fail()) + { + LocaleImpl.FlushWStream(); + return Split(*this, pos, npos, 0, false); + } + LocaleImpl.wstream.clear(); + Split split(*this, pos, pos + LocaleImpl.wstream.tellg(), 0, false); + LocaleImpl.FlushWStream(); + return split; +} template<> std::ctype::~ctype() { diff --git a/src/common/String.h b/src/common/String.h index 306bc9313..c13e5d385 100644 --- a/src/common/String.h +++ b/src/common/String.h @@ -9,6 +9,7 @@ class ByteStringBuilder; class String; class StringBuilder; +namespace Format { template struct FlagsOverride; } template class SplitBase { @@ -179,6 +180,71 @@ public: inline Split SplitFromEndBy(String const &str, size_t pos = npos) const { return Split(*this, pos,super::find(str, pos), str.size(), true); } inline Split SplitFromEndByAny(String const &str, size_t pos = npos) const { return Split(*this, pos, super::find_last_of(str, pos), 1, true); } inline Split SplitFromEndByNot(String const &str, size_t pos = npos) const { return Split(*this, pos, super::find_last_not_of(str, pos), 1, true); } +private: + Split SplitSigned(long long int &, size_t, std::ios_base::fmtflags, std::ios_base::fmtflags) const; + Split SplitUnsigned(unsigned long long int &, size_t, std::ios_base::fmtflags, std::ios_base::fmtflags) const; + Split SplitFloat(double &, size_t, std::ios_base::fmtflags, std::ios_base::fmtflags) const; +public: + template inline Split SplitSigned(T &ref, size_t pos, std::ios_base::fmtflags set, std::ios_base::fmtflags reset) const + { + long long int value = 0; + Split split = SplitSigned(value, pos, set, reset); + ref = value; + return split; + } + template inline Split SplitUnsigned(T &ref, size_t pos, std::ios_base::fmtflags set, std::ios_base::fmtflags reset) const + { + unsigned long long int value = 0; + Split split = SplitUnsigned(value, pos, set, reset); + ref = value; + return split; + } + template inline Split SplitFloat(T &ref, size_t pos, std::ios_base::fmtflags set, std::ios_base::fmtflags reset) const + { + double value = 0; + Split split = SplitFloat(value, pos, set, reset); + ref = value; + return split; + } + + inline Split SplitNumber(short int &ref, size_t pos = 0) const { return SplitSigned(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + inline Split SplitNumber(int &ref, size_t pos = 0) const { return SplitSigned(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + inline Split SplitNumber(long int &ref, size_t pos = 0) const { return SplitSigned(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + inline Split SplitNumber(long long int &ref, size_t pos = 0) const { return SplitSigned(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + inline Split SplitNumber(unsigned short int &ref, size_t pos = 0) const { return SplitUnsigned(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + inline Split SplitNumber(unsigned int &ref, size_t pos = 0) const { return SplitUnsigned(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + inline Split SplitNumber(unsigned long int &ref, size_t pos = 0) const { return SplitUnsigned(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + inline Split SplitNumber(unsigned long long int &ref, size_t pos = 0) const { return SplitUnsigned(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + inline Split SplitNumber(float &ref, size_t pos = 0) const { return SplitFloat(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + inline Split SplitNumber(double &ref, size_t pos = 0) const { return SplitFloat(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + + template inline Split SplitNumber(short int &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitSigned(ref, pos, set, reset); } + template inline Split SplitNumber(int &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitSigned(ref, pos, set, reset); } + template inline Split SplitNumber(long int &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitSigned(ref, pos, set, reset); } + template inline Split SplitNumber(long long int &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitSigned(ref, pos, set, reset); } + template inline Split SplitNumber(unsigned short int &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitUnsigned(ref, pos, set, reset); } + template inline Split SplitNumber(unsigned int &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitUnsigned(ref, pos, set, reset); } + template inline Split SplitNumber(unsigned long int &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitUnsigned(ref, pos, set, reset); } + template inline Split SplitNumber(unsigned long long int &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitUnsigned(ref, pos, set, reset); } + template inline Split SplitNumber(float &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitFloat(ref, pos, set, reset); } + template inline Split SplitNumber(double &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitFloat(ref, pos, set, reset); } + + template T ToNumber() const + { + T value = T(); + Split split = SplitNumber(value); + if(split.PositionBefore() != size()) + return T(); + return value; + } + template inline T ToNumber(Format::FlagsOverride fmt) const + { + T value = T(); + Split split = SplitNumber(value, fmt); + if(split.PositionBefore() != size()) + return T(); + return value; + } std::vector PartitionBy(value_type ch, bool includeEmpty = false) const; std::vector PartitionBy(String const &str, bool includeEmpty = false) const; From 5ff8cefca4c3fe73f5daed44ba89d789eba7a5b0 Mon Sep 17 00:00:00 2001 From: mniip Date: Thu, 3 May 2018 04:11:43 +0300 Subject: [PATCH 19/27] Replace String::Stream parsing with number splitting --- src/Format.h | 8 ++---- src/common/String.h | 10 ++++---- src/gui/game/PropertyTool.cpp | 45 ++++++++++++---------------------- src/lua/TPTSTypes.cpp | 12 ++++----- src/lua/TPTScriptInterface.cpp | 14 +++++------ 5 files changed, 34 insertions(+), 55 deletions(-) diff --git a/src/Format.h b/src/Format.h index 19cecf848..b29749bde 100644 --- a/src/Format.h +++ b/src/Format.h @@ -18,9 +18,7 @@ namespace format template String NumberToString(T number) { - String::Stream ss; - ss << number; - return ss.str(); + return String::Build(number); } template T ByteStringToNumber(const ByteString & text) @@ -32,9 +30,7 @@ namespace format template T StringToNumber(const String & text) { - String::Stream ss(text); - T number; - return (ss >> number)?number:0; + return text.ToNumber(true); } ByteString URLEncode(ByteString value); diff --git a/src/common/String.h b/src/common/String.h index c13e5d385..24715acb8 100644 --- a/src/common/String.h +++ b/src/common/String.h @@ -163,7 +163,7 @@ public: inline String Substr(size_t pos = 0, size_t count = npos) const { return super::substr(pos, count); } inline String SubstrFromEnd(size_t rpos = 0, size_t rcount = npos) const { return super::substr(rcount == npos || rcount > rpos ? 0 : rpos - rcount, size() - rpos); } - inline String Between(size_t from, size_t to) const { return from >= to ? String() : super::substr(from, to - from); } + inline String Between(size_t from, size_t to) const { return to == npos ? super::substr(from) : from >= to ? String() : super::substr(from, to - from); } inline bool Contains(value_type ch) const { return super::find(ch) != npos; } inline bool Contains(String const &other) const { return super::find(other) != npos; } @@ -229,20 +229,20 @@ public: template inline Split SplitNumber(float &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitFloat(ref, pos, set, reset); } template inline Split SplitNumber(double &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitFloat(ref, pos, set, reset); } - template T ToNumber() const + template T ToNumber(bool noThrow = false) const { T value = T(); Split split = SplitNumber(value); if(split.PositionBefore() != size()) - return T(); + return noThrow ? T() : throw std::runtime_error("Not a number"); return value; } - template inline T ToNumber(Format::FlagsOverride fmt) const + template inline T ToNumber(Format::FlagsOverride fmt, bool noThrow = false) const { T value = T(); Split split = SplitNumber(value, fmt); if(split.PositionBefore() != size()) - return T(); + return noThrow ? T() : throw std::runtime_error("Not a number"); return value; } diff --git a/src/gui/game/PropertyTool.cpp b/src/gui/game/PropertyTool.cpp index 487ab3528..ac762159a 100644 --- a/src/gui/game/PropertyTool.cpp +++ b/src/gui/game/PropertyTool.cpp @@ -107,18 +107,12 @@ void PropertyWindow::SetProperty() if(value.length() > 2 && value.BeginsWith("0x")) { //0xC0FFEE - String::Stream buffer; - buffer.exceptions(String::Stream::failbit | String::Stream::badbit); - buffer << std::hex << value.Substr(2); - buffer >> v; + v = value.Substr(2).ToNumber(Format::Hex()); } else if(value.length() > 1 && value.BeginsWith("0")) { //#C0FFEE - String::Stream buffer; - buffer.exceptions(String::Stream::failbit | String::Stream::badbit); - buffer << std::hex << value.Substr(1); - buffer >> v; + v = value.Substr(1).ToNumber(Format::Hex()); } else { @@ -133,9 +127,7 @@ void PropertyWindow::SetProperty() } else { - String::Stream buffer(value); - buffer.exceptions(String::Stream::failbit | String::Stream::badbit); - buffer >> v; + v = value.ToNumber(); } } @@ -158,24 +150,16 @@ void PropertyWindow::SetProperty() if(value.length() > 2 && value.BeginsWith("0x")) { //0xC0FFEE - String::Stream buffer; - buffer.exceptions(String::Stream::failbit | String::Stream::badbit); - buffer << std::hex << value.Substr(2); - buffer >> v; + v = value.Substr(2).ToNumber(Format::Hex()); } else if(value.length() > 1 && value.BeginsWith("#")) { //#C0FFEE - String::Stream buffer; - buffer.exceptions(String::Stream::failbit | String::Stream::badbit); - buffer << std::hex << value.Substr(1); - buffer >> v; + v = value.Substr(1).ToNumber(Format::Hex()); } else { - String::Stream buffer(value); - buffer.exceptions(String::Stream::failbit | String::Stream::badbit); - buffer >> v; + v = value.ToNumber(); } #ifdef DEBUG std::cout << "Got uint value " << v << std::endl; @@ -185,16 +169,17 @@ void PropertyWindow::SetProperty() } case StructProperty::Float: { - String::Stream buffer(value); - buffer.exceptions(String::Stream::failbit | String::Stream::badbit); - buffer >> tool->propValue.Float; - if (properties[property->GetOption().second].Name == "temp" && value.length()) + if (value.EndsWith("C")) { - if (value.EndsWith("C")) - tool->propValue.Float += 273.15; - else if (value.EndsWith("F")) - tool->propValue.Float = (tool->propValue.Float-32.0f)*5/9+273.15f; + float v = value.SubstrFromEnd(1).ToNumber(); + tool->propValue.Float = v + 273.15; } + else if(value.EndsWith("F")) + { + float v = value.SubstrFromEnd(1).ToNumber(); + tool->propValue.Float = (v-32.0f)*5/9+273.15f; + } + tool->propValue.Float = value.ToNumber(); #ifdef DEBUG std::cout << "Got float value " << tool->propValue.Float << std::endl; #endif diff --git a/src/lua/TPTSTypes.cpp b/src/lua/TPTSTypes.cpp index 0d77293c7..9615afbf6 100644 --- a/src/lua/TPTSTypes.cpp +++ b/src/lua/TPTSTypes.cpp @@ -71,13 +71,13 @@ AnyType::operator PointType() } else if(type == TypeString) { - String::Stream pointStream(*(value.str)); int x, y; - String::value_type comma; - pointStream >> x >> comma >> y; - if (pointStream.fail() || comma != ',') - throw InvalidConversionException(type, TypePoint); - return PointType(ui::Point(x, y)); + if(String::Split comma = (*value.str).SplitNumber(x)) + if(comma.After().BeginsWith(",")) + if(String::Split end = comma.After().Substr(1).SplitNumber(y)) + if(!end.After().size()) + return PointType(x, y); + throw InvalidConversionException(type, TypePoint); } else throw InvalidConversionException(type, TypePoint); diff --git a/src/lua/TPTScriptInterface.cpp b/src/lua/TPTScriptInterface.cpp index aa5f9de6f..7748dd535 100644 --- a/src/lua/TPTScriptInterface.cpp +++ b/src/lua/TPTScriptInterface.cpp @@ -150,10 +150,7 @@ int TPTScriptInterface::parseNumber(String str) } else { - int number; - String::Stream ss(str); - ss >> number; - return number; + return str.ToNumber(); } return currentNumber; } @@ -188,11 +185,12 @@ AnyType TPTScriptInterface::eval(std::deque * words) return FloatType(atof(word.ToUtf8().c_str())); case TypePoint: { - String::Stream pointStream(word); int x, y; - String::value_type comma; - pointStream >> x >> comma >> y; - return PointType(x, y); + if(String::Split comma = word.SplitNumber(x)) + if(comma.After().BeginsWith(",")) + if(comma.After().Substr(1).SplitNumber(y)) + return PointType(x, y); + return PointType(0, 0); } case TypeString: return StringType(word); From ecb41661f8c084c7ab924b77601ec29da7c2c50f Mon Sep 17 00:00:00 2001 From: mniip Date: Thu, 3 May 2018 04:12:09 +0300 Subject: [PATCH 20/27] Fix String::{Begins,Ends}With and with it a bunch of stuff --- src/common/String.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/common/String.h b/src/common/String.h index 24715acb8..3e64736fc 100644 --- a/src/common/String.h +++ b/src/common/String.h @@ -77,8 +77,8 @@ public: inline bool Contains(value_type ch) const { return super::find(ch) != npos; } inline bool Contains(ByteString const &other) { return super::find(other) != npos; } - inline bool BeginsWith(ByteString const &other) const { return super::compare(0, other.size(), other); } - inline bool EndsWith(ByteString const &other) const { return super::compare(size() - other.size(), other.size(), other); } + inline bool BeginsWith(ByteString const &other) const { return !super::compare(0, other.size(), other); } + inline bool EndsWith(ByteString const &other) const { return !super::compare(size() - other.size(), other.size(), other); } using Split = SplitBase; inline Split SplitBy(value_type ch, size_t pos = 0) const { return Split(*this, pos, super::find(ch, pos), 1, false); } @@ -168,8 +168,8 @@ public: inline bool Contains(value_type ch) const { return super::find(ch) != npos; } inline bool Contains(String const &other) const { return super::find(other) != npos; } - inline bool BeginsWith(String const &other) const { return super::compare(0, other.size(), other); } - inline bool EndsWith(String const &other) const { return super::compare(size() - other.size(), other.size(), other); } + inline bool BeginsWith(String const &other) const { return !super::compare(0, other.size(), other); } + inline bool EndsWith(String const &other) const { return !super::compare(size() - other.size(), other.size(), other); } using Split = SplitBase; inline Split SplitBy(value_type ch, size_t pos = 0) const { return Split(*this, pos, super::find(ch, pos), 1, false); } From 5d80d77f55fc54369868d31bc81738775a29d5ec Mon Sep 17 00:00:00 2001 From: mniip Date: Thu, 3 May 2018 04:18:40 +0300 Subject: [PATCH 21/27] Remove String::Stream and with it the locale hacks. Also fixes the crash when compiled with -O --- src/common/String.cpp | 132 ------------------------------------------ src/common/String.h | 2 - 2 files changed, 134 deletions(-) diff --git a/src/common/String.cpp b/src/common/String.cpp index a3e1788d9..c50f5fa34 100644 --- a/src/common/String.cpp +++ b/src/common/String.cpp @@ -437,135 +437,3 @@ String::Split String::SplitFloat(double &value, size_t pos, std::ios_base::fmtfl LocaleImpl.FlushWStream(); return split; } - -template<> std::ctype::~ctype() -{ -} -template<> std::numpunct::numpunct(size_t ref): std::locale::facet(ref) -{ -} -template<> std::numpunct::~numpunct() -{ -} - -static struct Locale32Impl -{ - std::ctype const &ctype16; - std::numpunct const &numpunct16; - Locale32Impl(): - ctype16(std::use_facet >(std::locale())), - numpunct16(std::use_facet >(std::locale())) - { - std::locale::global(std::locale(std::locale(), new std::ctype())); - std::locale::global(std::locale(std::locale(), new std::numpunct())); - std::locale::global(std::locale(std::locale(), new std::num_put())); - } -} -Locale32Impl; - -template<> bool std::ctype::do_is(mask m, char32_t ch) const -{ - return ch <= 0xFFFF ? Locale32Impl.ctype16.is(m, ch) : (m & print); -} -template<> char32_t const *std::ctype::do_is(char32_t const *low, char32_t const *high, mask *vec) const -{ - while(low < high) - { - if(*low <= 0xFFFF) - { - wchar_t l = *low; - Locale32Impl.ctype16.is(&l, &l + 1, vec); - } - else - *vec = print; - low++; - } - return high; -} -template<> char32_t const *std::ctype::do_scan_is(mask m, char32_t const *beg, char32_t const *end) const -{ - while(beg < end) - if(do_is(m, *beg)) - return beg; - else - beg++; - return end; -} -template<> char32_t const *std::ctype::do_scan_not(mask m, char32_t const *beg, char32_t const *end) const -{ - while(beg < end) - if(!do_is(m, *beg)) - return beg; - else - beg++; - return end; -} -template<> char32_t std::ctype::do_toupper(char32_t ch) const -{ - return ch <= 0xFFFF ? Locale32Impl.ctype16.toupper(ch) : ch; -} -template<> char32_t const *std::ctype::do_toupper(char32_t *beg, char32_t const *end) const -{ - while(beg < end) - { - *beg = do_toupper(*beg); - beg++; - } - return end; -} -template<> char32_t std::ctype::do_tolower(char32_t ch) const -{ - return ch <= 0xFFFF ? Locale32Impl.ctype16.tolower(ch) : ch; -} -template<> char32_t const *std::ctype::do_tolower(char32_t *beg, char32_t const *end) const -{ - while(beg < end) - { - *beg = do_tolower(*beg); - beg++; - } - return end; -} -template<> char32_t std::ctype::do_widen(char ch) const -{ - return Locale32Impl.ctype16.widen(ch); -} -template<> char const *std::ctype::do_widen(char const *beg, char const *end, char32_t *dst) const -{ - while(beg < end) - *(dst++) = do_widen(*(beg++)); - return end; -} -template<> char std::ctype::do_narrow(char32_t ch, char dflt) const -{ - return ch <= 0xFFFF ? Locale32Impl.ctype16.narrow(ch, dflt) : dflt; -} -template<> char32_t const *std::ctype::do_narrow(char32_t const *beg, char32_t const *end, char dflt, char *dst) const -{ - while(beg < end) - *(dst++) = do_narrow(*(beg++), dflt); - return end; -} - -template<> char32_t std::numpunct::do_decimal_point() const -{ - return Locale32Impl.numpunct16.decimal_point(); -} -template<> char32_t std::numpunct::do_thousands_sep() const -{ - return Locale32Impl.numpunct16.thousands_sep(); -} -template<> std::string std::numpunct::do_grouping() const -{ - return Locale32Impl.numpunct16.grouping(); -} -template<> std::basic_string std::numpunct::do_truename() const -{ - std::basic_string name = Locale32Impl.numpunct16.truename(); - return std::basic_string(name.begin(), name.end()); -} -template<> std::basic_string std::numpunct::do_falsename() const -{ - std::basic_string name = Locale32Impl.numpunct16.falsename(); - return std::basic_string(name.begin(), name.end()); -} diff --git a/src/common/String.h b/src/common/String.h index 3e64736fc..05629fc33 100644 --- a/src/common/String.h +++ b/src/common/String.h @@ -259,8 +259,6 @@ public: ByteString ToUtf8() const; ByteString ToAscii() const; template static String Build(Ts&&... args); - - using Stream = std::basic_stringstream; }; inline String operator+(String const &lhs, String const &rhs) { return static_cast const &>(lhs) + static_cast const &>(rhs); } From 730cf0806a0e9bd123ccb3c97a3f9b7a93fe317c Mon Sep 17 00:00:00 2001 From: mniip Date: Thu, 3 May 2018 04:55:20 +0300 Subject: [PATCH 22/27] Fix number to string conversion failing after a failed string to number conversion --- src/common/String.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/common/String.cpp b/src/common/String.cpp index c50f5fa34..e36003cc9 100644 --- a/src/common/String.cpp +++ b/src/common/String.cpp @@ -399,6 +399,7 @@ String::Split String::SplitSigned(long long int &value, size_t pos, std::ios_bas LocaleImpl.wstream >> value; if(LocaleImpl.wstream.fail()) { + LocaleImpl.wstream.clear(); LocaleImpl.FlushWStream(); return Split(*this, pos, npos, 0, false); } @@ -414,6 +415,7 @@ String::Split String::SplitUnsigned(unsigned long long int &value, size_t pos, s LocaleImpl.wstream >> value; if(LocaleImpl.wstream.fail()) { + LocaleImpl.wstream.clear(); LocaleImpl.FlushWStream(); return Split(*this, pos, npos, 0, false); } @@ -429,6 +431,7 @@ String::Split String::SplitFloat(double &value, size_t pos, std::ios_base::fmtfl LocaleImpl.wstream >> value; if(LocaleImpl.wstream.fail()) { + LocaleImpl.wstream.clear(); LocaleImpl.FlushWStream(); return Split(*this, pos, npos, 0, false); } From 7f5c164d22996c66f254ffa971d19ce77af9a76b Mon Sep 17 00:00:00 2001 From: mniip Date: Thu, 3 May 2018 05:22:05 +0300 Subject: [PATCH 23/27] Fix partial name element search --- src/gui/elementsearch/ElementSearchActivity.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/elementsearch/ElementSearchActivity.cpp b/src/gui/elementsearch/ElementSearchActivity.cpp index 3ffc2c8f8..9ad8d0853 100644 --- a/src/gui/elementsearch/ElementSearchActivity.cpp +++ b/src/gui/elementsearch/ElementSearchActivity.cpp @@ -117,7 +117,7 @@ void ElementSearchActivity::searchTools(String query) std::transform(nameLower.begin(), nameLower.end(), nameLower.begin(), ::tolower); if(nameLower == queryLower) exactmatches.push_back(*iter); - else if(!nameLower.BeginsWith(queryLower)) + else if(nameLower.BeginsWith(queryLower)) frontmatches.push_back(*iter); else if(nameLower.Contains(queryLower)) matches.push_back(*iter); From d6a92bdab579ea967e83f599e6a70628e3686ab9 Mon Sep 17 00:00:00 2001 From: mniip Date: Fri, 4 May 2018 14:45:57 +0300 Subject: [PATCH 24/27] Copy the String interface to ByteString --- src/common/String.cpp | 199 ++++++++++++++++++++++++++++++++++++++++-- src/common/String.h | 120 +++++++++++++++++++++++-- 2 files changed, 309 insertions(+), 10 deletions(-) diff --git a/src/common/String.cpp b/src/common/String.cpp index e36003cc9..cdca64827 100644 --- a/src/common/String.cpp +++ b/src/common/String.cpp @@ -234,7 +234,9 @@ inline wchar_t narrow_wchar(String::value_type ch) return wchar_t(ch); } -String numberChars = "-.+0123456789ABCDEFXabcdefx"; +char const numberChars[] = "-.+0123456789ABCDEFXabcdefx"; +ByteString numberByteString(numberChars); +String numberString(numberChars); static thread_local struct LocaleImpl { @@ -247,19 +249,51 @@ static thread_local struct LocaleImpl wstream.imbue(std::locale::classic()); } + inline void PrepareStream(ByteStringBuilder &b) + { + stream.flags(b.flags); + stream.width(b.width); + stream.precision(b.precision); + stream.fill(b.fill); + stream.clear(); + } + + inline void PrepareStream(ByteString const &str, size_t pos, std::ios_base::fmtflags set, std::ios_base::fmtflags reset) + { + stream.flags((std::ios_base::dec & ~ reset) | set); + std::basic_string bstr; + while(pos < str.size() && numberByteString.Contains(str[pos])) + bstr.push_back(narrow_wchar(str[pos++])); + stream.str(bstr); + stream.clear(); + } + + inline void FlushStream(ByteStringBuilder &b) + { + std::basic_string str = stream.str(); + b.AddChars(str.data(), str.size()); + stream.str(std::basic_string()); + } + + inline void FlushStream() + { + stream.str(std::basic_string()); + } + inline void PrepareWStream(StringBuilder &b) { wstream.flags(b.flags); wstream.width(b.width); wstream.precision(b.precision); wstream.fill(b.fill); + wstream.clear(); } inline void PrepareWStream(String const &str, size_t pos, std::ios_base::fmtflags set, std::ios_base::fmtflags reset) { wstream.flags((std::ios_base::dec & ~ reset) | set); std::basic_string wstr; - while(pos < str.size() && representable_wchar(str[pos]) && numberChars.Contains(str[pos])) + while(pos < str.size() && representable_wchar(str[pos]) && numberString.Contains(str[pos])) wstr.push_back(narrow_wchar(str[pos++])); wstream.str(wstr); wstream.clear(); @@ -283,6 +317,159 @@ static thread_local struct LocaleImpl } LocaleImpl; +ByteString ByteStringBuilder::Build() const +{ + return ByteString(buffer.begin(), buffer.end()); +} + +void ByteStringBuilder::AddChars(ByteString::value_type const *data, size_t count) +{ + buffer.reserve(buffer.size() + count); + buffer.insert(buffer.end(), data, data + count); +} + +ByteStringBuilder &operator<<(ByteStringBuilder &b, short int data) +{ + LocaleImpl.PrepareStream(b); + LocaleImpl.stream << data; + LocaleImpl.FlushStream(b); + return b; +} + +ByteStringBuilder &operator<<(ByteStringBuilder &b, int data) +{ + LocaleImpl.PrepareStream(b); + LocaleImpl.stream << data; + LocaleImpl.FlushStream(b); + return b; +} + +ByteStringBuilder &operator<<(ByteStringBuilder &b, long int data) +{ + LocaleImpl.PrepareStream(b); + LocaleImpl.stream << data; + LocaleImpl.FlushStream(b); + return b; +} + +ByteStringBuilder &operator<<(ByteStringBuilder &b, long long int data) +{ + LocaleImpl.PrepareStream(b); + LocaleImpl.stream << data; + LocaleImpl.FlushStream(b); + return b; +} + +ByteStringBuilder &operator<<(ByteStringBuilder &b, unsigned short int data) +{ + LocaleImpl.PrepareStream(b); + LocaleImpl.stream << data; + LocaleImpl.FlushStream(b); + return b; +} + +ByteStringBuilder &operator<<(ByteStringBuilder &b, unsigned int data) +{ + LocaleImpl.PrepareStream(b); + LocaleImpl.stream << data; + LocaleImpl.FlushStream(b); + return b; +} + +ByteStringBuilder &operator<<(ByteStringBuilder &b, unsigned long int data) +{ + LocaleImpl.PrepareStream(b); + LocaleImpl.stream << data; + LocaleImpl.FlushStream(b); + return b; +} + +ByteStringBuilder &operator<<(ByteStringBuilder &b, unsigned long long int data) +{ + LocaleImpl.PrepareStream(b); + LocaleImpl.stream << data; + LocaleImpl.FlushStream(b); + return b; +} + +ByteStringBuilder &operator<<(ByteStringBuilder &b, ByteString::value_type data) +{ + b.AddChars(&data, 1); + return b; +} + +ByteStringBuilder &operator<<(ByteStringBuilder &b, ByteString::value_type const *data) +{ + return b << ByteString(data); +} + +ByteStringBuilder &operator<<(ByteStringBuilder &b, ByteString const &data) +{ + b.AddChars(data.data(), data.size()); + return b; +} + +ByteStringBuilder &operator<<(ByteStringBuilder &b, float data) +{ + LocaleImpl.PrepareStream(b); + LocaleImpl.stream << data; + LocaleImpl.FlushStream(b); + return b; +} + +ByteStringBuilder &operator<<(ByteStringBuilder &b, double data) +{ + LocaleImpl.PrepareStream(b); + LocaleImpl.stream << data; + LocaleImpl.FlushStream(b); + return b; +} + +ByteString::Split ByteString::SplitSigned(long long int &value, size_t pos, std::ios_base::fmtflags set, std::ios_base::fmtflags reset) const +{ + LocaleImpl.PrepareStream(*this, pos, set, reset); + LocaleImpl.stream >> value; + if(LocaleImpl.stream.fail()) + { + LocaleImpl.FlushStream(); + return Split(*this, pos, npos, 0, false); + } + LocaleImpl.stream.clear(); + Split split(*this, pos, pos + LocaleImpl.stream.tellg(), 0, false); + LocaleImpl.FlushStream(); + return split; +} + +ByteString::Split ByteString::SplitUnsigned(unsigned long long int &value, size_t pos, std::ios_base::fmtflags set, std::ios_base::fmtflags reset) const +{ + LocaleImpl.PrepareStream(*this, pos, set, reset); + LocaleImpl.stream >> value; + if(LocaleImpl.stream.fail()) + { + LocaleImpl.FlushStream(); + return Split(*this, pos, npos, 0, false); + } + LocaleImpl.stream.clear(); + Split split(*this, pos, pos + LocaleImpl.stream.tellg(), 0, false); + LocaleImpl.FlushStream(); + return split; +} + +ByteString::Split ByteString::SplitFloat(double &value, size_t pos, std::ios_base::fmtflags set, std::ios_base::fmtflags reset) const +{ + LocaleImpl.PrepareStream(*this, pos, set, reset); + LocaleImpl.stream >> value; + if(LocaleImpl.stream.fail()) + { + LocaleImpl.FlushStream(); + return Split(*this, pos, npos, 0, false); + } + LocaleImpl.stream.clear(); + Split split(*this, pos, pos + LocaleImpl.stream.tellg(), 0, false); + LocaleImpl.FlushStream(); + return split; +} + String StringBuilder::Build() const { return String(buffer.begin(), buffer.end()); @@ -371,6 +558,11 @@ StringBuilder &operator<<(StringBuilder &b, String::value_type data) return b; } +StringBuilder &operator<<(StringBuilder &b, String::value_type const *data) +{ + return b << String(data); +} + StringBuilder &operator<<(StringBuilder &b, String const &data) { b.AddChars(data.data(), data.size()); @@ -399,7 +591,6 @@ String::Split String::SplitSigned(long long int &value, size_t pos, std::ios_bas LocaleImpl.wstream >> value; if(LocaleImpl.wstream.fail()) { - LocaleImpl.wstream.clear(); LocaleImpl.FlushWStream(); return Split(*this, pos, npos, 0, false); } @@ -415,7 +606,6 @@ String::Split String::SplitUnsigned(unsigned long long int &value, size_t pos, s LocaleImpl.wstream >> value; if(LocaleImpl.wstream.fail()) { - LocaleImpl.wstream.clear(); LocaleImpl.FlushWStream(); return Split(*this, pos, npos, 0, false); } @@ -431,7 +621,6 @@ String::Split String::SplitFloat(double &value, size_t pos, std::ios_base::fmtfl LocaleImpl.wstream >> value; if(LocaleImpl.wstream.fail()) { - LocaleImpl.wstream.clear(); LocaleImpl.FlushWStream(); return Split(*this, pos, npos, 0, false); } diff --git a/src/common/String.h b/src/common/String.h index 05629fc33..bb6be1841 100644 --- a/src/common/String.h +++ b/src/common/String.h @@ -72,10 +72,10 @@ public: inline ByteString Substr(size_t pos = 0, size_t count = npos) const { return super::substr(pos, count); } inline ByteString SubstrFromEnd(size_t rpos = 0, size_t rcount = npos) const { return super::substr(rcount == npos || rcount > rpos ? 0 : rpos - rcount, size() - rpos); } - inline ByteString Between(size_t from, size_t to) const { return from >= to ? ByteString() : super::substr(from, to - from); } + inline ByteString Between(size_t from, size_t to) const { return to == npos ? super::substr(from) : from >= to ? ByteString() : super::substr(from, to - from); } inline bool Contains(value_type ch) const { return super::find(ch) != npos; } - inline bool Contains(ByteString const &other) { return super::find(other) != npos; } + inline bool Contains(ByteString const &other) const { return super::find(other) != npos; } inline bool BeginsWith(ByteString const &other) const { return !super::compare(0, other.size(), other); } inline bool EndsWith(ByteString const &other) const { return !super::compare(size() - other.size(), other.size(), other); } @@ -89,6 +89,71 @@ public: inline Split SplitFromEndBy(ByteString const &str, size_t pos = npos) const { return Split(*this, pos, super::find(str, pos), str.size(), true); } inline Split SplitFromEndByAny(ByteString const &str, size_t pos = npos) const { return Split(*this, pos, super::find_last_of(str, pos), 1, true); } inline Split SplitFromEndByNot(ByteString const &str, size_t pos = npos) const { return Split(*this, pos, super::find_last_not_of(str, pos), 1, true); } +private: + Split SplitSigned(long long int &, size_t, std::ios_base::fmtflags, std::ios_base::fmtflags) const; + Split SplitUnsigned(unsigned long long int &, size_t, std::ios_base::fmtflags, std::ios_base::fmtflags) const; + Split SplitFloat(double &, size_t, std::ios_base::fmtflags, std::ios_base::fmtflags) const; +public: + template inline Split SplitSigned(T &ref, size_t pos, std::ios_base::fmtflags set, std::ios_base::fmtflags reset) const + { + long long int value = 0; + Split split = SplitSigned(value, pos, set, reset); + ref = value; + return split; + } + template inline Split SplitUnsigned(T &ref, size_t pos, std::ios_base::fmtflags set, std::ios_base::fmtflags reset) const + { + unsigned long long int value = 0; + Split split = SplitUnsigned(value, pos, set, reset); + ref = value; + return split; + } + template inline Split SplitFloat(T &ref, size_t pos, std::ios_base::fmtflags set, std::ios_base::fmtflags reset) const + { + double value = 0; + Split split = SplitFloat(value, pos, set, reset); + ref = value; + return split; + } + + inline Split SplitNumber(short int &ref, size_t pos = 0) const { return SplitSigned(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + inline Split SplitNumber(int &ref, size_t pos = 0) const { return SplitSigned(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + inline Split SplitNumber(long int &ref, size_t pos = 0) const { return SplitSigned(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + inline Split SplitNumber(long long int &ref, size_t pos = 0) const { return SplitSigned(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + inline Split SplitNumber(unsigned short int &ref, size_t pos = 0) const { return SplitUnsigned(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + inline Split SplitNumber(unsigned int &ref, size_t pos = 0) const { return SplitUnsigned(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + inline Split SplitNumber(unsigned long int &ref, size_t pos = 0) const { return SplitUnsigned(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + inline Split SplitNumber(unsigned long long int &ref, size_t pos = 0) const { return SplitUnsigned(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + inline Split SplitNumber(float &ref, size_t pos = 0) const { return SplitFloat(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + inline Split SplitNumber(double &ref, size_t pos = 0) const { return SplitFloat(ref, pos, std::ios_base::fmtflags(), std::ios_base::fmtflags()); } + + template inline Split SplitNumber(short int &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitSigned(ref, pos, set, reset); } + template inline Split SplitNumber(int &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitSigned(ref, pos, set, reset); } + template inline Split SplitNumber(long int &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitSigned(ref, pos, set, reset); } + template inline Split SplitNumber(long long int &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitSigned(ref, pos, set, reset); } + template inline Split SplitNumber(unsigned short int &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitUnsigned(ref, pos, set, reset); } + template inline Split SplitNumber(unsigned int &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitUnsigned(ref, pos, set, reset); } + template inline Split SplitNumber(unsigned long int &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitUnsigned(ref, pos, set, reset); } + template inline Split SplitNumber(unsigned long long int &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitUnsigned(ref, pos, set, reset); } + template inline Split SplitNumber(float &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitFloat(ref, pos, set, reset); } + template inline Split SplitNumber(double &ref, Format::FlagsOverride, size_t pos = 0) const { return SplitFloat(ref, pos, set, reset); } + + template T ToNumber(bool noThrow = false) const + { + T value = T(); + Split split = SplitNumber(value); + if(split.PositionBefore() != size()) + return noThrow ? T() : throw std::runtime_error("Not a number"); + return value; + } + template inline T ToNumber(Format::FlagsOverride fmt, bool noThrow = false) const + { + T value = T(); + Split split = SplitNumber(value, fmt); + if(split.PositionBefore() != size()) + return noThrow ? T() : throw std::runtime_error("Not a number"); + return value; + } std::vector PartitionBy(value_type ch, bool includeEmpty = false) const; std::vector PartitionBy(ByteString const &str, bool includeEmpty = false) const; @@ -102,6 +167,7 @@ public: String FromUtf8(bool ignoreError = true) const; inline String FromAscii() const; + template static ByteString Build(Ts&&... args); using Stream = std::basic_stringstream; }; @@ -177,7 +243,7 @@ public: inline Split SplitByAny(String const &str, size_t pos = 0) const { return Split(*this, pos, super::find_first_of(str, pos), 1, false); } inline Split SplitByNot(String const &str, size_t pos = 0) const { return Split(*this, pos, super::find_first_not_of(str, pos), 1, false); } inline Split SplitFromEndBy(value_type ch, size_t pos = npos) const { return Split(*this, pos, super::rfind(ch, pos), 1, true); } - inline Split SplitFromEndBy(String const &str, size_t pos = npos) const { return Split(*this, pos,super::find(str, pos), str.size(), true); } + inline Split SplitFromEndBy(String const &str, size_t pos = npos) const { return Split(*this, pos, super::find(str, pos), str.size(), true); } inline Split SplitFromEndByAny(String const &str, size_t pos = npos) const { return Split(*this, pos, super::find_last_of(str, pos), 1, true); } inline Split SplitFromEndByNot(String const &str, size_t pos = npos) const { return Split(*this, pos, super::find_last_not_of(str, pos), 1, true); } private: @@ -251,7 +317,7 @@ public: std::vector PartitionByAny(String const &str, bool includeEmpty = false) const; String &Substitute(String const &needle, String const &replacement); - + inline String &Insert(size_t pos, String const &str) { super::insert(pos, str); return *this; } inline String &Erase(size_t pos, size_t count) { super::erase(pos, count); return *this; } inline String &EraseBetween(size_t from, size_t to) { if(from < to) super::erase(from, to - from); return *this; } @@ -326,9 +392,52 @@ public: inline ConversionError(bool to): std::runtime_error(to ? "Could not convert to UTF-8" : "Could not convert from UTF-8") {} }; +class ByteStringBuilder +{ + std::vector buffer; +public: + std::ios_base::fmtflags flags; + ByteString::value_type fill; + size_t width, precision; + inline ByteStringBuilder(): flags(std::ios_base::skipws | std::ios_base::dec), fill(' '), width(0), precision(6) {} + + void AddChars(ByteString::value_type const *, size_t); + size_t Size() const { return buffer.size(); } + ByteString Build() const; + + template ByteStringBuilder &operator<<(T) = delete; + + template ByteStringBuilder &Add(T &&arg, Ts&&... args) + { + return (*this << std::forward(arg)).Add(std::forward(args)...); + } + ByteStringBuilder &Add() { return *this; } +}; + +ByteStringBuilder &operator<<(ByteStringBuilder &, short int); +ByteStringBuilder &operator<<(ByteStringBuilder &, int); +ByteStringBuilder &operator<<(ByteStringBuilder &, long int); +ByteStringBuilder &operator<<(ByteStringBuilder &, long long int); +ByteStringBuilder &operator<<(ByteStringBuilder &, unsigned short int); +ByteStringBuilder &operator<<(ByteStringBuilder &, unsigned int); +ByteStringBuilder &operator<<(ByteStringBuilder &, unsigned long int); +ByteStringBuilder &operator<<(ByteStringBuilder &, unsigned long long int); +ByteStringBuilder &operator<<(ByteStringBuilder &, ByteString::value_type); +ByteStringBuilder &operator<<(ByteStringBuilder &, ByteString::value_type const *); +ByteStringBuilder &operator<<(ByteStringBuilder &, ByteString const &); +ByteStringBuilder &operator<<(ByteStringBuilder &, float); +ByteStringBuilder &operator<<(ByteStringBuilder &, double); + +template ByteString ByteString::Build(Ts&&... args) +{ + ByteStringBuilder b; + b.Add(std::forward(args)...); + return b.Build(); +} + class StringBuilder { - std::vector buffer; // TODO: std::list > ? + std::vector buffer; public: std::ios_base::fmtflags flags; String::value_type fill; @@ -358,6 +467,7 @@ StringBuilder &operator<<(StringBuilder &, unsigned long int); StringBuilder &operator<<(StringBuilder &, unsigned long long int); StringBuilder &operator<<(StringBuilder &, ByteString::value_type); StringBuilder &operator<<(StringBuilder &, String::value_type); +StringBuilder &operator<<(StringBuilder &, String::value_type const *); StringBuilder &operator<<(StringBuilder &, String const &); StringBuilder &operator<<(StringBuilder &, float); StringBuilder &operator<<(StringBuilder &, double); From 1485ae5a2178d649b5ba0064ef47b1a72a808e23 Mon Sep 17 00:00:00 2001 From: mniip Date: Fri, 4 May 2018 20:05:26 +0300 Subject: [PATCH 25/27] Fix incorrect uses of String(char[]) --- src/client/GameSave.cpp | 2 +- src/gui/interface/Window.cpp | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/client/GameSave.cpp b/src/client/GameSave.cpp index 3b7f16f23..b7fd2af36 100644 --- a/src/client/GameSave.cpp +++ b/src/client/GameSave.cpp @@ -1947,7 +1947,7 @@ void GameSave::readPSv(char * saveDataChar, int dataLength) x = 254; memcpy(tempSignText, data+p, x); tempSignText[x] = 0; - tempSign.text = format::CleanString(tempSignText, true, true, true).Substr(0, 45); + tempSign.text = format::CleanString(ByteString(tempSignText).FromUtf8(), true, true, true).Substr(0, 45); tempSigns.push_back(tempSign); p += x; } diff --git a/src/gui/interface/Window.cpp b/src/gui/interface/Window.cpp index 37fcdbfbe..42a011db7 100644 --- a/src/gui/interface/Window.cpp +++ b/src/gui/interface/Window.cpp @@ -227,11 +227,10 @@ void Window::DoDraw() { int xPos = focusedComponent_->Position.X+focusedComponent_->Size.X+5+Position.X; Graphics * g = ui::Engine::Ref().g; - char tempString[512]; - char tempString2[512]; + String tempString, tempString2; - sprintf(tempString, "Position: L %d, R %d, T: %d, B: %d", focusedComponent_->Position.X, Size.X-(focusedComponent_->Position.X+focusedComponent_->Size.X), focusedComponent_->Position.Y, Size.Y-(focusedComponent_->Position.Y+focusedComponent_->Size.Y)); - sprintf(tempString2, "Size: %d, %d", focusedComponent_->Size.X, focusedComponent_->Size.Y); + tempString = String::Build("Position: L ", focusedComponent_->Position.X, ", R ", Size.X-(focusedComponent_->Position.X+focusedComponent_->Size.X), ", T: ", focusedComponent_->Position.Y, ", B: ", Size.Y-(focusedComponent_->Position.Y+focusedComponent_->Size.Y)); + tempString2 = String::Build("Size: ", focusedComponent_->Size.X, ", ", focusedComponent_->Size.Y); if (Graphics::textwidth(tempString)+xPos > WINDOWW) xPos = WINDOWW-(Graphics::textwidth(tempString)+5); From e29d2c58c20092acbb4d975c0e146245fff21144 Mon Sep 17 00:00:00 2001 From: mniip Date: Fri, 4 May 2018 21:12:47 +0300 Subject: [PATCH 26/27] Copy the Format interface too --- src/common/Format.h | 48 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/src/common/Format.h b/src/common/Format.h index c2db70752..3e76d2fab 100644 --- a/src/common/Format.h +++ b/src/common/Format.h @@ -80,6 +80,54 @@ namespace Format inline PrecisionOverride Precision(size_t precision) { return PrecisionOverride(precision); } }; +template inline ByteStringBuilder &operator<<(ByteStringBuilder &b, Format::FlagsOverride data) +{ + std::ios_base::fmtflags oldflags = b.flags; + b.flags = (b.flags & ~reset) | set; + b << data.value; + b.flags = oldflags; + return b; +} +template inline ByteStringBuilder &operator<<(ByteStringBuilder &b, Format::FlagsOverride data) +{ + b.flags = (b.flags & ~reset) | set; + return b; +} + +template inline ByteStringBuilder &operator<<(ByteStringBuilder &b, Format::WidthOverride data) +{ + size_t oldwidth = b.width; + b.width = data.width; + b << data.value; + b.width = oldwidth; + return b; +} +inline ByteStringBuilder &operator<<(ByteStringBuilder &b, Format::WidthOverride data) +{ + b.width = data.width; + return b; +} + +template inline ByteStringBuilder &operator<<(ByteStringBuilder &b, Format::PrecisionOverride data) +{ + std::ios_base::fmtflags oldflags = b.flags; + if(!(oldflags & std::ios_base::floatfield)) + b.flags |= std::ios_base::fixed; + size_t oldprecision = b.precision; + b.precision = data.precision; + b << data.value; + b.precision = oldprecision; + b.flags = oldflags; + return b; +} +inline ByteStringBuilder &operator<<(ByteStringBuilder &b, Format::PrecisionOverride data) +{ + if(!(b.flags & std::ios_base::floatfield)) + b.flags |= std::ios_base::fixed; + b.precision = data.precision; + return b; +} + template inline StringBuilder &operator<<(StringBuilder &b, Format::FlagsOverride data) { std::ios_base::fmtflags oldflags = b.flags; From f8586ea3a28241862c5b286ad6e4acdf0b6e7f91 Mon Sep 17 00:00:00 2001 From: mniip Date: Fri, 4 May 2018 23:10:39 +0300 Subject: [PATCH 27/27] Remove ByteString::Stream --- src/Format.h | 24 --- src/PowderToySDL.cpp | 6 +- src/client/Client.cpp | 188 ++++++++---------- src/client/GameSave.cpp | 8 +- src/client/HTTP.cpp | 10 +- src/client/requestbroker/APIRequest.cpp | 4 +- src/client/requestbroker/RequestBroker.cpp | 15 +- src/client/requestbroker/WebRequest.cpp | 4 +- src/common/Format.h | 54 +++++ src/common/String.h | 4 +- src/debug/ElementPopulation.cpp | 4 +- src/gui/colourpicker/ColourPickerActivity.cpp | 22 +- src/gui/dialogues/SaveIDMessage.cpp | 4 +- src/gui/font/FontEditor.cpp | 49 ++--- src/gui/game/GameController.cpp | 6 +- src/gui/game/GameView.cpp | 19 +- src/gui/interface/SaveButton.cpp | 2 +- src/gui/localbrowser/LocalBrowserView.cpp | 6 +- src/gui/options/OptionsView.cpp | 6 +- src/gui/preview/PreviewController.cpp | 5 +- src/gui/preview/PreviewModel.cpp | 37 ++-- src/gui/preview/PreviewView.cpp | 6 +- src/gui/profile/ProfileActivity.cpp | 8 +- src/gui/search/SearchView.cpp | 6 +- src/gui/update/UpdateActivity.cpp | 8 +- src/lua/LegacyLuaAPI.cpp | 25 +-- 26 files changed, 248 insertions(+), 282 deletions(-) diff --git a/src/Format.h b/src/Format.h index b29749bde..85b63c7f1 100644 --- a/src/Format.h +++ b/src/Format.h @@ -9,30 +9,6 @@ namespace format { const static char hex[] = "0123456789ABCDEF"; - template ByteString NumberToByteString(T number) - { - ByteString::Stream ss; - ss << number; - return ss.str(); - } - - template String NumberToString(T number) - { - return String::Build(number); - } - - template T ByteStringToNumber(const ByteString & text) - { - ByteString::Stream ss(text); - T number; - return (ss >> number)?number:0; - } - - template T StringToNumber(const String & text) - { - return text.ToNumber(true); - } - ByteString URLEncode(ByteString value); ByteString UnixtimeToDate(time_t unixtime, ByteString dateFomat = "%d %b %Y"); ByteString UnixtimeToDateMini(time_t unixtime); diff --git a/src/PowderToySDL.cpp b/src/PowderToySDL.cpp index 4fd0bb32e..e65f485b6 100644 --- a/src/PowderToySDL.cpp +++ b/src/PowderToySDL.cpp @@ -1009,7 +1009,7 @@ int main(int argc, char * argv[]) if(arguments["scale"].length()) { - tempScale = format::ByteStringToNumber(arguments["scale"]); + tempScale = arguments["scale"].ToNumber(); Client::Ref().SetPref("Scale", tempScale); } @@ -1181,9 +1181,7 @@ int main(int argc, char * argv[]) #ifdef DEBUG std::cout << "Got Ptsave: id: " << saveIdPart << std::endl; #endif - int saveId = format::ByteStringToNumber(saveIdPart); - if (!saveId) - throw std::runtime_error("Invalid Save ID"); + int saveId = saveIdPart.ToNumber(); SaveInfo * newSave = Client::Ref().GetSave(saveId, 0); if (!newSave) diff --git a/src/client/Client.cpp b/src/client/Client.cpp index 4741c896a..a43741dc1 100644 --- a/src/client/Client.cpp +++ b/src/client/Client.cpp @@ -150,7 +150,7 @@ void Client::Initialise(ByteString proxyString) if (authUser.UserID) { - ByteString idTempString = format::NumberToByteString(authUser.UserID); + ByteString idTempString = ByteString::Build(authUser.UserID); char *id = new char[idTempString.length() + 1]; std::strcpy (id, idTempString.c_str()); char *session = new char[authUser.SessionID.length() + 1]; @@ -378,12 +378,11 @@ bool Client::DoInstallation() "NoDisplay=true\n" "Categories=Game;Simulation\n" "Icon=powdertoy.png\n"; - ByteString::Stream protocolfiledata; - protocolfiledata << protocolfiledata_tmp << "Exec=" << filename << " ptsave %u\nPath=" << pathname << "\n"; + ByteString protocolfiledata = ByteString::Build(protocolfiledata_tmp, "Exec=", filename, " ptsave %u\nPath=", pathname, "\n"); f = fopen("powdertoy-tpt-ptsave.desktop", "wb"); if (!f) return 0; - fwrite(protocolfiledata.str().c_str(), 1, strlen(protocolfiledata.str().c_str()), f); + fwrite(protocolfiledata.c_str(), 1, protocolfiledata.size(), f); fclose(f); success = system("xdg-desktop-menu install powdertoy-tpt-ptsave.desktop"); @@ -396,12 +395,11 @@ bool Client::DoInstallation() "NoDisplay=true\n" "Categories=Game;Simulation\n" "Icon=powdertoy.png\n"; - ByteString::Stream desktopopenfiledata; - desktopopenfiledata << desktopopenfiledata_tmp << "Exec=" << filename << " open %f\nPath=" << pathname << "\n"; + ByteString desktopopenfiledata = ByteString::Build(desktopopenfiledata_tmp, "Exec=", filename, " open %f\nPath=", pathname, "\n"); f = fopen("powdertoy-tpt-open.desktop", "wb"); if (!f) return 0; - fwrite(desktopopenfiledata.str().c_str(), 1, strlen(desktopopenfiledata.str().c_str()), f); + fwrite(desktopopenfiledata.c_str(), 1, desktopopenfiledata.size(), f); fclose(f); success = system("xdg-mime install powdertoy-save.xml") && success; success = system("xdg-desktop-menu install powdertoy-tpt-open.desktop") && success; @@ -415,12 +413,11 @@ bool Client::DoInstallation() "Comment=Physics sandbox game\n" "Categories=Game;Simulation\n" "Icon=powdertoy.png\n"; - ByteString::Stream desktopfiledata; - desktopfiledata << desktopfiledata_tmp << "Exec=" << filename << "\nPath=" << pathname << "\n"; + ByteString desktopfiledata = ByteString::Build(desktopfiledata_tmp, "Exec=", filename, "\nPath=", pathname, "\n"); f = fopen("powdertoy-tpt.desktop", "wb"); if (!f) return 0; - fwrite(desktopfiledata.str().c_str(), 1, strlen(desktopfiledata.str().c_str()), f); + fwrite(desktopfiledata.c_str(), 1, desktopfiledata.size(), f); fclose(f); success = system("xdg-desktop-menu install powdertoy-tpt.desktop") && success; @@ -989,8 +986,7 @@ RequestStatus Client::UploadSave(SaveInfo & save) int dataStatus; char * data; int dataLength = 0; - ByteString::Stream userIDStream; - userIDStream << authUser.UserID; + ByteString userID = ByteString::Build(authUser.UserID); if (authUser.UserID) { if (!save.GetGameSave()) @@ -1020,13 +1016,13 @@ RequestStatus Client::UploadSave(SaveInfo & save) std::strcpy (saveName, save.GetName().ToUtf8().c_str()); char *saveDescription = new char[save.GetDescription().length() + 1]; std::strcpy (saveDescription, save.GetDescription().ToUtf8().c_str()); - char *userid = new char[userIDStream.str().length() + 1]; - std::strcpy (userid, userIDStream.str().c_str()); + char *userid = new char[userID.size() + 1]; + std::strcpy (userid, userID.c_str()); char *session = new char[authUser.SessionID.length() + 1]; std::strcpy (session, authUser.SessionID.c_str()); const char *const postNames[] = { "Name", "Description", "Data:save.bin", "Publish", NULL }; - const char *const postDatas[] = { saveName, saveDescription, gameData, (char *)(save.GetPublished()?"Public":"Private") }; + const char *const postDatas[] = { saveName, saveDescription, gameData, save.GetPublished()?"Public":"Private" }; size_t postLengths[] = { save.GetName().length(), save.GetDescription().length(), gameDataLength, (size_t)(save.GetPublished()?6:7) }; data = http_multipart_post("http://" SERVER "/Save.api", postNames, postDatas, postLengths, userid, NULL, session, &dataStatus, &dataLength); @@ -1044,7 +1040,7 @@ RequestStatus Client::UploadSave(SaveInfo & save) RequestStatus ret = ParseServerReturn(data, dataStatus, false); if (ret == RequestOkay) { - int saveID = format::ByteStringToNumber(data+3); + int saveID = ByteString(data+3).ToNumber(); if (!saveID) { lastError = "Server did not return Save ID"; @@ -1100,12 +1096,8 @@ void Client::DeleteStamp(ByteString stampID) { if((*iterator) == stampID) { - ByteString::Stream stampFilename; - stampFilename << STAMPS_DIR; - stampFilename << PATH_SEP; - stampFilename << stampID; - stampFilename << ".stm"; - remove(stampFilename.str().c_str()); + ByteString stampFilename = ByteString::Build(STAMPS_DIR, PATH_SEP, stampID, ".stm"); + remove(stampFilename.c_str()); stampIDs.erase(iterator); return; } @@ -1124,12 +1116,8 @@ ByteString Client::AddStamp(GameSave * saveData) } else lastStampName++; - ByteString::Stream saveID; - //sprintf(saveID, "%08x%02x", lastStampTime, lastStampName); - saveID - << std::setw(8) << std::setfill('0') << std::hex << lastStampTime - << std::setw(2) << std::setfill('0') << std::hex << lastStampName; - ByteString filename = STAMPS_DIR PATH_SEP + saveID.str() + ".stm"; + ByteString saveID = ByteString::Build(Format::Hex(Format::Width(lastStampTime, 8)), Format::Hex(Format::Width(lastStampName, 2))); + ByteString filename = STAMPS_DIR PATH_SEP + saveID + ".stm"; MakeDirectory(STAMPS_DIR); @@ -1157,11 +1145,11 @@ ByteString Client::AddStamp(GameSave * saveData) delete[] gameData; - stampIDs.push_front(saveID.str()); + stampIDs.push_front(saveID); updateStamps(); - return saveID.str(); + return saveID; } void Client::updateStamps() @@ -1233,8 +1221,8 @@ RequestStatus Client::ExecVote(int saveID, int direction) if (authUser.UserID) { char * directionText = (char*)(direction==1?"Up":"Down"); - ByteString saveIDText = format::NumberToByteString(saveID); - ByteString userIDText = format::NumberToByteString(authUser.UserID); + ByteString saveIDText = ByteString::Build(saveID); + ByteString userIDText = ByteString::Build(authUser.UserID); char *id = new char[saveIDText.length() + 1]; std::strcpy(id, saveIDText.c_str()); @@ -1267,14 +1255,14 @@ unsigned char * Client::GetSaveData(int saveID, int saveDate, int & dataLength) int dataStatus; char *data; dataLength = 0; - ByteString::Stream urlStream; + ByteString urlStr; if (saveDate) - urlStream << "http://" << STATICSERVER << "/" << saveID << "_" << saveDate << ".cps"; + urlStr = ByteString::Build("http://", STATICSERVER, "/", saveID, "_", saveDate, ".cps"); else - urlStream << "http://" << STATICSERVER << "/" << saveID << ".cps"; + urlStr = ByteString::Build("http://", STATICSERVER, "/", saveID, ".cps"); - char *url = new char[urlStream.str().length() + 1]; - std::strcpy(url, urlStream.str().c_str()); + char *url = new char[urlStr.size() + 1]; + std::strcpy(url, urlStr.c_str()); data = http_simple_get(url, &dataStatus, &dataLength); delete[] url; @@ -1300,13 +1288,13 @@ std::vector Client::GetSaveData(int saveID, int saveDate) RequestBroker::Request * Client::GetSaveDataAsync(int saveID, int saveDate) { - ByteString::Stream urlStream; + ByteString url; if(saveDate){ - urlStream << "http://" << STATICSERVER << "/" << saveID << "_" << saveDate << ".cps"; + url = ByteString::Build("http://", STATICSERVER, "/", saveID, "_", saveDate, ".cps"); } else { - urlStream << "http://" << STATICSERVER << "/" << saveID << ".cps"; + url = ByteString::Build("http://", STATICSERVER, "/", saveID, ".cps"); } - return new WebRequest(urlStream.str()); + return new WebRequest(url); } RequestBroker::Request * Client::SaveUserInfoAsync(UserInfo info) @@ -1381,7 +1369,6 @@ RequestBroker::Request * Client::GetUserInfoAsync(ByteString username) LoginStatus Client::Login(ByteString username, ByteString password, User & user) { lastError = ""; - ByteString::Stream hashStream; char passwordHash[33]; char totalHash[33]; @@ -1393,14 +1380,14 @@ LoginStatus Client::Login(ByteString username, ByteString password, User & user) //Doop md5_ascii(passwordHash, (const unsigned char *)password.c_str(), password.length()); passwordHash[32] = 0; - hashStream << username << "-" << passwordHash; - md5_ascii(totalHash, (const unsigned char *)(hashStream.str().c_str()), hashStream.str().length()); + ByteString total = ByteString::Build(username, "-", passwordHash); + md5_ascii(totalHash, (const unsigned char *)(total.c_str()), total.size()); totalHash[32] = 0; char * data; int dataStatus, dataLength; const char *const postNames[] = { "Username", "Hash", NULL }; - const char *const postDatas[] = { (char*)username.c_str(), totalHash }; + const char *const postDatas[] = { username.c_str(), totalHash }; size_t postLengths[] = { username.length(), 32 }; data = http_multipart_post("http://" SERVER "/Login.json", postNames, postDatas, postLengths, NULL, NULL, NULL, &dataStatus, &dataLength); RequestStatus ret = ParseServerReturn(data, dataStatus, true); @@ -1454,15 +1441,13 @@ LoginStatus Client::Login(ByteString username, ByteString password, User & user) RequestStatus Client::DeleteSave(int saveID) { lastError = ""; - ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; - urlStream << "http://" << SERVER << "/Browse/Delete.json?ID=" << saveID << "&Mode=Delete&Key=" << authUser.SessionKey; + ByteString url = ByteString::Build("http://", SERVER, "/Browse/Delete.json?ID=", saveID, "&Mode=Delete&Key=", authUser.SessionKey); if(authUser.UserID) { - ByteString::Stream userIDStream; - userIDStream << authUser.UserID; - data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); + ByteString userID = ByteString::Build(authUser.UserID); + data = http_auth_get(url.c_str(), userID.c_str(), NULL, authUser.SessionID.c_str(), &dataStatus, &dataLength); } else { @@ -1477,19 +1462,18 @@ RequestStatus Client::DeleteSave(int saveID) RequestStatus Client::AddComment(int saveID, String comment) { lastError = ""; - ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; - urlStream << "http://" << SERVER << "/Browse/Comments.json?ID=" << saveID; + ByteString url = ByteString::Build("http://", SERVER, "/Browse/Comments.json?ID=", saveID); if(authUser.UserID) { - ByteString::Stream userIDStream; - userIDStream << authUser.UserID; + ByteString userID = ByteString::Build(authUser.UserID); const char *const postNames[] = { "Comment", NULL }; - const char *const postDatas[] = { (char*)(comment.c_str()) }; - size_t postLengths[] = { comment.length() }; - data = http_multipart_post((char *)urlStream.str().c_str(), postNames, postDatas, postLengths, (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); + ByteString commentBytes = comment.ToUtf8(); + const char *const postDatas[] = { commentBytes.c_str() }; + size_t postLengths[] = { commentBytes.size() }; + data = http_multipart_post(url.c_str(), postNames, postDatas, postLengths, userID.c_str(), NULL, authUser.SessionID.c_str(), &dataStatus, &dataLength); } else { @@ -1504,7 +1488,7 @@ RequestStatus Client::AddComment(int saveID, String comment) RequestStatus Client::FavouriteSave(int saveID, bool favourite) { lastError = ""; - ByteString::Stream urlStream; + ByteStringBuilder urlStream; char * data = NULL; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse/Favourite.json?ID=" << saveID << "&Key=" << authUser.SessionKey; @@ -1512,9 +1496,8 @@ RequestStatus Client::FavouriteSave(int saveID, bool favourite) urlStream << "&Mode=Remove"; if(authUser.UserID) { - ByteString::Stream userIDStream; - userIDStream << authUser.UserID; - data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); + ByteString userID = ByteString::Build(authUser.UserID); + data = http_auth_get(urlStream.Build().c_str(), userID.c_str(), NULL, authUser.SessionID.c_str(), &dataStatus, &dataLength); } else { @@ -1529,19 +1512,18 @@ RequestStatus Client::FavouriteSave(int saveID, bool favourite) RequestStatus Client::ReportSave(int saveID, String message) { lastError = ""; - ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; - urlStream << "http://" << SERVER << "/Browse/Report.json?ID=" << saveID << "&Key=" << authUser.SessionKey; + ByteString url = ByteString::Build("http://", SERVER, "/Browse/Report.json?ID=", saveID, "&Key=", authUser.SessionKey); if(authUser.UserID) { - ByteString::Stream userIDStream; - userIDStream << authUser.UserID; + ByteString userID = ByteString::Build(authUser.UserID); const char *const postNames[] = { "Reason", NULL }; - const char *const postDatas[] = { (char*)(message.c_str()) }; - size_t postLengths[] = { message.length() }; - data = http_multipart_post((char *)urlStream.str().c_str(), postNames, postDatas, postLengths, (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); + ByteString messageBytes = message.ToUtf8(); + const char *const postDatas[] = { messageBytes.c_str() }; + size_t postLengths[] = { messageBytes.size() }; + data = http_multipart_post(url.c_str(), postNames, postDatas, postLengths, userID.c_str(), NULL, authUser.SessionID.c_str(), &dataStatus, &dataLength); } else { @@ -1556,15 +1538,14 @@ RequestStatus Client::ReportSave(int saveID, String message) RequestStatus Client::UnpublishSave(int saveID) { lastError = ""; - ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; - urlStream << "http://" << SERVER << "/Browse/Delete.json?ID=" << saveID << "&Mode=Unpublish&Key=" << authUser.SessionKey; + ByteString url = ByteString::Build("http://", SERVER, "/Browse/Delete.json?ID=", saveID, "&Mode=Unpublish&Key=", authUser.SessionKey); if(authUser.UserID) { - ByteString::Stream userIDStream; - userIDStream << authUser.UserID; - data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); + ByteString userID = ByteString::Build(authUser.UserID); + + data = http_auth_get(url.c_str(), userID.c_str(), NULL, authUser.SessionID.c_str(), &dataStatus, &dataLength); } else { @@ -1579,18 +1560,17 @@ RequestStatus Client::UnpublishSave(int saveID) RequestStatus Client::PublishSave(int saveID) { lastError = ""; - ByteString::Stream urlStream; char *data; int dataStatus; - urlStream << "http://" << SERVER << "/Browse/View.json?ID=" << saveID << "&Key=" << authUser.SessionKey; + ByteString url = ByteString::Build("http://", SERVER, "/Browse/View.json?ID=", saveID, "&Key=", authUser.SessionKey); if (authUser.UserID) { - ByteString::Stream userIDStream; - userIDStream << authUser.UserID; + ByteString userID = ByteString::Build(authUser.UserID); + const char *const postNames[] = { "ActionPublish", NULL }; const char *const postDatas[] = { "" }; - size_t postLengths[] = { 1 }; - data = http_multipart_post(urlStream.str().c_str(), postNames, postDatas, postLengths, userIDStream.str().c_str(), NULL, authUser.SessionID.c_str(), &dataStatus, NULL); } + size_t postLengths[] = { 0 }; + data = http_multipart_post(url.c_str(), postNames, postDatas, postLengths, userID.c_str(), NULL, authUser.SessionID.c_str(), &dataStatus, NULL); } else { lastError = "Not authenticated"; @@ -1604,7 +1584,7 @@ RequestStatus Client::PublishSave(int saveID) SaveInfo * Client::GetSave(int saveID, int saveDate) { lastError = ""; - ByteString::Stream urlStream; + ByteStringBuilder urlStream; urlStream << "http://" << SERVER << "/Browse/View.json?ID=" << saveID; if(saveDate) { @@ -1614,13 +1594,13 @@ SaveInfo * Client::GetSave(int saveID, int saveDate) int dataStatus, dataLength; if(authUser.UserID) { - ByteString::Stream userIDStream; - userIDStream << authUser.UserID; - data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); + ByteString userID = ByteString::Build(authUser.UserID); + + data = http_auth_get(urlStream.Build().c_str(), userID.c_str(), NULL, authUser.SessionID.c_str(), &dataStatus, &dataLength); } else { - data = http_simple_get((char *)urlStream.str().c_str(), &dataStatus, &dataLength); + data = http_simple_get(urlStream.Build().c_str(), &dataStatus, &dataLength); } if(dataStatus == 200 && data) { @@ -1677,7 +1657,7 @@ SaveInfo * Client::GetSave(int saveID, int saveDate) RequestBroker::Request * Client::GetSaveAsync(int saveID, int saveDate) { - ByteString::Stream urlStream; + ByteStringBuilder urlStream; urlStream << "http://" << SERVER << "/Browse/View.json?ID=" << saveID; if(saveDate) { @@ -1734,7 +1714,7 @@ RequestBroker::Request * Client::GetSaveAsync(int saveID, int saveDate) } virtual ~SaveInfoParser() { } }; - return new APIRequest(urlStream.str(), new SaveInfoParser()); + return new APIRequest(urlStream.Build(), new SaveInfoParser()); } RequestBroker::Request * Client::GetCommentsAsync(int saveID, int start, int count) @@ -1752,7 +1732,7 @@ RequestBroker::Request * Client::GetCommentsAsync(int saveID, int start, int cou for (Json::UInt j = 0; j < commentsArray.size(); j++) { - int userID = format::ByteStringToNumber(commentsArray[j]["UserID"].asString()); + int userID = ByteString(commentsArray[j]["UserID"].asString()).ToNumber(); ByteString username = commentsArray[j]["Username"].asString(); ByteString formattedUsername = commentsArray[j]["FormattedUsername"].asString(); if (formattedUsername == "jacobot") @@ -1775,9 +1755,8 @@ RequestBroker::Request * Client::GetCommentsAsync(int saveID, int start, int cou virtual ~CommentsParser() { } }; - ByteString::Stream urlStream; - urlStream << "http://" << SERVER << "/Browse/Comments.json?ID=" << saveID << "&Start=" << start << "&Count=" << count; - return new APIRequest(urlStream.str(), new CommentsParser()); + ByteString url = ByteString::Build("http://", SERVER, "/Browse/Comments.json?ID=", saveID, "&Start=", start, "&Count=", count); + return new APIRequest(url, new CommentsParser()); } std::vector > * Client::GetTags(int start, int count, String query, int & resultCount) @@ -1785,7 +1764,7 @@ std::vector > * Client::GetTags(int start, int count, lastError = ""; resultCount = 0; std::vector > * tagArray = new std::vector >(); - ByteString::Stream urlStream; + ByteStringBuilder urlStream; char * data; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse/Tags.json?Start=" << start << "&Count=" << count; @@ -1796,7 +1775,7 @@ std::vector > * Client::GetTags(int start, int count, urlStream << format::URLEncode(query.ToUtf8()); } - data = http_simple_get((char *)urlStream.str().c_str(), &dataStatus, &dataLength); + data = http_simple_get(urlStream.Build().c_str(), &dataStatus, &dataLength); if(dataStatus == 200 && data) { try @@ -1832,7 +1811,7 @@ std::vector * Client::SearchSaves(int start, int count, String query, lastError = ""; resultCount = 0; std::vector * saveArray = new std::vector(); - ByteString::Stream urlStream; + ByteStringBuilder urlStream; char * data; int dataStatus, dataLength; urlStream << "http://" << SERVER << "/Browse.json?Start=" << start << "&Count=" << count; @@ -1854,13 +1833,12 @@ std::vector * Client::SearchSaves(int start, int count, String query, } if(authUser.UserID) { - ByteString::Stream userIDStream; - userIDStream << authUser.UserID; - data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); + ByteString userID = ByteString::Build(authUser.UserID); + data = http_auth_get(urlStream.Build().c_str(), userID.c_str(), NULL, authUser.SessionID.c_str(), &dataStatus, &dataLength); } else { - data = http_simple_get((char *)urlStream.str().c_str(), &dataStatus, &dataLength); + data = http_simple_get(urlStream.Build().c_str(), &dataStatus, &dataLength); } ParseServerReturn(data, dataStatus, true); if (dataStatus == 200 && data) @@ -1917,15 +1895,13 @@ std::list * Client::RemoveTag(int saveID, ByteString tag) { lastError = ""; std::list * tags = NULL; - ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; - urlStream << "http://" << SERVER << "/Browse/EditTag.json?Op=delete&ID=" << saveID << "&Tag=" << tag << "&Key=" << authUser.SessionKey; + ByteString url = ByteString::Build("http://", SERVER, "/Browse/EditTag.json?Op=delete&ID=", saveID, "&Tag=", tag, "&Key=", authUser.SessionKey); if(authUser.UserID) { - ByteString::Stream userIDStream; - userIDStream << authUser.UserID; - data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); + ByteString userID = ByteString::Build(authUser.UserID); + data = http_auth_get(url.c_str(), userID.c_str(), NULL, authUser.SessionID.c_str(), &dataStatus, &dataLength); } else { @@ -1959,15 +1935,13 @@ std::list * Client::AddTag(int saveID, ByteString tag) { lastError = ""; std::list * tags = NULL; - ByteString::Stream urlStream; char * data = NULL; int dataStatus, dataLength; - urlStream << "http://" << SERVER << "/Browse/EditTag.json?Op=add&ID=" << saveID << "&Tag=" << tag << "&Key=" << authUser.SessionKey; + ByteString url = ByteString::Build("http://", SERVER, "/Browse/EditTag.json?Op=add&ID=", saveID, "&Tag=", tag, "&Key=", authUser.SessionKey); if(authUser.UserID) { - ByteString::Stream userIDStream; - userIDStream << authUser.UserID; - data = http_auth_get((char *)urlStream.str().c_str(), (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); + ByteString userID = ByteString::Build(authUser.UserID); + data = http_auth_get(url.c_str(), userID.c_str(), NULL, authUser.SessionID.c_str(), &dataStatus, &dataLength); } else { diff --git a/src/client/GameSave.cpp b/src/client/GameSave.cpp index b7fd2af36..eff87d3df 100644 --- a/src/client/GameSave.cpp +++ b/src/client/GameSave.cpp @@ -629,7 +629,7 @@ void GameSave::readOPS(char * data, int dataLength) int bz2ret; if ((bz2ret = BZ2_bzBuffToBuffDecompress((char*)bsonData, &bsonDataLen, (char*)(inputData+12), inputDataLen-12, 0, 0)) != BZ_OK) { - throw ParseException(ParseException::Corrupt, "Unable to decompress (ret " + format::NumberToString(bz2ret) + ")"); + throw ParseException(ParseException::Corrupt, String::Build("Unable to decompress (ret ", bz2ret, ")")); } set_bson_err_handler([](const char* err) { throw ParseException(ParseException::Corrupt, "BSON error when parsing save: " + ByteString(err).FromUtf8()); }); @@ -1406,7 +1406,7 @@ void GameSave::readPSv(char * saveDataChar, int dataLength) int bzStatus = 0; if ((bzStatus = BZ2_bzBuffToBuffDecompress((char *)data, (unsigned *)&size, (char *)(saveData+12), dataLength-12, 0, 0))) - throw ParseException(ParseException::Corrupt, "Cannot decompress: " + format::NumberToString(bzStatus)); + throw ParseException(ParseException::Corrupt, String::Build("Cannot decompress: ", bzStatus)); dataLength = size; #ifdef DEBUG @@ -2510,7 +2510,7 @@ char * GameSave::serialiseOPS(unsigned int & dataLength) unsigned int finalDataLen = bson_size(&b); auto outputData = std::unique_ptr(new unsigned char[finalDataLen*2+12]); if (!outputData) - throw BuildException("Save error, out of memory (finalData): " + format::NumberToString(finalDataLen*2+12)); + throw BuildException(String::Build("Save error, out of memory (finalData): ", finalDataLen*2+12)); outputData[0] = 'O'; outputData[1] = 'P'; @@ -2528,7 +2528,7 @@ char * GameSave::serialiseOPS(unsigned int & dataLength) unsigned int compressedSize = finalDataLen*2, bz2ret; if ((bz2ret = BZ2_bzBuffToBuffCompress((char*)(outputData.get()+12), &compressedSize, (char*)finalData, bson_size(&b), 9, 0, 0)) != BZ_OK) { - throw BuildException("Save error, could not compress (ret " + format::NumberToString(bz2ret) + ")"); + throw BuildException(String::Build("Save error, could not compress (ret ", bz2ret, ")")); } #ifdef DEBUG diff --git a/src/client/HTTP.cpp b/src/client/HTTP.cpp index 26da8f496..899122924 100644 --- a/src/client/HTTP.cpp +++ b/src/client/HTTP.cpp @@ -192,11 +192,7 @@ void http_init(char *proxy) free(host); free(port); } - ByteString::Stream userAgentBuilder; - userAgentBuilder << "PowderToy/" << SAVE_VERSION << "." << MINOR_VERSION << " "; - userAgentBuilder << "(" << IDENT_PLATFORM << "; " << IDENT_BUILD << "; M" << MOD_ID << ") "; - userAgentBuilder << "TPTPP/" << SAVE_VERSION << "." << MINOR_VERSION << "." << BUILD_NUM << IDENT_RELTYPE << "." << SNAPSHOT_ID; - ByteString newUserAgent = userAgentBuilder.str(); + ByteString newUserAgent = ByteString::Build("PowderToy/", SAVE_VERSION, ".", MINOR_VERSION, " (", IDENT_PLATFORM, "; ", IDENT_BUILD, "; M", MOD_ID, ") TPTPP/", SAVE_VERSION, ".", MINOR_VERSION, ".", BUILD_NUM, IDENT_RELTYPE, ".", SNAPSHOT_ID); userAgent = new char[newUserAgent.length()+1]; std::copy(newUserAgent.begin(), newUserAgent.end(), userAgent); userAgent[newUserAgent.length()] = 0; @@ -987,7 +983,7 @@ ByteString FindBoundary(std::map parts, ByteString bound // this function used in Download class, and eventually all http requests ByteString GetMultipartMessage(std::map parts, ByteString boundary) { - ByteString::Stream data; + ByteStringBuilder data; // loop through each part, adding it for (std::map::iterator iter = parts.begin(); iter != parts.end(); iter++) @@ -1014,7 +1010,7 @@ ByteString GetMultipartMessage(std::map parts, ByteStrin data << "\r\n"; } data << "--" << boundary << "--\r\n"; - return data.str(); + return data.Build(); } // add the header needed to make POSTS work diff --git a/src/client/requestbroker/APIRequest.cpp b/src/client/requestbroker/APIRequest.cpp index dcd2e143a..084e580c9 100644 --- a/src/client/requestbroker/APIRequest.cpp +++ b/src/client/requestbroker/APIRequest.cpp @@ -103,7 +103,7 @@ RequestBroker::ProcessResponse APIRequest::Process(RequestBroker & rb) User user = Client::Ref().GetAuthUser(); char userName[12]; char *userSession = new char[user.SessionID.length() + 1]; - std::strcpy(userName, format::NumberToByteString(user.UserID).c_str()); + std::strcpy(userName, ByteString::Build(user.UserID).c_str()); std::strcpy(userSession, user.SessionID.c_str()); HTTPContext = http_multipart_post_async((char*)URL.c_str(), postNames, postData, postLength, userName, NULL, userSession); delete[] userSession; @@ -122,7 +122,7 @@ RequestBroker::ProcessResponse APIRequest::Process(RequestBroker & rb) User user = Client::Ref().GetAuthUser(); char userName[12]; char *userSession = new char[user.SessionID.length() + 1]; - std::strcpy(userName, format::NumberToByteString(user.UserID).c_str()); + std::strcpy(userName, ByteString::Build(user.UserID).c_str()); std::strcpy(userSession, user.SessionID.c_str()); http_auth_headers(HTTPContext, userName, NULL, userSession); delete[] userSession; diff --git a/src/client/requestbroker/RequestBroker.cpp b/src/client/requestbroker/RequestBroker.cpp index b3395e78e..5a446a754 100644 --- a/src/client/requestbroker/RequestBroker.cpp +++ b/src/client/requestbroker/RequestBroker.cpp @@ -97,23 +97,22 @@ void RequestBroker::RenderThumbnail(GameSave * gameSave, bool decorations, bool void RequestBroker::RetrieveThumbnail(int saveID, int saveDate, int width, int height, RequestListener * tListener) { - ByteString::Stream urlStream; - urlStream << "http://" << STATICSERVER << "/" << saveID; + ByteStringBuilder url; + url << "http://" << STATICSERVER << "/" << saveID; if(saveDate) { - urlStream << "_" << saveDate; + url << "_" << saveDate; } - urlStream << "_small.pti"; + url << "_small.pti"; - RetrieveImage(urlStream.str(), width, height, tListener); + RetrieveImage(url.Build(), width, height, tListener); } void RequestBroker::RetrieveAvatar(ByteString username, int width, int height, RequestListener * tListener) { - ByteString::Stream urlStream; - urlStream << "http://" << STATICSERVER << "/avatars/" << username << ".pti"; + ByteString url = ByteString::Build("http://", STATICSERVER, "/avatars/", username, ".pti"); - RetrieveImage(urlStream.str(), width, height, tListener); + RetrieveImage(url, width, height, tListener); } void RequestBroker::Start(Request * request, RequestListener * tListener, int identifier) diff --git a/src/client/requestbroker/WebRequest.cpp b/src/client/requestbroker/WebRequest.cpp index bd8b99ea9..c72b130d0 100644 --- a/src/client/requestbroker/WebRequest.cpp +++ b/src/client/requestbroker/WebRequest.cpp @@ -106,7 +106,7 @@ RequestBroker::ProcessResponse WebRequest::Process(RequestBroker & rb) User user = Client::Ref().GetAuthUser(); char userName[12]; char *userSession = new char[user.SessionID.length() + 1]; - std::strcpy(userName, format::NumberToByteString(user.UserID).c_str()); + std::strcpy(userName, ByteString::Build(user.UserID).c_str()); std::strcpy(userSession, user.SessionID.c_str()); HTTPContext = http_multipart_post_async((char*)URL.c_str(), postNames, postData, postLength, userName, NULL, userSession); delete[] userSession; @@ -125,7 +125,7 @@ RequestBroker::ProcessResponse WebRequest::Process(RequestBroker & rb) User user = Client::Ref().GetAuthUser(); char userName[12]; char *userSession = new char[user.SessionID.length() + 1]; - std::strcpy(userName, format::NumberToByteString(user.UserID).c_str()); + std::strcpy(userName, ByteString::Build(user.UserID).c_str()); std::strcpy(userSession, user.SessionID.c_str()); http_auth_headers(HTTPContext, userName, NULL, userSession); delete[] userSession; diff --git a/src/common/Format.h b/src/common/Format.h index 3e76d2fab..e5afe1eae 100644 --- a/src/common/Format.h +++ b/src/common/Format.h @@ -25,6 +25,18 @@ namespace Format inline FlagsOverride() {} }; + template struct FillOverride + { + T value; + size_t fill; + inline FillOverride(T _value, size_t _fill): value(_value), fill(_fill) {} + }; + template<> struct FillOverride + { + String::value_type fill; + inline FillOverride(size_t _fill): fill(_fill) {} + }; + template struct WidthOverride { T value; @@ -74,8 +86,10 @@ namespace Format inline FlagsOverride Scientific() { return FlagsOverride(); } inline FlagsOverride FloatDefault() { return FlagsOverride(); } + template inline FillOverride Fill(T value, String::value_type fill) { return FillOverride(value, fill); } template inline WidthOverride Width(T value, size_t width) { return WidthOverride(value, width); } template inline PrecisionOverride Precision(T value, size_t precision) { return PrecisionOverride(value, precision); } + inline FillOverride Fill(String::value_type fill) { return FillOverride(fill); } inline WidthOverride Width(size_t width) { return WidthOverride(width); } inline PrecisionOverride Precision(size_t precision) { return PrecisionOverride(precision); } }; @@ -94,16 +108,36 @@ template inline Byte return b; } +template inline ByteStringBuilder &operator<<(ByteStringBuilder &b, Format::FillOverride data) +{ + size_t oldfill = b.fill; + b.fill = data.fill; + b << data.value; + b.fill = oldfill; + return b; +} +inline ByteStringBuilder &operator<<(ByteStringBuilder &b, Format::FillOverride data) +{ + b.fill = data.fill; + return b; +} + template inline ByteStringBuilder &operator<<(ByteStringBuilder &b, Format::WidthOverride data) { + String::value_type oldfill = b.fill; + if(oldfill == ' ') + b.fill = '0'; size_t oldwidth = b.width; b.width = data.width; b << data.value; b.width = oldwidth; + b.fill = oldfill; return b; } inline ByteStringBuilder &operator<<(ByteStringBuilder &b, Format::WidthOverride data) { + if(b.fill == ' ') + b.fill = '0'; b.width = data.width; return b; } @@ -142,16 +176,36 @@ template inline Stri return b; } +template inline StringBuilder &operator<<(StringBuilder &b, Format::FillOverride data) +{ + size_t oldfill = b.fill; + b.fill = data.fill; + b << data.value; + b.fill = oldfill; + return b; +} +inline StringBuilder &operator<<(StringBuilder &b, Format::FillOverride data) +{ + b.fill = data.fill; + return b; +} + template inline StringBuilder &operator<<(StringBuilder &b, Format::WidthOverride data) { + String::value_type oldfill = b.fill; + if(oldfill == ' ') + b.fill = '0'; size_t oldwidth = b.width; b.width = data.width; b << data.value; b.width = oldwidth; + b.fill = oldfill; return b; } inline StringBuilder &operator<<(StringBuilder &b, Format::WidthOverride data) { + if(b.fill == ' ') + b.fill = '0'; b.width = data.width; return b; } diff --git a/src/common/String.h b/src/common/String.h index bb6be1841..4ac454a17 100644 --- a/src/common/String.h +++ b/src/common/String.h @@ -168,8 +168,6 @@ public: String FromUtf8(bool ignoreError = true) const; inline String FromAscii() const; template static ByteString Build(Ts&&... args); - - using Stream = std::basic_stringstream; }; inline ByteString operator+(ByteString const &lhs, ByteString const &rhs) { return static_cast const &>(lhs) + static_cast const &>(rhs); } @@ -405,7 +403,7 @@ public: size_t Size() const { return buffer.size(); } ByteString Build() const; - template ByteStringBuilder &operator<<(T) = delete; + template ByteStringBuilder &operator<<(T) &&= delete; template ByteStringBuilder &Add(T &&arg, Ts&&... args) { diff --git a/src/debug/ElementPopulation.cpp b/src/debug/ElementPopulation.cpp index 3de462a11..c9739bd84 100644 --- a/src/debug/ElementPopulation.cpp +++ b/src/debug/ElementPopulation.cpp @@ -37,8 +37,8 @@ void ElementPopulationDebug::Draw() maxAverage = (maxAverage*(1.0f-0.015f)) + (0.015f*maxVal); scale = 255.0f/maxAverage; - maxValString = format::NumberToString(maxAverage); - halfValString = format::NumberToString(maxAverage/2); + maxValString = String::Build(maxAverage); + halfValString = String::Build(maxAverage/2); g->fillrect(xStart-5, yBottom - 263, bars+10+Graphics::textwidth(maxValString)+10, 255 + 13, 0, 0, 0, 180); diff --git a/src/gui/colourpicker/ColourPickerActivity.cpp b/src/gui/colourpicker/ColourPickerActivity.cpp index a3bef8f23..93c58b378 100644 --- a/src/gui/colourpicker/ColourPickerActivity.cpp +++ b/src/gui/colourpicker/ColourPickerActivity.cpp @@ -28,10 +28,10 @@ ColourPickerActivity::ColourPickerActivity(ui::Colour initialColour, ColourPicke void TextChangedCallback(ui::Textbox * sender) { int r, g, b, alpha; - r = format::StringToNumber(a->rValue->GetText()); - g = format::StringToNumber(a->gValue->GetText()); - b = format::StringToNumber(a->bValue->GetText()); - alpha = format::StringToNumber(a->aValue->GetText()); + r = a->rValue->GetText().ToNumber(true); + g = a->gValue->GetText().ToNumber(true); + b = a->bValue->GetText().ToNumber(true); + alpha = a->aValue->GetText().ToNumber(true); if (r > 255) r = 255; if (g > 255) @@ -82,9 +82,9 @@ ColourPickerActivity::ColourPickerActivity(ui::Colour initialColour, ColourPicke void ActionCallback(ui::Button * sender) { int Red, Green, Blue; - Red = format::StringToNumber(a->rValue->GetText()); - Green = format::StringToNumber(a->gValue->GetText()); - Blue = format::StringToNumber(a->bValue->GetText()); + Red = a->rValue->GetText().ToNumber(true); + Green = a->gValue->GetText().ToNumber(true); + Blue = a->bValue->GetText().ToNumber(true); ui::Colour col(Red, Green, Blue, a->currentAlpha); if(a->callback) a->callback->ColourPicked(col); @@ -104,10 +104,10 @@ ColourPickerActivity::ColourPickerActivity(ui::Colour initialColour, ColourPicke void ColourPickerActivity::UpdateTextboxes(int r, int g, int b, int a) { - rValue->SetText(format::NumberToString(r)); - gValue->SetText(format::NumberToString(g)); - bValue->SetText(format::NumberToString(b)); - aValue->SetText(format::NumberToString(a)); + rValue->SetText(String::Build(r)); + gValue->SetText(String::Build(g)); + bValue->SetText(String::Build(b)); + aValue->SetText(String::Build(a)); hexValue->SetText(String::Build(Format::Hex(), Format::Uppercase(), Format::Width(2), a, r, g, b)); } void ColourPickerActivity::OnTryExit(ExitMethod method) diff --git a/src/gui/dialogues/SaveIDMessage.cpp b/src/gui/dialogues/SaveIDMessage.cpp index 2969708c8..53b922f04 100644 --- a/src/gui/dialogues/SaveIDMessage.cpp +++ b/src/gui/dialogues/SaveIDMessage.cpp @@ -28,8 +28,8 @@ SaveIDMessage::SaveIDMessage(int id): copyTextLabel->Appearance.HorizontalAlign = ui::Appearance::AlignCentre; AddComponent(copyTextLabel); - textWidth = Graphics::textwidth(format::NumberToString(id).c_str()); - ui::CopyTextButton * copyTextButton = new ui::CopyTextButton(ui::Point((Size.X-textWidth-10)/2, 50), ui::Point(textWidth+10, 18), format::NumberToString(id), copyTextLabel); + textWidth = Graphics::textwidth(String::Build(id)); + ui::CopyTextButton * copyTextButton = new ui::CopyTextButton(ui::Point((Size.X-textWidth-10)/2, 50), ui::Point(textWidth+10, 18), String::Build(id), copyTextLabel); AddComponent(copyTextButton); class DismissAction: public ui::ButtonAction diff --git a/src/gui/font/FontEditor.cpp b/src/gui/font/FontEditor.cpp index 82a761f60..79d84517f 100644 --- a/src/gui/font/FontEditor.cpp +++ b/src/gui/font/FontEditor.cpp @@ -293,9 +293,7 @@ FontEditor::FontEditor(ByteString _header): CharNumberAction(FontEditor *_v): v(_v) {} void TextChangedCallback(ui::Textbox *) { - unsigned int number; - ByteString::Stream ss(v->currentCharTextbox->GetText().ToUtf8()); - ss >> std::hex >> number; + unsigned int number = v->currentCharTextbox->GetText().ToNumber(true); if(number <= 0x10FFFF) v->currentChar = number; } @@ -426,14 +424,13 @@ FontEditor::FontEditor(ByteString _header): ColorComponentAction(int &_color): color(_color) {} void TextChangedCallback(ui::Textbox *box) { - ByteString::Stream ss(box->GetText().ToUtf8()); - ss >> color; + color = box->GetText().ToNumber(true); } }; int *refs[6] = {&fgR, &fgG, &fgB, &bgR, &bgG, &bgB}; for(int i = 0; i < 6; i++) { - ui::Textbox *colorComponent = new ui::Textbox(ui::Point(currentX, baseline), ui::Point(27, 17), format::NumberToString(*refs[i])); + ui::Textbox *colorComponent = new ui::Textbox(ui::Point(currentX, baseline), ui::Point(27, 17), String::Build(*refs[i])); currentX += 28; colorComponent->SetActionCallback(new ColorComponentAction(*refs[i])); AddComponent(colorComponent); @@ -489,28 +486,26 @@ FontEditor::FontEditor(ByteString _header): PreviewAction(FontEditor *_v): v(_v) {} void TextChangedCallback(ui::Textbox *box) { - ByteString::Stream ss(box->GetText().ToUtf8()); // ByteString::Stream for now - String text; - while(!ss.eof()) + String str = box->GetText(); + size_t at = 0; + StringBuilder text; + while(at < str.size()) { - if(ss.peek() == '\n') - { - text.push_back('\n'); - ss.get(); - } unsigned int ch; - ss >> std::hex >> ch; - if(ss.fail()) - { - ss.clear(); - String::value_type ch = ss.get(); - if(!ss.eof()) - text.push_back(ch); - continue; - } - text.push_back(ch); + if(str[at] != ' ') + if(String::Split split = str.SplitNumber(ch, Format::Hex(), at)) + { + text << String::value_type(ch); + at = split.PositionAfter(); + } + else + { + text << str[at++]; + } + else + at++; } - v->outputPreview->SetText(text); + v->outputPreview->SetText(text.Build()); } }; ui::Textbox *inputPreview = new ui::Textbox(ui::Point(0, baseline), ui::Point(Size.X, (Size.Y - baseline) * 3 / 5)); @@ -611,9 +606,7 @@ void FontEditor::OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bo void FontEditor::UpdateCharNumber() { - ByteString::Stream ss; - ss << std::hex << currentChar; - currentCharTextbox->SetText(ByteString(ss.str()).FromUtf8()); + currentCharTextbox->SetText(String::Build(Format::Hex((unsigned int)currentChar))); } void FontEditor::PrevChar() diff --git a/src/gui/game/GameController.cpp b/src/gui/game/GameController.cpp index f82dc4a5d..cdc60911d 100644 --- a/src/gui/game/GameController.cpp +++ b/src/gui/game/GameController.cpp @@ -679,7 +679,7 @@ bool GameController::MouseUp(int x, int y, unsigned button, char type) { case 'c': { - int saveID = format::StringToNumber(link); + int saveID = link.ToNumber(true); if (saveID) OpenSavePreview(saveID, 0, false); break; @@ -687,9 +687,7 @@ bool GameController::MouseUp(int x, int y, unsigned button, char type) case 't': { // buff is already confirmed to be a number by sign::splitsign - ByteString::Stream uri; - uri << "http://powdertoy.co.uk/Discussions/Thread/View.html?Thread=" << link.ToUtf8(); - Platform::OpenURI(uri.str()); + Platform::OpenURI(ByteString::Build("http://powdertoy.co.uk/Discussions/Thread/View.html?Thread=", link.ToUtf8())); break; } case 's': diff --git a/src/gui/game/GameView.cpp b/src/gui/game/GameView.cpp index 37b95e3c9..e0a7bc58e 100644 --- a/src/gui/game/GameView.cpp +++ b/src/gui/game/GameView.cpp @@ -1060,10 +1060,8 @@ int GameView::Record(bool record) { time_t startTime = time(NULL); recordingFolder = startTime; - ByteString::Stream recordingDir; - recordingDir << "recordings" << PATH_SEP << recordingFolder; Client::Ref().MakeDirectory("recordings"); - Client::Ref().MakeDirectory(recordingDir.str().c_str()); + Client::Ref().MakeDirectory(ByteString::Build("recordings", PATH_SEP, recordingFolder).c_str()); recording = true; recordingIndex = 0; } @@ -2211,12 +2209,9 @@ void GameView::OnDraw() VideoBuffer screenshot(ren->DumpFrame()); std::vector data = format::VideoBufferToPNG(screenshot); - ByteString::Stream filename; - filename << "screenshot_"; - filename << std::setfill('0') << std::setw(6) << (screenshotIndex++); - filename << ".png"; + ByteString filename = ByteString::Build("screenshot_", Format::Width(screenshotIndex++, 6), ".png"); - Client::Ref().WriteFile(data, filename.str()); + Client::Ref().WriteFile(data, filename); doScreenshot = false; } @@ -2225,13 +2220,9 @@ void GameView::OnDraw() VideoBuffer screenshot(ren->DumpFrame()); std::vector data = format::VideoBufferToPPM(screenshot); - ByteString::Stream filename; - filename << "recordings" << PATH_SEP << recordingFolder << PATH_SEP; - filename << "frame_"; - filename << std::setfill('0') << std::setw(6) << (recordingIndex++); - filename << ".ppm"; + ByteString filename = ByteString::Build("recordings", PATH_SEP, recordingFolder, PATH_SEP, "frame_", Format::Width(screenshotIndex++, 6), ".ppm"); - Client::Ref().WriteFile(data, filename.str()); + Client::Ref().WriteFile(data, filename); } if (logEntries.size()) diff --git a/src/gui/interface/SaveButton.cpp b/src/gui/interface/SaveButton.cpp index 8fd9aef2c..1dc93a46a 100644 --- a/src/gui/interface/SaveButton.cpp +++ b/src/gui/interface/SaveButton.cpp @@ -40,7 +40,7 @@ SaveButton::SaveButton(Point position, Point size, SaveInfo * save): String votes, icon; - votes = format::NumberToString(save->GetVotesUp()-save->GetVotesDown()); + votes = String::Build(save->GetVotesUp()-save->GetVotesDown()); icon += 0xE03B; for (size_t j = 1; j < votes.length(); j++) icon += 0xE03C; diff --git a/src/gui/localbrowser/LocalBrowserView.cpp b/src/gui/localbrowser/LocalBrowserView.cpp index 1a87a42e1..850264d07 100644 --- a/src/gui/localbrowser/LocalBrowserView.cpp +++ b/src/gui/localbrowser/LocalBrowserView.cpp @@ -108,11 +108,11 @@ LocalBrowserView::LocalBrowserView(): void LocalBrowserView::textChanged() { - int num = format::StringToNumber(pageTextbox->GetText()); + int num = pageTextbox->GetText().ToNumber(true); if (num < 0) //0 is allowed so that you can backspace the 1 pageTextbox->SetText("1"); else if (num > pageCount) - pageTextbox->SetText(format::NumberToString(pageCount)); + pageTextbox->SetText(String::Build(pageCount)); changed = true; #ifdef USE_SDL lastChanged = GetTicks()+600; @@ -126,7 +126,7 @@ void LocalBrowserView::OnTick(float dt) if (changed && lastChanged < GetTicks()) { changed = false; - c->SetPage(std::max(format::StringToNumber(pageTextbox->GetText()), 0)); + c->SetPage(std::max(pageTextbox->GetText().ToNumber(true), 0)); } #endif } diff --git a/src/gui/options/OptionsView.cpp b/src/gui/options/OptionsView.cpp index a40794023..c2881d2cd 100644 --- a/src/gui/options/OptionsView.cpp +++ b/src/gui/options/OptionsView.cpp @@ -158,7 +158,7 @@ OptionsView::OptionsView(): { if (current_scale == ix_scale) current_scale_valid = true; - scale->AddOption(std::pair(format::NumberToString(ix_scale), ix_scale)); + scale->AddOption(std::pair(String::Build(ix_scale), ix_scale)); ix_scale += 1; } while (ui::Engine::Ref().GetMaxWidth() >= ui::Engine::Ref().GetWidth() * ix_scale && ui::Engine::Ref().GetMaxHeight() >= ui::Engine::Ref().GetHeight() * ix_scale); @@ -233,9 +233,9 @@ OptionsView::OptionsView(): OptionsView * v; public: DepthAction(OptionsView * v_) { v = v_; } - virtual void TextChangedCallback(ui::Textbox * sender) { v->c->Set3dDepth(format::StringToNumber(sender->GetText())); } + virtual void TextChangedCallback(ui::Textbox * sender) { v->c->Set3dDepth(sender->GetText().ToNumber(true)); } }; - depthTextbox = new ui::Textbox(ui::Point(8, Size.Y-58), ui::Point(25, 16), format::NumberToString(ui::Engine::Ref().Get3dDepth())); + depthTextbox = new ui::Textbox(ui::Point(8, Size.Y-58), ui::Point(25, 16), String::Build(ui::Engine::Ref().Get3dDepth())); depthTextbox->SetInputType(ui::Textbox::Numeric); depthTextbox->SetActionCallback(new DepthAction(this)); AddComponent(depthTextbox); diff --git a/src/gui/preview/PreviewController.cpp b/src/gui/preview/PreviewController.cpp index 44870f9d2..ea19620c7 100644 --- a/src/gui/preview/PreviewController.cpp +++ b/src/gui/preview/PreviewController.cpp @@ -153,9 +153,8 @@ void PreviewController::FavouriteSave() void PreviewController::OpenInBrowser() { - ByteString::Stream uriStream; - uriStream << "http://" << SERVER << "/Browse/View.html?ID=" << saveId; - Platform::OpenURI(uriStream.str()); + ByteString uri = ByteString::Build("http://", SERVER, "/Browse/View.html?ID=", saveId); + Platform::OpenURI(uri); } bool PreviewController::NextCommentPage() diff --git a/src/gui/preview/PreviewModel.cpp b/src/gui/preview/PreviewModel.cpp index 5cc503e15..cb3987c12 100644 --- a/src/gui/preview/PreviewModel.cpp +++ b/src/gui/preview/PreviewModel.cpp @@ -70,30 +70,28 @@ void PreviewModel::UpdateSave(int saveID, int saveDate) notifySaveChanged(); notifySaveCommentsChanged(); - ByteString::Stream urlStream; + ByteString url; if (saveDate) - urlStream << "http://" << STATICSERVER << "/" << saveID << "_" << saveDate << ".cps"; + url = ByteString::Build("http://", STATICSERVER, "/", saveID, "_", saveDate, ".cps"); else - urlStream << "http://" << STATICSERVER << "/" << saveID << ".cps"; - saveDataDownload = new Download(urlStream.str()); + url = ByteString::Build("http://", STATICSERVER, "/", saveID, ".cps"); + saveDataDownload = new Download(url); saveDataDownload->Start(); - urlStream.str(""); - urlStream << "http://" << SERVER << "/Browse/View.json?ID=" << saveID; + url = ByteString::Build("http://", SERVER , "/Browse/View.json?ID=", saveID); if (saveDate) - urlStream << "&Date=" << saveDate; - saveInfoDownload = new Download(urlStream.str()); - saveInfoDownload->AuthHeaders(format::NumberToByteString(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID); + url += ByteString::Build("&Date=", saveDate); + saveInfoDownload = new Download(url); + saveInfoDownload->AuthHeaders(ByteString::Build(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID); saveInfoDownload->Start(); if (!GetDoOpen()) { commentsLoaded = false; - urlStream.str(""); - urlStream << "http://" << SERVER << "/Browse/Comments.json?ID=" << saveID << "&Start=" << (commentsPageNumber-1)*20 << "&Count=20"; - commentsDownload = new Download(urlStream.str()); - commentsDownload->AuthHeaders(format::NumberToByteString(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID); + url = ByteString::Build("http://", SERVER, "/Browse/Comments.json?ID=", saveID, "&Start=", (commentsPageNumber-1)*20, "&Count=20"); + commentsDownload = new Download(url); + commentsDownload->AuthHeaders(ByteString::Build(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID); commentsDownload->Start(); } } @@ -143,10 +141,9 @@ void PreviewModel::UpdateComments(int pageNumber) commentsPageNumber = pageNumber; if (!GetDoOpen()) { - ByteString::Stream urlStream; - urlStream << "http://" << SERVER << "/Browse/Comments.json?ID=" << saveID << "&Start=" << (commentsPageNumber-1)*20 << "&Count=20"; - commentsDownload = new Download(urlStream.str()); - commentsDownload->AuthHeaders(format::NumberToByteString(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID); + ByteString url = ByteString::Build("http://", SERVER, "/Browse/Comments.json?ID=", saveID, "&Start=", (commentsPageNumber-1)*20, "&Count=20"); + commentsDownload = new Download(url); + commentsDownload->AuthHeaders(ByteString::Build(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID); commentsDownload->Start(); } @@ -242,9 +239,7 @@ bool PreviewModel::ParseSaveInfo(char * saveInfoResponse) saveDataDownload->Cancel(); delete saveData; saveData = NULL; - ByteString::Stream urlStream; - urlStream << "http://" << STATICSERVER << "/2157797.cps"; - saveDataDownload = new Download(urlStream.str()); + saveDataDownload = new Download(ByteString::Build("http://", STATICSERVER, "/2157797.cps")); saveDataDownload->Start(); } return true; @@ -268,7 +263,7 @@ bool PreviewModel::ParseComments(char *commentsResponse) for (Json::UInt j = 0; j < commentsArray.size(); j++) { - int userID = format::ByteStringToNumber(commentsArray[j]["UserID"].asString()); + int userID = ByteString(commentsArray[j]["UserID"].asString()).ToNumber(); ByteString username = commentsArray[j]["Username"].asString(); ByteString formattedUsername = commentsArray[j]["FormattedUsername"].asString(); if (formattedUsername == "jacobot") diff --git a/src/gui/preview/PreviewView.cpp b/src/gui/preview/PreviewView.cpp index d1565471b..05140c921 100644 --- a/src/gui/preview/PreviewView.cpp +++ b/src/gui/preview/PreviewView.cpp @@ -227,11 +227,11 @@ void PreviewView::AttachController(PreviewController * controller) saveIDLabel->Appearance.HorizontalAlign = ui::Appearance::AlignCentre; AddComponent(saveIDLabel); - textWidth = Graphics::textwidth(format::NumberToString(c->SaveID()).c_str()); + textWidth = Graphics::textwidth(String::Build(c->SaveID())); saveIDLabel2 = new ui::Label(ui::Point((Size.X-textWidth-20)/2-37, Size.Y+22), ui::Point(40, 16), "Save ID:"); AddComponent(saveIDLabel2); - saveIDButton = new ui::CopyTextButton(ui::Point((Size.X-textWidth-10)/2, Size.Y+20), ui::Point(textWidth+10, 18), format::NumberToString(c->SaveID()), saveIDLabel); + saveIDButton = new ui::CopyTextButton(ui::Point((Size.X-textWidth-10)/2, Size.Y+20), ui::Point(textWidth+10, 18), String::Build(c->SaveID()), saveIDLabel); AddComponent(saveIDButton); } @@ -514,7 +514,7 @@ void PreviewView::NotifySaveChanged(PreviewModel * sender) userIsAuthor = true; else userIsAuthor = false; - viewsLabel->SetText("\bgViews:\bw " + format::NumberToString(save->Views)); + viewsLabel->SetText(String::Build("\bgViews:\bw ", save->Views)); saveDescriptionLabel->SetText(save->Description); if(save->Favourite) { diff --git a/src/gui/profile/ProfileActivity.cpp b/src/gui/profile/ProfileActivity.cpp index e012e833a..7e9ee0644 100644 --- a/src/gui/profile/ProfileActivity.cpp +++ b/src/gui/profile/ProfileActivity.cpp @@ -122,7 +122,7 @@ void ProfileActivity::setUserInfo(UserInfo newInfo) scrollPanel->AddChild(ageTitle); // can't figure out how to tell a null from a 0 in the json library we use - ui::Label *age = new ui::Label(ui::Point(8+ageTitle->Size.X, currentY), ui::Point(40, 15), info.age ? format::NumberToString(info.age) : "\bgNot Provided"); + ui::Label *age = new ui::Label(ui::Point(8+ageTitle->Size.X, currentY), ui::Point(40, 15), info.age ? String::Build(info.age) : "\bgNot Provided"); age->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; scrollPanel->AddChild(age); currentY += 2+age->Size.Y; @@ -165,7 +165,7 @@ void ProfileActivity::setUserInfo(UserInfo newInfo) saveCountTitle->SetTextColour(ui::Colour(180, 180, 180)); scrollPanel->AddChild(saveCountTitle); - ui::Label *savesCount = new ui::Label(ui::Point(12+saveCountTitle->Size.X, currentY), ui::Point(Size.X-saveCountTitle->Size.X-16, 15), format::NumberToString(info.saveCount)); + ui::Label *savesCount = new ui::Label(ui::Point(12+saveCountTitle->Size.X, currentY), ui::Point(Size.X-saveCountTitle->Size.X-16, 15), String::Build(info.saveCount)); savesCount->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; scrollPanel->AddChild(savesCount); currentY += savesCount->Size.Y; @@ -176,7 +176,7 @@ void ProfileActivity::setUserInfo(UserInfo newInfo) averageScoreTitle->SetTextColour(ui::Colour(180, 180, 180)); scrollPanel->AddChild(averageScoreTitle); - ui::Label *averageScore = new ui::Label(ui::Point(12+averageScoreTitle->Size.X, currentY), ui::Point(Size.X-averageScoreTitle->Size.X-16, 15), format::NumberToString(info.averageScore)); + ui::Label *averageScore = new ui::Label(ui::Point(12+averageScoreTitle->Size.X, currentY), ui::Point(Size.X-averageScoreTitle->Size.X-16, 15), String::Build(info.averageScore)); averageScore->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; scrollPanel->AddChild(averageScore); currentY += averageScore->Size.Y; @@ -187,7 +187,7 @@ void ProfileActivity::setUserInfo(UserInfo newInfo) highestScoreTitle->SetTextColour(ui::Colour(180, 180, 180)); scrollPanel->AddChild(highestScoreTitle); - ui::Label *highestScore = new ui::Label(ui::Point(12+highestScoreTitle->Size.X, currentY), ui::Point(Size.X-highestScoreTitle->Size.X-16, 15), format::NumberToString(info.highestScore)); + ui::Label *highestScore = new ui::Label(ui::Point(12+highestScoreTitle->Size.X, currentY), ui::Point(Size.X-highestScoreTitle->Size.X-16, 15), String::Build(info.highestScore)); highestScore->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; scrollPanel->AddChild(highestScore); currentY += 2+highestScore->Size.Y; diff --git a/src/gui/search/SearchView.cpp b/src/gui/search/SearchView.cpp index 14fe3798f..e37658e2f 100644 --- a/src/gui/search/SearchView.cpp +++ b/src/gui/search/SearchView.cpp @@ -270,11 +270,11 @@ void SearchView::clearSearch() void SearchView::textChanged() { - int num = format::StringToNumber(pageTextbox->GetText()); + int num = pageTextbox->GetText().ToNumber(true); if (num < 0) //0 is allowed so that you can backspace the 1 pageTextbox->SetText("1"); else if (num > pageCount) - pageTextbox->SetText(format::NumberToString(pageCount)); + pageTextbox->SetText(String::Build(pageCount)); changed = true; #ifdef USE_SDL lastChanged = GetTicks()+600; @@ -763,7 +763,7 @@ void SearchView::OnTick(float dt) if (changed && lastChanged < GetTicks()) { changed = false; - c->SetPage(std::max(format::StringToNumber(pageTextbox->GetText()), 0)); + c->SetPage(std::max(pageTextbox->GetText().ToNumber(true), 0)); } #endif } diff --git a/src/gui/update/UpdateActivity.cpp b/src/gui/update/UpdateActivity.cpp index 3f9ddcb8b..03877c07d 100644 --- a/src/gui/update/UpdateActivity.cpp +++ b/src/gui/update/UpdateActivity.cpp @@ -116,13 +116,13 @@ private: }; UpdateActivity::UpdateActivity() { - ByteString::Stream file; + ByteString file; #ifdef UPDATESERVER - file << "http://" << UPDATESERVER << Client::Ref().GetUpdateInfo().File; + file = ByteString::Build("http://", UPDATESERVER, Client::Ref().GetUpdateInfo().File); #else - file << "http://" << SERVER << Client::Ref().GetUpdateInfo().File; + file = ByteString::Build("http://", SERVER, Client::Ref().GetUpdateInfo().File); #endif - updateDownloadTask = new UpdateDownloadTask(file.str(), this); + updateDownloadTask = new UpdateDownloadTask(file, this); updateWindow = new TaskWindow("Downloading update...", updateDownloadTask, true); } diff --git a/src/lua/LegacyLuaAPI.cpp b/src/lua/LegacyLuaAPI.cpp index b72c5a6d5..e24e33dcd 100644 --- a/src/lua/LegacyLuaAPI.cpp +++ b/src/lua/LegacyLuaAPI.cpp @@ -1914,13 +1914,12 @@ int luatpt_getscript(lua_State* l) int runScript = luaL_optint(l, 3, 0); int confirmPrompt = luaL_optint(l, 4, 1); - ByteString::Stream url; - url << "http://starcatcher.us/scripts/main.lua?get=" << scriptID; - if (confirmPrompt && !ConfirmPrompt::Blocking("Do you want to install script?", ByteString(url.str()).FromUtf8(), "Install")) + ByteString url = ByteString::Build("http://starcatcher.us/scripts/main.lua?get=", scriptID); + if (confirmPrompt && !ConfirmPrompt::Blocking("Do you want to install script?", url.FromUtf8(), "Install")) return 0; int ret, len; - char *scriptData = http_simple_get(url.str().c_str(), &ret, &len); + char *scriptData = http_simple_get(url.c_str(), &ret, &len); if (len <= 0 || !filename) { free(scriptData); @@ -1968,9 +1967,7 @@ int luatpt_getscript(lua_State* l) outputfile = NULL; if (runScript) { - ByteString::Stream luaCommand; - luaCommand << "dofile('" << filename << "')"; - luaL_dostring(l, luaCommand.str().c_str()); + luaL_dostring(l, ByteString::Build("dofile('", filename, "')").c_str()); } return 0; @@ -2018,18 +2015,16 @@ int luatpt_screenshot(lua_State* l) data = format::VideoBufferToPNG(screenshot); } } - ByteString::Stream filename; - filename << "screenshot_"; - filename << std::setfill('0') << std::setw(6) << (screenshotIndex++); + ByteString filename = ByteString::Build("screenshot_", Format::Width(screenshotIndex++, 6)); if(fileType == 1) { - filename << ".bmp"; + filename += ".bmp"; } else if(fileType == 2) { - filename << ".ppm"; + filename += ".ppm"; } else { - filename << ".png"; + filename += ".png"; } - Client::Ref().WriteFile(data, filename.str()); - lua_pushstring(l, filename.str().c_str()); + Client::Ref().WriteFile(data, filename); + lua_pushstring(l, filename.c_str()); return 1; }