Exemplo n.º 1
0
OldGetFileString::OldGetFileString(FILE *SrcFile):
    SrcFile(SrcFile),
    wReadBuf(new wchar_t[ReadBufCount]),
    ReadBuf(new char[ReadBufCount]),
    m_nwStrLength(DELTA),
    m_nStrLength(DELTA),
    wStr(static_cast<wchar_t*>(xf_malloc(m_nwStrLength * sizeof(wchar_t)))),
    Str(static_cast<char*>(xf_malloc(m_nStrLength))),
    ReadPos(0),
    ReadSize(0),
    SomeDataLost(false),
    bCrCr(false)
{
}
Exemplo n.º 2
0
// max - без учета символа конца строки!
wchar_t *Clipboard::PasteEx(int max)
{
    wchar_t *ClipText=nullptr;
    HANDLE hClipData=GetData(CF_UNICODETEXT);

    if (hClipData)
    {
        wchar_t *ClipAddr=(wchar_t *)GlobalLock(hClipData);

        if (ClipAddr)
        {
            int BufferSize;
            BufferSize=StrLength(ClipAddr);

            if (BufferSize>max)
                BufferSize=max;

            ClipText=(wchar_t *)xf_malloc((BufferSize+1)*sizeof(wchar_t));

            if (ClipText)
            {
                wmemset(ClipText,0,BufferSize+1);
                xwcsncpy(ClipText,ClipAddr,BufferSize+1);
            }

            GlobalUnlock(hClipData);
        }
    }

    return ClipText;
}
Exemplo n.º 3
0
void FileList::FileListToPluginItem(FileListItem *fi,PluginPanelItem *pi)
{
	pi->FileName = xf_wcsdup(fi->strName);
	pi->AlternateFileName = xf_wcsdup(fi->strShortName);
	pi->FileSize=fi->FileSize;
	pi->AllocationSize=fi->AllocationSize;
	pi->FileAttributes=fi->FileAttr;
	pi->LastWriteTime=fi->WriteTime;
	pi->CreationTime=fi->CreationTime;
	pi->LastAccessTime=fi->AccessTime;
	pi->NumberOfLinks=fi->NumberOfLinks;
	pi->Flags=fi->UserFlags;

	if (fi->Selected)
		pi->Flags|=PPIF_SELECTED;

	pi->CustomColumnData=fi->CustomColumnData;
	pi->CustomColumnNumber=fi->CustomColumnNumber;
	pi->Description=fi->DizText; //BUGBUG???

	if (fi->UserData && (fi->UserFlags & PPIF_USERDATA))
	{
		DWORD Size=*(DWORD *)fi->UserData;
		pi->UserData=(DWORD_PTR)xf_malloc(Size);
		memcpy((void *)pi->UserData,(void *)fi->UserData,Size);
	}
	else
		pi->UserData=fi->UserData;

	pi->CRC32=fi->CRC32;
	pi->Reserved[0]=pi->Reserved[1]=0;
	pi->Owner=fi->strOwner.IsEmpty()?nullptr:(wchar_t*)fi->strOwner.CPtr();
}
Exemplo n.º 4
0
bool History::ReadLastItem(const wchar_t *RegKey, string &strStr)
{
	strStr.Clear();
	HKEY hKey=OpenRegKey(RegKey);

	if (!hKey)
		return false;

	DWORD Type;
	DWORD Size=0;

	if (RegQueryValueEx(hKey,L"Lines",0,&Type,nullptr,&Size)!=ERROR_SUCCESS || Size<sizeof(wchar_t)) // Нету ничерта
		return false;

	wchar_t *Buffer=(wchar_t*)xf_malloc(Size);

	if (!Buffer)
		return false;

	if (RegQueryValueEx(hKey,L"Lines",0,&Type,(unsigned char *)Buffer,&Size)!=ERROR_SUCCESS)
	{
		xf_free(Buffer);
		return false;
	}

	Buffer[Size/sizeof(wchar_t)-1]=0; //safety
	strStr = Buffer; //last item is first in registry, null terminated
	xf_free(Buffer);
	return true;
}
Exemplo n.º 5
0
bool FileMasksProcessor::Set(const wchar_t *masks, DWORD Flags)
{
	Free();
	// разделителем масок является не только запятая, но и точка с запятой!
	DWORD flags=ULF_PACKASTERISKS|ULF_PROCESSBRACKETS|ULF_SORT|ULF_UNIQUE;

	if (Flags&FMPF_ADDASTERISK)
		flags|=ULF_ADDASTERISK;

	bRE = (masks && *masks == L'/');

	if (bRE)
	{
		re = new RegExp;

		if (re && re->Compile(masks, OP_PERLSTYLE|OP_OPTIMIZE))
		{
			n = re->GetBracketsCount();
			m = (SMatch *)xf_malloc(n*sizeof(SMatch));

			if (!m)
			{
				n = 0;
				return false;
			}

			return true;
		}

		return false;
	}

	Masks.SetParameters(L',',L';',flags);
	return Masks.Set(masks);
}
Exemplo n.º 6
0
wchar_t *ReadString(FILE *file, wchar_t *lpwszDest, int nDestLength, int nCodePage)
{
    char *lpDest = (char*)xf_malloc((nDestLength+1)*3);  //UTF-8, up to 3 bytes per char support
    memset(lpDest, 0, (nDestLength+1)*3);
    memset(lpwszDest, 0, nDestLength*sizeof(wchar_t));

    if ((nCodePage == CP_UNICODE) || (nCodePage == CP_REVERSEBOM))
    {
        if (!fgetws(lpwszDest, nDestLength, file))
        {
            xf_free(lpDest);
            return nullptr;
        }

        if (nCodePage == CP_REVERSEBOM)
        {
            _swab((char*)lpwszDest, (char*)lpwszDest, nDestLength*sizeof(wchar_t));
            wchar_t *Ch = lpwszDest;
            int nLength = Min(static_cast<int>(wcslen(lpwszDest)), nDestLength);

            while (*Ch)
            {
                if (*Ch == L'\n')
                {
                    *(Ch+1) = 0;
                    break;
                }

                Ch++;
            }

            int nNewLength = Min(static_cast<int>(wcslen(lpwszDest)), nDestLength);
            fseek(file, (nNewLength-nLength)*sizeof(wchar_t), SEEK_CUR);
        }
    }
    else if (nCodePage == CP_UTF8)
    {
        if (fgets(lpDest, nDestLength*3, file))
            MultiByteToWideChar(CP_UTF8, 0, lpDest, -1, lpwszDest, nDestLength);
        else
        {
            xf_free(lpDest);
            return nullptr;
        }
    }
    else if (nCodePage != -1)
    {
        if (fgets(lpDest, nDestLength, file))
            MultiByteToWideChar(nCodePage, 0, lpDest, -1, lpwszDest, nDestLength);
        else
        {
            xf_free(lpDest);
            return nullptr;
        }
    }

    xf_free(lpDest);
    return lpwszDest;
}
Exemplo n.º 7
0
void* __cdecl xf_realloc(void * _Memory, size_t _Size XF_PLACE_ARGS_DEF)
{
	_ASSERTE(ghHeap);
	_ASSERTE(_Size>0);
	if (!_Memory)
	{
		return xf_malloc(_Size
			#ifdef TRACK_MEMORY_ALLOCATIONS
				, lpszFileName, nLine
			#endif
			);
	}
#ifdef TRACK_MEMORY_ALLOCATIONS
	xf_mem_block* pOld = ((xf_mem_block*)_Memory)-1;

	size_t _Size1 = HeapSize(ghHeap, 0, pOld);
	//_ASSERTE(_Size1 < (_Size+sizeof(xf_mem_block)+8));
	_ASSERTE(_Size1 > (sizeof(xf_mem_block)+8));
	size_t _Size2 = 0;

	if (pOld->bBlockUsed == TRUE)
	{
		int nCCcmp = memcmp(((LPBYTE)_Memory)+pOld->nBlockSize, "\xCC\xCC\xCC\xCC\xCC\xCC\xCC\xCC", 8);
		_ASSERTE(nCCcmp == 0);
		_ASSERTE(_Size1 == (pOld->nBlockSize+sizeof(xf_mem_block)+8));
		_Size2 = pOld->nBlockSize;
	}
	else
	{
		_ASSERTE(pOld->bBlockUsed == TRUE);
		if (_Size1 > (sizeof(xf_mem_block)+8))
			_Size2 = _Size1 - (sizeof(xf_mem_block)+8);
	}

	xf_mem_block* p = (xf_mem_block*)HeapReAlloc(ghHeap, 0, pOld, _Size+sizeof(xf_mem_block)+8);
	if (p)
	{
		p->bBlockUsed = TRUE;
		p->nBlockSize = _Size;

		xf_set_tag(p+1, lpszFileName, nLine);

		#ifdef _DEBUG
		if (_Size > _Size2) memset(((LPBYTE)(p+1))+_Size2, 0xFD, _Size - _Size2);
		#endif

		memset(((LPBYTE)(p+1))+_Size, 0xCC, 8);
	}
	else
	{
		_ASSERTE(p!=NULL);
	}
	return p?(p+1):p;
#else
	void* p = HeapReAlloc(ghHeap, HEAP_ZERO_MEMORY, _Memory, _Size);
	return p;
#endif
}
Exemplo n.º 8
0
GetFileString::GetFileString(File& SrcFile):
    SrcFile(SrcFile),
    ReadPos(0),
    ReadSize(0),
    Peek(false),
    LastLength(0),
    LastString(nullptr),
    LastResult(0),
    ReadBuf(new char[ReadBufCount]),
    wReadBuf(new wchar_t[ReadBufCount]),
    m_nStrLength(DELTA),
    Str(static_cast<LPSTR>(xf_malloc(m_nStrLength))),
    m_nwStrLength(DELTA),
    wStr(static_cast<LPWSTR>(xf_malloc(m_nwStrLength * sizeof(wchar_t)))),
    SomeDataLost(false),
    bCrCr(false)
{
}
Exemplo n.º 9
0
void FileList::PluginToFileListItem(PluginPanelItem *pi,FileListItem *fi)
{
	fi->strName = pi->FileName;
	fi->strShortName = pi->AlternateFileName;
	fi->strOwner = pi->Owner;

	if (pi->Description)
	{
		fi->DizText=new wchar_t[StrLength(pi->Description)+1];
		wcscpy(fi->DizText, pi->Description);
		fi->DeleteDiz=TRUE;
	}
	else
		fi->DizText=nullptr;

	fi->FileSize=pi->FileSize;
	fi->AllocationSize=pi->AllocationSize;
	fi->FileAttr=pi->FileAttributes;
	fi->WriteTime=pi->LastWriteTime;
	fi->CreationTime=pi->CreationTime;
	fi->AccessTime=pi->LastAccessTime;
	fi->ChangeTime.dwHighDateTime = 0;
	fi->ChangeTime.dwLowDateTime = 0;
	fi->NumberOfLinks=pi->NumberOfLinks;
	fi->NumberOfStreams=1;
	fi->UserFlags=pi->Flags;

	if (pi->UserData && (pi->Flags & PPIF_USERDATA))
	{
		DWORD Size=*(DWORD *)pi->UserData;
		fi->UserData=(DWORD_PTR)xf_malloc(Size);
		memcpy((void *)fi->UserData,(void *)pi->UserData,Size);
	}
	else
		fi->UserData=pi->UserData;

	if (pi->CustomColumnNumber>0)
	{
		fi->CustomColumnData=new wchar_t*[pi->CustomColumnNumber];

		for (size_t I=0; I<pi->CustomColumnNumber; I++)
			if (pi->CustomColumnData && pi->CustomColumnData[I])
			{
				fi->CustomColumnData[I]=new wchar_t[StrLength(pi->CustomColumnData[I])+1];
				wcscpy(fi->CustomColumnData[I],pi->CustomColumnData[I]);
			}
			else
			{
				fi->CustomColumnData[I]=new wchar_t[1];
				fi->CustomColumnData[I][0]=0;
			}
	}

	fi->CustomColumnNumber=pi->CustomColumnNumber;
	fi->CRC32=pi->CRC32;
}
Exemplo n.º 10
0
void * __cdecl operator new[] (size_t _Size)
{
	void * p = xf_malloc(
		_Size
		#ifdef TRACK_MEMORY_ALLOCATIONS
		,__FILE__,__LINE__
		#endif
		);
	#ifdef MVALIDATE_POINTERS
		_ASSERTE(p != NULL);
		if (p == NULL) InvalidOp();
	#endif
	return p;
}
Exemplo n.º 11
0
wchar_t *Clipboard::PasteFormat(const wchar_t *Format)
{
    bool isOEMVBlock=false;
    UINT FormatType=RegisterFormat(Format);

    if (!FormatType)
        return nullptr;

    if (!StrCmp(Format,FAR_VerticalBlock_Unicode) && !IsFormatAvailable(FormatType))
    {
        FormatType=RegisterFormat(FAR_VerticalBlock);
        isOEMVBlock=true;
    }

    if (!FormatType || !IsFormatAvailable(FormatType))
        return nullptr;

    wchar_t *ClipText=nullptr;
    HANDLE hClipData=GetData(FormatType);

    if (hClipData)
    {
        wchar_t *ClipAddr=(wchar_t *)GlobalLock(hClipData);

        if (ClipAddr)
        {
            size_t BufferSize;

            if (isOEMVBlock)
                BufferSize=strlen((LPCSTR)ClipAddr)+1;
            else
                BufferSize=wcslen(ClipAddr)+1;

            ClipText=(wchar_t *)xf_malloc(BufferSize*sizeof(wchar_t));

            if (ClipText)
            {
                if (isOEMVBlock)
                    MultiByteToWideChar(CP_OEMCP,0,(LPCSTR)ClipAddr,-1,ClipText,(int)BufferSize);
                else
                    wcscpy(ClipText,ClipAddr);
            }

            GlobalUnlock(hClipData);
        }
    }

    return ClipText;
}
Exemplo n.º 12
0
	SIDCacheItem(const wchar_t *Computer,PSID InitSID)
	{
		Sid=xf_malloc(GetLengthSid(InitSID));
		if(Sid)
		{
			if(CopySid(GetLengthSid(InitSID),Sid,InitSID))
			{
				DWORD AccountLength=0,DomainLength=0;
				SID_NAME_USE snu;
				LookupAccountSid(Computer,Sid,nullptr,&AccountLength,nullptr,&DomainLength,&snu);
				if (AccountLength && DomainLength)
				{
					string strAccountName,strDomainName;
					LPWSTR AccountName=strAccountName.GetBuffer(AccountLength);
					LPWSTR DomainName=strDomainName.GetBuffer(DomainLength);
					if (AccountName && DomainName)
					{
						if(LookupAccountSid(Computer,Sid,AccountName,&AccountLength,DomainName,&DomainLength,&snu))
						{
							strUserName=string(DomainName).Append(L"\\").Append(AccountName);
						}
					}
				}
				else
				{
					LPWSTR StrSid;
					if(ConvertSidToStringSid(Sid, &StrSid))
					{
						strUserName = StrSid;
						LocalFree(StrSid);
					}
				}
			}
		}

		if(strUserName.IsEmpty())
		{
			xf_free(Sid);
			Sid=nullptr;
		}
	}
Exemplo n.º 13
0
Manager::Manager():
	FrameCount(0),
	InsertedFrame(nullptr),
	DeletedFrame(nullptr),
	ActivatedFrame(nullptr),
	RefreshedFrame(nullptr),
	ModalizedFrame(nullptr),
	UnmodalizedFrame(nullptr),
	DeactivatedFrame(nullptr),
	ExecutedFrame(nullptr),
	CurrentFrame(nullptr),
	ModalStack(nullptr),
	FrameList(static_cast<Frame **>(xf_malloc(sizeof(Frame*)*(FrameCount+1)))),
	ModalStackCount(0),
	ModalStackSize(0),
	FrameListSize(0),
	FramePos(-1),
	ModalEVCount(0),
	EndLoop(FALSE),
	ModalExitCode(-1),
	StartManager(FALSE)
{
}
Exemplo n.º 14
0
bool History::ReadHistory(bool bOnlyLines)
{
	HKEY hKey=OpenRegKey(strRegKey);

	if (!hKey)
		return false;

	bool ret = false;
	wchar_t *TypesBuffer=nullptr;
	wchar_t *LocksBuffer=nullptr;
	FILETIME *TimesBuffer=nullptr;
	wchar_t *Buffer=nullptr;
	int Position=-1;
	DWORD Size=sizeof(Position);
	DWORD Type;

	if (!bOnlyLines)
		RegQueryValueEx(hKey,L"Position",0,&Type,(BYTE *)&Position,&Size);

	bool NeedReadType=false;
	bool NeedReadLock=false;
	bool NeedReadTime=false;
	Size=0;

	if (!bOnlyLines && SaveType && RegQueryValueEx(hKey,L"Types",0,&Type,nullptr,&Size)==ERROR_SUCCESS && Size>0)
	{
		NeedReadType=true;
		Size=Max(Size,(DWORD)((HistoryCount+2)*sizeof(wchar_t)));
		TypesBuffer=(wchar_t *)xf_malloc(Size);

		if (TypesBuffer)
		{
			memset(TypesBuffer,0,Size);

			if (RegQueryValueEx(hKey,L"Types",0,&Type,(BYTE *)TypesBuffer,&Size)!=ERROR_SUCCESS)
				goto end;
		}
		else
			goto end;
	}

	Size=0;

	if (!bOnlyLines && RegQueryValueEx(hKey,L"Locks",0,&Type,nullptr,&Size)==ERROR_SUCCESS && Size>0)
	{
		NeedReadLock=true;
		Size=Max(Size,(DWORD)((HistoryCount+2)*sizeof(wchar_t)));
		LocksBuffer=(wchar_t *)xf_malloc(Size);

		if (LocksBuffer)
		{
			memset(LocksBuffer,0,Size);

			if (RegQueryValueEx(hKey,L"Locks",0,&Type,(BYTE *)LocksBuffer,&Size)!=ERROR_SUCCESS)
				goto end;
		}
		else
			goto end;
	}

	Size=0;

	if (!bOnlyLines && RegQueryValueEx(hKey,L"Times",0,&Type,nullptr,&Size)==ERROR_SUCCESS && Size>0)
	{
		NeedReadTime=true;
		Size=Max(Size,(DWORD)((HistoryCount+2)*sizeof(FILETIME)));
		TimesBuffer=(FILETIME *)xf_malloc(Size);

		if (TimesBuffer)
		{
			memset(TimesBuffer,0,Size);

			if (RegQueryValueEx(hKey,L"Times",0,&Type,(BYTE *)TimesBuffer,&Size)!=ERROR_SUCCESS)
				goto end;
		}
		else
			goto end;
	}

	Size=0;

	if (RegQueryValueEx(hKey,L"Lines",0,&Type,nullptr,&Size)!=ERROR_SUCCESS || !Size) // Нету ничерта
	{
		ret = true;
		goto end;
	}

	if (!(Buffer=(wchar_t*)xf_malloc(Size)))
		goto end;

	if (RegQueryValueEx(hKey,L"Lines",0,&Type,(unsigned char *)Buffer,&Size)==ERROR_SUCCESS)
	{
		CurrentItem=nullptr;
		wchar_t *TypesBuf=TypesBuffer;
		wchar_t *LockBuf=LocksBuffer;
		FILETIME *TimeBuf=TimesBuffer;
		size_t StrPos=0;
		wchar_t *Buf=Buffer;
		Size/=sizeof(wchar_t);
		Buf[Size-1]=0; //safety

		while (Size > 1 && StrPos < HistoryCount)
		{
			int Length=StrLength(Buf)+1;
			HistoryRecord AddRecord;
			AddRecord.strName = Buf;
			Buf+=Length;
			Size-=Length;

			if (NeedReadType)
			{
				if (iswdigit(*TypesBuf))
				{
					AddRecord.Type = *TypesBuf-L'0';
					TypesBuf++;
				}
			}

			if (NeedReadLock)
			{
				if (iswdigit(*LockBuf))
				{
					AddRecord.Lock = (*LockBuf-L'0')? true:false;
					LockBuf++;
				}
			}

			if (NeedReadTime)
			{
				AddRecord.Timestamp.dwLowDateTime=TimeBuf->dwLowDateTime;
				AddRecord.Timestamp.dwHighDateTime=TimeBuf->dwHighDateTime;
				TimeBuf++;
			}

			if (AddRecord.strName.GetLength())
			{
				HistoryList.Unshift(&AddRecord);

				if (StrPos == static_cast<size_t>(Position))
					CurrentItem=HistoryList.First();
			}

			StrPos++;
		}
	}
	else
		goto end;

	ret=true;
end:
	RegCloseKey(hKey);

	if (TypesBuffer)
		xf_free(TypesBuffer);

	if (Buffer)
		xf_free(Buffer);

	if (LocksBuffer)
		xf_free(LocksBuffer);

	if (TimesBuffer)
		xf_free(TimesBuffer);

	//if (!ret)
	//clear();
	return ret;
}
Exemplo n.º 15
0
void FileList::UpdatePlugin(int KeepSelection, int IgnoreVisible)
{
	_ALGO(CleverSysLog clv(L"FileList::UpdatePlugin"));
	_ALGO(SysLog(L"(KeepSelection=%d, IgnoreVisible=%d)",KeepSelection,IgnoreVisible));

	if (!IsVisible() && !IgnoreVisible)
	{
		UpdateRequired=TRUE;
		UpdateRequiredMode=KeepSelection;
		return;
	}

	DizRead=FALSE;
	FileListItem *CurPtr, **OldData=0;
	string strCurName, strNextCurName;
	int OldFileCount=0;
	StopFSWatcher();
	LastCurFile=-1;
	OpenPanelInfo Info;
	CtrlObject->Plugins->GetOpenPanelInfo(hPlugin,&Info);

	FreeDiskSize=0;
	if (Opt.ShowPanelFree)
	{
		if (Info.Flags & OPIF_REALNAMES)
		{
			unsigned __int64 TotalSize,TotalFree;
			if (!apiGetDiskSize(strCurDir,&TotalSize,&TotalFree,&FreeDiskSize))
				FreeDiskSize=0;
		}
		else if (Info.Flags & OPIF_USEFREESIZE)
			FreeDiskSize=Info.FreeSize;
	}

	PluginPanelItem *PanelData=nullptr;
	size_t PluginFileCount;

	if (!CtrlObject->Plugins->GetFindData(hPlugin,&PanelData,&PluginFileCount,0))
	{
		DeleteListData(ListData,FileCount);
		PopPlugin(TRUE);
		Update(KeepSelection);

		// WARP> явный хак, но очень способствует - восстанавливает позицию на панели при ошибке чтения архива.
		if (!PrevDataList.Empty())
			GoToFile((*PrevDataList.Last())->strPrevName);

		return;
	}

	size_t PrevSelFileCount=SelFileCount;
	SelFileCount=0;
	SelFileSize=0;
	TotalFileCount=0;
	TotalFileSize=0;
	CacheSelIndex=-1;
	CacheSelClearIndex=-1;
	strPluginDizName.Clear();

	if (FileCount>0)
	{
		CurPtr=ListData[CurFile];
		strCurName = CurPtr->strName;

		if (CurPtr->Selected)
		{
			for (int i=CurFile+1; i < FileCount; i++)
			{
				CurPtr = ListData[i];

				if (!CurPtr->Selected)
				{
					strNextCurName = CurPtr->strName;
					break;
				}
			}
		}
	}
	else if (Info.Flags & OPIF_ADDDOTS)
	{
		strCurName = L"..";
	}

	if (KeepSelection || PrevSelFileCount>0)
	{
		OldData=ListData;
		OldFileCount=FileCount;
	}
	else
	{
		DeleteListData(ListData,FileCount);
	}

	FileCount=static_cast<int>(PluginFileCount);
	ListData=(FileListItem**)xf_malloc(sizeof(FileListItem*)*(FileCount+1));

	if (!ListData)
	{
		FileCount=0;
		return;
	}

	if (!Filter)
		Filter=new FileFilter(this,FFT_PANEL);

	//Рефреш текущему времени для фильтра перед началом операции
	Filter->UpdateCurrentTime();
	CtrlObject->HiFiles->UpdateCurrentTime();
	int DotsPresent=FALSE;
	int FileListCount=0;
	bool UseFilter=Filter->IsEnabledOnPanel();

	for (int i=0; i < FileCount; i++)
	{
		ListData[FileListCount] = new FileListItem;
		FileListItem *CurListData=ListData[FileListCount];
		CurListData->Clear();

		if (UseFilter && !(Info.Flags & OPIF_DISABLEFILTER))
		{
			//if (!(CurPanelData->FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
			if (!Filter->FileInFilter(PanelData[i]))
				continue;
		}

		if (!Opt.ShowHidden && (PanelData[i].FileAttributes & (FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)))
			continue;

		//ClearStruct(*CurListData);
		PluginToFileListItem(&PanelData[i],CurListData);
		CurListData->Position=i;

		if (!(Info.Flags & OPIF_DISABLESORTGROUPS)/* && !(CurListData->FileAttr & FILE_ATTRIBUTE_DIRECTORY)*/)
			CurListData->SortGroup=CtrlObject->HiFiles->GetGroup(CurListData);
		else
			CurListData->SortGroup=DEFAULT_SORT_GROUP;

		if (!CurListData->DizText)
		{
			CurListData->DeleteDiz=FALSE;
			//CurListData->DizText=nullptr;
		}

		if (TestParentFolderName(CurListData->strName))
		{
			DotsPresent=TRUE;
			CurListData->FileAttr|=FILE_ATTRIBUTE_DIRECTORY;
		}
		else if (!(CurListData->FileAttr & FILE_ATTRIBUTE_DIRECTORY))
		{
			TotalFileCount++;
		}

		TotalFileSize += CurListData->FileSize;
		FileListCount++;
	}

	if (!(Info.Flags & OPIF_DISABLEHIGHLIGHTING) || (Info.Flags & OPIF_USEATTRHIGHLIGHTING))
		CtrlObject->HiFiles->GetHiColor(ListData,FileListCount,(Info.Flags&OPIF_USEATTRHIGHLIGHTING)!=0);

	FileCount=FileListCount;

	if ((Info.Flags & OPIF_ADDDOTS) && !DotsPresent)
	{
		ListData[FileCount] = new FileListItem;
		CurPtr = ListData[FileCount];
		CurPtr->Clear();
		AddParentPoint(CurPtr,FileCount);

		if (!(Info.Flags & OPIF_DISABLEHIGHLIGHTING) || (Info.Flags & OPIF_USEATTRHIGHLIGHTING))
			CtrlObject->HiFiles->GetHiColor(&CurPtr,1,(Info.Flags&OPIF_USEATTRHIGHLIGHTING)!=0);

		if (Info.HostFile && *Info.HostFile)
		{
			FAR_FIND_DATA_EX FindData;

			if (apiGetFindDataEx(Info.HostFile, FindData))
			{
				CurPtr->WriteTime=FindData.ftLastWriteTime;
				CurPtr->CreationTime=FindData.ftCreationTime;
				CurPtr->AccessTime=FindData.ftLastAccessTime;
				CurPtr->ChangeTime=FindData.ftChangeTime;
			}
		}

		FileCount++;
	}

	if (CurFile >= FileCount)
		CurFile = FileCount ? FileCount-1 : 0;

	/* $ 25.02.2001 VVM
	    ! Не считывать повторно список файлов с панели плагина */
	if (IsColumnDisplayed(DIZ_COLUMN))
		ReadDiz(PanelData,static_cast<int>(PluginFileCount),RDF_NO_UPDATE);

	CorrectPosition();
	CtrlObject->Plugins->FreeFindData(hPlugin,PanelData,PluginFileCount);

	if (KeepSelection || PrevSelFileCount>0)
	{
		MoveSelection(ListData,FileCount,OldData,OldFileCount);
		DeleteListData(OldData,OldFileCount);
	}

	if (!KeepSelection && PrevSelFileCount>0)
	{
		SaveSelection();
		ClearSelection();
	}

	SortFileList(FALSE);

	if (CurFile>=FileCount || StrCmpI(ListData[CurFile]->strName,strCurName))
		if (!GoToFile(strCurName) && !strNextCurName.IsEmpty())
			GoToFile(strNextCurName);

	SetTitle();
}
Exemplo n.º 16
0
bool GetVHDName(const wchar_t *DeviceName, string &strVolumePath)
{
	bool Result=false;
	if(ifn.pfnGetStorageDependencyInformation)
	{
		File Device;
		if(Device.Open(DeviceName, FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, nullptr, OPEN_EXISTING))
		{
			ULONG Size = 1024;
			PSTORAGE_DEPENDENCY_INFO StorageDependencyInfo = reinterpret_cast<PSTORAGE_DEPENDENCY_INFO>(xf_malloc(Size));
			if(StorageDependencyInfo)
			{
				StorageDependencyInfo->Version = STORAGE_DEPENDENCY_INFO_VERSION_2;
				DWORD Used = 0;
				if(!Device.GetStorageDependencyInformation(GET_STORAGE_DEPENDENCY_FLAG_HOST_VOLUMES, Size, StorageDependencyInfo, &Used) && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
				{
					StorageDependencyInfo = reinterpret_cast<PSTORAGE_DEPENDENCY_INFO>(xf_realloc(StorageDependencyInfo, Used));
					if(StorageDependencyInfo)
					{
						Device.GetStorageDependencyInformation(GET_STORAGE_DEPENDENCY_FLAG_HOST_VOLUMES, Used, StorageDependencyInfo, &Used);
					}
				}
				if(GetLastError() == ERROR_SUCCESS)
				{
					Result = true;
					if(StorageDependencyInfo->NumberEntries)
					{
						strVolumePath = StorageDependencyInfo->Version2Entries[0].HostVolumeName;
						strVolumePath += StorageDependencyInfo->Version2Entries[0].DependentVolumeRelativePath;
					}
				}
			}
		}
	}
	return Result;
}
Exemplo n.º 17
0
bool History::SaveHistory()
{
	if (!*EnableSave)
		return true;

	if (!HistoryList.Count())
	{
		DeleteRegKey(strRegKey);
		return true;
	}

	//for dialogs, locked items should show first (be last in the list)
	if (TypeHistory == HISTORYTYPE_DIALOG)
	{
		for (const HistoryRecord *HistoryItem=HistoryList.First(), *LastItem=HistoryList.Last(); HistoryItem; )
		{
			const HistoryRecord *tmp = HistoryItem;

			HistoryItem=HistoryList.Next(HistoryItem);

			if (tmp->Lock)
				HistoryList.MoveAfter(HistoryList.Last(), tmp);

			if (tmp == LastItem)
				break;
		}
	}

	wchar_t *TypesBuffer=nullptr;

	if (SaveType)
	{
		TypesBuffer=(wchar_t *)xf_malloc((HistoryList.Count()+1)*sizeof(wchar_t));

		if (!TypesBuffer)
			return false;
	}

	wchar_t *LocksBuffer=nullptr;

	if (!(LocksBuffer=(wchar_t *)xf_malloc((HistoryList.Count()+1)*sizeof(wchar_t))))
	{
		if (TypesBuffer)
			xf_free(TypesBuffer);

		return false;
	}

	FILETIME *TimesBuffer=nullptr;

	if (!(TimesBuffer=(FILETIME *)xf_malloc((HistoryList.Count()+1)*sizeof(FILETIME))))
	{
		if (LocksBuffer)
			xf_free(LocksBuffer);

		if (TypesBuffer)
			xf_free(TypesBuffer);

		return false;
	}

	memset(TimesBuffer,0,(HistoryList.Count()+1)*sizeof(FILETIME));
	wmemset(LocksBuffer,0,HistoryList.Count()+1);

	if (SaveType)
		wmemset(TypesBuffer,0,HistoryList.Count()+1);

	bool ret = false;
	HKEY hKey = nullptr;
	wchar_t *BufferLines=nullptr, *PtrBuffer;
	size_t SizeLines=0, SizeTypes=0, SizeLocks=0, SizeTimes=0;
	int Position = -1;
	size_t i=HistoryList.Count()-1;

	for (const HistoryRecord *HistoryItem=HistoryList.Last(); HistoryItem ; HistoryItem=HistoryList.Prev(HistoryItem))
	{
		if (!(PtrBuffer=(wchar_t*)xf_realloc(BufferLines,(SizeLines+HistoryItem->strName.GetLength()+2)*sizeof(wchar_t))))
		{
			ret = false;
			goto end;
		}

		BufferLines=PtrBuffer;
		xwcsncpy(BufferLines+SizeLines,HistoryItem->strName,HistoryItem->strName.GetLength()+1);
		SizeLines+=HistoryItem->strName.GetLength()+1;

		if (SaveType)
			TypesBuffer[SizeTypes++]=HistoryItem->Type+L'0';

		LocksBuffer[SizeLocks++]=HistoryItem->Lock+L'0';
		TimesBuffer[SizeTimes].dwLowDateTime=HistoryItem->Timestamp.dwLowDateTime;
		TimesBuffer[SizeTimes].dwHighDateTime=HistoryItem->Timestamp.dwHighDateTime;
		SizeTimes++;

		if (HistoryItem == CurrentItem)
			Position = static_cast<int>(i);

		i--;
	}

	hKey=CreateRegKey(strRegKey);

	if (hKey)
	{
		RegSetValueEx(hKey,L"Lines",0,REG_MULTI_SZ,(unsigned char *)BufferLines,static_cast<DWORD>(SizeLines*sizeof(wchar_t)));

		if (SaveType)
			RegSetValueEx(hKey,L"Types",0,REG_SZ,(unsigned char *)TypesBuffer,static_cast<DWORD>((SizeTypes+1)*sizeof(wchar_t)));

		RegSetValueEx(hKey,L"Locks",0,REG_SZ,(unsigned char *)LocksBuffer,static_cast<DWORD>((SizeLocks+1)*sizeof(wchar_t)));
		RegSetValueEx(hKey,L"Times",0,REG_BINARY,(unsigned char *)TimesBuffer,(DWORD)SizeTimes*sizeof(FILETIME));
		RegSetValueEx(hKey,L"Position",0,REG_DWORD,(BYTE *)&Position,sizeof(Position));
		RegCloseKey(hKey);
		ret = true;
	}

end:

	if (BufferLines)
		xf_free(BufferLines);

	if (TypesBuffer)
		xf_free(TypesBuffer);

	if (LocksBuffer)
		xf_free(LocksBuffer);

	if (TimesBuffer)
		xf_free(TimesBuffer);

	return ret;
}
Exemplo n.º 18
0
wchar_t *Clipboard::Paste()
{
    wchar_t *ClipText=nullptr;
    HANDLE hClipData=GetData(CF_UNICODETEXT);

    if (hClipData)
    {
        wchar_t *ClipAddr=(wchar_t *)GlobalLock(hClipData);

        if (ClipAddr)
        {
            int BufferSize;
            BufferSize=StrLength(ClipAddr)+1;
            ClipText=(wchar_t *)xf_malloc(BufferSize*sizeof(wchar_t));

            if (ClipText)
                wcscpy(ClipText, ClipAddr);

            GlobalUnlock(hClipData);
        }
    }
    else
    {
        hClipData=GetData(CF_HDROP);
        if (hClipData)
        {
            LPDROPFILES Files=static_cast<LPDROPFILES>(GlobalLock(hClipData));
            if (Files)
            {
                LPCSTR StartA=reinterpret_cast<LPCSTR>(Files)+Files->pFiles;
                LPCWSTR Start=reinterpret_cast<LPCWSTR>(StartA);
                string strClipText;
                if(Files->fWide)
                {
                    while(*Start)
                    {
                        size_t l1=strClipText.GetLength();
                        strClipText+=Start;
                        Start+=strClipText.GetLength()-l1;
                        Start++;
                        if(*Start)
                        {
                            strClipText+=L"\r\n";
                        }
                    }
                }
                else
                {
                    while(*StartA)
                    {
                        size_t l1=strClipText.GetLength();
                        strClipText+=StartA;
                        StartA+=strClipText.GetLength()-l1;
                        StartA++;
                        if(*StartA)
                        {
                            strClipText+=L"\r\n";
                        }
                    }
                }
                if(!strClipText.IsEmpty())
                {
                    ClipText=static_cast<LPWSTR>(xf_malloc((strClipText.GetLength()+1)*sizeof(WCHAR)));
                    wcscpy(ClipText, strClipText);
                }
                GlobalUnlock(hClipData);
            }
        }
    }
    return ClipText;
}
Exemplo n.º 19
0
void PrintFiles(Panel *SrcPanel)
{
	_ALGO(CleverSysLog clv(L"Alt-F5 (PrintFiles)"));
	string strPrinterName;
	DWORD Needed,Returned;
	int PrinterNumber;
	DWORD FileAttr;
	string strSelName;
	long DirsCount=0;
	int SelCount=SrcPanel->GetSelCount();

	if (!SelCount)
	{
		_ALGO(SysLog(L"Error: !SelCount"));
		return;
	}

	// проверка каталогов
	_ALGO(SysLog(L"Check for FILE_ATTRIBUTE_DIRECTORY"));
	SrcPanel->GetSelName(nullptr,FileAttr);

	while (SrcPanel->GetSelName(&strSelName,FileAttr))
	{
		if (TestParentFolderName(strSelName) || (FileAttr & FILE_ATTRIBUTE_DIRECTORY))
			DirsCount++;
	}

	if (DirsCount==SelCount)
		return;

	PRINTER_INFO *pi = nullptr;

	if (EnumPrinters(PRINTER_ENUM_LOCAL|PRINTER_ENUM_CONNECTIONS,nullptr,PRINTER_INFO_LEVEL,nullptr,0,&Needed,&Returned) || Needed<=0)
		return;

	pi = (PRINTER_INFO *)xf_malloc(Needed);

	if (!EnumPrinters(PRINTER_ENUM_LOCAL|PRINTER_ENUM_CONNECTIONS,nullptr,PRINTER_INFO_LEVEL,(LPBYTE)pi,Needed,&Needed,&Returned))
	{
		Message(MSG_WARNING|MSG_ERRORTYPE,1,MSG(MPrintTitle),MSG(MCannotEnumeratePrinters),MSG(MOk));
		xf_free(pi);
		return;
	}

	{
		_ALGO(CleverSysLog clv2(L"Show Menu"));
		string strTitle;
		string strName;

		if (SelCount==1)
		{
			SrcPanel->GetSelName(nullptr,FileAttr);
			SrcPanel->GetSelName(&strName,FileAttr);
			TruncStr(strName,50);
			strSelName=strName;
			InsertQuote(strSelName);
			strTitle.Format(MSG(MPrintTo), strSelName.CPtr());
		}
		else
		{
			_ALGO(SysLog(L"Correct: SelCount-=DirsCount"));
			SelCount-=DirsCount;
			strTitle.Format(MSG(MPrintFilesTo),SelCount);
		}

		VMenu PrinterList(strTitle,nullptr,0,ScrY-4);
		PrinterList.SetFlags(VMENU_WRAPMODE|VMENU_SHOWAMPERSAND);
		PrinterList.SetPosition(-1,-1,0,0);
		AddToPrintersMenu(&PrinterList,pi,Returned);
		PrinterList.Process();
		PrinterNumber=PrinterList.Modal::GetExitCode();

		if (PrinterNumber<0)
		{
			xf_free(pi);
			_ALGO(SysLog(L"ESC"));
			return;
		}

		int nSize = PrinterList.GetUserDataSize();
		wchar_t *PrinterName = strPrinterName.GetBuffer(nSize);
		PrinterList.GetUserData(PrinterName, nSize);
		strPrinterName.ReleaseBuffer();
	}

	HANDLE hPrinter;

	if (!OpenPrinter((wchar_t*)strPrinterName.CPtr(),&hPrinter,nullptr))
	{
		Message(MSG_WARNING|MSG_ERRORTYPE,1,MSG(MPrintTitle),MSG(MCannotOpenPrinter),
		        strPrinterName,MSG(MOk));
		xf_free(pi);
		_ALGO(SysLog(L"Error: Cannot Open Printer"));
		return;
	}

	{
		_ALGO(CleverSysLog clv3(L"Print selected Files"));
		//SaveScreen SaveScr;
		TPreRedrawFuncGuard preRedrawFuncGuard(PR_PrintMsg);
		SetCursorType(FALSE,0);
		PR_PrintMsg();
		HANDLE hPlugin=SrcPanel->GetPluginHandle();
		int PluginMode=SrcPanel->GetMode()==PLUGIN_PANEL &&
		               !CtrlObject->Plugins.UseFarCommand(hPlugin,PLUGIN_FARGETFILE);
		SrcPanel->GetSelName(nullptr,FileAttr);

		while (SrcPanel->GetSelName(&strSelName,FileAttr))
		{
			if (TestParentFolderName(strSelName) || (FileAttr & FILE_ATTRIBUTE_DIRECTORY))
				continue;

			int Success=FALSE;
			LPCWSTR FileName = nullptr;
			string strTempDir, strTempName;

			if (PluginMode)
			{
				if (FarMkTempEx(strTempDir))
				{
					apiCreateDirectory(strTempDir,nullptr);
					FileListItem ListItem;

					if (SrcPanel->GetLastSelectedItem(&ListItem))
					{
						PluginPanelItem PanelItem;
						FileList::FileListToPluginItem(&ListItem,&PanelItem);

						if (CtrlObject->Plugins.GetFile(hPlugin,&PanelItem,strTempDir,strTempName,OPM_SILENT))
							FileName = strTempName;
						else
							apiRemoveDirectory(strTempDir);

						FileList::FreePluginPanelItem(&PanelItem);
					}
				}
			}
			else
				FileName = strSelName;

			File SrcFile;
			if(SrcFile.Open(FileName, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, nullptr, OPEN_EXISTING))
			{
				DOC_INFO_1 di1 = {const_cast<LPWSTR>(FileName)};

				if (StartDocPrinter(hPrinter,1,(LPBYTE)&di1))
				{
					char Buffer[8192];
					DWORD Read,Written;
					Success=TRUE;

					while (SrcFile.Read(Buffer, sizeof(Buffer), Read) && Read > 0)
						if (!WritePrinter(hPrinter,Buffer,Read,&Written))
						{
							Success=FALSE;
							break;
						}

					EndDocPrinter(hPrinter);
				}
				SrcFile.Close();
			}

			if (!strTempName.IsEmpty())
			{
				DeleteFileWithFolder(strTempName);
			}

			if (Success)
				SrcPanel->ClearLastGetSelection();
			else
			{
				if (Message(MSG_WARNING|MSG_ERRORTYPE,2,MSG(MPrintTitle),MSG(MCannotPrint),
				            strSelName,MSG(MSkip),MSG(MCancel)))
					break;
			}
		}

		ClosePrinter(hPrinter);
	}

	SrcPanel->Redraw();
	xf_free(pi);
}
Exemplo n.º 20
0
//- AN ----------------------------------------------
//  Компиляция строки BufPtr в байткод CurMacroBuffer
//- AN ----------------------------------------------
int __parseMacroString(DWORD *&CurMacroBuffer, int &CurMacroBufferSize, const wchar_t *BufPtr)
{
	_KEYMACRO(CleverSysLog Clev(L"parseMacroString"));
	//_KEYMACRO(SysLog(L"BufPtr[%p]='%s'", BufPtr,BufPtr));
	_macro_nErr = 0;
	_macro_nLine= 0;
	_macro_nPos = 0;
	pSrcString = emptyString;
	inloop = 0;
	/*pSrcString = */oSrcString = sSrcString = emptyString;

	if (!BufPtr || !*BufPtr)
	{
		keyMacroParseError(err_ZeroLengthMacro);
		return FALSE;
	}

	bool useUDL=true;
	const wchar_t *NewBufPtr;

	UserDefinedList MacroSrcList(ULF_NOTRIM|ULF_NOUNQUOTE, L"\r\n");
	if(!MacroSrcList.Set(BufPtr))
		useUDL=false; // все в одну строку
	//{
	//	_SVS(SysLog(L"MacroSrcList.GetTotal()=%d",MacroSrcList.GetTotal()));
	//	while((NewBufPtr=MacroSrcList.GetNext()) )
	//		_SVS(SysLog(L"[%s]",NewBufPtr));
	//	MacroSrcList.Reset();
	//}

	size_t SizeCurKeyText = (StrLength(BufPtr)*2)*sizeof(wchar_t);
	string strCurrKeyText;
	//- AN ----------------------------------------------
	//  Буфер под парсинг выражений
	//- AN ----------------------------------------------
	DWORD *dwExprBuff = (DWORD*)xf_malloc(SizeCurKeyText*sizeof(DWORD));

	if (!dwExprBuff)
		return FALSE;

	TExec exec;
	wchar_t varName[256];
	DWORD KeyCode, *CurMacro_Buffer = nullptr;

	if(useUDL)
		BufPtr=MacroSrcList.GetNext();

	pSrcString=BufPtr;

	for (;;)
	{
		int Size = 1;
		int SizeVarName = 0;
		const wchar_t *oldBufPtr = BufPtr;

		if (!(BufPtr = __GetNextWord(BufPtr, strCurrKeyText, _macro_nLine)))
		{
			if(!useUDL)
				break;
			NewBufPtr=MacroSrcList.GetNext();
			if(!NewBufPtr)
				break;
			_macro_nLine++;
			pSrcString=BufPtr=NewBufPtr;
			continue;
		}
		_SVS(SysLog(L"_macro_nLine   = [%d]",_macro_nLine));
		_SVS(SysLog(L"BufPtr         = [%s]",BufPtr));
		_SVS(SysLog(L"pSrcString     = [%s]",pSrcString));
		_SVS(SysLog(L"strCurrKeyText = [%s]",strCurrKeyText.CPtr()));

		//- AN ----------------------------------------------
		//  Проверка на строковый литерал
		//  Сделаем $Text опциональным
		//- AN ----------------------------------------------
		if (strCurrKeyText.At(0) == L'\"' && strCurrKeyText.At(1))
		{
			KeyCode = MCODE_OP_PLAINTEXT;
			BufPtr = oldBufPtr;
		}
		else if ((KeyCode = KeyNameMacroToKey(strCurrKeyText)) == (DWORD)-1 && (KeyCode = KeyNameToKey(strCurrKeyText)) == (DWORD)-1)
		{
			int ProcError=0;

			if (strCurrKeyText.At(0) == L'%' &&
			        (
			            (IsAlphaNum(strCurrKeyText.At(1)) || strCurrKeyText.At(1) == L'_') ||
			            (
			                strCurrKeyText.At(1) == L'%' &&
			                (IsAlphaNum(strCurrKeyText.At(2)) || strCurrKeyText.At(2)==L'_')
			            )
			        )
			   )
			{
				BufPtr = oldBufPtr;

				while (*BufPtr && (IsSpace(*BufPtr) || IsEol(*BufPtr)))
				{
					if (IsEol(*BufPtr))
					{
						_macro_nLine++;//TODO!!!
					}
					BufPtr++;
				}

				ClearArray(varName);
				KeyCode = MCODE_OP_SAVE;
				wchar_t* p = varName;
				const wchar_t* s = strCurrKeyText.CPtr()+1;

				if (*s == L'%')
					*p++ = *s++;

				wchar_t ch;
				*p++ = *s++;

				while ((iswalnum(ch = *s++) || (ch == L'_')))
					*p++ = ch;

				*p = 0;
				size_t Length = (StrLength(varName)+1)*sizeof(wchar_t);
				// строка должна быть выровнена на 4
				SizeVarName = static_cast<int>(Length/sizeof(DWORD));

				if (Length == sizeof(wchar_t) || (Length % sizeof(DWORD)) )    // дополнение до sizeof(DWORD) нулями.
					SizeVarName++;

				_SVS(SysLog(L"BufPtr=%s",BufPtr));
				BufPtr += Length/sizeof(wchar_t);
				_SVS(SysLog(L"BufPtr=%s",BufPtr));
				Size += parseExpr(BufPtr, dwExprBuff, L'=', L';');

				if (_macro_nErr)
				{
					ProcError++;
				}
			}
			else
			{
				// проверим вариант, когда вызвали функцию, но результат не присвоили,
				// например, вызвали MsgBox(), но результат неважен
				// тогда SizeVarName=1 и varName=""
				wchar_t *lpwszCurrKeyText = strCurrKeyText.GetBuffer();
				wchar_t *Brack=(wchar_t *)wcspbrk(lpwszCurrKeyText,L"( "), Chr=0;

				if (Brack)
				{
					Chr=*Brack;
					*Brack=0;
				}

				if (funcLook(lpwszCurrKeyText) != MCODE_F_NOFUNC)
				{
					if (Brack) *Brack=Chr;

					BufPtr = oldBufPtr;

					while (*BufPtr && (IsSpace(*BufPtr) || IsEol(*BufPtr)))
					{
						if (IsEol(*BufPtr))
						{
							_macro_nLine++;//TODO!!!
						}
						BufPtr++;
					}

					Size += parseExpr(BufPtr, dwExprBuff, 0, 0);

					/*
					// этого пока ненадо, считаем, что ';' идет сразу за функцией, иначе это отдельный символ ';', который нужно поместить в поток
					while ( *BufPtr && (IsSpace(*BufPtr) || IsEol(*BufPtr)) )
					{
						if (IsEol(*BufPtr))
						{
							_macro_nLine++;//TODO!!!
						}
						BufPtr++;
					}
					*/
					if (*BufPtr == L';')
						BufPtr++; // здесь Size не увеличиваем, т.к. мы прокидываем символ ';'

					//Size--; //???
					if (_macro_nErr)
					{
						ProcError++;
					}
					else
					{
						KeyCode=MCODE_OP_SAVE;
						SizeVarName=1;
						ClearArray(varName);
					}
				}
				else
				{
					if (Brack) *Brack=Chr;

					ProcError++;
				}

				strCurrKeyText.ReleaseBuffer();
			}

			if (ProcError)
			{
				if (!_macro_nErr)
					//keyMacroParseError(err_Unrecognized_keyword, strCurrKeyText, strCurrKeyText,strCurrKeyText);
					keyMacroParseError(err_Unrecognized_keyword, oldBufPtr, pSrcString, strCurrKeyText);

				if (CurMacro_Buffer )
				{
					xf_free(CurMacro_Buffer);
					CurMacroBuffer = nullptr;
				}

				CurMacroBufferSize = 0;
				xf_free(dwExprBuff);
				return FALSE;
			}
		}
		else if (!(strCurrKeyText.At(0) == L'$' && strCurrKeyText.At(1)))
		{
			Size=3;
			KeyCode=MCODE_OP_KEYS;
		}

		switch (KeyCode)
		{
			// $Text
			// -------------------------------------
			//            MCODE_OP_PLAINTEXT
			//            <expr>
			case MCODE_OP_PLAINTEXT:
			{
				Size += parseExpr(BufPtr, dwExprBuff, 0, 0);
				break;
			}
			// $If (expr) ... $End
			// -------------------------------------
			//            <expr>
			//            MCODE_OP_JZ                     p1=*+0
			//            addr1        ------------+
			//            ...                      |
			//            MCODE_OP_JMP             |
			// +--------- addr2                    |
			// |          ...          <-----------+
			// +--------> MCODE_OP_END
			// или
			//            <expr>
			//            MCODE_OP_JZ                     p1=*+0
			//            addr1        ------------+
			//            ...                      |
			//            MCODE_OP_END <-----------+
			case MCODE_OP_IF:
			{
				Size += parseExpr(BufPtr, dwExprBuff, L'(', L')');

				if (!exec.add(emmThen, CurMacroBufferSize+Size))
				{
					if (CurMacro_Buffer )
					{
						xf_free(CurMacro_Buffer);
						CurMacroBuffer = nullptr;
					}

					CurMacroBufferSize = 0;
					xf_free(dwExprBuff);
					return FALSE;
				}

				Size++;
				break;
			}
			case MCODE_OP_ELSE:
			{
				Size++;
				break;
			}
			// $Rep (expr) ... $End
			// -------------------------------------
			//            <expr>
			//            MCODE_OP_SAVEREPCOUNT       1
			// +--------> MCODE_OP_REP                    p1=*
			// |          <counter>                   3
			// |          <counter>                   4
			// |          MCODE_OP_JZ                 5   p2=*+2
			// |          addr1        ------------+
			// |          ...                      |
			// |          MCODE_OP_JMP             |
			// +--------- addr2                    |
			//            MCODE_OP_END <-----------+
			case MCODE_OP_REP:
			{
				inloop++;
				Size += parseExpr(BufPtr, dwExprBuff, L'(', L')');

				if (!exec.add(emmRep, CurMacroBufferSize+Size, CurMacroBufferSize+Size+4))   //??? 3
				{
					if (CurMacro_Buffer )
					{
						xf_free(CurMacro_Buffer);
						CurMacroBuffer = nullptr;
					}

					CurMacroBufferSize = 0;
					xf_free(dwExprBuff);
					return FALSE;
				}

				Size += 5;  // естественно, размер будет больше = 4
				break;
			}
			// $While (expr) ... $End
			// -------------------------------------
			// +--------> <expr>
			// |          MCODE_OP_JZ                    CurMacroBufferSize + Size - 2
			// |          addr1        ------------+     CurMacroBufferSize + Size - 1
			// |          ...                      |     ...
			// |          MCODE_OP_JMP             |     CurMacroBufferSize + Size - 3
			// +--------- addr2                    |     CurMacroBufferSize + Size - 2
			//            MCODE_OP_END <-----------+     CurMacroBufferSize + Size - 1
			//                                           CurMacroBufferSize + Size
			case MCODE_OP_WHILE:
			{
				inloop++;
				Size += parseExpr(BufPtr, dwExprBuff, L'(', L')');

				if (!exec.add(emmWhile, CurMacroBufferSize, CurMacroBufferSize+Size))
				{
					if (CurMacro_Buffer )
					{
						xf_free(CurMacro_Buffer);
						CurMacroBuffer = nullptr;
					}

					CurMacroBufferSize = 0;
					xf_free(dwExprBuff);
					return FALSE;
				}

				Size++;
				break;
			}
			// $continue
			// -------------------------------------
			// ^          MCODE_OP_CONTINUE
			// |          MCODE_OP_JMP
			// +--------- addr
			case MCODE_OP_CONTINUE:
			{
				Size++; // Место под адрес
				break;
			}
			// $break
			// -------------------------------------
			//            MCODE_OP_BREAK
			//            MCODE_OP_JMP
			//            addr -->
			case MCODE_OP_BREAK:
			{
				Size++; // Место под адрес
				break;
			}
			case MCODE_OP_END:
			{
				switch (exec().state)
				{
					case emmRep:
					case emmWhile:
						Size += 2; // Место под дополнительный JMP
						break;
					default:
						break;
				}

				break;
			}
		}

		if (_macro_nErr)
		{
			if (CurMacro_Buffer )
			{
				xf_free(CurMacro_Buffer);
				CurMacroBuffer = nullptr;
			}

			CurMacroBufferSize = 0;
			xf_free(dwExprBuff);
			return FALSE;
		}

		if (!BufPtr)   // ???
			break;

		// код найден, добавим этот код в буфер последовательности.
		CurMacro_Buffer = (DWORD *)xf_realloc(CurMacro_Buffer,sizeof(*CurMacro_Buffer)*(CurMacroBufferSize+Size+SizeVarName));

		if (!CurMacro_Buffer)
		{
			CurMacroBuffer = nullptr;
			CurMacroBufferSize = 0;
			xf_free(dwExprBuff);
			return FALSE;
		}

		switch (KeyCode)
		{
			case MCODE_OP_PLAINTEXT:
			{
				_SVS(SysLog(L"[%d] Size=%u",__LINE__,Size));
				memcpy(CurMacro_Buffer+CurMacroBufferSize, dwExprBuff, Size*sizeof(DWORD));
				CurMacro_Buffer[CurMacroBufferSize+Size-1] = KeyCode;
				break;
			}
			case MCODE_OP_SAVE:
			{
				memcpy(CurMacro_Buffer+CurMacroBufferSize, dwExprBuff, Size*sizeof(DWORD));
				CurMacro_Buffer[CurMacroBufferSize+Size-1] = KeyCode;
				memcpy(CurMacro_Buffer+CurMacroBufferSize+Size, varName, SizeVarName*sizeof(DWORD));
				break;
			}
			case MCODE_OP_IF:
			{
				memcpy(CurMacro_Buffer+CurMacroBufferSize, dwExprBuff, Size*sizeof(DWORD));
				CurMacro_Buffer[CurMacroBufferSize+Size-2] = MCODE_OP_JZ;
				break;
			}
			case MCODE_OP_REP:
			{
				memcpy(CurMacro_Buffer+CurMacroBufferSize, dwExprBuff, Size*sizeof(DWORD));
				CurMacro_Buffer[CurMacroBufferSize+Size-6] = MCODE_OP_SAVEREPCOUNT;
				CurMacro_Buffer[CurMacroBufferSize+Size-5] = KeyCode;
				CurMacro_Buffer[CurMacroBufferSize+Size-4] = 0; // Initilize 0
				CurMacro_Buffer[CurMacroBufferSize+Size-3] = 0;
				CurMacro_Buffer[CurMacroBufferSize+Size-2] = MCODE_OP_JZ;
				break;
			}
			case MCODE_OP_WHILE:
			{
				memcpy(CurMacro_Buffer+CurMacroBufferSize, dwExprBuff, Size*sizeof(DWORD));
				CurMacro_Buffer[CurMacroBufferSize+Size-2] = MCODE_OP_JZ;
				break;
			}
			case MCODE_OP_ELSE:
			{
				if (exec().state == emmThen)
				{
					exec().state = emmElse;
					CurMacro_Buffer[exec().pos1] = CurMacroBufferSize+2;
					exec().pos1 = CurMacroBufferSize;
					CurMacro_Buffer[CurMacroBufferSize] = 0;
				}
				else // тут $else и не предвиделось :-/
				{
					keyMacroParseError(err_Not_expected_ELSE, BufPtr, pSrcString); // strCurrKeyText

					if (CurMacro_Buffer )
					{
						xf_free(CurMacro_Buffer);
						CurMacroBuffer = nullptr;
					}

					CurMacroBufferSize = 0;
					xf_free(dwExprBuff);
					return FALSE;
				}

				break;
			}
			case MCODE_OP_BREAK:
			case MCODE_OP_CONTINUE:
			{
				TExecItem *ei=nullptr;
				if (!inloop || (KeyCode==MCODE_OP_CONTINUE && exec.findnearloop(&ei) == -1))
				{
					keyMacroParseError(KeyCode==MCODE_OP_CONTINUE?err_Continue_Outside_The_Loop:err_Break_Outside_The_Loop, oldBufPtr, pSrcString);//BufPtr, pSrcString); // strCurrKeyText

					if (CurMacro_Buffer )
					{
						xf_free(CurMacro_Buffer);
						CurMacroBuffer = nullptr;
					}

					CurMacroBufferSize = 0;
					xf_free(dwExprBuff);
					return FALSE;
				}
				CurMacro_Buffer[CurMacroBufferSize+Size-2] = KeyCode==MCODE_OP_CONTINUE?MCODE_OP_JMP:MCODE_OP_BREAK;
				CurMacro_Buffer[CurMacroBufferSize+Size-1] = KeyCode==MCODE_OP_CONTINUE?ei->pos1:0;
				break;
			}
			case MCODE_OP_END:
			{
				switch (exec().state)
				{
					case emmMain:
						// тут $end и не предвиделось :-/
						keyMacroParseError(err_Not_expected_END, BufPtr, pSrcString); // strCurrKeyText

						if (CurMacro_Buffer )
						{
							xf_free(CurMacro_Buffer);
							CurMacroBuffer = nullptr;
						}

						CurMacroBufferSize = 0;
						xf_free(dwExprBuff);
						return FALSE;
					case emmThen:
						CurMacro_Buffer[exec().pos1-1] = MCODE_OP_JZ;
						CurMacro_Buffer[exec().pos1+0] = CurMacroBufferSize+Size-1;
						CurMacro_Buffer[CurMacroBufferSize+Size-1] = KeyCode;
						break;
					case emmElse:
						CurMacro_Buffer[exec().pos1-0] = MCODE_OP_JMP;
						CurMacro_Buffer[exec().pos1+1] = CurMacroBufferSize+Size-1;
						CurMacro_Buffer[CurMacroBufferSize+Size-1] = KeyCode;
						break;
					case emmRep:
					case emmWhile:
						inloop--;
						CurMacro_Buffer[exec().pos2] = CurMacroBufferSize+Size-1;
						CurMacro_Buffer[CurMacroBufferSize+Size-3] = MCODE_OP_JMP;
						CurMacro_Buffer[CurMacroBufferSize+Size-2] = exec().pos1;
						CurMacro_Buffer[CurMacroBufferSize+Size-1] = KeyCode;
						CorrectBreakCode(CurMacro_Buffer,CurMacro_Buffer+exec().pos1,CurMacro_Buffer+(CurMacroBufferSize+Size-1));
						break;
				}

				if (!exec.del())    // Вообще-то этого быть не должно,  но подстрахуемся
				{
					if (CurMacro_Buffer )
					{
						xf_free(CurMacro_Buffer);
						CurMacroBuffer = nullptr;
					}

					CurMacroBufferSize = 0;
					xf_free(dwExprBuff);
					return FALSE;
				}

				break;
			}
			case MCODE_OP_KEYS:
			{
				CurMacro_Buffer[CurMacroBufferSize+Size-3]=MCODE_OP_KEYS;
				CurMacro_Buffer[CurMacroBufferSize+Size-2]=KeyNameToKey(strCurrKeyText);
				CurMacro_Buffer[CurMacroBufferSize+Size-1]=MCODE_OP_ENDKEYS;
				break;
			}
			default:
				CurMacro_Buffer[CurMacroBufferSize]=KeyCode;
		} // end switch(KeyCode)

		CurMacroBufferSize += Size+SizeVarName;
	} // END for (;;)

	if (CurMacroBufferSize == 1)
	{
		CurMacro_Buffer = (DWORD *)xf_realloc(CurMacro_Buffer,sizeof(*CurMacro_Buffer)*(CurMacroBufferSize+1));

		if (!CurMacro_Buffer)
		{
			CurMacroBuffer = nullptr;
			CurMacroBufferSize = 0;
			xf_free(dwExprBuff);
			return FALSE;
		}

		CurMacro_Buffer[CurMacroBufferSize]=MCODE_OP_NOP;
		CurMacroBufferSize++;
	}

#ifdef _DEBUG
#ifdef SYSLOG_KEYMACRO
	SysLogDump(L"Macro Buffer",0,(LPBYTE)CurMacro_Buffer,CurMacroBufferSize*sizeof(DWORD),nullptr);
	SysLog(L"<ByteCode>{");

	if (CurMacro_Buffer)
	{
		int ii;

		for (ii = 0 ; ii < CurMacroBufferSize ; ii++)
			printKeyValue(CurMacro_Buffer, ii);
	}
	else
		SysLog(L"??? is nullptr");

	SysLog(L"}</ByteCode>");
#endif
#endif

	if (CurMacroBufferSize > 1)
		CurMacroBuffer = CurMacro_Buffer;
	else if (CurMacro_Buffer)
	{
		CurMacroBuffer = reinterpret_cast<DWORD*>((intptr_t)(*CurMacro_Buffer));
		xf_free(CurMacro_Buffer);
	}

	xf_free(dwExprBuff);

	if (exec().state != emmMain)
	{
		keyMacroParseError(err_Unexpected_EOS, strCurrKeyText, strCurrKeyText);
		return FALSE;
	}

	if (_macro_nErr)
	{
		return FALSE;
	}

	return TRUE;
}
Exemplo n.º 21
0
intptr_t WINAPI FileFilterConfigDlgProc(HANDLE hDlg,intptr_t Msg,intptr_t Param1,void* Param2)
{
    switch (Msg)
    {
    case DN_INITDIALOG:
    {
        FilterDlgRelativeDateItemsUpdate(hDlg, false);
        return TRUE;
    }
    case DN_BTNCLICK:
    {
        if (Param1==ID_FF_CURRENT || Param1==ID_FF_BLANK) //Current и Blank
        {
            FILETIME ft;
            string strDate, strTime;

            if (Param1==ID_FF_CURRENT)
            {
                GetSystemTimeAsFileTime(&ft);
                ConvertDate(ft,strDate,strTime,12,FALSE,FALSE,2);
            }
            else
            {
                strDate.Clear();
                strTime.Clear();
            }

            SendDlgMessage(hDlg,DM_ENABLEREDRAW,FALSE,0);
            int relative = (int)SendDlgMessage(hDlg,DM_GETCHECK,ID_FF_DATERELATIVE,0);
            int db = relative ? ID_FF_DAYSBEFOREEDIT : ID_FF_DATEBEFOREEDIT;
            int da = relative ? ID_FF_DAYSAFTEREDIT  : ID_FF_DATEAFTEREDIT;
            SendDlgMessage(hDlg,DM_SETTEXTPTR,da,const_cast<wchar_t*>(strDate.CPtr()));
            SendDlgMessage(hDlg,DM_SETTEXTPTR,ID_FF_TIMEAFTEREDIT,const_cast<wchar_t*>(strTime.CPtr()));
            SendDlgMessage(hDlg,DM_SETTEXTPTR,db,const_cast<wchar_t*>(strDate.CPtr()));
            SendDlgMessage(hDlg,DM_SETTEXTPTR,ID_FF_TIMEBEFOREEDIT,const_cast<wchar_t*>(strTime.CPtr()));
            SendDlgMessage(hDlg,DM_SETFOCUS,da,0);
            COORD r;
            r.X=r.Y=0;
            SendDlgMessage(hDlg,DM_SETCURSORPOS,da,&r);
            SendDlgMessage(hDlg,DM_ENABLEREDRAW,TRUE,0);
            break;
        }
        else if (Param1==ID_FF_RESET) // Reset
        {
            SendDlgMessage(hDlg,DM_ENABLEREDRAW,FALSE,0);
            intptr_t ColorConfig = SendDlgMessage(hDlg, DM_GETDLGDATA, 0, 0);
            SendDlgMessage(hDlg,DM_SETTEXTPTR,ID_FF_MASKEDIT,const_cast<wchar_t*>(L"*"));
            SendDlgMessage(hDlg,DM_SETTEXTPTR,ID_FF_SIZEFROMEDIT,nullptr);
            SendDlgMessage(hDlg,DM_SETTEXTPTR,ID_FF_SIZETOEDIT,nullptr);

            for (int I=ID_FF_READONLY; I <= ID_FF_VIRTUAL; ++I)
            {
                SendDlgMessage(hDlg,DM_SETCHECK,I,ToPtr(BSTATE_3STATE));
            }

            if (!ColorConfig)
                SendDlgMessage(hDlg,DM_SETCHECK,ID_FF_DIRECTORY,ToPtr(BSTATE_UNCHECKED));

            FarListPos LPos= {sizeof(FarListPos)};
            SendDlgMessage(hDlg,DM_LISTSETCURPOS,ID_FF_DATETYPE,&LPos);
            SendDlgMessage(hDlg,DM_SETCHECK,ID_FF_MATCHMASK,ToPtr(BSTATE_CHECKED));
            SendDlgMessage(hDlg,DM_SETCHECK,ID_FF_MATCHSIZE,ToPtr(BSTATE_UNCHECKED));
            SendDlgMessage(hDlg,DM_SETCHECK,ID_FF_HARDLINKS,ToPtr(BSTATE_UNCHECKED));
            SendDlgMessage(hDlg,DM_SETCHECK,ID_FF_MATCHDATE,ToPtr(BSTATE_UNCHECKED));
            SendDlgMessage(hDlg,DM_SETCHECK,ID_FF_DATERELATIVE,ToPtr(BSTATE_UNCHECKED));
            FilterDlgRelativeDateItemsUpdate(hDlg, true);
            SendDlgMessage(hDlg,DM_SETCHECK,ID_FF_MATCHATTRIBUTES,ToPtr(ColorConfig?BSTATE_UNCHECKED:BSTATE_CHECKED));
            SendDlgMessage(hDlg,DM_ENABLEREDRAW,TRUE,0);
            break;
        }
        else if (Param1==ID_FF_MAKETRANSPARENT)
        {
            HighlightDataColor *Colors = (HighlightDataColor *) SendDlgMessage(hDlg, DM_GETDLGDATA, 0, 0);

            for (int i=0; i<2; i++)
                for (int j=0; j<4; j++)
                {
                    MAKE_TRANSPARENT(Colors->Color[i][j].ForegroundColor);
                    MAKE_TRANSPARENT(Colors->Color[i][j].BackgroundColor);
                }

            SendDlgMessage(hDlg,DM_SETCHECK,ID_HER_MARKTRANSPARENT,ToPtr(BSTATE_CHECKED));
            break;
        }
        else if (Param1==ID_FF_DATERELATIVE)
        {
            FilterDlgRelativeDateItemsUpdate(hDlg, true);
            break;
        }
    }
    case DN_CONTROLINPUT:

        if ((Msg==DN_BTNCLICK && Param1 >= ID_HER_NORMALFILE && Param1 <= ID_HER_SELECTEDCURSORMARKING)
                || (Msg==DN_CONTROLINPUT && Param1==ID_HER_COLOREXAMPLE && ((INPUT_RECORD *)Param2)->EventType == MOUSE_EVENT && ((INPUT_RECORD *)Param2)->Event.MouseEvent.dwButtonState==FROM_LEFT_1ST_BUTTON_PRESSED))
        {
            HighlightDataColor *EditData = (HighlightDataColor *) SendDlgMessage(hDlg, DM_GETDLGDATA, 0, 0);

            if (Msg==DN_CONTROLINPUT)
            {
                Param1 = ID_HER_NORMALFILE + ((INPUT_RECORD *)Param2)->Event.MouseEvent.dwMousePosition.Y*2;

                if (((INPUT_RECORD *)Param2)->Event.MouseEvent.dwMousePosition.X==1 && (EditData->MarkChar&0x0000FFFF))
                    Param1 = ID_HER_NORMALMARKING + ((INPUT_RECORD *)Param2)->Event.MouseEvent.dwMousePosition.Y*2;
            }

            //Color[0=file, 1=mark][0=normal,1=selected,2=undercursor,3=selectedundercursor]
            FarColor Color=EditData->Color[(Param1-ID_HER_NORMALFILE)&1][(Param1-ID_HER_NORMALFILE)/2];
            Global->Console->GetColorDialog(Color,true,true);
            EditData->Color[(Param1-ID_HER_NORMALFILE)&1][(Param1-ID_HER_NORMALFILE)/2]=Color;

            size_t Size = SendDlgMessage(hDlg,DM_GETDLGITEM,ID_HER_COLOREXAMPLE,0);
            FarGetDialogItem gdi = {sizeof(FarGetDialogItem), Size, static_cast<FarDialogItem*>(xf_malloc(Size))};
            SendDlgMessage(hDlg,DM_GETDLGITEM,ID_HER_COLOREXAMPLE,&gdi);
            //MarkChar это FIXEDIT размером в 1 символ
            wchar_t MarkChar[2];
            FarDialogItemData item= {sizeof(FarDialogItemData),1,MarkChar};
            SendDlgMessage(hDlg,DM_GETTEXT,ID_HER_MARKEDIT,&item);
            EditData->MarkChar=*MarkChar;
            HighlightDlgUpdateUserControl(gdi.Item->VBuf,*EditData);
            SendDlgMessage(hDlg,DM_SETDLGITEM,ID_HER_COLOREXAMPLE,gdi.Item);
            xf_free(gdi.Item);
            return TRUE;
        }

        break;
    case DN_EDITCHANGE:

        if (Param1 == ID_HER_MARKEDIT)
        {
            HighlightDataColor *EditData = (HighlightDataColor *) SendDlgMessage(hDlg, DM_GETDLGDATA, 0, 0);
            size_t Size = SendDlgMessage(hDlg,DM_GETDLGITEM,ID_HER_COLOREXAMPLE,0);
            FarGetDialogItem gdi = {sizeof(FarGetDialogItem), Size, static_cast<FarDialogItem*>(xf_malloc(Size))};
            SendDlgMessage(hDlg,DM_GETDLGITEM,ID_HER_COLOREXAMPLE,&gdi);
            //MarkChar это FIXEDIT размером в 1 символ
            wchar_t MarkChar[2];
            FarDialogItemData item= {sizeof(FarDialogItemData),1,MarkChar};
            SendDlgMessage(hDlg,DM_GETTEXT,ID_HER_MARKEDIT,&item);
            EditData->MarkChar=*MarkChar;
            HighlightDlgUpdateUserControl(gdi.Item->VBuf,*EditData);
            SendDlgMessage(hDlg,DM_SETDLGITEM,ID_HER_COLOREXAMPLE,gdi.Item);
            xf_free(gdi.Item);
            return TRUE;
        }

        break;
    case DN_CLOSE:

        if (Param1 == ID_FF_OK && SendDlgMessage(hDlg,DM_GETCHECK,ID_FF_MATCHSIZE,0))
        {
            string strTemp;
            FarDialogItemData item = {sizeof(FarDialogItemData)};
            item.PtrLength = SendDlgMessage(hDlg,DM_GETTEXT,ID_FF_SIZEFROMEDIT,0);
            item.PtrData = strTemp.GetBuffer(item.PtrLength+1);
            SendDlgMessage(hDlg,DM_GETTEXT,ID_FF_SIZEFROMEDIT,&item);
            bool bTemp = !*item.PtrData || CheckFileSizeStringFormat(item.PtrData);
            item.PtrLength = SendDlgMessage(hDlg,DM_GETTEXT,ID_FF_SIZETOEDIT,0);
            item.PtrData = strTemp.GetBuffer(item.PtrLength+1);
            SendDlgMessage(hDlg,DM_GETTEXT,ID_FF_SIZETOEDIT,&item);
            bTemp = bTemp && (!*item.PtrData || CheckFileSizeStringFormat(item.PtrData));

            if (!bTemp)
            {
                intptr_t ColorConfig = SendDlgMessage(hDlg, DM_GETDLGDATA, 0, 0);
                Message(MSG_WARNING,1,ColorConfig?MSG(MFileHilightTitle):MSG(MFileFilterTitle),MSG(MBadFileSizeFormat),MSG(MOk));
                return FALSE;
            }
        }

        break;
    default:
        break;
    }

    return DefDlgProc(hDlg,Msg,Param1,Param2);
}
Exemplo n.º 22
0
// На основе имени файла (Src) и маски (Dest) генерируем новое имя
// SelectedFolderNameLength - длина каталога. Например, есть
// каталог dir1, а в нем файл file1. Нужно сгенерировать имя по маске для dir1.
// Параметры могут быть следующими: Src="dir1", SelectedFolderNameLength=0
// или Src="dir1\\file1", а SelectedFolderNameLength=4 (длина "dir1")
int ConvertWildcards(const wchar_t *SrcName, string &strDest, int SelectedFolderNameLength)
{
	string strPartAfterFolderName;
	string strSrc = SrcName;
	wchar_t *DestName = strDest.GetBuffer(strDest.GetLength()+strSrc.GetLength()+1);  //???
	wchar_t *DestNamePtr = (wchar_t*)PointToName(DestName);
	string strWildName = DestNamePtr;

	if (!wcschr(strWildName, L'*') && !wcschr(strWildName, L'?'))
	{
		//strDest.ReleaseBuffer (); не надо так как строка не поменялась
		return FALSE;
	}

	if (SelectedFolderNameLength)
	{
		strPartAfterFolderName = ((const wchar_t *)strSrc+SelectedFolderNameLength);
		strSrc.SetLength(SelectedFolderNameLength);
	}

	const wchar_t *Src = strSrc;

	const wchar_t *SrcNamePtr = PointToName(Src);

	int BeforeNameLength = DestNamePtr==DestName ? (int)(SrcNamePtr-Src) : 0;

	wchar_t *PartBeforeName = (wchar_t*)xf_malloc((BeforeNameLength+1)*sizeof(wchar_t));

	xwcsncpy(PartBeforeName, Src, BeforeNameLength+1);

	const wchar_t *SrcNameDot = wcsrchr(SrcNamePtr, L'.');

	const wchar_t *CurWildPtr = strWildName;

	while (*CurWildPtr)
	{
		switch (*CurWildPtr)
		{
			case L'?':
				CurWildPtr++;

				if (*SrcNamePtr)
					*(DestNamePtr++)=*(SrcNamePtr++);

				break;
			case L'*':
				CurWildPtr++;

				while (*SrcNamePtr)
				{
					if (*CurWildPtr==L'.' && SrcNameDot && !wcschr(CurWildPtr+1,L'.'))
					{
						if (SrcNamePtr==SrcNameDot)
							break;
					}
					else if (*SrcNamePtr==*CurWildPtr)
					{
						break;
					}

					*(DestNamePtr++)=*(SrcNamePtr++);
				}

				break;
			case L'.':
				CurWildPtr++;
				*(DestNamePtr++)=L'.';

				if (wcspbrk(CurWildPtr,L"*?"))
					while (*SrcNamePtr)
						if (*(SrcNamePtr++)==L'.')
							break;

				break;
			default:
				*(DestNamePtr++)=*(CurWildPtr++);

				if (*SrcNamePtr && *SrcNamePtr!=L'.')
					SrcNamePtr++;

				break;
		}
	}

	*DestNamePtr=0;

	if (DestNamePtr!=DestName && *(DestNamePtr-1)==L'.')
		*(DestNamePtr-1)=0;

	strDest.ReleaseBuffer();

	if (*PartBeforeName)
		strDest = PartBeforeName+strDest;

	if (SelectedFolderNameLength)
		strDest += strPartAfterFolderName; //BUGBUG???, was src in 1.7x

	xf_free(PartBeforeName);
	return TRUE;
}
Exemplo n.º 23
0
	TreeItem()
	{
		LastCount=MAX_PATH/2;
		Last=static_cast<int*>(xf_malloc(LastCount*sizeof(*Last)));
		Clear();
	}
Exemplo n.º 24
0
string& WINAPI FarFormatText(const wchar_t *SrcText,     // источник
                             int Width,               // заданная ширина
                             string &strDestText,          // приемник
                             const wchar_t* Break,       // брик, если = nullptr, то принимается '\n'
                             DWORD Flags)             // один из FFTM_*
{
	const wchar_t *breakchar;
	breakchar = Break?Break:L"\n";

	if (!SrcText || !*SrcText)
	{
		strDestText.Clear();
		return strDestText;
	}

	string strSrc = SrcText; //copy string in case of SrcText == strDestText

	if (!wcspbrk(strSrc,breakchar) && strSrc.GetLength() <= static_cast<size_t>(Width))
	{
		strDestText = strSrc;
		return strDestText;
	}

	long i=0, l=0, pgr=0, last=0;
	wchar_t *newtext;
	const wchar_t *text= strSrc;
	long linelength = Width;
	int breakcharlen = StrLength(breakchar);
	int docut = Flags&FFTM_BREAKLONGWORD?1:0;
	/* Special case for a single-character break as it needs no
	   additional storage space */

	if (breakcharlen == 1 && !docut)
	{
		newtext = xf_wcsdup(text);

		if (!newtext)
		{
			strDestText.Clear();
			return strDestText;
		}

		while (newtext[i] != L'\0')
		{
			/* prescan line to see if it is greater than linelength */
			l = 0;

			while (newtext[i+l] != breakchar[0])
			{
				if (newtext[i+l] == L'\0')
				{
					l--;
					break;
				}

				l++;
			}

			if (l >= linelength)
			{
				pgr = l;
				l = linelength;

				/* needs breaking; work backwards to find previous word */
				while (l >= 0)
				{
					if (newtext[i+l] == L' ')
					{
						newtext[i+l] = breakchar[0];
						break;
					}

					l--;
				}

				if (l == -1)
				{
					/* couldn't break is backwards, try looking forwards */
					l = linelength;

					while (l <= pgr)
					{
						if (newtext[i+l] == L' ')
						{
							newtext[i+l] = breakchar[0];
							break;
						}

						l++;
					}
				}
			}

			i += l+1;
		}
	}
	else
	{
		/* Multiple character line break */
		newtext = (wchar_t*)xf_malloc((strSrc.GetLength() * (breakcharlen+1)+1)*sizeof(wchar_t));

		if (!newtext)
		{
			strDestText.Clear();
			return strDestText;
		}

		newtext[0] = L'\0';
		i = 0;

		while (text[i] != L'\0')
		{
			/* prescan line to see if it is greater than linelength */
			l = 0;

			while (text[i+l] != L'\0')
			{
				if (text[i+l] == breakchar[0])
				{
					if (breakcharlen == 1 || !StrCmpN(text+i+l, breakchar, breakcharlen))
						break;
				}

				l++;
			}

			if (l >= linelength)
			{
				pgr = l;
				l = linelength;

				/* needs breaking; work backwards to find previous word */
				while (l >= 0)
				{
					if (text[i+l] == L' ')
					{
						wcsncat(newtext, text+last, i+l-last);
						wcscat(newtext, breakchar);
						last = i + l + 1;
						break;
					}

					l--;
				}

				if (l == -1)
				{
					/* couldn't break it backwards, try looking forwards */
					l = linelength - 1;

					while (l <= pgr)
					{
						if (!docut)
						{
							if (text[i+l] == L' ')
							{
								wcsncat(newtext, text+last, i+l-last);
								wcscat(newtext, breakchar);
								last = i + l + 1;
								break;
							}
						}

						if (docut == 1)
						{
							if (text[i+l] == L' ' || l > i-last)
							{
								wcsncat(newtext, text+last, i+l-last+1);
								wcscat(newtext, breakchar);
								last = i + l + 1;
								break;
							}
						}

						l++;
					}
				}

				i += l+1;
			}
			else
			{
				i += (l ? l : 1);
			}
		}

		if (i+l > last)
		{
			wcscat(newtext, text+last);
		}
	}

	strDestText = newtext;
	xf_free(newtext);
	return strDestText;
}
Exemplo n.º 25
0
bool OldGetFileFormat(FILE *file, UINT &nCodePage, bool *pSignatureFound, bool bUseHeuristics)
{
    DWORD dwTemp=0;
    bool bSignatureFound = false;
    bool bDetect=false;

    if (fread(&dwTemp, 1, 4, file))
    {
        if (LOWORD(dwTemp) == SIGN_UNICODE)
        {
            nCodePage = CP_UNICODE;
            fseek(file, 2, SEEK_SET);
            bSignatureFound = true;
        }
        else if (LOWORD(dwTemp) == SIGN_REVERSEBOM)
        {
            nCodePage = CP_REVERSEBOM;
            fseek(file, 2, SEEK_SET);
            bSignatureFound = true;
        }
        else if ((dwTemp & 0x00FFFFFF) == SIGN_UTF8)
        {
            nCodePage = CP_UTF8;
            fseek(file, 3, SEEK_SET);
            bSignatureFound = true;
        }
        else
            fseek(file, 0, SEEK_SET);
    }

    if (bSignatureFound)
    {
        bDetect = true;
    }
    else if (bUseHeuristics)
    {
        fseek(file, 0, SEEK_SET);
        size_t sz=0x8000; // BUGBUG. TODO: configurable
        LPVOID Buffer=xf_malloc(sz);
        sz=fread(Buffer,1,sz,file);
        fseek(file,0,SEEK_SET);

        if (sz)
        {
            int test=
                IS_TEXT_UNICODE_STATISTICS|
                IS_TEXT_UNICODE_REVERSE_STATISTICS|
                IS_TEXT_UNICODE_CONTROLS|
                IS_TEXT_UNICODE_REVERSE_CONTROLS|
                IS_TEXT_UNICODE_ILLEGAL_CHARS|
                IS_TEXT_UNICODE_ODD_LENGTH|
                IS_TEXT_UNICODE_NULL_BYTES;

            if (IsTextUnicode(Buffer, (int)sz, &test))
            {
                if (!(test&IS_TEXT_UNICODE_ODD_LENGTH) && !(test&IS_TEXT_UNICODE_ILLEGAL_CHARS))
                {
                    if ((test&IS_TEXT_UNICODE_NULL_BYTES) ||
                            (test&IS_TEXT_UNICODE_CONTROLS) ||
                            (test&IS_TEXT_UNICODE_REVERSE_CONTROLS))
                    {
                        if ((test&IS_TEXT_UNICODE_CONTROLS) || (test&IS_TEXT_UNICODE_STATISTICS))
                        {
                            nCodePage=CP_UNICODE;
                            bDetect=true;
                        }
                        else if ((test&IS_TEXT_UNICODE_REVERSE_CONTROLS) || (test&IS_TEXT_UNICODE_REVERSE_STATISTICS))
                        {
                            nCodePage=CP_REVERSEBOM;
                            bDetect=true;
                        }
                    }
                }
            }
            else if (IsTextUTF8((const LPBYTE)Buffer, sz))
            {
                nCodePage=CP_UTF8;
                bDetect=true;
            }
            else
            {
                nsUniversalDetectorEx *ns = new nsUniversalDetectorEx();
                ns->HandleData((const char*)Buffer,(PRUint32)sz);
                ns->DataEnd();
                int cp = ns->getCodePage();

                if (cp != -1)
                {
                    nCodePage = cp;
                    bDetect = true;
                }

                delete ns;
            }
        }

        xf_free(Buffer);
    }

    if (pSignatureFound)
        *pSignatureFound = bSignatureFound;

    return bDetect;
}
Exemplo n.º 26
0
bool GetVHDName(const string& DeviceName, string &strVolumePath)
{
	bool Result=false;
	File Device;
	if(Device.Open(DeviceName, FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, nullptr, OPEN_EXISTING))
	{
		ULONG Size = 1024;
		PSTORAGE_DEPENDENCY_INFO StorageDependencyInfo = static_cast<PSTORAGE_DEPENDENCY_INFO>(xf_malloc(Size));
		if(StorageDependencyInfo)
		{
			StorageDependencyInfo->Version = STORAGE_DEPENDENCY_INFO_VERSION_2;
			DWORD Used = 0;
			Result = Device.GetStorageDependencyInformation(GET_STORAGE_DEPENDENCY_FLAG_HOST_VOLUMES, Size, StorageDependencyInfo, &Used);
			if(!Result && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
			{
				StorageDependencyInfo = static_cast<PSTORAGE_DEPENDENCY_INFO>(xf_realloc(StorageDependencyInfo, Used));
				if(StorageDependencyInfo)
				{
					Result = Device.GetStorageDependencyInformation(GET_STORAGE_DEPENDENCY_FLAG_HOST_VOLUMES, Used, StorageDependencyInfo, &Used);
				}
			}
			if(Result)
			{
				if(StorageDependencyInfo->NumberEntries)
				{
					strVolumePath = StorageDependencyInfo->Version2Entries[0].HostVolumeName;
					strVolumePath += StorageDependencyInfo->Version2Entries[0].DependentVolumeRelativePath;
					// trick: ConvertNameToReal also converts \\?\{GUID} to drive letter, if possible.
					ConvertNameToReal(strVolumePath, strVolumePath);
				}
			}
		}
	}
	return Result;
}
Exemplo n.º 27
0
void Grabber::CopyGrabbedArea(int Append, int VerticalBlock)
{
	if (GArea.X1 < 0)
		return;

	int X1,Y1,X2,Y2;
	X1=Min(GArea.X1,GArea.X2);
	X2=Max(GArea.X1,GArea.X2);
	Y1=Min(GArea.Y1,GArea.Y2);
	Y2=Max(GArea.Y1,GArea.Y2);
	int GWidth=X2-X1+1,GHeight=Y2-Y1+1;
	int BufSize=(GWidth+3)*GHeight;
	FAR_CHAR_INFO* CharBuf=new FAR_CHAR_INFO[BufSize], *PtrCharBuf;
	wchar_t *CopyBuf=(wchar_t *)xf_malloc(BufSize*sizeof(wchar_t)), *PtrCopyBuf;
	WORD Chr;
	GetText(X1,Y1,X2,Y2,CharBuf,BufSize*sizeof(FAR_CHAR_INFO));
	*CopyBuf=0;
	PtrCharBuf=CharBuf;
	PtrCopyBuf=CopyBuf;

	for (int I=0; I<GHeight; I++)
	{
		if (I>0)
		{
			*PtrCopyBuf++=L'\r';
			*PtrCopyBuf++=L'\n';
			*PtrCopyBuf=0;
		}

		for (int J=0; J<GWidth; J++, ++PtrCharBuf)
		{
			WORD Chr2 = PtrCharBuf->Char;
			Chr=PtrCharBuf->Char;

			if (Opt.CleanAscii)
			{
				switch (Chr2)
				{
					case L'.':  Chr=L'.'; break;
					case 0x07: Chr=L'*'; break;
					case 0x10: Chr=L'>'; break;
					case 0x11: Chr=L'<'; break;
					case 0x18:
					case 0x19: Chr=L'|'; break;
					case 0x1E:
					case 0x1F: Chr=L'X'; break;
					case 0xFF: Chr=L' '; break;
					default:

						if (Chr2 < 0x20)
							Chr=L'.';
						else if (Chr2 < 0x100)
							Chr=Chr2;

						break;
				}
			}

			if (Opt.NoGraphics && Chr2 >=0xB3 && Chr2 <= 0xDA)
			{
				switch (Chr2)
				{
					case 0xB3:
					case 0xBA: Chr=L'|'; break;
					case 0xC4: Chr=L'-'; break;
					case 0xCD: Chr=L'='; break;
					default:   Chr=L'+'; break;
				}
			}

			*PtrCopyBuf++=Chr;
			*PtrCopyBuf=0;
		}

		for (int K=StrLength(CopyBuf)-1; K>=0 && CopyBuf[K]==L' '; K--)
			CopyBuf[K]=0;

		PtrCopyBuf=CopyBuf+StrLength(CopyBuf);
	}

	Clipboard clip;

	if (clip.Open())
	{
		if (Append)
		{
			wchar_t *AppendBuf=clip.Paste();
			if (AppendBuf)
			{
				int add=0;
				size_t DataSize=StrLength(AppendBuf);

				if (AppendBuf[DataSize-1]!=L'\n')
				{
					add=2;
				}

				AppendBuf=(wchar_t *)xf_realloc(AppendBuf,(DataSize+BufSize+add)*sizeof(wchar_t));
				wmemcpy(AppendBuf+DataSize+add,CopyBuf,BufSize);

				if (add)
					wmemcpy(AppendBuf+DataSize,L"\r\n",2);

				xf_free(CopyBuf);
				CopyBuf=AppendBuf;
			}
		}

		if (VerticalBlock)
			clip.CopyFormat(FAR_VerticalBlock_Unicode,CopyBuf);
		else
			clip.Copy(CopyBuf);

		clip.Close();
	}

	if (CopyBuf)
		xf_free(CopyBuf);

	delete[] CharBuf;
}
Exemplo n.º 28
0
int Message(
    DWORD Flags,
    size_t Buttons,
    const wchar_t *Title,
    const wchar_t * const *Items,
    size_t ItemsNumber,
    Plugin* PluginNumber,
    const GUID* Id
)
{
	string strTempStr;
	string strClipText;
	int X1,Y1,X2,Y2;
	int Length, BtnLength;
	DWORD I, MaxLength, StrCount;
	BOOL ErrorSets=FALSE;
	const wchar_t **Str;
	wchar_t *PtrStr;
	const wchar_t *CPtrStr;
	string strErrStr;

	IsWarningStyle = (Flags&MSG_WARNING) != 0;
	IsErrorType = (Flags&MSG_ERRORTYPE) != 0;

	if(IsErrorType)
	{
		LastError = GetLastError();
		NtStatus = ifn.RtlGetLastNtStatus();
		ErrorSets = GetErrorString(strErrStr);
	}

#if 1 // try to replace inserts
	if (Items && 0 != (Flags & MSG_INSERT_STRINGS))
	{
		string str_err(strErrStr);
		DWORD insert_mask = 0;
		size_t len = strErrStr.GetLength(), pos = 0, inserts_n = 0, inserts[10];

		for (size_t i = 1; i <= ItemsNumber-Buttons; ++i)
		{
			if (0 != (Flags & MSG_INSERT_STR(i)))
			{
				inserts[inserts_n++] = i;
				if (inserts_n >= ARRAYSIZE(inserts))
					break;
			}
		}

		while (str_err.Pos(pos, L"%", pos))
		{
			if (pos >= len-1)
				break;

			if (str_err.At(pos+1) >= L'1' && str_err.At(pos+1) <= L'9')
			{
				size_t insert_i = 0, pos1 = pos+1;
				while (pos1 < len && str_err.At(pos1) >= L'0' && str_err.At(pos1) <= L'9')
				{
					insert_i = 10*insert_i + str_err.At(pos1) - L'0';
					++pos1;
				}
				if (insert_i >= 1 && insert_i <= inserts_n)
				{
					insert_mask |= MSG_INSERT_STR(inserts[insert_i-1]);
					const wchar_t *replacement = Items[inserts[insert_i-1]-1];
					str_err.Replace(pos,pos1-pos,replacement);
					len += wcslen(replacement) - (pos1-pos);
					pos += wcslen(replacement) - (pos1-pos);
				}
				else
					pos = pos1;
			}
			else if (str_err.At(pos+1) == L'%') // "%%"
				pos += 2;
			else
				++pos;
		}
		if (insert_mask == (Flags & MSG_INSERT_STRINGS))
			strErrStr = str_err;
	}
#endif

	// выделим пам¤ть под рабочий массив указателей на строки (+запас 16)
	Str=(const wchar_t **)xf_malloc((ItemsNumber+ADDSPACEFORPSTRFORMESSAGE) * sizeof(wchar_t*));

	if (!Str)
		return -1;

	StrCount=static_cast<DWORD>(ItemsNumber-Buttons);

	// предварительный обсчет максимального размера.
	for (BtnLength=0,I=0; I<static_cast<DWORD>(Buttons); I++) //??
	{
		BtnLength+=HiStrlen(Items[I+StrCount])+2+2+1; // "[ ", " ]", " "
	}
	if(BtnLength)
	{
		BtnLength--;
	}

	DWORD MAX_WIDTH_MESSAGE = Max(ScrX-1-5-5, BtnLength);

	for (MaxLength=BtnLength,I=0; I<StrCount; I++)
	{
		if (static_cast<DWORD>(Length=StrLength(Items[I]))>MaxLength)
			MaxLength=Length;
	}

	// учтем размер заголовка
	if (Title && *Title)
	{
		I=(DWORD)StrLength(Title)+2;

		if (MaxLength < I)
			MaxLength=I;

		strClipText.Append(Title).Append(L"\r\n\r\n");
	}

	// перва¤ коррекци¤ максимального размера
	MaxLength = Min(MaxLength, MAX_WIDTH_MESSAGE);

	// теперь обработаем MSG_ERRORTYPE
	DWORD CountErrorLine=0;

	if ((Flags & MSG_ERRORTYPE) && ErrorSets)
	{
		strClipText.Append(strErrStr).Append(L"\r\n");

		// подсчет количества строк во врапенном сообщениеи
		++CountErrorLine;
		//InsertQuote(ErrStr); // оквочим
		// вычисление "красивого" размера
		DWORD LenErrStr=(DWORD)strErrStr.GetLength();

		if (LenErrStr > MAX_WIDTH_MESSAGE)
		{
			// половина меньше?
			if (LenErrStr/2 < MAX_WIDTH_MESSAGE)
			{
				// а половина + 1/3?
				if ((LenErrStr+LenErrStr/3)/2 < MAX_WIDTH_MESSAGE)
					LenErrStr=(LenErrStr+LenErrStr/3)/2;
				else
					LenErrStr/=2;
			}
			else
				LenErrStr=MAX_WIDTH_MESSAGE;
		}

		MaxLength = Max(MaxLength, LenErrStr);

		// а теперь проврапим
		FarFormatText(strErrStr,LenErrStr,strErrStr,L"\n",0); //?? MaxLength ??
		PtrStr = strErrStr.GetBuffer();

		//BUGBUG: string не предназначен дл¤ хранени¤ строк разделЄнных \0
		while ((PtrStr=wcschr(PtrStr,L'\n')) )
		{
			*PtrStr++=0;

			if (*PtrStr)
				CountErrorLine++;
		}

		strErrStr.ReleaseBuffer();

		if (CountErrorLine > ADDSPACEFORPSTRFORMESSAGE)
			CountErrorLine=ADDSPACEFORPSTRFORMESSAGE; //??
	}

	//BUGBUG: string не предназначен дл¤ хранени¤ строк разделЄнных \0
	// заполн¤ем массив...
	CPtrStr=strErrStr;

	for (I=0; I < CountErrorLine; I++)
	{
		Str[I]=CPtrStr;
		CPtrStr+=StrLength(CPtrStr)+1;

		if (!*CPtrStr) // два идущих подр¤д нул¤ - "хандец" всему
		{
			++I;
			break;
		}
	}

	bool EmptyText=false;
	if(ItemsNumber==Buttons && !I)
	{
		EmptyText=true;
		Str[I]=L"";
		I++;
		StrCount++;
		ItemsNumber++;
	}

	for (size_t J=0; J < ItemsNumber-(EmptyText?1:0); ++J, ++I)
	{
		Str[I]=Items[J];
	}

	for (size_t i = 0; i < ItemsNumber-Buttons; ++i)
	{
		strClipText.Append(Items[i]).Append(L"\r\n");
	}
	strClipText.Append(L"\r\n");
	for (size_t i = ItemsNumber-Buttons; i < ItemsNumber; ++i)
	{
		if(i > ItemsNumber-Buttons)
		{
			strClipText.Append(L' ');
		}
		strClipText.Append(Items[i]);
	}

	StrCount+=CountErrorLine;
	MessageX1=X1=(int(ScrX-MaxLength))/2-4;
	MessageX2=X2=X1+MaxLength+9;
	Y1=(ScrY-static_cast<int>(StrCount))/2-2;

	if (Y1 < 0)
		Y1=0;

	MessageY1=Y1;
	MessageY2=Y2=Y1+StrCount+3;
	string strHelpTopic(strMsgHelpTopic);
	strMsgHelpTopic.Clear();
	// *** ¬ариант с ƒиалогом ***

	if (Buttons>0)
	{
		size_t ItemCount=StrCount+Buttons+1;
		DialogItemEx *PtrMsgDlg;
		DialogItemEx *MsgDlg = new DialogItemEx[ItemCount+1];

		if (!MsgDlg)
		{
			xf_free(Str);
			return -1;
		}

		for (DWORD i=0; i<ItemCount+1; i++)
			MsgDlg[i].Clear();

		int RetCode;
		MessageY2=++Y2;
		MsgDlg[0].Type=DI_DOUBLEBOX;
		MsgDlg[0].X1=3;
		MsgDlg[0].Y1=1;
		MsgDlg[0].X2=X2-X1-3;
		MsgDlg[0].Y2=Y2-Y1-1;

		if (Title && *Title)
			MsgDlg[0].strData = Title;

		FARDIALOGITEMTYPES TypeItem=DI_TEXT;
		unsigned __int64 FlagsItem=DIF_SHOWAMPERSAND;
		BOOL IsButton=FALSE;
		int CurItem=0;
		bool StrSeparator=false;
		bool Separator=false;
		for (PtrMsgDlg=MsgDlg+1,I=1; I < ItemCount; ++I, ++PtrMsgDlg, ++CurItem)
		{
			if (I==StrCount+1 && !StrSeparator && !Separator)
			{
				PtrMsgDlg->Type=DI_TEXT;
				PtrMsgDlg->Flags=DIF_SEPARATOR;
				PtrMsgDlg->Y1=PtrMsgDlg->Y2=I+1;
				CurItem--;
				I--;
				Separator=true;
				continue;
			}
			if(I==StrCount+1)
			{
				TypeItem=DI_BUTTON;
				FlagsItem=DIF_CENTERGROUP|DIF_DEFAULTBUTTON|DIF_FOCUS;
				IsButton=TRUE;
				FirstButtonIndex=CurItem+1;
				LastButtonIndex=CurItem;
			}
			else
			{
				FlagsItem&=~DIF_DEFAULTBUTTON;
			}

			PtrMsgDlg->Type=TypeItem;
			PtrMsgDlg->Flags|=FlagsItem;
			CPtrStr=Str[CurItem];

			if (IsButton)
			{
				PtrMsgDlg->Y1=Y2-Y1-2+(Separator?1:0);
				PtrMsgDlg->strData+=CPtrStr;
				LastButtonIndex++;
			}
			else
			{
				PtrMsgDlg->X1=(Flags & MSG_LEFTALIGN)?5:-1;
				PtrMsgDlg->Y1=I+1;
				wchar_t Chr=*CPtrStr;

				if (Chr == L'\1' || Chr == L'\2')
				{
					CPtrStr++;
					PtrMsgDlg->Flags|=(Chr==2?DIF_SEPARATOR2:DIF_SEPARATOR);
					if(I==StrCount)
					{
						StrSeparator=true;
					}
				}
				else
				{
					if (StrLength(CPtrStr)>X2-X1-9)
					{
						PtrMsgDlg->Type=DI_EDIT;
						PtrMsgDlg->Flags|=DIF_READONLY|DIF_BTNNOCLOSE|DIF_SELECTONENTRY;
						PtrMsgDlg->X1=5;
						PtrMsgDlg->X2=X2-X1-5;
						PtrMsgDlg->strData=CPtrStr;
					}
					else
					{
						//xstrncpy(PtrMsgDlg->Data,CPtrStr,Min((int)MAX_WIDTH_MESSAGE,(int)sizeof(PtrMsgDlg->Data))); //?? ScrX-15 ??
						PtrMsgDlg->strData = CPtrStr; //BUGBUG, wrong len
					}
				}
			}
		}

		{
			if(Separator)
			{
				FirstButtonIndex++;
				LastButtonIndex++;
				MessageY2++;
				Y2++;
				MsgDlg[0].Y2++;
				ItemCount++;
			}
			Dialog Dlg(MsgDlg,ItemCount,MsgDlgProc, &strClipText);
			if (X1 == -1) X1 = 0;
			if (Y1 == -1) Y1 = 0;
			Dlg.SetPosition(X1,Y1,X2,Y2);
			if(Id) Dlg.SetId(*Id);

			if (!strHelpTopic.IsEmpty())
				Dlg.SetHelp(strHelpTopic);

			Dlg.SetPluginOwner(reinterpret_cast<Plugin*>(PluginNumber)); // «апомним номер плагина

			if (IsWarningStyle)
			{
				Dlg.SetDialogMode(DMODE_WARNINGSTYLE);
			}

			Dlg.SetDialogMode(DMODE_MSGINTERNAL);
			if (Flags & MSG_NOPLUGINS)
				Dlg.SetDialogMode(DMODE_NOPLUGINS);
			FlushInputBuffer();

			if (Flags & MSG_KILLSAVESCREEN)
				SendDlgMessage((HANDLE)&Dlg,DM_KILLSAVESCREEN,0,0);

			Dlg.Process();
			RetCode=Dlg.GetExitCode();
		}

		delete [] MsgDlg;
		xf_free(Str);
		return(RetCode<0?RetCode:RetCode-StrCount-1-(Separator?1:0));
	}

	// *** Ѕез ƒиалога! ***
	SetCursorType(0,0);

	if (!(Flags & MSG_KEEPBACKGROUND))
	{
		SetScreen(X1,Y1,X2,Y2,L' ',ColorIndexToColor((Flags & MSG_WARNING)?COL_WARNDIALOGTEXT:COL_DIALOGTEXT));
		MakeShadow(X1+2,Y2+1,X2+2,Y2+1);
		MakeShadow(X2+1,Y1+1,X2+2,Y2+1);
		Box(X1+3,Y1+1,X2-3,Y2-1,ColorIndexToColor((Flags & MSG_WARNING)?COL_WARNDIALOGBOX:COL_DIALOGBOX),DOUBLE_BOX);
	}

	SetColor((Flags & MSG_WARNING)?COL_WARNDIALOGTEXT:COL_DIALOGTEXT);

	if (Title && *Title)
	{
		string strTempTitle = Title;

		if (strTempTitle.GetLength() > MaxLength)
			strTempTitle.SetLength(MaxLength);

		GotoXY(X1+(X2-X1-1-(int)strTempTitle.GetLength())/2,Y1+1);
		FS<<L" "<<strTempTitle<<L" ";
	}

	for (I=0; I<StrCount; I++)
	{
		CPtrStr=Str[I];
		wchar_t Chr=*CPtrStr;

		if (Chr == 1 || Chr == 2)
		{
			Length=X2-X1-5;

			if (Length>1)
			{
				SetColor((Flags & MSG_WARNING)?COL_WARNDIALOGBOX:COL_DIALOGBOX);
				GotoXY(X1+3,Y1+I+2);
				DrawLine(Length,(Chr == 2?3:1));
				CPtrStr++;
				int TextLength=StrLength(CPtrStr);

				if (TextLength<Length)
				{
					GotoXY(X1+3+(Length-TextLength)/2,Y1+I+2);
					Text(CPtrStr);
				}

				SetColor((Flags & MSG_WARNING)?COL_WARNDIALOGBOX:COL_DIALOGTEXT);
			}

			continue;
		}

		if ((Length=StrLength(CPtrStr))>ScrX-15)
			Length=ScrX-15;

		int Width=X2-X1+1;
		wchar_t *lpwszTemp = nullptr;
		int PosX;
		if (Flags & MSG_LEFTALIGN)
		{
			lpwszTemp = (wchar_t*)xf_malloc((Width-10+1)*sizeof(wchar_t));
			_snwprintf(lpwszTemp,Width-10+1,L"%.*s",Width-10,CPtrStr);
			GotoXY(X1+5,Y1+I+2);
		}
		else
		{
			PosX=X1+(Width-Length)/2;
			lpwszTemp = (wchar_t*)xf_malloc((PosX-X1-4+Length+X2-PosX-Length-3+1)*sizeof(wchar_t));
			_snwprintf(lpwszTemp,PosX-X1-4+Length+X2-PosX-Length-3+1,L"%*s%.*s%*s",PosX-X1-4,L"",Length,CPtrStr,X2-PosX-Length-3,L"");
			GotoXY(X1+4,Y1+I+2);
		}

		Text(lpwszTemp);
		xf_free(lpwszTemp);
	}

	/* $ 13.01.2003 IS
	   - ѕринудительно уберем запрет отрисовки экрана, если количество кнопок
	     в сообщении равно нулю и макрос закончил выполн¤тьс¤. Ёто необходимо,
	     чтобы заработал прогресс-бар от плагина, который был запущен при помощи
	     макроса запретом отрисовки (bugz#533).
	*/
	xf_free(Str);

	if (!Buttons)
	{
		if (ScrBuf.GetLockCount()>0 && !CtrlObject->Macro.PeekKey())
			ScrBuf.SetLockCount(0);

		ScrBuf.Flush();
	}

	return 0;
}
Exemplo n.º 29
0
bool GetFileFormat(File& file, UINT& nCodePage, bool* pSignatureFound, bool bUseHeuristics)
{
    DWORD dwTemp=0;
    bool bSignatureFound = false;
    bool bDetect=false;

    DWORD Readed = 0;
    if (file.Read(&dwTemp, sizeof(dwTemp), Readed) && Readed > 1 ) // minimum signature size is 2 bytes
    {
        if (LOWORD(dwTemp) == SIGN_UNICODE)
        {
            nCodePage = CP_UNICODE;
            file.SetPointer(2, nullptr, FILE_BEGIN);
            bSignatureFound = true;
        }
        else if (LOWORD(dwTemp) == SIGN_REVERSEBOM)
        {
            nCodePage = CP_REVERSEBOM;
            file.SetPointer(2, nullptr, FILE_BEGIN);
            bSignatureFound = true;
        }
        else if ((dwTemp & 0x00FFFFFF) == SIGN_UTF8)
        {
            nCodePage = CP_UTF8;
            file.SetPointer(3, nullptr, FILE_BEGIN);
            bSignatureFound = true;
        }
        else
        {
            file.SetPointer(0, nullptr, FILE_BEGIN);
        }
    }

    if (bSignatureFound)
    {
        bDetect = true;
    }
    else if (bUseHeuristics)
    {
        file.SetPointer(0, nullptr, FILE_BEGIN);
        DWORD Size=0x8000; // BUGBUG. TODO: configurable
        LPVOID Buffer=xf_malloc(Size);
        DWORD ReadSize = 0;
        bool ReadResult = file.Read(Buffer, Size, ReadSize);
        file.SetPointer(0, nullptr, FILE_BEGIN);

        if (ReadResult && ReadSize)
        {
            int test=
                IS_TEXT_UNICODE_STATISTICS|
                IS_TEXT_UNICODE_REVERSE_STATISTICS|
                IS_TEXT_UNICODE_CONTROLS|
                IS_TEXT_UNICODE_REVERSE_CONTROLS|
                IS_TEXT_UNICODE_ILLEGAL_CHARS|
                IS_TEXT_UNICODE_ODD_LENGTH|
                IS_TEXT_UNICODE_NULL_BYTES;

            if (IsTextUnicode(Buffer, ReadSize, &test))
            {
                if (!(test&IS_TEXT_UNICODE_ODD_LENGTH) && !(test&IS_TEXT_UNICODE_ILLEGAL_CHARS))
                {
                    if ((test&IS_TEXT_UNICODE_NULL_BYTES) || (test&IS_TEXT_UNICODE_CONTROLS) || (test&IS_TEXT_UNICODE_REVERSE_CONTROLS))
                    {
                        if ((test&IS_TEXT_UNICODE_CONTROLS) || (test&IS_TEXT_UNICODE_STATISTICS))
                        {
                            nCodePage=CP_UNICODE;
                            bDetect=true;
                        }
                        else if ((test&IS_TEXT_UNICODE_REVERSE_CONTROLS) || (test&IS_TEXT_UNICODE_REVERSE_STATISTICS))
                        {
                            nCodePage=CP_REVERSEBOM;
                            bDetect=true;
                        }
                    }
                }
            }
            else if (IsTextUTF8(static_cast<LPBYTE>(Buffer), ReadSize))
            {
                nCodePage=CP_UTF8;
                bDetect=true;
            }
            else
            {
                nsUniversalDetectorEx *ns = new nsUniversalDetectorEx();
                ns->HandleData(static_cast<LPCSTR>(Buffer), ReadSize);
                ns->DataEnd();
                int cp = ns->getCodePage();
                if ( cp >= 0 )
                {
                    const wchar_t *deprecated = Opt.strNoAutoDetectCP.CPtr();

                    if ( 0 == wcscmp(deprecated, L"-1") )
                    {
                        if ( Opt.CPMenuMode )
                        {
                            if ( static_cast<UINT>(cp) != GetACP() && static_cast<UINT>(cp) != GetOEMCP() )
                            {
                                int selectType = 0;
                                wchar_t szcp[16];
                                _snwprintf(szcp, ARRAYSIZE(szcp), L"%d", cp);
                                GeneralCfg->GetValue(FavoriteCodePagesKey, szcp, &selectType, 0);
                                if (0 == (selectType & CPST_FAVORITE))
                                    cp = -1;
                            }
                        }
                    }
                    else
                    {
                        while (*deprecated)
                        {
                            while (*deprecated && (*deprecated < L'0' || *deprecated > L'9'))
                                ++deprecated;

                            int dp = (int)wcstol(deprecated, (wchar_t **)&deprecated, 0);
                            if (cp == dp)
                            {
                                cp = -1;
                                break;
                            }
                        }
                    }
                }

                if (cp != -1)
                {
                    nCodePage = cp;
                    bDetect = true;
                }

                delete ns;
            }
        }

        xf_free(Buffer);
    }

    if (pSignatureFound)
    {
        *pSignatureFound = bSignatureFound;
    }
    return bDetect;
}
Exemplo n.º 30
0
bool Panel::MakeListFile(string &strListFileName,bool ShortNames,const wchar_t *Modifers)
{
	bool Ret=false;

	if (FarMkTempEx(strListFileName))
	{
		File ListFile;
		if (ListFile.Open(strListFileName,GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,nullptr,CREATE_ALWAYS))
		{
			UINT CodePage=CP_OEMCP;
			LPCVOID Eol="\r\n";
			DWORD EolSize=2;

			if (Modifers && *Modifers)
			{
				if (wcschr(Modifers,L'A')) // ANSI
				{
					CodePage=CP_ACP;
				}
				else
				{
					DWORD Signature=0;
					int SignatureSize=0;

					if (wcschr(Modifers,L'W')) // UTF16LE
					{
						CodePage=CP_UNICODE;
						Signature=SIGN_UNICODE;
						SignatureSize=2;
						Eol=DOS_EOL_fmt;
						EolSize=2*sizeof(WCHAR);
					}
					else
					{
						if (wcschr(Modifers,L'U')) // UTF8
						{
							CodePage=CP_UTF8;
							Signature=SIGN_UTF8;
							SignatureSize=3;
						}
					}

					if (Signature && SignatureSize)
					{
						DWORD NumberOfBytesWritten;
						ListFile.Write(&Signature,SignatureSize, NumberOfBytesWritten);
					}
				}
			}

			string strFileName,strShortName;
			DWORD FileAttr;
			GetSelName(nullptr,FileAttr);

			while (GetSelName(&strFileName,FileAttr,&strShortName))
			{
				if (ShortNames)
					strFileName = strShortName;

				if (Modifers && *Modifers)
				{
					if (wcschr(Modifers,L'F') && PointToName(strFileName) == strFileName.CPtr()) // 'F' - использовать полный путь; //BUGBUG ?
					{
						string strTempFileName=strCurDir;

						if (ShortNames)
							ConvertNameToShort(strTempFileName,strTempFileName);

						AddEndSlash(strTempFileName);
						strTempFileName+=strFileName; //BUGBUG ?
						strFileName=strTempFileName;
					}

					if (wcschr(Modifers,L'Q')) // 'Q' - заключать имена с пробелами в кавычки;
						QuoteSpaceOnly(strFileName);

					if (wcschr(Modifers,L'S')) // 'S' - использовать '/' вместо '\' в путях файлов;
					{
						size_t Len=strFileName.GetLength();
						wchar_t *FileName=strFileName.GetBuffer();

						for (size_t i=0; i<Len; i++)
						{
							if (FileName[i]==L'\\')
							{
								FileName[i]=L'/';
							}
						}

						strFileName.ReleaseBuffer();
					}
				}

				LPCVOID Ptr=nullptr;
				LPSTR Buffer=nullptr;
				DWORD NumberOfBytesToWrite=0,NumberOfBytesWritten=0;

				if (CodePage==CP_UNICODE)
				{
					Ptr=strFileName.CPtr();
					NumberOfBytesToWrite=static_cast<DWORD>(strFileName.GetLength()*sizeof(WCHAR));
				}
				else
				{
					int Size=WideCharToMultiByte(CodePage,0,strFileName,static_cast<int>(strFileName.GetLength()),nullptr,0,nullptr,nullptr);

					if (Size)
					{
						Buffer=static_cast<LPSTR>(xf_malloc(Size));

						if (Buffer)
						{
							NumberOfBytesToWrite=WideCharToMultiByte(CodePage,0,strFileName,static_cast<int>(strFileName.GetLength()),Buffer,Size,nullptr,nullptr);
							Ptr=Buffer;
						}
					}
				}

				BOOL Written=ListFile.Write(Ptr,NumberOfBytesToWrite,NumberOfBytesWritten);

				if (Buffer)
					xf_free(Buffer);

				if (Written && NumberOfBytesWritten==NumberOfBytesToWrite)
				{
					if (ListFile.Write(Eol,EolSize,NumberOfBytesWritten) && NumberOfBytesWritten==EolSize)
					{
						Ret=true;
					}
				}
				else
				{
					Message(MSG_WARNING|MSG_ERRORTYPE,1,MSG(MError),MSG(MCannotCreateListFile),MSG(MCannotCreateListWrite),MSG(MOk));
					apiDeleteFile(strListFileName);
					break;
				}
			}

			ListFile.Close();
		}
		else
		{
			Message(MSG_WARNING|MSG_ERRORTYPE,1,MSG(MError),MSG(MCannotCreateListFile),MSG(MCannotCreateListTemp),MSG(MOk));
		}
	}
	else
	{
		Message(MSG_WARNING|MSG_ERRORTYPE,1,MSG(MError),MSG(MCannotCreateListFile),MSG(MCannotCreateListTemp),MSG(MOk));
	}

	return Ret;
}