Example #1
0
static NTSTATUS Open(FSP_FILE_SYSTEM *FileSystem,
    PWSTR FileName, UINT32 CreateOptions, UINT32 GrantedAccess,
    PVOID *PFileContext, FSP_FSCTL_FILE_INFO *FileInfo)
{
    PTFS *Ptfs = (PTFS *)FileSystem->UserContext;
    WCHAR FullPath[FULLPATH_SIZE];
    ULONG CreateFlags;
    PTFS_FILE_CONTEXT *FileContext;

    if (!ConcatPath(Ptfs, FileName, FullPath))
        return STATUS_OBJECT_NAME_INVALID;

    FileContext = malloc(sizeof *FileContext);
    if (0 == FileContext)
        return STATUS_INSUFFICIENT_RESOURCES;
    memset(FileContext, 0, sizeof *FileContext);

    CreateFlags = FILE_FLAG_BACKUP_SEMANTICS;
    if (CreateOptions & FILE_DELETE_ON_CLOSE)
        CreateFlags |= FILE_FLAG_DELETE_ON_CLOSE;

    FileContext->Handle = CreateFileW(FullPath,
        GrantedAccess, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0,
        OPEN_EXISTING, CreateFlags, 0);
    if (INVALID_HANDLE_VALUE == FileContext->Handle)
    {
        free(FileContext);
        return FspNtStatusFromWin32(GetLastError());
    }

    *PFileContext = FileContext;

    return GetFileInfoInternal(FileContext->Handle, FileInfo);
}
Example #2
0
bool GetWinShellLocation(CString &sWinShell)
{
    CRegistry theRegistry;
    sWinShell.Empty();
    g_sEditor.Empty();

    if (theRegistry.Connect(HKEY_LOCAL_MACHINE) == FALSE) {
//          theLog("Registry: can't connect to HKEY_LOCAL_MACHINE (Error %d)\n",
//                 GetLastError());
        return false;
    }
    if (theRegistry.Open(TEXT("SOFTWARE\\Classes\\tex_auto_file\\DefaultIcon"),
                         (CRegistry::CreatePermissions)CRegistry::permissionRead) == FALSE ) {
//          theLog("Registry: can't open WinShell.Document\\DefaultIcon key (Error %d)\n",
//                 GetLastError());
        theRegistry.Close();
        return false;
    }
    theRegistry.GetValue("", sWinShell);
    theRegistry.Close();

    // It might be quoted !
    sWinShell.Remove(TEXT('\"'));
    sWinShell.Remove(TEXT('\''));
    ::GetParentDirectory(sWinShell);
    g_sEditor = ConcatPath(sWinShell, "WinShell.exe");

    if (! FileExists(g_sEditor)) {
        g_sEditor.Empty();
        sWinShell.Empty();
        return false;
    }

    return true;
}
Example #3
0
bool InstallWinShell()
{
    CString sCmd = ConcatPath(g_sBinDir, "TeXSetup --add-package=winshell --quick");
    bool bRet = true;
    bRet = bRet && RunProcess(sCmd);
    return bRet;
}
Example #4
0
bool InstallGhostscript()
{
    CString sCmd = ConcatPath(g_sBinDir, "TeXSetup --add-package=ghostscript-free --quick");
    bool bRet = true;
    bRet = bRet && RunProcess(sCmd, true);
    return bRet;
}
Example #5
0
Url WindowsEnvFun::GetUserData(cstring org, cstring app)
{
    if(!org && !app)
    {
        org = ApplicationData().organization_name.c_str();
        app = ApplicationData().application_name.c_str();
    }

    CString out;
    out = GetUserHome().internUrl;
    out = ConcatPath(out.c_str(), "AppData");
    out = ConcatPath(out.c_str(), "Local");
    out = ConcatPath(out.c_str(), org);
    out = ConcatPath(out.c_str(), app);
    out = str::replace::str(out, "\\", "/");
    return MkUrl(out, RSCA::SystemFile);
}
Example #6
0
bool __cdecl MakeFormats(LPVOID pParam)
{
    char *cmd = "fmtutil --byfmt=%s --dolinks";
    char buf[_MAX_PATH];
    UINT i = (UINT)pParam;
    CString sFmt = ConcatPath(g_sVarTexmf, "web2c");
    sFmt = ConcatPath(sFmt, g_formatFiles[i]);
    if (! FileExists(sFmt)) {
        CString sFormat = g_formatFiles[i];
        int nPos;
        if ((nPos = sFormat.Find('.')) > -1) {
            sFormat = sFormat.Left(nPos);
        }
        wsprintf(buf, cmd, (LPCTSTR)sFormat);
        RunProcess(buf, true, true, SW_HIDE);
    }
    return true;
}
Example #7
0
static NTSTATUS Create(FSP_FILE_SYSTEM *FileSystem,
    PWSTR FileName, UINT32 CreateOptions, UINT32 GrantedAccess,
    UINT32 FileAttributes, PSECURITY_DESCRIPTOR SecurityDescriptor, UINT64 AllocationSize,
    PVOID *PFileContext, FSP_FSCTL_FILE_INFO *FileInfo)
{
    PTFS *Ptfs = (PTFS *)FileSystem->UserContext;
    WCHAR FullPath[FULLPATH_SIZE];
    SECURITY_ATTRIBUTES SecurityAttributes;
    ULONG CreateFlags;
    PTFS_FILE_CONTEXT *FileContext;

    if (!ConcatPath(Ptfs, FileName, FullPath))
        return STATUS_OBJECT_NAME_INVALID;

    FileContext = malloc(sizeof *FileContext);
    if (0 == FileContext)
        return STATUS_INSUFFICIENT_RESOURCES;
    memset(FileContext, 0, sizeof *FileContext);

    SecurityAttributes.nLength = sizeof SecurityAttributes;
    SecurityAttributes.lpSecurityDescriptor = SecurityDescriptor;
    SecurityAttributes.bInheritHandle = FALSE;

    CreateFlags = FILE_FLAG_BACKUP_SEMANTICS;
    if (CreateOptions & FILE_DELETE_ON_CLOSE)
        CreateFlags |= FILE_FLAG_DELETE_ON_CLOSE;

    if (CreateOptions & FILE_DIRECTORY_FILE)
    {
        /*
         * It is not widely known but CreateFileW can be used to create directories!
         * It requires the specification of both FILE_FLAG_BACKUP_SEMANTICS and
         * FILE_FLAG_POSIX_SEMANTICS. It also requires that FileAttributes has
         * FILE_ATTRIBUTE_DIRECTORY set.
         */
        CreateFlags |= FILE_FLAG_POSIX_SEMANTICS;
        FileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
    }
    else
        FileAttributes &= ~FILE_ATTRIBUTE_DIRECTORY;

    if (0 == FileAttributes)
        FileAttributes = FILE_ATTRIBUTE_NORMAL;

    FileContext->Handle = CreateFileW(FullPath,
        GrantedAccess, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SecurityAttributes,
        CREATE_NEW, CreateFlags | FileAttributes, 0);
    if (INVALID_HANDLE_VALUE == FileContext->Handle)
    {
        free(FileContext);
        return FspNtStatusFromWin32(GetLastError());
    }

    *PFileContext = FileContext;

    return GetFileInfoInternal(FileContext->Handle, FileInfo);
}
Example #8
0
static NTSTATUS Rename(FSP_FILE_SYSTEM *FileSystem,
    PVOID FileContext,
    PWSTR FileName, PWSTR NewFileName, BOOLEAN ReplaceIfExists)
{
    PTFS *Ptfs = (PTFS *)FileSystem->UserContext;
    WCHAR FullPath[FULLPATH_SIZE], NewFullPath[FULLPATH_SIZE];

    if (!ConcatPath(Ptfs, FileName, FullPath))
        return STATUS_OBJECT_NAME_INVALID;

    if (!ConcatPath(Ptfs, NewFileName, NewFullPath))
        return STATUS_OBJECT_NAME_INVALID;

    if (!MoveFileExW(FullPath, NewFullPath, ReplaceIfExists ? MOVEFILE_REPLACE_EXISTING : 0))
        return FspNtStatusFromWin32(GetLastError());

    return STATUS_SUCCESS;
}
Example #9
0
static NTSTATUS GetSecurityByName(FSP_FILE_SYSTEM *FileSystem,
    PWSTR FileName, PUINT32 PFileAttributes,
    PSECURITY_DESCRIPTOR SecurityDescriptor, SIZE_T *PSecurityDescriptorSize)
{
    PTFS *Ptfs = (PTFS *)FileSystem->UserContext;
    WCHAR FullPath[FULLPATH_SIZE];
    HANDLE Handle;
    FILE_ATTRIBUTE_TAG_INFO AttributeTagInfo;
    DWORD SecurityDescriptorSizeNeeded;
    NTSTATUS Result;

    if (!ConcatPath(Ptfs, FileName, FullPath))
        return STATUS_OBJECT_NAME_INVALID;

    Handle = CreateFileW(FullPath,
        FILE_READ_ATTRIBUTES | READ_CONTROL, 0, 0,
        OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
    if (INVALID_HANDLE_VALUE == Handle)
    {
        Result = FspNtStatusFromWin32(GetLastError());
        goto exit;
    }

    if (0 != PFileAttributes)
    {
        if (!GetFileInformationByHandleEx(Handle,
            FileAttributeTagInfo, &AttributeTagInfo, sizeof AttributeTagInfo))
        {
            Result = FspNtStatusFromWin32(GetLastError());
            goto exit;
        }

        *PFileAttributes = AttributeTagInfo.FileAttributes;
    }

    if (0 != PSecurityDescriptorSize)
    {
        if (!GetKernelObjectSecurity(Handle,
            OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
            SecurityDescriptor, (DWORD)*PSecurityDescriptorSize, &SecurityDescriptorSizeNeeded))
        {
            *PSecurityDescriptorSize = SecurityDescriptorSizeNeeded;
            Result = FspNtStatusFromWin32(GetLastError());
            goto exit;
        }

        *PSecurityDescriptorSize = SecurityDescriptorSizeNeeded;
    }

    Result = STATUS_SUCCESS;

exit:
    if (INVALID_HANDLE_VALUE != Handle)
        CloseHandle(Handle);

    return Result;
}
Example #10
0
bool __cdecl UnblockFormats(LPVOID pParam)
{
    // Unblock formats
    KeyValFile kFmtutilCnf;
    kFmtutilCnf.Open(ConcatPath(g_sVarTexmf, "web2c\\fmtutil.cnf"));
    kFmtutilCnf.RawReplace("#!#", "");
    kFmtutilCnf.Commit();
    kFmtutilCnf.Close();
    return true;
}
Example #11
0
bool __cdecl CleanupCDRom(LPVOID pParam)
{
    CString sTmp = g_sVarTexmf;
    GetParentDirectory(sTmp);
    RecursivelyRemove(sTmp);

#if 0
    CString sWinShellDir;
    if (! GetWinShellLocation(sWinShellDir) || ! DirectoryExists(sWinShellDir))
        return true;

    if (MessageBox(NULL, "Do you want to remove WinShell too ?", 
                   NULL, MB_YESNO | MB_ICONINFORMATION) == IDYES) {
        char buf[_MAX_PATH];
        CString sUninstCmd;
        for (int i = 0; i < 1000; i++) {
            wsprintf(buf, "unins%.3d.exe", i);
            sUninstCmd = ConcatPath(sWinShellDir, buf);
            if (! FileExists(sUninstCmd)) {
                i--;
                break;
            }
        }
        if (i > -1) {
            wsprintf(buf, "unins%.3d.exe", i);
            sUninstCmd = ConcatPath(sWinShellDir, buf);
            RunProcess(sUninstCmd, true);
            RecursivelyRemove(sWinShellDir);
        }
    }
#endif

    // Remove the registry key
    CRegistry theRegistry;
    if (theRegistry.Connect(HKEY_CURRENT_USER) == TRUE) {
        theRegistry.DeleteKey(g_sRegKey);
    }

    return true;
}
Example #12
0
bool __cdecl SetupDirs(LPVOID pParam)
{
    CString sDir, sSrc, sDst;

    if (g_bIsWindowsNT) {
        HANDLE hLog = 0;
	// theLog("Creating %s directory ", (LPCTSTR)g_sInstallRootDir);
        // CreateDirectoryPath(g_sInstallRootDir);
        // theLog("and granting everyone read access to it.\n");
        // if (! GrantPermissions(g_sInstallRootDir, "everyone", "read", FALSE, hLog)) {
            // Appropriate message
            // theLog("Warning: Fail to grant everyone read access to %s (Error %ld).\n", 
            //        (LPCTSTR)g_sInstallRootDir, GetLastError());
        // }
        if (! g_sVarTexmf.IsEmpty()) {
            // theLog("Creating %s directory ", (LPCTSTR)g_sVarTexmf);
            CreateDirectoryPath(g_sVarTexmf);
            // theLog("and granting everyone full access to it.\n");
            if (! GrantPermissions(g_sVarTexmf, "everyone", "full", FALSE, hLog)) {
                // Appropriate message
                // theLog("Warning: Fail to grand everyone full access to %s (Error %ld).\n", 
                //        (LPCTSTR)g_sVarTexmf, GetLastError());
            }
        }
    }


    // First run : copy all configuration files.
    for (int i = 0; i < sizeof(g_confFiles)/sizeof(g_confFiles[0]); i += 2) {
        sSrc = ConcatPath(g_sTexmfMain, g_confFiles[i]);
        sDst = ConcatPath(g_sVarTexmf, g_confFiles[i+1]);
        if (FileExists(sSrc) && ! FileExists(sDst)){
            SafeCopyFile(sSrc, sDst, TRUE);
        }
    }
    
    return true;
}
Example #13
0
void Initialize()
{
    char buffer[_MAX_PATH];
    if (GetTempPath(sizeof(buffer), buffer) == 0) {
        g_sTempPath = "c:\\";
    }
    else {
        g_sTempPath = buffer;
    }

    g_bIsAdmin = ::IsAdmin();
    g_bIsWindowsNT = ::IsWindowsNT();
    
    g_bIE5 = (GetDllVersion("shdocvw.dll") >= PACKVERSION(5,0));
    // Guess which mode !
    g_sInternetMethod = (g_bIE5 ? "ie5" : "direct");

    // The TeXLive registry key
    g_sRegKey = ConcatPath( TEXLIVE_REGENTRY, TEXLIVE_VERSION);

    // VarTexmf will be stored in temp dir
    g_sVarTexmf = ConcatPath(g_sTempPath, "TeX\\texmf");

    // Get the cdrom texmf tree
    CString sDummyName;
    DWORD dwDummySize;
#ifdef TEST
	g_sTexmfMain = "e:\\TeXLive\\setupw32";
#else
    GetExecutableDirectory(g_sTexmfMain, sDummyName, dwDummySize);
#endif
    // Assume we are in \bin\win32 subdirectory, so:
    GetParentDirectory(g_sTexmfMain);
    GetParentDirectory(g_sTexmfMain);
    g_sDriveRootPath = g_sTexmfMain;
    g_sBinDir = ConcatPath(g_sTexmfMain, "bin\\win32");
    g_sSetupw32 = ConcatPath(g_sTexmfMain, "setupw32");
    g_sSupport = ConcatPath(g_sTexmfMain, "support");
    g_sTexmfMain = ConcatPath(g_sTexmfMain, "texmf");
    if (! DirectoryExists(g_sTexmfMain) ) {
        AfxMessageBox(IDS_NO_TEXLIVE_TEXMF, MB_OK | MB_ICONSTOP);
        exit(1);
    }
    if (! DirectoryExists(g_sBinDir) ) {
        AfxMessageBox(IDS_NO_TEXLIVE_BINARIES, MB_OK | MB_ICONSTOP);
        exit(1);
    }
    GetEditorLocation(g_sEditor);
}
Example #14
0
bool __cdecl SetupEnv(LPVOID pParam)
{
    char buf[4096];
    CString sPath = g_sBinDir;
    sPath = GetSafePathName(sPath);
    sPath = sPath + ";";
    // Path
    GetEnvironmentVariable("PATH", buf, sizeof(buf));
    g_sDefaultPath = buf;
    sPath = sPath + buf;
    if (! g_sGhostscript.IsEmpty()) {
        char path[_MAX_PATH], *fp;
        // If not on the PATH, then add it
        if (SearchPath(buf, "gswin32c.exe", NULL, sizeof(path), path, &fp) == 0) {
            CString sGhostscriptBinDir = g_sGhostscript;
            sGhostscriptBinDir.Replace('/','\\');
            GetParentDirectory(sGhostscriptBinDir);
            // Remove terminating '\\' if needed
            if (sGhostscriptBinDir.Right(1) == "\\"
                && sGhostscriptBinDir.Right(2) != ":\\")
                sGhostscriptBinDir = sGhostscriptBinDir.Left(sGhostscriptBinDir.GetLength() - 1);
            // Retrieve safe path name for win9x users
            sGhostscriptBinDir = GetSafePathName(sGhostscriptBinDir, false);
            sPath = sPath + ";" + sGhostscriptBinDir;
        }
    }
    SetEnvironmentVariable("PATH", (LPCTSTR)sPath);

    CString sDir = ConcatPath(g_sVarTexmf, "web2c");
    SetEnvironmentVariable("TEXMFCNF", (LPCTSTR)sDir);

    SetEnvironmentVariable("TEXMFMAIN", (LPCTSTR)g_sTexmfMain);

    SetEnvironmentVariable("VARTEXMF", (LPCTSTR)g_sVarTexmf);

    return true;
}
Example #15
0
void RunTeXDocTK()
{
    //pDialog initialized to NULL in the constructor of CMyWnd class
    CActionProgressDlg *pDialog = new CActionProgressDlg();
    //Check if new succeeded and we got a valid pointer to a dialog object
    if(pDialog != NULL) {
        BOOL ret = pDialog->Create(IDD_ACTION_PROGRESS_DIALOG,AfxGetMainWnd());
        if(!ret)   //Create failed.
            AfxMessageBox("Error creating Dialog");
        pDialog->CenterWindow(AfxGetMainWnd());
        pDialog->ShowWindow(SW_SHOW);
    }
    else
        AfxMessageBox("Error Creating Dialog Object");

    pDialog->AddAction("Setting up directories ...", SetupDirs);
    pDialog->AddAction("Setting up environment ...", SetupEnv);
    pDialog->StartActions();
        
    CString sCmd = ConcatPath(g_sBinDir, "TeXDocTK.exe");
    RunProcess(sCmd, false, true, SW_SHOWDEFAULT);

    CleanupEnv();
}
Example #16
0
void RunOffCDRom()
{
#if 0
    // Be safe !
    if (g_sEditor.IsEmpty()) {
        AfxMessageBox("You need to select a TeX-oriented text editor!", MB_ICONWARNING);
        return;
    }
    // Ghostscript might have been installed in the mean time ...
    if (g_sGhostscript.IsEmpty()) {
        GetGhostscriptLocation(g_sGhostscript);
    }
    
    if (g_sGhostscript.IsEmpty()) {
        AfxMessageBox("Ghostscript is missing,\r\nrendering might be poor.\r\nPlease, consider installing it.", MB_ICONWARNING);
    }
    
#if 0
    if (! GetEditorLocation(g_sEditor)) {
        bAskingEditor = true;

        if (!SelectEditor(g_sEditor)) {
            AfxMessageBox("You need to select a TeX-oriented text editor!",
                          MB_ICONWARNING);
            return;
        }
    }
#endif

    //pDialog initialized to NULL in the constructor of CMyWnd class
    CActionProgressDlg *pDialog = new CActionProgressDlg();
    //Check if new succeeded and we got a valid pointer to a dialog object
    if(pDialog != NULL) {
        BOOL ret = pDialog->Create(IDD_ACTION_PROGRESS_DIALOG,AfxGetMainWnd());
        if(!ret)   //Create failed.
            AfxMessageBox("Error creating Dialog");
        pDialog->CenterWindow(AfxGetMainWnd());
        pDialog->ShowWindow(SW_SHOW);
    }
    else
        AfxMessageBox("Error Creating Dialog Object");

    pDialog->AddAction("Setting up directories ...", SetupDirs);
    pDialog->AddAction("Setting up environment ...", SetupEnv);
    // No need to build formats anymore !
    // pDialog->AddAction("Building TeX format", MakeFormats, 0);
    // pDialog->AddAction("Building LaTeX format", MakeFormats, (LPVOID)1);
    // pDialog->AddAction("Building PDFLaTeX format", MakeFormats, (LPVOID)2);
    // pDialog->AddAction("Building ConTeXt format", MakeFormats, (LPVOID)3);
    pDialog->AddAction("Building ls-R database ...", MakelsR);
    pDialog->StartActions();
#endif
    
    RunProcess(ConcatPath(g_sDriveRootPath, g_sEditor), false, true, SW_SHOWDEFAULT);

#if 0
    if (bAskingEditor) {
        if (AfxMessageBox("Do you want me to remember this editor for another session ?", MB_YESNO)
            == IDYES) {
            SaveEditorLocation(g_sEditor);
        }
    }
#endif

    CleanupEnv();

}
DWORD WINAPI CMYK_ThreadProc(void*)
{
	OutputDebugString(L"\n*** Loading CMYK.png...");
	ULONG_PTR gdiplusToken = 0; bool bTokenInitialized = false;
	BOOL bCoInitialized = FALSE;
	wchar_t* pszFileName = NULL; //ConcatPath(g_SelfPath, L"CMYK.png");
	Gdiplus::GdiplusStartupInput gdiplusStartupInput;
	Gdiplus::Status lRc;
	Gdiplus::GpBitmap *img = NULL;
	UINT lWidth = 0, lHeight = 0, pf = 0, nBPP = 0;
	Gdiplus::BitmapData bmd; bool bBitsLocked = false;
	Gdiplus::GpRect rect(0, 0, 256, 256);

	typedef Gdiplus::Status (WINAPI *GdiplusStartup_t)(OUT ULONG_PTR *token, const Gdiplus::GdiplusStartupInput *input, OUT Gdiplus::GdiplusStartupOutput *output);
	typedef VOID (WINAPI *GdiplusShutdown_t)(ULONG_PTR token);
	typedef Gdiplus::GpStatus (WINGDIPAPI *GdipCreateBitmapFromFile_t)(GDIPCONST WCHAR* filename, Gdiplus::GpBitmap **bitmap);
	typedef Gdiplus::GpStatus (WINGDIPAPI *GdipGetImageWidth_t)(Gdiplus::GpImage *image, UINT *width);
	typedef Gdiplus::GpStatus (WINGDIPAPI *GdipGetImageHeight_t)(Gdiplus::GpImage *image, UINT *height);
	typedef Gdiplus::GpStatus (WINGDIPAPI *GdipGetImagePixelFormat_t)(Gdiplus::GpImage *image, Gdiplus::PixelFormat *format);
	typedef Gdiplus::GpStatus (WINGDIPAPI *GdipBitmapLockBits_t)(Gdiplus::GpBitmap* bitmap, GDIPCONST Gdiplus::GpRect* rect, UINT flags, Gdiplus::PixelFormat format, Gdiplus::BitmapData* lockedBitmapData);
	typedef Gdiplus::GpStatus (WINGDIPAPI *GdipBitmapUnlockBits_t)(Gdiplus::GpBitmap* bitmap, Gdiplus::BitmapData* lockedBitmapData);
	typedef Gdiplus::GpStatus (WINGDIPAPI *GdipDisposeImage_t)(Gdiplus::GpImage *image);

	#define DllGetFunction(hModule, FunctionName) FunctionName = (FunctionName##_t)GetProcAddress(hModule, #FunctionName)
	
	GdiplusStartup_t GdiplusStartup;
	GdiplusShutdown_t GdiplusShutdown;
	GdipCreateBitmapFromFile_t GdipCreateBitmapFromFile;
	GdipGetImageWidth_t GdipGetImageWidth;
	GdipGetImageHeight_t GdipGetImageHeight;
	GdipGetImagePixelFormat_t GdipGetImagePixelFormat;
	GdipBitmapLockBits_t GdipBitmapLockBits;
	GdipBitmapUnlockBits_t GdipBitmapUnlockBits;
	GdipDisposeImage_t GdipDisposeImage;


	//gs_CMYK_ErrorInfo[0] = 0;
	//g_Plugin.nCMYK_ErrorNumber = g_Plugin.nCMYK_LastError = 0;

	HRESULT hr = CoInitialize(NULL);
	if (!(bCoInitialized = SUCCEEDED(hr))) {
		//wsprintf(gs_CMYK_ErrorInfo, L"CoInitialize failed. Code=0x%08X", (DWORD)hr);
		g_Plugin.nCMYK_ErrorNumber = MICMYKCoInitializeFailed;
		g_Plugin.nCMYK_LastError = (DWORD)hr;
		goto wrap;
	}

	g_Plugin.hGDIPlus = LoadLibraryW(L"GdiPlus.dll");
	if (!g_Plugin.hGDIPlus) {
		//dwLastError = GetLastError();
		//wsprintf(gs_CMYK_ErrorInfo, L"LoadLibrary(GdiPlus.dll) failed. Code=0x%08X", (DWORD)hr);
		g_Plugin.nCMYK_ErrorNumber = MICMYKLoadLibraryFailed;
		g_Plugin.nCMYK_LastError = GetLastError();
		goto wrap;
	}

	DllGetFunction(g_Plugin.hGDIPlus, GdiplusStartup);
	DllGetFunction(g_Plugin.hGDIPlus, GdiplusShutdown);
	DllGetFunction(g_Plugin.hGDIPlus, GdipCreateBitmapFromFile);
	DllGetFunction(g_Plugin.hGDIPlus, GdipGetImageWidth);
	DllGetFunction(g_Plugin.hGDIPlus, GdipGetImageHeight);
	DllGetFunction(g_Plugin.hGDIPlus, GdipGetImagePixelFormat);
	DllGetFunction(g_Plugin.hGDIPlus, GdipBitmapLockBits);
	DllGetFunction(g_Plugin.hGDIPlus, GdipBitmapUnlockBits);
	DllGetFunction(g_Plugin.hGDIPlus, GdipDisposeImage);

	if (!GdiplusStartup || !GdiplusShutdown || !GdipCreateBitmapFromFile || !GdipGetImageWidth || !GdipGetImageHeight 
		|| !GdipGetImagePixelFormat || !GdipBitmapLockBits || !GdipBitmapUnlockBits || !GdipDisposeImage)
	{
		//lstrcpy(gs_CMYK_ErrorInfo, L"One of GdiPlus flat api functions not found!");
		g_Plugin.nCMYK_ErrorNumber = MICMYKBadGdiFlat;
		goto wrap;
	}

	bTokenInitialized = Gdiplus::Ok == (lRc = GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL));
	if (!bTokenInitialized) {
		//wsprintf(gs_CMYK_ErrorInfo, L"GdiplusStartup failed. Code=%i", (DWORD)lRc);
		g_Plugin.nCMYK_ErrorNumber = MICMYKGdipStartupFailed;
		g_Plugin.nCMYK_LastError = (DWORD)lRc;
		goto wrap;
	}

	pszFileName = ConcatPath(g_SelfPath, L"CMYK.png");

	if (Gdiplus::Ok != (lRc = GdipCreateBitmapFromFile(pszFileName, &img))) {
		//wsprintf(gs_CMYK_ErrorInfo, L"GdipCreateBitmapFromFile(CMYK.png) failed. Code=%i", (DWORD)lRc);
		g_Plugin.nCMYK_ErrorNumber = MICMYKCreateBitmapFailed;
		g_Plugin.nCMYK_LastError = (DWORD)lRc;
		goto wrap;
	}

	lRc = GdipGetImageWidth(img, &lWidth);
	lRc = GdipGetImageHeight(img, &lHeight);
	lRc = GdipGetImagePixelFormat(img, (Gdiplus::PixelFormat*)&pf);
	nBPP = pf >> 8 & 0xFF;

	if (lWidth != (16*16) || lHeight != (16*16)) {
		g_Plugin.nCMYK_ErrorNumber = MICMYKpaletteInvalidSize;
		goto wrap;
	}
	if (nBPP != 24 && nBPP != 32) {
		g_Plugin.nCMYK_ErrorNumber = MICMYKpaletteInvalidBPP;
		goto wrap;
	}

	rect.Width = lWidth; rect.Height = lHeight;

	if (Gdiplus::Ok != (lRc = GdipBitmapLockBits(img, &rect, Gdiplus::ImageLockModeRead, PixelFormat32bppRGB, &bmd))) {
		g_Plugin.nCMYK_ErrorNumber = MICMYKpaletteInvalidBPP;
		goto wrap;
	}
	bBitsLocked = true;



	g_Plugin.nCMYKparts = 17; // пока фиксировано
	g_Plugin.nCMYKsize = lWidth * lHeight;
	g_Plugin.pCMYKpalette = (DWORD*)calloc(g_Plugin.nCMYKsize,4);

	if (!g_Plugin.pCMYKpalette) {
		g_Plugin.nCMYK_ErrorNumber = MIMemoryAllocationFailed;
		goto wrap;

	} else {

		BYTE* pDst = (BYTE*)g_Plugin.pCMYKpalette;
		BYTE* pSrc = (BYTE*)bmd.Scan0;
		uint lAbsSrcPitch = 0;
		int lDstPitch = lWidth * 4;

		if (bmd.Stride < 0)
		{
			pDst += (int)(lHeight - 1) * lDstPitch;
			lAbsSrcPitch = -bmd.Stride;
			lDstPitch = -lDstPitch;
		} else {
			lAbsSrcPitch = bmd.Stride;
		}

		BltHelper::Blit32_BGRA(pDst, pSrc, 0, lWidth, lHeight, lAbsSrcPitch, lDstPitch, 0, 0, 0, 0);

		OutputDebugString(L"Succeeded.\n");
	}

	// OK

wrap:
	if (bBitsLocked) {
		GdipBitmapUnlockBits(img, &bmd); bBitsLocked = false;
	}
	if (img) {
		GdipDisposeImage(img); img = NULL;
	}
	if (pszFileName) {
		free(pszFileName); pszFileName = NULL;
	}
	if (bTokenInitialized) {
		GdiplusShutdown(gdiplusToken); bTokenInitialized = false;
	}
	//if (hGDIPlus) {
	//	FreeLibrary(hGDIPlus);
	//	hGDIPlus = NULL;
	//}
	//if (bCoInitialized)
	//	CoUninitialize();

	return 0;
}
Example #18
0
HRESULT Helpers::LoadScriptFromFile(LPCSTR filenameToLoad, LPCSTR& contents, UINT* lengthBytesOut /*= nullptr*/, std::string* fullPath /*= nullptr*/, bool shouldMute /*=false */)
{
    static char sHostApplicationPathBuffer[MAX_URI_LENGTH];
    static uint sHostApplicationPathBufferLength = (uint) -1;
    char combinedPathBuffer[MAX_URI_LENGTH];

    HRESULT hr = S_OK;
    BYTE * pRawBytes = nullptr;
    BYTE * pRawBytesFromMap = nullptr;
    UINT lengthBytes = 0;
    contents = nullptr;
    FILE * file = NULL;
    size_t bufferLength = 0;

    LPCSTR filename = fullPath == nullptr ? filenameToLoad : LPCSTR(fullPath->c_str());
    if (sHostApplicationPathBufferLength == (uint)-1)
    {
        // consider incoming filename as the host app and base its' path for others
        sHostApplicationPathBufferLength = GetPathNameLocation(filename);
        if (sHostApplicationPathBufferLength == -1)
        {
            // host app has no path info. (it must be located on current folder!)
            sHostApplicationPathBufferLength = 0;
        }
        else
        {
            sHostApplicationPathBufferLength += 1;
            Assert(sHostApplicationPathBufferLength < MAX_URI_LENGTH);
            // save host app's path and fix the path separator for platform
            pathcpy(sHostApplicationPathBuffer, filename, sHostApplicationPathBufferLength);
        }
        sHostApplicationPathBuffer[sHostApplicationPathBufferLength] = char(0);
    }
    else if (filename[0] != '/' && filename[0] != '\\' && fullPath == nullptr) // make sure it's not a full path
    {
        // concat host path and filename
        uint len = ConcatPath(sHostApplicationPathBuffer, sHostApplicationPathBufferLength,
                   filename, combinedPathBuffer, MAX_URI_LENGTH);

        if (len == (uint)-1)
        {
            hr = E_FAIL;
            goto Error;
        }
        filename = combinedPathBuffer;
    }

    // check if have it registered
    AutoString *data;
    if (SourceMap::Find(filenameToLoad, strlen(filenameToLoad), &data) ||
        SourceMap::Find(filename, strlen(filename), &data))
    {
        pRawBytesFromMap = (BYTE*) data->GetString();
        lengthBytes = (UINT) data->GetLength();
    }
    else
    {
        // Open the file as a binary file to prevent CRT from handling encoding, line-break conversions,
        // etc.
        if (fopen_s(&file, filename, "rb") != 0)
        {
            if (!HostConfigFlags::flags.MuteHostErrorMsgIsEnabled && !shouldMute)
            {
#ifdef _WIN32
                DWORD lastError = GetLastError();
                char16 wszBuff[MAX_URI_LENGTH];
                fprintf(stderr, "Error in opening file '%s' ", filename);
                wszBuff[0] = 0;
                if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                    nullptr,
                    lastError,
                    0,
                    wszBuff,
                    _countof(wszBuff),
                    nullptr))
                {
                    fwprintf(stderr, _u(": %s"), wszBuff);
                }
                fwprintf(stderr, _u("\n"));
#elif defined(_POSIX_VERSION)
                fprintf(stderr, "Error in opening file: ");
                perror(filename);
#endif
            }

            IfFailGo(E_FAIL);
        }
    }

    if (file != NULL)
    {
        // Determine the file length, in bytes.
        fseek(file, 0, SEEK_END);
        lengthBytes = ftell(file);
        fseek(file, 0, SEEK_SET);
    }

    if (lengthBytes != 0)
    {
        bufferLength = lengthBytes + sizeof(BYTE);
        pRawBytes = (LPBYTE)malloc(bufferLength);
    }
    else
    {
        bufferLength = 1;
        pRawBytes = (LPBYTE)malloc(bufferLength);
    }

    if (nullptr == pRawBytes)
    {
        fwprintf(stderr, _u("out of memory"));
        IfFailGo(E_OUTOFMEMORY);
    }

    if (lengthBytes != 0)
    {
        if (file != NULL)
        {
            //
            // Read the entire content as a binary block.
            //
            size_t readBytes = fread(pRawBytes, sizeof(BYTE), lengthBytes, file);
            if (readBytes < lengthBytes * sizeof(BYTE))
            {
                IfFailGo(E_FAIL);
            }
        }
        else // from module source register
        {
            // Q: module source is on persistent memory. Why do we use the copy instead?
            // A: if we use the same memory twice, ch doesn't know that during FinalizeCallback free.
            // the copy memory will be freed by the finalizer
            Assert(pRawBytesFromMap);
            memcpy_s(pRawBytes, bufferLength, pRawBytesFromMap, lengthBytes);
        }
    }

    if (pRawBytes)
    {
        pRawBytes[lengthBytes] = 0; // Null terminate it. Could be UTF16
    }

    if (file != NULL)
    {
        //
        // Read encoding to make sure it's supported
        //
        // Warning: The UNICODE buffer for parsing is supposed to be provided by the host.
        // This is not a complete read of the encoding. Some encodings like UTF7, UTF1, EBCDIC, SCSU, BOCU could be
        // wrongly classified as ANSI
        //
#pragma warning(push)
        // suppressing prefast warning that "readable size is bufferLength
        // bytes but 2 may be read" as bufferLength is clearly > 2 in the code that follows
#pragma warning(disable:6385)
        C_ASSERT(sizeof(WCHAR) == 2);
        if (bufferLength > 2)
        {
            __analysis_assume(bufferLength > 2);
#pragma prefast(push)
#pragma prefast(disable:6385, "PREfast incorrectly reports this as an out-of-bound access.");
            if ((pRawBytes[0] == 0xFE && pRawBytes[1] == 0xFF) ||
                (pRawBytes[0] == 0xFF && pRawBytes[1] == 0xFE) ||
                (bufferLength > 4 && pRawBytes[0] == 0x00 && pRawBytes[1] == 0x00 &&
                    ((pRawBytes[2] == 0xFE && pRawBytes[3] == 0xFF) ||
                    (pRawBytes[2] == 0xFF && pRawBytes[3] == 0xFE))))

            {
                // unicode unsupported
                fwprintf(stderr, _u("unsupported file encoding. Only ANSI and UTF8 supported"));
                IfFailGo(E_UNEXPECTED);
            }
#pragma prefast(pop)
        }
#pragma warning(pop)
    }

    contents = reinterpret_cast<LPCSTR>(pRawBytes);

Error:
    if (SUCCEEDED(hr))
    {
        if (lengthBytesOut)
        {
            *lengthBytesOut = lengthBytes;
        }
    }

    if (file != NULL)
    {
        fclose(file);
    }

    if (pRawBytes && reinterpret_cast<LPCSTR>(pRawBytes) != contents)
    {
        free(pRawBytes);
    }

    return hr;
}