GacUI的高亮Demo做了一半。现在的进度是,可以手写着色器的状态转换函数,但是自动从正则表达式产生着色器的状态转换函数部分还没有集成进GacUI。这篇博客还是照旧,看图、看Demo代码,说着色原理。
这次的Demo要做一个可以动态切换着色器的小程序,里面包含INI、XML和C++三种着色器。现在只实现了INI一中,手写的。另外两种将要通过正则表达式来做。窗口包含一个表格,来排版label、选着色器用的下拉框和一个大大的文本框。先看图:
在选择了INI Colorizer之后,里面的INI内容被识别了出来并正确着色。现在我们来看Demo的代码怎么写。首先是窗口自己的代码:
class TextBoxColorizerWindow : public GuiWindow
{
private:
GuiMultilineTextBox* textBox;
GuiComboBoxListControl* comboSelector;
void comboSelector_SelectedIndexChanged(GuiGraphicsComposition* sender, GuiEventArgs& arguments)
{
switch(comboSelector->GetSelectedIndex())
{
case 0:
textBox->SetColorizer(new IniColorizer);
textBox->SetText(
L";This is a comment\r\n"
L"[Section1]\r\n"
L"Name=John Smith\r\n"
L"ID=008\r\n"
L"\r\n"
L"[Section2]\r\n"
L"Name=Kyon\r\n"
L"ID=009\r\n"
);
break;
default:
textBox->SetColorizer(0);
}
}
public:
TextBoxColorizerWindow()
:GuiWindow(GetCurrentTheme()->CreateWindowStyle())
{
this->SetText(L"Controls.TextBox.Colorizer");
this->GetContainerComposition()->SetMinSizeLimitation(GuiGraphicsComposition::LimitToElementAndChildren);
GuiTableComposition* table=new GuiTableComposition;
table->SetAlignmentToParent(Margin(0, 0, 0, 0));
table->SetCellPadding(2);
table->SetRowsAndColumns(2, 3);
table->SetRowOption(0, GuiCellOption::MinSizeOption());
table->SetRowOption(1, GuiCellOption::PercentageOption(1.0));
table->SetColumnOption(0, GuiCellOption::MinSizeOption());
table->SetColumnOption(1, GuiCellOption::MinSizeOption());
table->SetColumnOption(2, GuiCellOption::PercentageOption(1.0));
this->GetContainerComposition()->AddChild(table);
{
GuiCellComposition* cell=new GuiCellComposition;
table->AddChild(cell);
cell->SetSite(0, 0, 1, 1);
GuiLabel* label=g::NewLabel();
label->SetText(L"Select a colorizer: ");
label->GetBoundsComposition()->SetAlignmentToParent(Margin(0, -1, 0, 0));
cell->AddChild(label->GetBoundsComposition());
}
{
GuiCellComposition* cell=new GuiCellComposition;
table->AddChild(cell);
cell->SetSite(0, 1, 1, 1);
// combo box doesn't have a minimum width, so set it to 150.
cell->SetPreferredMinSize(Size(150, 0));
// create a text list control.
GuiTextList* listContent=g::NewTextList();
// insert text items.
listContent->GetItems().Add(L"INI colorizer");
listContent->GetItems().Add(L"XML colorizer");
listContent->GetItems().Add(L"C++ colorizer");
// use the text list control to create a combo box.
// items in the text list control will be the data source.
// the text list control will be displayed in the combo box dropdown.
comboSelector=g::NewComboBox(listContent);
comboSelector->GetBoundsComposition()->SetAlignmentToParent(Margin(0, 0, 0, 0));
comboSelector->SelectedIndexChanged.AttachMethod(this, &TextBoxColorizerWindow::comboSelector_SelectedIndexChanged);
cell->AddChild(comboSelector->GetBoundsComposition());
}
{
GuiCellComposition* cell=new GuiCellComposition;
table->AddChild(cell);
cell->SetSite(1, 0, 1, 3);
textBox=g::NewMultilineTextBox();
textBox->GetBoundsComposition()->SetAlignmentToParent(Margin(0, 0, 0, 0));
cell->AddChild(textBox->GetBoundsComposition());
}
comboSelector->SetSelectedIndex(0);
// set the preferred minimum client size
this->GetBoundsComposition()->SetPreferredMinSize(Size(640, 480));
// call this to calculate the size immediately if any indirect content in the table changes
// so that the window can calcaulte its correct size before calling the MoveToScreenCenter()
this->ForceCalculateSizeImmediately();
// move to the screen center
this->MoveToScreenCenter();
}
~TextBoxColorizerWindow()
{
}
};
void GuiMain()
{
GuiWindow* window=new TextBoxColorizerWindow();
GetApplication()->Run(window);
delete window;
}
对于这段代码现在已经不需要多加解释了。首先创造了一个table,然后第一行放label和combobox,第二行撑开了放textbox。关键就在与combobox的SelectedIndexChanged事件。一开始是-1,在这个函数的最后我把它改成了0,这样就出发了事件,安装了IniColorizer着色器。然后我们来看IniColorizer的代码:
class IniColorizer : public GuiTextBoxColorizerBase
{
typedef collections::Array<text::ColorEntry> ColorArray;
private:
static const int NORMAL_COLOR=0;
static const int SECTION_COLOR=1;
static const int ATTRIBUTE_COLOR=2;
static const int OPERATOR_COLOR=3;
static const int COMMENT_COLOR=4;
ColorArray colors;
public:
IniColorizer()
{
text::ColorEntry entry=win7::Win7GetTextBoxTextColor();
colors.Resize(5);
// text color
colors[NORMAL_COLOR]=entry;
// section color
entry.normal.text=Color(163, 21, 21);
colors[SECTION_COLOR]=entry;
// attribute color
entry.normal.text=Color(255, 0, 0);
colors[ATTRIBUTE_COLOR]=entry;
// operator color
entry.normal.text=Color(0, 0, 255);
colors[OPERATOR_COLOR]=entry;
// operator color
entry.normal.text=Color(24, 128, 24);
colors[COMMENT_COLOR]=entry;
}
int GetStartState()
{
return 0;
}
int ColorizeLine(const wchar_t* text, unsigned __int32* colors, int length, int startState)
{
if(length>0)
{
if(text[0]==L';')
{
for(int i=0;i<length;i++)
{
colors[i]=COMMENT_COLOR;
}
}
else if(text[0]==L'[')
{
for(int i=0;i<length;i++)
{
colors[i]=(text[i]==L'[' || text[i]==L']')?OPERATOR_COLOR:SECTION_COLOR;
}
}
else
{
bool afterAssign=false;
for(int i=0;i<length;i++)
{
if(text[i]==L'=' && !afterAssign)
{
afterAssign=true;
colors[i]=OPERATOR_COLOR;
}
else
{
colors[i]=afterAssign?NORMAL_COLOR:ATTRIBUTE_COLOR;
}
}
}
}
return 0;
}
const ColorArray& GetColors()
{
return colors;
}
};
着色器的规格是这样的。首先有一个起始状态。其次对每一行进行着色的时候,文本框会把文本的内容和上一行的中介状态传给着色器。因为第一行并没有“上一行”,所以第一行的起始状态就是需要着色器自己给出的。第三个是指定所有支持的颜色。在这里ColorizeLine函数是异步的,也就是说不会在GUI线程里面运行。这样哪怕是着色器写得很慢,用户看起来也就是一行一行的颜色依次出现,对于编辑文字则毫无影响。不过上面这个着色器因为相当简单,所以他的速度其实是非常快的。我测试了一下,贴了10M的代码进去(这个过程会很慢,因为每一行都new了两个buffer,下个星期我会修掉他。不过一旦贴进去了,以后编辑相当流畅,这这个速度跟文本框有多少行字符是独立的。),大概有30多万行。在所有的文字最终都被贴进去之后,着色器会开始异步执行。黏贴之后光标直接跳到了最后,然后颜色也立刻就出来了。10M的代码着色花的时间相当的短。
每一次文字修改之后,着色器会从修改的那一行开始着色。如果那一行以前还没有被着色过,则会从上一次的最后一行开始着色。这样总是可以一边打字,着色器一边额外运算。在着色器开始运算的时候,会把当前着色的行复制一份,然后异步算好颜色。这个时候就开始对文本框进行加锁,看看着色的这一行和上面的所有行是不是没有被修改过(修改的时候记录一个最小行号就可以了),如果有则丢掉结果从上一次修改的第一行开始着色,否则就把颜色复制进文本框。这个过程的代码基本上如下所示:
(下面这段代码属于GacUI,使用GacUI开发着色器的时候,只要直接从GuiTextBoxColorizerBase继承即可)
void GuiTextBoxColorizerBase::ColorizerThreadProc(void* argument)
{
GuiTextBoxColorizerBase* colorizer=(GuiTextBoxColorizerBase*)argument;
while(!colorizer->isFinalizing)
{
int lineIndex=-1;
wchar_t* text=0;
unsigned __int32* colors=0;
int length=0;
int startState=-1;
{
SpinLock::Scope scope(*colorizer->elementModifyLock);
if(colorizer->colorizedLineCount>=colorizer->element->GetLines().GetCount())
{
colorizer->isColorizerRunning=false;
break;
}
lineIndex=colorizer->colorizedLineCount++;
TextLine& line=colorizer->element->GetLines().GetLine(lineIndex);
length=line.dataLength;
text=new wchar_t[length];
colors=new unsigned __int32[length];
memcpy(text, line.text, sizeof(wchar_t)*length);
startState=lineIndex==0?colorizer->GetStartState():colorizer->element->GetLines().GetLine(lineIndex-1).lexerFinalState;
}
int finalState=colorizer->ColorizeLine(text, colors, length, startState);
{
SpinLock::Scope scope(*colorizer->elementModifyLock);
if(lineIndex<colorizer->colorizedLineCount)
{
TextLine& line=colorizer->element->GetLines().GetLine(lineIndex);
line.lexerFinalState=finalState;
for(int i=0;i<length;i++)
{
line.att[i].colorIndex=colors[i];
}
}
delete[] text;
delete[] colors;
}
}
colorizer->colorizerRunningEvent.Leave();
}
void GuiTextBoxColorizerBase::StartColorizer()
{
if(!isColorizerRunning)
{
isColorizerRunning=true;
colorizerRunningEvent.Enter();
ThreadPoolLite::Queue(&GuiTextBoxColorizerBase::ColorizerThreadProc, this);
}
}
void GuiTextBoxColorizerBase::StopColorizer()
{
isFinalizing=true;
colorizerRunningEvent.Enter();
colorizerRunningEvent.Leave();
colorizedLineCount=0;
isFinalizing=false;
}
GuiTextBoxColorizerBase::GuiTextBoxColorizerBase()
:element(0)
,elementModifyLock(0)
,colorizedLineCount(0)
,isColorizerRunning(false)
,isFinalizing(false)
{
}
GuiTextBoxColorizerBase::~GuiTextBoxColorizerBase()
{
StopColorizer();
}
void GuiTextBoxColorizerBase::Attach(elements::GuiColorizedTextElement* _element, SpinLock& _elementModifyLock)
{
if(_element)
{
SpinLock::Scope scope(_elementModifyLock);
element=_element;
elementModifyLock=&_elementModifyLock;
StartColorizer();
}
}
void GuiTextBoxColorizerBase::Detach()
{
if(element && elementModifyLock)
{
StopColorizer();
SpinLock::Scope scope(*elementModifyLock);
element=0;
elementModifyLock=0;
}
}
void GuiTextBoxColorizerBase::TextEditNotify(TextPos originalStart, TextPos originalEnd, const WString& originalText, TextPos inputStart, TextPos inputEnd, const WString& inputText)
{
if(element && elementModifyLock)
{
SpinLock::Scope scope(*elementModifyLock);
int line=originalStart.row<originalEnd.row?originalStart.row:originalEnd.row;
if(colorizedLineCount>line)
{
colorizedLineCount=line;
}
StartColorizer();
}
}
由于每一次加锁做的事情都是检查几个int,复制几个buffer,花的时间相当的短,所以这里都用spinlock来做。由于spinlock的内在性质,就算按键盘每一次都wait了一次spinlock,其性能损失也是不可察觉的。因此整个编辑过程显得相当的流畅。
接下来我要继续补充这个Demo,写一下如何通过正则表达式绑定颜色,用GacUI轻松制造上下文无关文本框着色效果。