Beispiel #1
0
//登録名・ファイルのパス・フォントの名前を指定
//ex ("HG96", "hoge.ttf", "Hogeman's_Font", 96, 5)
void Font::LoadFont(std::string reg_name, std::string file_path, std::string font_name, int fontsize, int thick){

	file_path = "Fonts/" + file_path;
	const char* filename = file_path.c_str();

	// ファイルのサイズを得る
	int FontFileSize = FileRead_size(filename);
	// フォントファイルを開く
	int FontFileHandle = FileRead_open(filename);
	// フォントデータ格納用のメモリ領域を確保
	void *Buffer = malloc(FontFileSize);
	// フォントファイルを丸ごとメモリに読み込む
	FileRead_read(Buffer, FontFileSize, FontFileHandle);
	// AddFontMemResourceEx引数用
	DWORD font_num = 0;
	// メモリに読み込んだフォントデータをシステムに追加
	if (AddFontMemResourceEx(Buffer, FontFileSize, NULL, &font_num) != 0){}
	else
	{
		// フォント読込エラー処理
		MessageBox(NULL, "フォント読込失敗", "", MB_OK);
	}

	int tmp_handle = CreateFontToHandle(font_name.c_str(), fontsize, thick, DX_FONTTYPE_ANTIALIASING_4X4);
	handlemap.emplace(reg_name.c_str(), tmp_handle);
}
    WindowsTypeface (const void* data, size_t dataSize)
        : Typeface (String(), String()),
          fontH (0), previousFontH (0),
          dc (CreateCompatibleDC (0)), memoryFont (0),
          ascent (1.0f), heightToPointsFactor (1.0f),
          defaultGlyph (-1)
    {
        DWORD numInstalled = 0;
        memoryFont = AddFontMemResourceEx (const_cast<void*> (data), (DWORD) dataSize,
                                           nullptr, &numInstalled);

        MemoryInputStream m (data, dataSize, false);
        name = TTFNameExtractor::getTypefaceNameFromFile (m);
        loadFont();
    }
Beispiel #3
0
// Rename the font and install the new font data into the system
HANDLE renameAndActivateFont(const SharedBuffer& fontData, const String& fontName)
{
    Vector<char> rewrittenFontData;
    if (!renameFont(fontData, fontName, rewrittenFontData))
        return 0;

    DWORD numFonts = 0;
    HANDLE fontHandle = AddFontMemResourceEx(rewrittenFontData.data(), rewrittenFontData.size(), 0, &numFonts);

    if (fontHandle && numFonts < 1) {
        RemoveFontMemResourceEx(fontHandle);
        return 0;
    }

    return fontHandle;
}
int DirectXDraw9::LoadFontFile( HMODULE module, const char *resource )
{
	void *font;
	HRSRC hres;
	unsigned long count;

	hres = FindResource( module, resource, "FONTFILE" );
	font = LockResource( LoadResource( NULL, hres ) );

	if ( AddFontMemResourceEx( font, SizeofResource( NULL, hres ), NULL, &count ) == NULL )
	{
		return 1;
	}

	return 0;
}
// Rename the font and install the new font data into the system
HANDLE renameAndActivateFont(SharedBuffer* fontData, const String& fontName)
{
    Vector<char> rewrittenFontData;
    size_t nameTableSize = renameFont(fontData, fontName, rewrittenFontData);
    if (!nameTableSize)
        return 0;

    DWORD numFonts = 0;
    HANDLE fontHandle = AddFontMemResourceEx(rewrittenFontData.data(), fontData->size() + nameTableSize, 0, &numFonts);

    if (fontHandle && numFonts < 1) {
        RemoveFontMemResourceEx(fontHandle);
        return 0;
    }

    return fontHandle;
}
/*
=================
- Use windows to create a custom font in memory.
=================
*/
HRESULT cD3DXFont::createCustomFont(HINSTANCE hInstance, LPCSTR fontName)	// Use windows to create a custom font in memory;
{
	 if (locateFontResource(hInstance, fontName)) 
     {
          HGLOBAL mem = LoadResource(hInstance, mCustFont);
          void *data = LockResource(mem);
          size_t len = SizeofResource(hInstance, mCustFont);

          DWORD nFonts;
          mHFontHdle = AddFontMemResourceEx(data, len, NULL, &nFonts);

          if(mHFontHdle == 0)
		  {
			  OutputDebugString("Error: Font add fails");
			  return S_FALSE;
		  }
     }
	 return S_OK;
}
Beispiel #7
0
/*****************************************************************************
 * GdipPrivateAddMemoryFont [GDIPLUS.@]
 */
GpStatus WINGDIPAPI GdipPrivateAddMemoryFont(GpFontCollection* fontCollection,
        GDIPCONST void* memory, INT length)
{
    WCHAR buf[32], *name;
    DWORD count = 0;
    HANDLE font;
    TRACE("%p, %p, %d\n", fontCollection, memory, length);

    if (!fontCollection || !memory || !length)
        return InvalidParameter;

    name = load_ttf_name_id(memory, length, NAME_ID_FULL_FONT_NAME, buf, sizeof(buf)/sizeof(*buf));
    if (!name)
        return OutOfMemory;

    font = AddFontMemResourceEx((void*)memory, length, NULL, &count);
    TRACE("%s: %p/%u\n", debugstr_w(name), font, count);
    if (!font || !count)
        return InvalidParameter;

    if (count)
    {
        HDC hdc;
        LOGFONTW lfw;

        hdc = GetDC(0);

        lfw.lfCharSet = DEFAULT_CHARSET;
        lstrcpyW(lfw.lfFaceName, name);
        lfw.lfPitchAndFamily = 0;

        if (!EnumFontFamiliesExW(hdc, &lfw, add_font_proc, (LPARAM)fontCollection, 0))
        {
            ReleaseDC(0, hdc);
            return OutOfMemory;
        }

        ReleaseDC(0, hdc);
    }
    return Ok;
}
Beispiel #8
0
gfxFontEntry* 
gfxGDIFontList::MakePlatformFont(const gfxProxyFontEntry *aProxyEntry, 
                                 const PRUint8 *aFontData,
                                 PRUint32 aLength)
{
    // MakePlatformFont is responsible for deleting the font data with NS_Free
    // so we set up a stack object to ensure it is freed even if we take an
    // early exit
    struct FontDataDeleter {
        FontDataDeleter(const PRUint8 *aFontData)
            : mFontData(aFontData) { }
        ~FontDataDeleter() { NS_Free((void*)mFontData); }
        const PRUint8 *mFontData;
    };
    FontDataDeleter autoDelete(aFontData);

    // if calls aren't available, bail
    if (!TTLoadEmbeddedFontPtr || !TTDeleteEmbeddedFontPtr)
        return nsnull;

    PRBool isCFF = gfxFontUtils::IsCffFont(aFontData);
        
    nsresult rv;
    HANDLE fontRef = nsnull;
    PRBool isEmbedded = PR_FALSE;

    nsAutoString uniqueName;
    rv = gfxFontUtils::MakeUniqueUserFontName(uniqueName);
    if (NS_FAILED(rv))
        return nsnull;

    // for TTF fonts, first try using the t2embed library
    if (!isCFF) {
        // TrueType-style glyphs, use EOT library
        AutoFallibleTArray<PRUint8,2048> eotHeader;
        PRUint8 *buffer;
        PRUint32 eotlen;

        isEmbedded = PR_TRUE;
        PRUint32 nameLen = PR_MIN(uniqueName.Length(), LF_FACESIZE - 1);
        nsPromiseFlatString fontName(Substring(uniqueName, 0, nameLen));
        
        FontDataOverlay overlayNameData = {0, 0, 0};

        rv = gfxFontUtils::MakeEOTHeader(aFontData, aLength, &eotHeader, 
                                         &overlayNameData);
        if (NS_SUCCEEDED(rv)) {

            // load in embedded font data
            eotlen = eotHeader.Length();
            buffer = reinterpret_cast<PRUint8*> (eotHeader.Elements());
            
            PRInt32 ret;
            ULONG privStatus, pulStatus;
            EOTFontStreamReader eotReader(aFontData, aLength, buffer, eotlen,
                                          &overlayNameData);

            ret = TTLoadEmbeddedFontPtr(&fontRef, TTLOAD_PRIVATE, &privStatus,
                                       LICENSE_PREVIEWPRINT, &pulStatus,
                                       EOTFontStreamReader::ReadEOTStream,
                                       &eotReader,
                                       (PRUnichar*)(fontName.get()), 0, 0);
            if (ret != E_NONE) {
                fontRef = nsnull;
                char buf[256];
                sprintf(buf, "font (%s) not loaded using TTLoadEmbeddedFont - error %8.8x", NS_ConvertUTF16toUTF8(aProxyEntry->FamilyName()).get(), ret);
                NS_WARNING(buf);
            }
        }
    }

    // load CFF fonts or fonts that failed with t2embed loader
    if (fontRef == nsnull) {
        // Postscript-style glyphs, swizzle name table, load directly
        FallibleTArray<PRUint8> newFontData;

        isEmbedded = PR_FALSE;
        rv = gfxFontUtils::RenameFont(uniqueName, aFontData, aLength, &newFontData);

        if (NS_FAILED(rv))
            return nsnull;
        
        DWORD numFonts = 0;

        PRUint8 *fontData = reinterpret_cast<PRUint8*> (newFontData.Elements());
        PRUint32 fontLength = newFontData.Length();
        NS_ASSERTION(fontData, "null font data after renaming");

        // http://msdn.microsoft.com/en-us/library/ms533942(VS.85).aspx
        // "A font that is added by AddFontMemResourceEx is always private 
        //  to the process that made the call and is not enumerable."
        fontRef = AddFontMemResourceEx(fontData, fontLength, 
                                       0 /* reserved */, &numFonts);
        if (!fontRef)
            return nsnull;

        // only load fonts with a single face contained in the data
        if (fontRef && numFonts != 1) {
            RemoveFontMemResourceEx(fontRef);
            return nsnull;
        }
    }

    // make a new font entry using the unique name
    WinUserFontData *winUserFontData = new WinUserFontData(fontRef, isEmbedded);
    PRUint16 w = (aProxyEntry->mWeight == 0 ? 400 : aProxyEntry->mWeight);

    GDIFontEntry *fe = GDIFontEntry::CreateFontEntry(uniqueName, 
        gfxWindowsFontType(isCFF ? GFX_FONT_TYPE_PS_OPENTYPE : GFX_FONT_TYPE_TRUETYPE) /*type*/, 
        PRUint32(aProxyEntry->mItalic ? FONT_STYLE_ITALIC : FONT_STYLE_NORMAL), 
        w, winUserFontData);

    if (!fe)
        return fe;

    fe->mIsUserFont = PR_TRUE;

    // Uniscribe doesn't place CFF fonts loaded privately 
    // via AddFontMemResourceEx on XP/Vista
    if (isCFF && gfxWindowsPlatform::WindowsOSVersion() 
                 < gfxWindowsPlatform::kWindows7) {
        fe->mForceGDI = PR_TRUE;
    }
 
    return fe;
}
Beispiel #9
0
int kGUIFace::LoadFont(const char *filename,bool bold)
{
	int size,glyph_index;
	int advance;
	unsigned int c;
	unsigned long fontfilesize;

	m_haskerning=false;
	m_bold=bold;
	/* handle bigfile based fonts */
	m_memfile=kGUI::LoadFile(filename,&fontfilesize);
	assert(m_memfile!=0,"Couldn't find font!");

#if defined(WIN32) || defined(MINGW)
	//windows only, this is so that when printing, reports can use these fonts too!
	AddFontMemResourceEx(m_memfile, fontfilesize,0,&kGUIFont::m_numreg);
#elif defined(LINUX) || defined(MACINTOSH)
#else
#error
#endif

	if(FT_New_Memory_Face( kGUIFont::GetLibrary(),
							m_memfile,	/* first byte in memory */
							fontfilesize,	/* size in bytes */
							0,				/* face_index */
							GetFacePtr() ))
		return(-1);

	/* make a name for this font */
	if(!strcmp(m_ftface->style_name, "Regular"))
		m_name.Sprintf("%s", m_ftface->family_name);
    else
        m_name.Sprintf("%s %s",m_ftface->family_name, m_ftface->style_name);

	/* calculate pixel heights for different sizes of this font */
	for(size=1;size<=MAXFONTSIZE;++size)
	{
		kGUI::SelectFont(this,size);
		m_pixabove[size]=-1;
		m_pixbelow[size]=-1;

		/* pre-calculate character widths */
		if(size<=MAXQUICKSIZE)
		{
			for(c=0;c<MAXCCACHE;++c)
			{
				advance=0;
				glyph_index = FT_Get_Char_Index( m_ftface, c );
				if(glyph_index>0)
				{
					if(FT_Load_Glyph(m_ftface, glyph_index, FT_LOAD_DEFAULT)==0)
					{
						if(bold)
						{
							if(!FT_Render_Glyph( m_ftface->glyph, ft_render_mode_normal ))
								FT_GlyphSlot_Embolden(m_ftface->glyph);
						}
						advance=m_ftface->glyph->advance.x >> 6;
					}
				}
				m_quickwidths[size][c]=advance;
			}
		}
	}
	m_haskerning = FT_HAS_KERNING( m_ftface )!=0; 

	return(0);	/* ok */
}
Beispiel #10
0
void loadFontFromMemory(void* font_data, int num_bytes) {
    DWORD one = 1;
    assert(AddFontMemResourceEx(font_data, num_bytes, 0, &one));
}
BOOL COngTVApp::InitInstance()
{
    // customisation des barres d'outils non autorisée
    CMFCToolBar::SetCustomizeMode(FALSE);
#ifdef SCINTILLA_DLL
    // Chargement de la DLL Scintilla : on va la chercher dans le repertoire de l'exe et nul part ailleurs
    // recuperation du path de l'exe
    char lpFilename[255];
    memset(lpFilename,0,255);
    GetModuleFileName(NULL ,lpFilename, 255);
    std::string strSciLexerDllName = CPathMgr::ExtractPath(lpFilename);
    strSciLexerDllName = strSciLexerDllName + "\\SciLexer.dll";
    m_hSciDLL = LoadLibrary(strSciLexerDllName.c_str());
    if (NULL == m_hSciDLL)
    {
        // DLL scintilla non disponible => on ne pourra pas editer de scrip LUA
    }
    else
    {
        CVersion versionSciDLL(strSciLexerDllName);
        if (versionSciDLL.GetProductVersion() < std::string(EXPECTED_SCINTILLA_VERSION))
        {
            // version de la DLL inferieur a la version attendue => on ne pourra pas editer de scrip LUA
            FreeLibrary(m_hSciDLL);
            m_hSciDLL = NULL;
            std::string strMsgError = "Dll min expected version : "EXPECTED_SCINTILLA_VERSION" obtained : ";
            strMsgError += versionSciDLL.GetProductVersion();
            MessageBox(NULL, strMsgError.c_str(), "Unable to load SciLexer.dll", MB_ICONEXCLAMATION);
        }
    }
#endif

#ifdef TEST_ENGLISH
    // Pour forcer une langue
    ::SetThreadLocale(MAKELCID(MAKELANGID(LANG_ENGLISH,
                       SUBLANG_DEFAULT),SORT_DEFAULT));
#endif

    // nettoyage des clefs de registres de la version precedente
    // si la version qui s'execute n'est pas identique a celle enregistree dans la base de registres
    // MFCFP = MFC Feature Pack => pour pouvoir faire cohabiter sur un même PC des versions antérieures à la 1.6.0 et des versions postérieures
    // a la 1.6.0
    // avant la 1.6.0 => IHM basée sur UltimateToolbox et sauvegarde des caractéristiques des fenêtres à plat dans la base de registre
    // à partir de 1.6.0 => IHM basée sur MFC Feature Pack et sauvegarde des caractéristiques des fenêtres dans une arborescence de clefs
    // dans la base de registres
    // le nettoyage de la base de registres plantait si on essaiyait de revenir à une version < 1.6.0 => on différencie la clef de base

    std::string strReg = "\\CurrentUser\\Software\\" + m_versionInfos.GetCompanyName() + "\\" + m_versionInfos.GetProductName() + "MFCFP\\";
    g_Registry.SetFullRegistryItem(strReg.c_str());
    CString sVersion=g_Registry.GetStringValue(REGISTRY_KEY_VERSION);
    CString sProductVersion(m_versionInfos.GetProductVersion().c_str());
    if (sVersion != sProductVersion)
    {
        DeleteRegTree(&g_Registry);
    }
    g_Registry.Close();

    // Pour utilisation de RichEditCtrl
    AfxEnableControlContainer();
    AfxInitRichEdit();
    // InitCommonControlsEx() est requis sur Windows XP si le manifeste de l'application
    // spécifie l'utilisation de ComCtl32.dll version 6 ou ultérieure pour activer les
    // styles visuels.  Dans le cas contraire, la création de fenêtres échouera.
    INITCOMMONCONTROLSEX InitCtrls;
    InitCtrls.dwSize = sizeof(InitCtrls);
    // À définir pour inclure toutes les classes de contrôles communs à utiliser
    // dans votre application.
    InitCtrls.dwICC = ICC_WIN95_CLASSES;
    InitCommonControlsEx(&InitCtrls);

    InitContextMenuManager();
    InitShellManager();
    InitKeyboardManager();
    InitTooltipManager();
    CMFCToolTipInfo ttParams;
    ttParams.m_bVislManagerTheme = TRUE;
    GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL, RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams);

    // enregistrement Scintilla
#ifndef SCINTILLA_DLL
    Scintilla_RegisterClasses(AfxGetInstanceHandle());
    Scintilla_LinkLexers();
#endif

// Supprime pour la gestion multi-lingues
//    CWinAppEx::InitInstance();


    // Initialisation standard
    // Si vous n'utilisez pas ces fonctionnalités et que vous souhaitez réduire la taille
    // de votre exécutable final, vous devez supprimer ci-dessous
    // les routines d'initialisation spécifiques dont vous n'avez pas besoin.
    // Changez la clé de Registre sous laquelle nos paramètres sont enregistrés
    // TODO : modifiez cette chaîne avec des informations appropriées,
    // telles que le nom de votre société ou organisation
    SetRegistryKey(m_versionInfos.GetCompanyName().c_str());

    //First free the string allocated by MFC at CWinApp startup.
    //The string is allocated before InitInstance is called.
    free((void*)m_pszProfileName);
    //Change the name of the .INI file.
    //The CWinApp destructor will free the memory.
    // Ce nom est utilise pour la sauvegarde des parametres
    strReg = m_versionInfos.GetProductName() + "MFCFP";
    m_pszProfileName = _tcsdup(strReg.c_str());

    LoadStdProfileSettings(4);  // Charge les options de fichier INI standard (y compris les derniers fichiers utilisés)
    // Inscrire les modèles de document de l'application. Ces modèles
    //  lient les documents, fenêtres frame et vues entre eux
    
    // creation du manager de doc specifique afin de gerer specifiquement les repertoires
    // de sauvegarde des diffents documents.
    // cf http://www.codeguru.com/cpp/w-d/dislog/commondialogs/article.php/c1967
    m_pDocManager = new COngTVDocManager;

    // Creation doc template pour les scripts LUA (uniquement si DLL scintilla disponible)
    if (NULL != m_hSciDLL)
    {
        m_pNewLuaDocTemplate = new CMultiDocTemplate( IDR_LUATYPE
                                                    , RUNTIME_CLASS(CLuaDoc)
                                                    , RUNTIME_CLASS(CLuaChildFrame)
                                                    , RUNTIME_CLASS(CLuaView)
                                                    );
        if (!m_pNewLuaDocTemplate)
            return FALSE;
        AddDocTemplate(m_pNewLuaDocTemplate);
    }

    // Installe la police DINA
    HRSRC hRes   = FindResource(NULL, MAKEINTRESOURCE(IDR_DINA), _T("DINA"));
    PVOID lpFont = LockResource(LoadResource(NULL, hRes)); 
    DWORD dwSize = SizeofResource(NULL, hRes), cFonts = 0;
    m_hDinaFont = AddFontMemResourceEx(lpFont, dwSize, NULL, &cFonts);
    ASSERT(cFonts > 0);

    // crée la fenêtre frame MDI principale
    CMainFrame* pMainFrame = new CMainFrame;
    // On parse la ligne de commande
    CCmdLine cmdLine;
    cmdLine.SplitLine(__argc, __argv);
    // On indique le fichier de configuration ("" par defaut)
    std::string configFileName = cmdLine.GetSafeArgument("-cnx", 0, "");
    pMainFrame->SetConfigFile(configFileName);

    m_pMainWnd = pMainFrame;
    if (!pMainFrame || !pMainFrame->LoadFrame(IDR_MAINFRAME))
    {
        delete pMainFrame;
        return FALSE;
    }

    // La fenêtre principale a été initialisée et peut donc être affichée et mise à jour
    pMainFrame->ShowWindow(m_nCmdShow);
    pMainFrame->UpdateWindow();

    return TRUE;
}