// V7Form.cpp: implementation of the CFormEx class.
//
// Written by Dmitriy Trapeznikov aka trad, mailto: tdf2002@mail.ru
// Copyright (c) 2006. All Rights Reserved.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
//#include "V7Form.h"
#include "GlobalMethods.h"
#include "..\FormEx.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif



/*
<-CSplittFrame(840/200)<-CChildFrame7(640/440)<-SECMDIChildWnd(200/0)<-CMDIChildWnd(200/8)<-CFrameWnd(192/128)<-CWnd(64/32)<-CCmdTarget(32/28)<-CObject(4/4)
  <-CSplitterWnd(200/136)<-CWnd(64/32)<-CCmdTarget(32/28)<-CObject(4/4)
    <-CBodyTextView(528/0)<-CTextEditor(528/460)<-CView(68/4)<-CWnd(64/32)<-CCmdTarget(32/28)<-CObject(4/4)
    (Frame:<-CSplittFrame(840/200)<-CChildFrame7(640/440)<-SECMDIChildWnd(200/0)<-CMDIChildWnd(200/8)<-CFrameWnd(192/128)<-CWnd(64/32)<-CCmdTarget(32/28)<-CObject(4/4))
    (Document:<-CBodyTextDoc(376/24)<-CTextDocument(352/268)<-CDocument(84/52)<-CCmdTarget(32/28)<-CObject(4/4))

<-CSplittFrame(840/200)<-CChildFrame7(640/440)<-SECMDIChildWnd(200/0)<-CMDIChildWnd(200/8)<-CFrameWnd(192/128)<-CWnd(64/32)<-CCmdTarget(32/28)<-CObject(4/4)
  <-CSplitterWnd(200/136)<-CWnd(64/32)<-CCmdTarget(32/28)<-CObject(4/4)
    <-CBodyTextView(528/0)<-CTextEditor(528/460)<-CView(68/4)<-CWnd(64/32)<-CCmdTarget(32/28)<-CObject(4/4)
    (Frame:<-CSplittFrame(840/200)<-CChildFrame7(640/440)<-SECMDIChildWnd(200/0)<-CMDIChildWnd(200/8)<-CFrameWnd(192/128)<-CWnd(64/32)<-CCmdTarget(32/28)<-CObject(4/4))
    (Document:<-CBodyTextDoc(376/24)<-CTextDocument(352/268)<-CDocument(84/52)<-CCmdTarget(32/28)<-CObject(4/4))
*/

// #define STATIC_CTRL_TYPE 1
// #define EDIT_CTRL_TYPE 2
// #define BUTTON_CTRL_TYPE 3
// #define GROUPBOX_CTRL_TYPE 4
// 
// #define GROUP_TREE_CTRL_TYPE 8
// #define BROWSE_COLUMN_STATIC_TYPE 9
// #define PICTURE_CTRL_TYPE 10
// #define VALUES_LIST_CTRL_TYPE 11
// #define CHECK_BOX_CTRL_TYPE 12
// #define RADIO_BTN_CTRL_TYPE 13
// #define LIST_FIELD_CTRL_TYPE 14
// #define VALUES_TABLE_CTRL_TYPE 15

void __TraceFieldsArray(CGetFieldsArray &FieldsArray)
{
	for (int i=0; i<FieldsArray.GetSize(); i++)
	{
		CGetField* pField = FieldsArray[i];
		DoMsgLine("%d, %d, %d, %d, %d, %d, %d, %d, %d, %s, %d", mmNone,
			pField->GetInTable(),
			pField->IsBrOldStateEnable(),
			pField->IsHideStateEnable(),
			pField->IsStatic(),
			pField->WhantCheckLinkValue(),
			pField->AvtoActivate(),
			pField->GetFlagSkipping(),
			pField->GetCtrlID(),
			pField->m_Flag10,
			pField->GetCtrlInfo()->GetCodeName(),
			pField->GetParamNo()
			);
		if (pField->GetCtrlInfo()->GetCtrlType()==EDIT_CTRL_TYPE)
		{
			int ff=0;
		}
	}
}

void __TraceGetCtrlArray(CGetDoc* pGetDoc)
{
	for (int i=0; i<pGetDoc->m_GetCtrlArray.GetSize(); i++)
	{
		CGetCtrl* pGetCtrl = (CGetCtrl*)pGetDoc->m_GetCtrlArray[i];
		CString str;
        GetRTCFull(pGetCtrl->GetRuntimeClass(), str);
        DoMsgLine("%d, %s", mmNone, pGetCtrl->m_uiID, str);
	}
}
void __TraceColArray(CBrowse* pBr)
{
	for (int i=0; i<pBr->m_colArray.GetSize(); i++)
	{
		CColumn* pColumn = (CColumn*)pBr->m_colArray[i];
		if (pColumn->GetRuntimeClass() == RUNTIME_CLASS(CGetColumn))
		{
			CGetColumn* pGetColumn = (CGetColumn*)pColumn;
			int i=0;
		}
		CString str;
        GetRTCFull(pColumn->GetRuntimeClass(), str);
        DoMsgLine("%d, %d, %d, %d, %d, %d, %s, %s", mmNone,
			pColumn->m_ID,
			pColumn->m_Flag1,
			pColumn->m_Flag2,
			pColumn->m_Width,
			pColumn->m_Width2,
			pColumn->m_ColPositionFlag,
			pColumn->m_Caption,
			str);
	}
}

class CGetDoc7_Temp : public CGetDoc7
{
	friend CFormEx;
};

BOOL CFormEx::CreateStdControl_Static(CValue& rValue, CValue** ppValues)
{
	CGetDoc7* pDoc = GetDoc();

	BOOL bInTable = FALSE;
	if (ppValues[5]->GetNumeric())
	{
		if (pDoc->GetBrowse())
			bInTable = TRUE;
		else
			return TRUE;
	}
	DWORD nColInsertPos = ppValues[6]->GetNumeric(); //1-based: 1..n - insert; 0 - add to end

	int nID = pDoc->m_cControlList.GetTail()->GetCtrlID()+1;
	const CString &str = ppValues[0]->GetString();

	CControlID CtrlInfo;
	CtrlInfo.SetCtrlID(nID);
	CtrlInfo.SetCodeName(str);
	CtrlInfo.SetTitle("Title");
	CtrlInfo.SetToolTip("ToolTip");

	CtrlInfo.SetHelpString("HelpString");
	CtrlInfo.SetFormul("-2*2");

// #define DP_Unk4               0x00000004L
// #define DP_Unk8               0x00000008L
// #define DP_UseHelpString      0x00000010L
// #define DP_Unk00004000        0x00004000L
// #define DP_Unk00200000        0x00200000L
// #define DP_ColumnInNewLine    0x00400000L
// #define DP_ColumnInSameCol    0x00800000L
// #define DP_RedNegativeDisplay 0x04000000L
// #define DP_Unk10000000        0x10000000L
// 
// #define ST_Unknown1  0x00000001L //выравнивание вправо в ТЧ, по центру не в ТЧ //ST_CenterAlignment
// #define ST_Unknown2  0x00000002L //выравнивание вправо не в ТЧ //ST_RightAlignment

	DWORD dwStyle = WS_VISIBLE | WS_CHILD; //0x50000000L
	DWORD dwDependParam = 0;
	//dwDependParam |= DP_UseHelpString;

	if (bInTable)
	{
		CtrlInfo.SetCtrlType(BROWSE_COLUMN_STATIC_TYPE);
		CtrlInfo.SetValType(CType(STRING_TYPE_1C));
		dwStyle |= ST_RightAlignmentInTable; //ST_Unknown1;
		dwDependParam |= DP_Unk00200000|DP_Unk00004000|DP_Unk10000000;
		dwDependParam |= DP_ColumnInNewLine|DP_RedNegativeDisplay;
	}
	else
	{
		dwStyle |= WS_GROUP; //0x00020000L
		CtrlInfo.SetCtrlType(STATIC_CTRL_TYPE);
	}
	CtrlInfo.SetStyle(dwStyle);
	CtrlInfo.SetDependParam(dwDependParam);

	CtrlInfo.SetExStyle(0);
	CtrlInfo.SetLongID(0);
	CtrlInfo.SetLayerName(pDoc->m_pEditDoc->m_layers[pDoc->m_pEditDoc->m_iActiveLayer]);
	CtrlInfo.SetPlace(CRect(ppValues[1]->GetNumeric(),ppValues[2]->GetNumeric(),ppValues[3]->GetNumeric(),ppValues[4]->GetNumeric()));
	pDoc->m_cControlList.AddTail(&CtrlInfo);

	CGetField* pField = pDoc->m_cGetFieldsArray1.NewItem();
	pField->SetCtrlID(nID);
	pField->SetDoc(pDoc);
	pField->SetCtrlInfo(pDoc->m_cControlList.GetTail());
	pField->SetInTable(bInTable);
	if (bInTable)
	{
		pField->SetBrOldStateEnable(0);
		pField->SetReadOnly(1);
	}
	((CGetDoc7_Temp*)pDoc)->InitStandartFields(pField, &CtrlInfo);

	if (bInTable)
	{
		CBrowse* pBr = pDoc->GetBrowse();
		CGetColumn* pColumn = new CGetColumn(pField->m_ID, CtrlInfo.GetTitle(), CtrlInfo.m_Place.left, pField->m_Flag10);

		if (nColInsertPos > 0)
		{
			nColInsertPos--;
			nColInsertPos = min(nColInsertPos, pBr->GetColumnNum());
		}
		else
			nColInsertPos = pBr->GetColumnNum();

		DWORD nColInOneCount = 1;
		DWORD nColPositionFlag = 0;
		if (nColInsertPos > 1)
		{
			if (dwDependParam & DP_ColumnInNewLine)
			{
				nColInOneCount = 2;
				for (int i=nColInsertPos; i; nColInOneCount++)
					if (pBr->operator [](--i).m_ColPositionFlag < 2)
						break;
				for (i=nColInsertPos; i<pBr->GetColumnNum(); i++, nColInOneCount++)
					if (pBr->operator [](i).m_ColPositionFlag < 2)
						break;
				nColPositionFlag = 2;
			}
			else if (dwDependParam & DP_ColumnInSameCol)
				nColPositionFlag = 1;
		}
		if (nColInsertPos == pBr->GetColumnNum())
			pBr->Add(pColumn, nColPositionFlag);
		else
			pBr->Insert(nColInsertPos, pColumn, nColPositionFlag);

		if (nColInOneCount > pBr->GetMaxHeadLines())
			pBr->SetMaxHeadLines(nColInOneCount);

		CCellGet* pCellGet = new CCellGet(pBr, pField->m_ID, pField->m_strWindowName, pField->m_Flag14);
		pDoc->AddGet(pCellGet);
	}

	pField->TranslateType();
	pField->UpdateMask();


	CFormAllCtrlsContext* m_pFormAllCtrlsContext = GetForm();

	m_pFormAllCtrlsContext->m_GetFieldsArray.Add(pField);
	DWORD dwSize = m_pFormAllCtrlsContext->m_GetFieldsArray.GetSize();
	m_pFormAllCtrlsContext->m_Data1 = (CFormCtrlContext**)realloc((void*)m_pFormAllCtrlsContext->m_Data1, dwSize*4);
	m_pFormAllCtrlsContext->m_Data1[dwSize-1] = 0x0;

	void* p;
	p = &pDoc->m_Flag247;
	p = &pDoc->m_cBLModule7;
	p = &pDoc->m_pBLModule;

	if (pDoc->IsDocLayouted())
	{
		//ToolTip
		CString strToolTip;
		if (CtrlInfo.GetDependParam() & DP_UseHelpString)
			strToolTip = CtrlInfo.GetHelpString();
		else
			strToolTip = CtrlInfo.GetToolTip();
		if (strToolTip.IsEmpty())
			((CGetDoc7_Temp*)pDoc)->GetMsgString(CGetDoc7::msgtToolTip, nID, strToolTip);

		//HelpString
		CString strHelpString = CtrlInfo.GetHelpString();
		if (strHelpString.IsEmpty())
			((CGetDoc7_Temp*)pDoc)->GetMsgString(CGetDoc7::msgtHelpString, nID, strHelpString);

		CWnd* pWnd = NULL;
		CRect Rect;
		CRect* pRect;
		if (!bInTable)
		{
			if (CtrlInfo.GetCtrlType() == BUTTON_CTRL_TYPE)
			{
				CString strHK;
				((CGetDoc7_Temp*)pDoc)->GetMsgString(CGetDoc7::msgtHotKey, nID, strHK);
				if (!strHK.IsEmpty())
				{
					strToolTip += " (";
					strToolTip += strHK;
					strToolTip += ")";
				}
			}
			pDoc->LayoutControl((CFormView*)pDoc->GetForm(), pField);
			pWnd = pDoc->GetFieldWnd(pField);
			pRect = NULL;
			nColInsertPos = 0;
		}
		else
		{
			pWnd = pDoc->GetBrowse();
			pRect = &Rect;
			Rect.left = -20;
			Rect.top = -20;
			Rect.right = -10;
			Rect.bottom = -10;
			nColInsertPos++;
		}

		if (!strToolTip.IsEmpty())
			pDoc->m_cToolTipCtrl.AddTool(pWnd, strToolTip, pRect, nColInsertPos);

		if (!strHelpString.IsEmpty())
			pDoc->m_cOnLineHelp.SetItem(pWnd, strHelpString, 0);

		//Прочее
		pDoc->InitFieldsState();

		if (pDoc->GetBrowse() && !pDoc->IsBrowseVisible())
			pDoc->SetBrowseVisible(0,1);

		//if (CFormContext* pFormContext = pDoc->GetFormContext())
		//	pDoc->TrySetFocusOnCtrl(pFormContext->m_strFieldNeedActivate, 0);

		pDoc->CorrectActiveCtrl();
	}
	return TRUE;
}

void TraceWindows(CWnd* pWnd, CString Indent = "") // отступ
{
    CString Str;
    GetRTCFull(pWnd->GetRuntimeClass(), Str);
    DoMsgLine("%s%s", mmNone, Indent, Str);
	if (pWnd->IsKindOf(RUNTIME_CLASS(CView)))
	{
		CView* pView = (CView*)pWnd;
		Str.Empty();
		GetRTCFull(pView->GetParentFrame()->GetRuntimeClass(), Str);
	    DoMsgLine("%s(Frame:%s)", mmNone, Indent, Str);
		Str.Empty();
		GetRTCFull(pView->GetDocument()->GetRuntimeClass(), Str);
	    DoMsgLine("%s(Document:%s)", mmNone, Indent, Str);
	};
    for (pWnd = pWnd->GetWindow(GW_CHILD); pWnd; pWnd = pWnd->GetWindow(GW_HWNDNEXT))
            TraceWindows(pWnd, Indent+"  ");
}

BOOL CFormEx::TraceWindows(CValue& rValue, CValue** ppValues)
{
	if (ppValues[0]->GetNumeric() == 1)
		::TraceWindows(GetMainFrame());
	else
		::TraceWindows(CWnd::GetForegroundWindow());
	return TRUE;
}

BOOL CFormEx::Test(CValue& rValue, CValue** ppValues)
{
	CGetDoc7* pDoc = GetDoc();
	MessageFullRTC((CObject*)&pDoc->m_cOnLineHelp.m_Flag1);

	//<-CReportForm(1708/416)<-CGetDoc7(1292/1132)<-CGetDoc(160/76)<-CDocument(84/52)<-CCmdTarget(32/28)<-CObject(4/4)
//	MessageFullRTC(pDoc);
	/*
	CBLContext* pCont = ppValues[0]->GetContext();
	TraceBLContext(pCont);
	if (!strcmp("CGroupContext",pCont->GetRuntimeClass()->m_lpszClassName))
		TraceGC(pCont);
		*/

/*
	CFormContextForDoc* pCont = (CFormContextForDoc*)pGC->GetContext(0);
	MessageFullRTC(pCont);
	MES_CLASS_SIZE(CFormContextForDoc);
	MessageFullRTC(&pCont->m_StringArray);
	MessageFullRTC(&pCont->m_ByteArray);
	MessageFullRTC(pCont->m_pForm);
	MessageFullRTC(pCont->m_pDocForm);
	MessageFullRTC(&pCont->m_GetFieldsArray);
	MessageFullRTC(&pCont->m_DWordArray);
	MessageFullRTC(pCont->m_pDocContext);

	CGetField* fld = (CGetField*)pCont->m_GetFieldsArray.GetAt(0);
	DoMsgLine(fld->GetCtrlInfo()->GetCodeName());
*/
//<-CRepFormContext(40/8)<-CRepFormContextDef(32/0)<-CBLContext(32/28)<-CObject(4/4)
//<-CFormContext(224/192)<-CBLContext(32/28)<-CObject(4/4)

//<-CFormContextForDoc(228/196)<-CBLContext(32/28)<-CObject(4/4)
//<-CDocFormContext(184/-40)<-CFormContext(224/192)<-CBLContext(32/28)<-CObject(4/4)
//<-CDocContext(148/104)<-CDocContextDef(44/12)<-CBLContext(32/28)<-CObject(4/4)

	return TRUE;
}

void __AddColumn(CValueTable* pVT, CString name, int Type1C)
{
	pVT->AddColumn(name, CType(Type1C), name, 0, "", 0);
}
void __AddCtrlInfo(CValue* pAddParams, CControlID* pCtrlInfo)
{
	pAddParams[0] = pCtrlInfo->GetCodeName();
	pAddParams[1] = pCtrlInfo->GetAccel().alAccel;
	//pAddParams[1] = (long)pCtrlInfo->GetAccel().GetAccel();
	pAddParams[2] = pCtrlInfo->GetBkColor();
	pAddParams[3] = pCtrlInfo->GetChooseForm();
	pAddParams[4] = pCtrlInfo->GetCtrlID();
	pAddParams[5] = pCtrlInfo->GetCtrlType();
	pAddParams[6] = pCtrlInfo->GetDependParam();
	pAddParams[7] = pCtrlInfo->GetExStyle();

	tagLOGFONTA lf;
	pCtrlInfo->GetFont(&lf);
	pAddParams[8] = lf.lfFaceName;

	pAddParams[9] = pCtrlInfo->GetFontColor();
	pAddParams[10] = pCtrlInfo->GetFormul();
	pAddParams[11] = pCtrlInfo->GetHelpString();
	pAddParams[12] = pCtrlInfo->GetLayerName();
	pAddParams[13] = pCtrlInfo->GetLongID();
	pAddParams[16] = pCtrlInfo->GetSDependParam();
	pAddParams[17] = pCtrlInfo->GetStyle();
	pAddParams[18] = pCtrlInfo->GetTitle();
	pAddParams[19] = pCtrlInfo->GetToolTip();
	pAddParams[20] = pCtrlInfo->GetValType().GetTypeTitle();

	pAddParams[14].CreateObject("Picture");
	CPictureContext* pPicCont = (CPictureContext*)pAddParams[14].GetContext();
	pPicCont->m_PictureHolder7.Copy(pCtrlInfo->GetPicture());

	CRect& rect = pCtrlInfo->GetPlace();
	CString str;
	str.Format("%dx%d-%dx%d", rect.left, rect.top, rect.right, rect.bottom);

	pAddParams[15].CreateObject("СписокЗначений");
	CValue& valVL = pAddParams[15];
	CPtrArray* pVL = (CPtrArray*)(((CValueListContext*)(valVL.GetContext()))->m_pValueItemList);

	CValueItem* pValueItem = new CValueItem;
	pValueItem->m_value = rect.left;
	pValueItem->m_text = "left";
	pVL->Add(pValueItem);
	pValueItem = new CValueItem;
	pValueItem->m_value = rect.top;
	pValueItem->m_text = "top";
	pVL->Add(pValueItem);
	pValueItem = new CValueItem;
	pValueItem->m_value = rect.right;
	pValueItem->m_text = "right";
	pVL->Add(pValueItem);
	pValueItem = new CValueItem;
	pValueItem->m_value = rect.bottom;
	pValueItem->m_text = "bottom";
	pVL->Add(pValueItem);
	pValueItem = new CValueItem;
	pValueItem->m_value = str;
	pValueItem->m_text = "str";
	pVL->Add(pValueItem);
}


BOOL CFormEx::CtrlInfo(CValue& rValue, CValue** ) //ppValues)
{
	CGetDoc7* pDoc = GetDoc();
	if (!pDoc)
		return FALSE;

	CValueTable* pVT;
	rValue.CreateObject("ТаблицаЗначений");
	pVT = ((CValueTableContextData*)(rValue.GetContext()->GetInternalData()))->GetValueTable();
	__AddColumn(pVT, "CodeName", STRING_TYPE_1C);
	__AddColumn(pVT, "Accel", NUMBER_TYPE_1C);
	__AddColumn(pVT, "BkColor", NUMBER_TYPE_1C);
	__AddColumn(pVT, "ChooseForm", NUMBER_TYPE_1C);
	__AddColumn(pVT, "CtrlID", NUMBER_TYPE_1C);
	__AddColumn(pVT, "CtrlType", NUMBER_TYPE_1C);
	__AddColumn(pVT, "DependParam", NUMBER_TYPE_1C);
	__AddColumn(pVT, "ExStyle", NUMBER_TYPE_1C);
	__AddColumn(pVT, "Font", STRING_TYPE_1C);
	__AddColumn(pVT, "FontColor", NUMBER_TYPE_1C);
	__AddColumn(pVT, "Formul", STRING_TYPE_1C);
	__AddColumn(pVT, "HelpString", STRING_TYPE_1C);
	__AddColumn(pVT, "LayerName", STRING_TYPE_1C);
	__AddColumn(pVT, "LongID", NUMBER_TYPE_1C);
	__AddColumn(pVT, "Picture", AGREGATE_TYPE_1C);
	__AddColumn(pVT, "Place", AGREGATE_TYPE_1C);
	__AddColumn(pVT, "SDependParam", STRING_TYPE_1C);
	__AddColumn(pVT, "Style", NUMBER_TYPE_1C);
	__AddColumn(pVT, "Title", STRING_TYPE_1C);
	__AddColumn(pVT, "ToolTip", STRING_TYPE_1C);
	__AddColumn(pVT, "ValType", STRING_TYPE_1C);

	CValue* pAddParams = new CValue[pVT->GetColumnCount()];
	CValue** ppAddParams = new CValue*[pVT->GetColumnCount()];
	CValue** ppVal = ppAddParams;
	CValue* pVal = pAddParams;
	for (int cc = pVT->GetColumnCount() ; cc; cc--)
		*ppVal++ = pVal++;

	__AddCtrlInfo(pAddParams, &pDoc->m_cControlID1);
	pVT->AddRow(ppAddParams, -1);
	__AddCtrlInfo(pAddParams, &pDoc->m_cControlID2);
	pVT->AddRow(ppAddParams, -1);

	POSITION pos = pDoc->m_cControlList.GetHeadPosition();
	while (pos)
	{
		__AddCtrlInfo(pAddParams, pDoc->m_cControlList.GetNext(pos));
		pVT->AddRow(ppAddParams, -1);
	}

	delete[] ppAddParams;
	delete[] pAddParams;

	for (int i=0; i<pDoc->m_cGetFieldsArray1.GetSize(); i++)
	{
		CGetField* pField = pDoc->m_cGetFieldsArray1[i];
		if (pField->GetCtrlInfo()->GetCtrlType() == STATIC_CTRL_TYPE)
		{
			int i=0;
		}
	}
	return TRUE;
}

BOOL CFormEx::FieldsArray(CValue& rValue, CValue** ) //ppValues)
{
	CGetDoc7* pDoc = GetDoc();
	DoMsgLine("CGetDoc::m_cGetFieldsArray1");
	__TraceFieldsArray(pDoc->m_cGetFieldsArray1);

	DoMsgLine("CGetDoc::m_cGetFieldsArray2");
	__TraceFieldsArray(pDoc->m_cGetFieldsArray2);

	DoMsgLine("CGetDoc::m_cGetFieldsArray3");
	__TraceFieldsArray(pDoc->m_cGetFieldsArray3);

	DoMsgLine("CGetDoc::m_cGetFieldsArray4");
	__TraceFieldsArray(pDoc->m_cGetFieldsArray4);

	DoMsgLine("CGetDoc::CFormContext::m_cGetFieldsArray");
	__TraceFieldsArray(pDoc->m_pFormContext->m_GetFieldsArray);

	DoMsgLine("CGetDoc::CFormContext::_pArrayOfFlagsRefresh[%d]", mmNone, pDoc->m_pFormContext->m_GetFieldsArray.GetSize());
	CFormContext* pForm = pDoc->m_pFormContext;
	for (int i = 0; i<pDoc->m_pFormContext->m_GetFieldsArray.GetSize(); i++)
	{
	    DoMsgLine("%d (int:%d)", mmNone, i, pForm->m_pArrayOfFlagsRefresh[i]);
	}

	DoMsgLine("CGetDoc::CFormContext::m_StringArray[%d]", mmNone, pDoc->m_pFormContext->m_StringArray.GetSize());
	for (i = 0; i<pDoc->m_pFormContext->m_StringArray.GetSize(); i++)
	{
	    DoMsgLine("%d (int:%s)", mmNone, i, pForm->m_StringArray.GetAt(i));
	}

	DoMsgLine("CGetDoc::CFormContext::m_ByteArray[%d]", mmNone, pDoc->m_pFormContext->m_ByteArray.GetSize());
	for (i = 0; i<pDoc->m_pFormContext->m_ByteArray.GetSize(); i++)
	{
		long l = pForm->m_ByteArray.GetAt(i);
	    DoMsgLine("%d (int:%d)", mmNone, i, l);
	}
	
	
	return TRUE;
}

BOOL CFormEx::GetCtrl(CValue& rValue, CValue** ) //ppValues)
{
	CGetDoc7* pDoc = GetDoc();
	DoMsgLine("CGetDoc::m_GetCtrlArray");
	__TraceGetCtrlArray(pDoc);
	return TRUE;
}

BOOL CFormEx::ColArray(CValue& rValue, CValue** ) //ppValues)
{
	CGetDoc7* pDoc = GetDoc();
	DoMsgLine("CBrowse::m_colArray");
	if (pDoc->GetBrowse())
	{
		__TraceColArray(pDoc->GetBrowse());
	}
	return TRUE;
}

//bool CMetaDataWork::SetTypeAndKind(CType &dest_type, const CString &source)
bool SetTypeAndKind(CType &dest_type, const CString &source)
{
  int state = 0; //now max = 29
  int nType = UNDEFINE_TYPE_1C;
  int nLenght = source.GetLength();

  bool ret = false;
  bool bNotBreak = true;
  int i = 0;
  for(; bNotBreak && i < nLenght; ++i)
  {
    switch(source[i])
    {
      case 'Н':
      case 'н':
      case 'U':
      case 'u':
        {
          if (state == 0)
          {
          nType = UNDEFINE_TYPE_1C;
          bNotBreak = false;
        }
          else if (state == 28)
          {
            nType = SUBCONTOKIND_TYPE_1C;
            bNotBreak = false;
          }
        }
        break;
      case 'S':
      case 's':
        {
          if (state == 0) state = 28;
        }
        break;
      case 'С': //рус
      case 'с': //рус
        {
          if(state == 0) state = 10;
          else if (state == 27)
          {
            nType = SUBCONTOKIND_TYPE_1C;
            bNotBreak = false;
          }
        }
        break;
      case 'т': //рус
      case 'Т': //рус
        {
          if(state == 10)
          {
            nType = STRING_TYPE_1C;
            bNotBreak = false;
          }
        }
        break;
      case 'п': //рус
      case 'П': //рус
        {
          if(state == 10)
          {
            nType = REFERENCE_TYPE_1C;
            bNotBreak = false;
          }
          else if (state == 0)
          {
            state = 24;
          }
        }
        break;
      case 'e':
      case 'E':
        {
          if (state == 0)
          {
            nType = ENUM_TYPE_1C;
            bNotBreak = false;
          }
          else if (state == 22)
          {
            nType = CALENDAR_TYPE_1C;
            bNotBreak = false;
          }
        }
        break;
      case 'N':
      case 'n': //lat
      case 'ч':
      case 'Ч':
        {
          if (state == 10)
          {
            nType = ACCOUNT_TYPE_1C;
            bNotBreak = false;
          }
          else
          {
          nType = NUMBER_TYPE_1C;
          bNotBreak = false;
        }
        }
        break;
      case 'Д':
      case 'д':
        {
          if (state == 0) state = 2;
          else if (state == 26) state = 27;
        }
        break;

      case 'D':
      case 'd':
        {
          if (state == 0) state = 2;
        }
        break;
      case 'O': // Lat
      case 'o': // Lat
        {
          if (state == 2)
          {
            nType = DOCUMENT_TYPE_1C;
            bNotBreak = false;
          }
        }
        break;
      case 'О': // Rus
      case 'о': // Rus
        {
          if (state == 2)
          {
            nType = DOCUMENT_TYPE_1C;
            bNotBreak = false;
          }
        }
        break;
      case 'a': // Lat
      case 'A': // Lat
        {
          if (state == 2)
          {
            nType = DATE_TYPE_1C;
            bNotBreak = false;
          }
          else if (state == 20)
          {
            state = 21;
        }
          else
          {
            state = 23;
          }
        }
        break;
      case 'а': // Rus
      case 'А': // Rus
        {
          if (state == 2)
          {
            nType = DATE_TYPE_1C;
            bNotBreak = false;
          }
          else if (state == 29)
          {
            nType = CALENDAR_TYPE_1C;
            bNotBreak = false;
          }
        }
        break;
      case 'C': //lat
      case 'c': //lat
        {
          if (state == 0)
            state = 20;
          else if (state == 22)
          {
            nType = CALCULATIONKIND_TYPE_1C;
            bNotBreak = false;
          }
          else if (state == 23)
          {
            nType = ACCOUNT_TYPE_1C;
            bNotBreak = false;
          }
        }
        break;
      case 'L': //lat
      case 'l': //lat
        {
          if (state == 21)
          {
              state = 22;
          }
          else if (state == 20)
          {
            nType = AGREGATE_TYPE_1C;
            bNotBreak = false;
          }
        }
        break;
      case 'К':
      case 'к':
        {
          if (state == 0) state = 29;
        }
        break;
      case 'В': //рус
      case 'в': //рус
        {
          if (state == 0) state = 25;
        }
        break;
      case 'е': //рус
      case 'Е': //рус
        {
          if (state == 24)
          {
            nType = ENUM_TYPE_1C;
            bNotBreak = false;
          }
        }
        break;
      case 'л':
      case 'Л':
        {
          if (state == 24)
          {
            nType = CHART_OF_ACC_TYPE_1C;
            bNotBreak = false;
          }
          else if (state == 29)
          {
            nType = AGREGATE_TYPE_1C;
            bNotBreak = false;
          }
        }
        break;
      case 'h':
      case 'H':
        {
          if (state == 20)
          {
            nType = CHART_OF_ACC_TYPE_1C;
            bNotBreak = false;
          }
        }
        break;
      case 'и':
      case 'И':
        {
          if (state == 25) state = 26;
        }
        break;
      case 'р':
      case 'Р':
        {
          if (state == 27)
        {
          nType = CALCULATIONKIND_TYPE_1C;
          bNotBreak = false;
        }
        }
        break;
      case 't':
      case 'T':
        {
          if (state == 28)
          {
            nType = STRING_TYPE_1C;
            bNotBreak = false;
          }
        }
        break;
      case 'r':
      case 'R':
        {
          nType = REFERENCE_TYPE_1C;
          bNotBreak = false;
        }
        break;
      default:
      {
        bNotBreak = false;
      }
    }
  }

  if (nType != UNDEFINE_TYPE_1C && NUMBER_TYPE_1C != nType && STRING_TYPE_1C != nType && DATE_TYPE_1C != nType && AGREGATE_TYPE_1C != nType)
  {
    CString kind;
    CMetaDataObj * Obj = NULL;

    int nPosOfDot = source.Find('.', i);
    if(nPosOfDot == -1)
    {
      dest_type = CType(nType);
      ret = true;
    }
    else
    {
      kind = source.Mid(nPosOfDot+1);
	    switch (nType)
      {
	      case ENUM_TYPE_1C:
		      Obj = pMetaDataCont->GetEnumDefs()->GetItem(kind);
		      break;
	      case REFERENCE_TYPE_1C:
		      Obj = pMetaDataCont->GetSTypeDefs()->GetItem(kind);
		      break;
	      case DOCUMENT_TYPE_1C:
		      Obj = pMetaDataCont->GetDocDefs()->GetItem(kind);
		      break;
	      case CALENDAR_TYPE_1C:
		      Obj = pMetaDataCont->GetCalendarTypeDefs()->GetItem(kind);
		      break;
	      case CALCULATIONKIND_TYPE_1C:
		      Obj = pMetaDataCont->GetAlgorithmDefs()->GetItem(kind);
		      break;
	      case ACCOUNT_TYPE_1C:
              {
                  CBuhDef* pBuhDef = pMetaDataCont->GetBuhDef();
                  if (pBuhDef)
        		      Obj = pBuhDef->GetPlanDef(kind);
              }
		      break;
	      default:
		      break;
	    }
	    if(Obj!=NULL)
      {
		    dest_type = CType(nType,Obj->GetID());
        ret = true;
	    }
    }
  }
  else
  {
    dest_type = CType(nType);
    ret = true;
  }
  return ret;
}

BOOL CFormEx::AddAttrib(int iMethNum, CValue& rValue, CValue** ppValues)
{
	return AddAttrib(iMethNum, rValue, *ppValues[0], *ppValues[1], *ppValues[2], *ppValues[3]);
}

static bool FindAndCallMethodOfSystemFrom1CPP(const char* szMethodsName, CValue** ppParams);

//BOOL CFormEx::AddAttrib(int iMethNum, CValue& rValue, const CValue& ValueAttribID, const CValue& ValueAttribType, const CValue& ValueAttribValueKindOrFormul, const CValue& ValueAttribValueKind )
BOOL CFormEx::AddAttrib(int iMethNum, CValue& rValue, const CValue& ValueAttribID, const CValue& ValueAttribType, const CValue& ValueAttribValueKindOrFormul, const CValue& ValuePosInTable )
{
	// подавляющая и самая главная концепция кода по возможности добавления атрибутов найдена trad-ом для своих ВК
	// остальное доделал artbear - работа с типами
 	if (ValueAttribID.GetTypeCode() != STRING_TYPE_1C)
		RuntimeError("Неверный идентификатор для нового атрибута");
 	if (ValueAttribType.GetTypeCode() != NUMBER_TYPE_1C)
		RuntimeError("Неверный тип для нового атрибута, нужно число");

	CGetDoc7_ProtectedAccess* pDoc = GetDoc();

	rValue.Reset();

	CString strAttrName = ValueAttribID.GetString();
	const UINT CtrlType = ValueAttribType.GetNumeric();

	{
		CGetField* pField = pDoc->GetField(strAttrName);
		if (pField)
			RuntimeError("Атрибут с подобным идентификатором уже существует");
	}
	
	bool bIsStatic = STATIC_CTRL_TYPE == CtrlType;
	bool bIsStaticInBrowse = BROWSE_COLUMN_STATIC_TYPE == CtrlType;
	bool bIsBrowseColumn = (BROWSE_COLUMN_STATIC_TYPE == CtrlType) || (BROWSE_COLUMN_EDIT_TYPE == CtrlType);
	//bool bInTable = bIsBrowseColumn && (BROWSE_COLUMN_STATIC_TYPE == CtrlType); // TODO
	bool bInTable = bIsBrowseColumn; // TODO
	
	if(!pDoc->HasBrowse()) // нет табличной части, ничего не делаем
		if (bIsBrowseColumn)
			RuntimeError("Колонку табличной части создать нельзя, т.к. на форме нет табличной части");

	CBrowse* pBrowse = pDoc->GetBrowse(); // artbear
	if (!pBrowse)
		if (bIsBrowseColumn)
			RuntimeError("Колонку табличной части можно создать только после физического открытия формы");

	DWORD nColInsertPos = 0;
	nColInsertPos = ValuePosInTable.GetNumeric(); //1-based: 1..n - insert; 0 - add to end

// ----------------------  ----------------------  ----------------------  
//
// artbear TODO важно проверить, чтобы тип формы соответствовал документу или справочнику,
// иначе возможно обращение к неверным адресам
// разобраться, как определить pDoc какого типа - CGetDoc7 или его наследник CDocForm
//
// ----------------------  ----------------------  ----------------------  
					
	int nID = pDoc->m_cControlList.GetTail()->GetCtrlID()+1;
	CControlID CtrlInfo;
	CtrlInfo.SetCodeName(strAttrName);
// 	if (bIsStatic){
		CtrlInfo.SetTitle(strAttrName); // возможно, для формульных статиков не нужно
//  }
	
	// TODO пока есть ошибка/вылет 1С для типов 8 и 9 artbear
	CtrlInfo.SetCtrlType(CtrlType);
	CtrlInfo.SetCtrlID(nID);
	//CtrlInfo.SetStyle(WS_VISIBLE | WS_CHILD); //0x50000000L
	CtrlInfo.SetLayerName(pDoc->m_pEditDoc->m_layers[pDoc->m_pEditDoc->m_iActiveLayer]);
	//CtrlInfo.SetExStyle(0);
	CtrlInfo.SetLongID(0);

	CtrlInfo.SetToolTip("Подсказка");
	CtrlInfo.SetHelpString("Описание");

	// TODO обязательно нужно задать какую-то формулу, но не пустую и без пробельных символов!
	// иначе потом нельзя будет изменить формулу
	CtrlInfo.SetFormul("0"); 

// 	bool bHaveFormul = methAddAttribWithFormul == iMethNum;
// 	CString strFormul;
// 
// 	if(bHaveFormul){
// 		strFormul = ValueAttribValueKindOrFormul.GetString();
// 		if (!strFormul.IsEmpty())
// 			CtrlInfo.SetFormul(strFormul); //"ФормулаДляСтатикНовый()");
// 	}

	DWORD dwStyle = WS_VISIBLE | WS_CHILD; //0x50000000L
	DWORD dwExStyle = CS_EX_VISIBLE;

	DWORD dwDependParam = 0;
	//dwDependParam |= DP_UseHelpString;

	if (bInTable)
	{
		// CtrlInfo.SetCtrlType(BROWSE_COLUMN_STATIC_TYPE);
		CtrlInfo.SetValType(CType(STRING_TYPE_1C));
		//CType& type = CtrlInfo.GetValType();
		CType type(STRING_TYPE_1C);
		type.m_length = 10;
		CtrlInfo.SetValType(type);

		//dwStyle |= ST_RightAlignmentInTable; //ST_Unknown1; // вправо
// 		dwDependParam |= DP_Unk00200000|DP_Unk00004000|DP_Unk10000000;
// 		dwDependParam |= DP_ColumnInNewLine|DP_RedNegativeDisplay;
		dwDependParam |= DP_Unk00200000|DP_Unk00004000|DP_Unk10000000;
		dwDependParam |= DP_RedNegativeDisplay;

		// dwDependParam = 0x10004000L; //268451840;
	}
	else if (bIsStatic) // TODO
	{
		dwStyle |= WS_GROUP; //0x00020000L
	}
	CtrlInfo.SetStyle(dwStyle);
	CtrlInfo.SetExStyle(dwExStyle);

	CtrlInfo.SetDependParam(dwDependParam);

	// CtrlInfo.SetPlace(CRect(40,40,80,25)
	CtrlInfo.SetPlace(CRect(10,10,80,25)); // artbear TODO возможно, что не нужно

// 				if (2 == CtrlType) // 2  - 1CEDIT (Поле ввода)
// 				{
// 					CType type(11);
// 					//type.SetTypeCode(100);
// 					//pField->ReCreateValue(type);
// 					CtrlInfo.SetValType(type);
// 				}
				
	// artbear - без этого флага не будет работать назначение типов - метод Форма.Атрибут.НазначитьТип
	if (!bIsStatic && !bIsStaticInBrowse)
		CtrlInfo.SetDependParam(CtrlInfo.GetDependParam() | C_CCONTROLID_DEPENDPARAM_IS_TYPE_ASSIGNED);

	pDoc->m_cControlList.AddTail(&CtrlInfo);

	CGetField* pField = pDoc->m_cGetFieldsArray1.NewItem();
	pField->SetCtrlID(nID);
	pField->SetDoc(pDoc);

	pField->SetInTable(bInTable);
	if (bInTable)
	{
		pField->SetBrOldStateEnable(0);
		pField->SetReadOnly(1);
		
		pField->m_ParamNo = pDoc->m_cGetFieldsArray4.GetSize();
		//pDoc->m_cGetFieldsArray4.AddItem(pField);
		//pField->m_ParamNo = 4;
	}

 	CControlID* pNewCtrlInfo = pDoc->m_cControlList.GetTail();
 	pField->SetCtrlInfo(pNewCtrlInfo); // здесь нельзя использовать просто &CtrlInfo - будет ошибка при обращении к подобному контролу

	//pField->m_Visible = pNewCtrlInfo->GetStyle() & WS_VISIBLE ? TRUE : FALSE;
	
	pDoc->InitStandartFields(pField, pNewCtrlInfo);

// 	CDocForm* pDoc1 = (CDocForm*)pDoc;
// 	CValuePtrArray& arr1 = *pDoc1->m_PtrArray.GetAt(0);
// 	CValuePtrArray& arr2 = *pDoc1->m_PtrArray.GetAt(1);
// 	CValue** ppValues1 = arr1.GetData();
// 	CValue** ppValues2 = arr2.GetData();
// 
// 	CValue** ppValues3 = arr2.GetData();
// 
// 	{
// 		CValuePtrArray& arr1 = *pDoc1->m_PtrArray.GetAt(0);
// 
// 		CValuePtrArray* pNewValuesArray = new CValuePtrArray;
// 		for (int i=0; i < arr1.GetSize();i++)
// 		{
// 			CValue* pVal = new CValue;
// 			//pNewValuesArray->SetAt(i, pVal);
// 			pNewValuesArray->Add(pVal);
// 		}
// 		//pDoc1->m_pPtArray.SetAt(pDoc1->m_pPtArray.GetSize(), pNewValuesArray);
// 		pDoc1->m_PtrArray.Add(pNewValuesArray);
// 	}


// 	if (bInTable && (pDoc->GetRuntimeClass() == RUNTIME_CLASS(CDocForm)))
// 	{
// 		CFormContext* pForm = pDoc->m_pFormContext;
// // 		int dwSize = pForm->m_GetFieldsArray.GetSize();
// // 		//pForm->m_pArrayOfFlagsRefresh = (int*)realloc((void*)pForm->m_pArrayOfFlagsRefresh, dwSize*4);
// // 		shared_array<int> Array(new int[dwSize]);
// // 		copy(pForm->m_pArrayOfFlagsRefresh, pForm->m_pArrayOfFlagsRefresh+dwSize-1, Array.get());
// // 		pForm->m_pArrayOfFlagsRefresh = new int[dwSize];
// // 		copy(Array.get(), Array.get()+dwSize-1, pForm->m_pArrayOfFlagsRefresh);
// // 		pForm->m_pArrayOfFlagsRefresh[dwSize-1] = 2;
// 	}
	
// 	CString strTypeKindName;
// 	if (methAddAttrib == iMethNum)
//		strTypeKindName	= ValueAttribValueKindOrFormul.GetString();
	CString strTypeKindName	= ValueAttribValueKindOrFormul.GetString();
// 	else if(bHaveFormul)
// 		strTypeKindName = ValueAttribValueKind.GetString();
// 	else
// 		; //todo исключение

	if (!bIsStaticInBrowse && !strTypeKindName.IsEmpty())
	{
		CType type(0);
		if (SetTypeAndKind(type, strTypeKindName)){
			pField->SetInternalValue(type);
			//pField->TranslateType(); // artbear !
		}
	}

// 	if (bIsStatic) // попытка 
// 	{
//  		//CValue& Value = *new CValue(CType(STRING_TYPE_1C));
//  		CValue* pValue = new CValue(CType(STRING_TYPE_1C));
//  		pField->SetPValue(pValue);
// 	}

	if (bInTable)
	{
		CBrowse* pBr = pDoc->GetBrowse();
		//CGetColumn* pColumn = new CGetColumn(pField->m_ID, CtrlInfo.GetTitle(), CtrlInfo.m_Place.left, pField->m_Flag10);
		
		CColumn* pColumn = NULL;
		//if (pDoc->GetRuntimeClass() == RUNTIME_CLASS(CDocForm))
		if (false)
		{
			class CPictureColumnDocForm
			{
				DWORD data[0x12];
			public:
				CPictureColumnDocForm(CGetDoc7* pDoc, CGetField* pField, UINT CtrlID, LPCSTR title, int nWidth, int Unk)
				{
					*(DWORD*)this = 0x2A0F3508; //vft
					typedef void (CPictureColumnDocForm::*PF_Constructor)(CGetDoc7*, CGetField*, UINT, LPCSTR, int, int);
					DWORD addr = 0x2A02F6C0;
					(this->*(*(PF_Constructor*)&addr))(pDoc, pField, CtrlID, title, nWidth, Unk); //вызов конструктора
				}
				virtual ~CPictureColumnDocForm(){};
			};
// 			class CGetColumnDocForm
// 			{
// 				DWORD data[0x12];
			class CGetColumnDocForm : public CColumn
			{
				//DWORD data[0x12];
				CDocForm* m_pDocForm;
				CGetField* m_pGetField;
				//size 48h
			public:
				//CGetColumnDocForm(CGetDoc7* pDoc, CGetField* pField, UINT CtrlID, LPCSTR title, int nWidth, int Unk)
				//CGetColumnDocForm(UINT CtrlID, LPCSTR title, int Unk) : CColumn()
				CGetColumnDocForm(CGetDoc7* pDoc, CGetField* pField, UINT CtrlID, LPCSTR title, int nWidth, int Unk) : 
					CColumn(CtrlID, title, nWidth)
				{
					*(DWORD*)this = 0x2A0F3498; //vft
					typedef void* (CGetColumnDocForm::*PF_Constructor)(CGetDoc7*, CGetField*, UINT, LPCSTR, int, int);
					//typedef void* (CGetColumnDocForm::*PF_Constructor)(UINT CtrlID, LPCSTR title, int Unk);
					typedef void* (CGetColumnDocForm::*PF_Constructor)(CGetDoc7*, CGetField*, UINT, LPCSTR, int, int);
					DWORD addr = 0x2A02F5B0;
					(this->*(*(PF_Constructor*)&addr))(pDoc, pField, CtrlID, title, nWidth, Unk); //вызов конструктора
					//(this->*(*(PF_Constructor*)&addr))(CtrlID, title, Unk); //вызов конструктора
				}
				virtual ~CGetColumnDocForm(){};
			};
			if (dwDependParam & DP_ShowPictograph)
				pColumn = (CColumn*)new CPictureColumnDocForm(pDoc, pField, pField->m_ID, CtrlInfo.GetTitle(), CtrlInfo.m_Place.left, pField->m_Flag10);
			else
				pColumn = (CColumn*)new CGetColumnDocForm(pDoc, pField, pField->m_ID, CtrlInfo.GetTitle(), CtrlInfo.m_Place.left, pField->m_Flag10);
				//pColumn = (CColumn*)new CGetColumnDocForm(pField->m_ID, CtrlInfo.GetTitle(), 0);
		}
		else
		{

			class CGetColumnDocForm : public CColumn
			{
				//DWORD data[0x12];
				//DWORD data[0x10];
				CDocForm* m_pDocForm;
				CGetField* m_pGetField;
				//size 48h
			public:
				static CGetColumnDocForm* Create_CGetColumnDocForm(CGetDoc7* pDoc, CGetField* pField, UINT CtrlID, LPCSTR title, int nWidth, int Unk)
				{
					//CGetColumnDocForm* pNew = new CGetColumnDocForm(pDoc, pField, CtrlID, title, nWidth, Unk);
					CGetColumnDocForm* pNew = (CGetColumnDocForm*)new char[sizeof(CGetColumnDocForm)];

					typedef void* (CGetColumnDocForm::*PF_Constructor)(CGetDoc7*, CGetField*, UINT, LPCSTR, int, int);
					DWORD addr = 0x2A02F5B0;
					(pNew->*(*(PF_Constructor*)&addr))(pDoc, pField, CtrlID, title, nWidth, Unk); //вызов конструктора
					//(this->*(*(PF_Constructor*)&addr))(CtrlID, title, Unk); //вызов конструктора
					//*(DWORD*)pNew = 0x2A0F3498; //vft
					return pNew;
				};

			// 	CGetColumnDocForm(CGetDoc7* pDoc, CGetField* pField, UINT CtrlID, LPCSTR title, int nWidth, int Unk)
			// 	{	};
				virtual ~CGetColumnDocForm(){};
			};

			if (dwDependParam & DP_ShowPictograph)
				pColumn = new CPictureColumn(pDoc, pField->m_ID, CtrlInfo.GetTitle(), CtrlInfo.m_Place.left);
			else
				//pColumn = new CFColumn(pField->m_ID, (char*)(strTypeKindName.operator LPCTSTR()),CtrlInfo.GetTitle(), CtrlInfo.m_Place.left, pField->m_Flag10, 0);
				pColumn = new CGetColumn(pField->m_ID, CtrlInfo.GetTitle(), CtrlInfo.m_Place.left, pField->m_Flag10);
				//pColumn = (CColumn*)CGetColumnDocForm::Create_CGetColumnDocForm(pDoc, pField, pField->m_ID, CtrlInfo.GetTitle(), CtrlInfo.m_Place.left, pField->m_Flag10);
			int i = 1;
		}

		if (nColInsertPos > 0)
		{
			nColInsertPos--;
			nColInsertPos = min(nColInsertPos, pBr->GetColumnNum());
		}
		else
			nColInsertPos = pBr->GetColumnNum();

		DWORD nColInOneCount = 1;
		DWORD nColPositionFlag = 0;
		if (nColInsertPos > 1)
		{
			if (dwDependParam & DP_ColumnInNewLine)
			{
				nColInOneCount = 2;
				for (int i=nColInsertPos; i; nColInOneCount++)
					if (pBr->operator [](--i).m_ColPositionFlag < 2)
						break;
				for (i=nColInsertPos; i<pBr->GetColumnNum(); i++, nColInOneCount++)
					if (pBr->operator [](i).m_ColPositionFlag < 2)
						break;
				nColPositionFlag = 2;
			}
			else if (dwDependParam & DP_ColumnInSameCol)
				nColPositionFlag = 1;
		}
		/*
		if (nColInsertPos == pBr->GetColumnNum())
			pBr->Add(pColumn, nColPositionFlag);
		else
			pBr->Insert(nColInsertPos, pColumn, nColPositionFlag);

		if (nColInOneCount > pBr->GetMaxHeadLines())
			pBr->SetMaxHeadLines(nColInOneCount);
		*/

		CCellGet* pCellGet = new CCellGet(pBr, pField->m_ID, pField->m_strWindowName, pField->m_Flag14);
		pDoc->AddGet(pCellGet);

	}

	//pField->TranslateType(); // TODO trad есть - но влияет на работу Доступность - баг http://cvs.alterplast.ru/bugs/show_bug.cgi?id=4015
	pField->UpdateMask();

// DWORD dwSize = m_Form->m_GetFieldsArray.GetSize();
// m_Form->m_Data1 = (CFormCtrlContext**)realloc((void*)m_Form->m_Data1, dwSize*4);
// 
// m_Form->m_Data1[dwSize-1] = 0x0;
// 
// m_pDoc->LayoutControl((CFormView*)m_pDoc->GetForm(), pField);
				
	CSafeContextPtr<CFormAllCtrlsContext> pForm = GetForm();
	pForm->m_GetFieldsArray.Add(pField);

	// три следующие строки и есть самое главное !!
	DWORD dwSize = pForm->m_GetFieldsArray.GetSize();
	pForm->m_Data1 = (CFormCtrlContext**)realloc((void*)pForm->m_Data1, dwSize*4);
	pForm->m_Data1[dwSize-1] = 0x0;

	//pField->UpdateState();
	if (bInTable)
	{
		if (pDoc->GetRuntimeClass() == RUNTIME_CLASS(CDocForm))
		{
			CDocForm* pDocForm = (CDocForm*)pDoc;
			pDocForm->m_GetFieldsArray.AddItem(pField);
			//CInternalParamsForDocForm* m_pArray; // 0x774 // индексом является поле m_Field818
			pDocForm->m_FormContextForDoc.m_GetFieldsArray.AddItem(pField);
		}
	}

	if (pDoc->IsDocLayouted())
	{
		//ToolTip
		// TODO для колонок в журнале документов и списке справочников происходит сдвиг описания
		// если добавить колонку в самое начало, то описания соответственно не сдвигаются :(
		// Например, есть 2 колонки - ДатаДок и НомерДок, если в начало добавить колонку Тест,
		// то описание для Тест на самом деле описание для Дата, а для Даты станет описанием от Номер
		// для документов, скорее всего, будет тоже самое
		//
		CString strToolTip;
		if (CtrlInfo.GetDependParam() & DP_UseHelpString)
			strToolTip = CtrlInfo.GetHelpString();
		else
			strToolTip = CtrlInfo.GetToolTip();
		if (strToolTip.IsEmpty())
			pDoc->GetMsgString(CGetDoc7::msgtToolTip, nID, strToolTip);

		//HelpString
		CString strHelpString = CtrlInfo.GetHelpString();
		if (strHelpString.IsEmpty())
			pDoc->GetMsgString(CGetDoc7::msgtHelpString, nID, strHelpString);

// 		CFormView* pFormView = (CFormView*)pDoc->GetForm();
// 		pDoc->LayoutControl(pFormView, pField);

		if (!bInTable)
		{
			if (CtrlInfo.GetCtrlType() == BUTTON_CTRL_TYPE)
			{
				CString strHK;
				pDoc->GetMsgString(CGetDoc7::msgtHotKey, nID, strHK);
				if (!strHK.IsEmpty())
				{
					strToolTip += " (";
					strToolTip += strHK;
					strToolTip += ")";
				}
			}
	 		CFormView* pFormView = static_cast<CFormView*>(pDoc->GetForm());
			pDoc->LayoutControl(pFormView, pField);
			CWnd* pWnd = pDoc->GetFieldWnd(pField);

			if (!strToolTip.IsEmpty())
				pDoc->m_cToolTipCtrl.AddTool(pWnd, strToolTip);
			if (!strHelpString.IsEmpty())
				pDoc->m_cOnLineHelp.SetItem(pWnd, strHelpString, 0);
		}
		else
		{
			nColInsertPos++;
			CBrowse* pBr = pDoc->GetBrowse();
			CToolInfo TI;
			for (int i = pBr->GetColumnNum(); i>=nColInsertPos; i--)
			{
				if (pDoc->m_cToolTipCtrl.GetToolInfo(TI, pBr, i))
				{
					pDoc->m_cToolTipCtrl.AddTool(pBr,TI.szText, &TI.rect, i+1);
					pDoc->m_cToolTipCtrl.DelTool(pBr, i);
				}
				CString strTemp;
				if (pDoc->m_cOnLineHelp.GetItemText(pBr, strTemp, i))
				{
					pDoc->m_cOnLineHelp.SetItem(pBr, strTemp, i+1);
					pDoc->m_cOnLineHelp.DelItem(pBr, i);
				}
			}

			if (!strToolTip.IsEmpty())
				pDoc->m_cToolTipCtrl.AddTool(pBr, strToolTip, &CRect(-20,-20,-10,-10), nColInsertPos);
			if (!strHelpString.IsEmpty())
				pDoc->m_cOnLineHelp.SetItem(pBr, strHelpString, nColInsertPos);
		}

// 		if (bInTable && (pDoc->GetRuntimeClass() == RUNTIME_CLASS(CDocForm)))
// 		{
// 			CFormContext* pForm = pDoc->m_pFormContext;
// 			int dwSize = pForm->m_GetFieldsArray.GetSize();
//  			pForm->m_pArrayOfFlagsRefresh[dwSize-1] = 2;
// 			
// 			FieldsArray(CValue(), NULL);
// 		}
	
		//Прочее
		pDoc->InitFieldsState();

// 		if (pDoc->GetBrowse() && !pDoc->IsBrowseVisible())
// 			pDoc->SetBrowseVisible(0,1);

		//if (CFormContext* pFormContext = pDoc->GetFormContext())
		//	pDoc->TrySetFocusOnCtrl(pFormContext->m_strFieldNeedActivate, 0);

		pDoc->CorrectActiveCtrl();
	}

// 	// доступ к protected членам и методам
// 	//class CFormEx;
// 	class CFormContext_ProtectedAccess : public CFormContext
// 	{
// 		friend class CFormEx;
// 		friend class CAttribEx;
// 	};
// 
// 	CFormContext_ProtectedAccess* pForm1 = (CFormContext_ProtectedAccess*)pDoc->m_pFormContext;
// 	//pForm1->SetForm(pDoc);
// 
// 	CGroupContext* pGroupContext = GetGroupContext();
// 	//pGroupContext->m_nAllPropsCount++;
// 	//pGroupContext->Accept();
// 	
//  	CValue GroupContValue; GroupContValue.AssignContext(GetGroupContext());
//  	CValue* pValue = &GroupContValue;
//  
//  	FindAndCallMethodOfSystemFrom1CPP("ОбновитьДанныеГК", &pValue);
// 
// 	//CGroupContext* pGroupContext = GetGroupContext();
// 	//pGroupContext->m_nAllPropsCount++;
// 	TraceGroupContext(pGroupContext);

	ReturnAttrib(rValue, pDoc->m_cGetFieldsArray1.GetSize()-1);
	
	return TRUE;
}

CSafeContextPtrDef GetSystemObjectFrom1CPP(void)
{
	CSafeContextPtrDef pCont;
	try
	{
		pCont.Create("Система"); 
	}
	catch(...)
	{
		return pCont; // 1C++ не загружена
	}

	return pCont;
}
	
static bool FindAndCallMethodOfSystemFrom1CPP(const char* szMethodsName, CValue** ppParams)
{
	CSafeContextPtrDef pCont = GetSystemObjectFrom1CPP();
	if (!pCont)
		return false;

	int nMethod = pCont->FindMethod(szMethodsName);
	if (-1 == nMethod)
		return false; // старая версия ФормЕкс, без оптимизатора
	
	int res = pCont->CallAsProc(nMethod, ppParams);
	
	return true;
}
