update emoji autocorrect entries from po-files
[LibreOffice.git] / vcl / source / gdi / embeddedfontshelper.cxx
blob6a4f79260d99797aadd06d9cae2c557758c9249c
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
10 #include <config_folders.h>
11 #include <config_eot.h>
13 #include <osl/file.hxx>
14 #include <rtl/bootstrap.hxx>
15 #include <vcl/outdev.hxx>
16 #include <vcl/svapp.hxx>
18 #include "fontsubset.hxx"
19 #include "outdev.h"
20 #include "outfont.hxx"
21 #include "PhysicalFontCollection.hxx"
22 #include "salgdi.hxx"
23 #include "sft.hxx"
25 #include <vcl/embeddedfontshelper.hxx>
27 #if ENABLE_EOT
28 extern "C"
30 namespace libeot
32 #include <libeot/libeot.h>
33 } // namespace libeot
34 } // extern "C"
35 #endif
37 using namespace com::sun::star;
38 using namespace vcl;
40 static void clearDir( const OUString& path )
42 osl::Directory dir( path );
43 if( dir.reset() == osl::Directory::E_None )
45 for(;;)
47 osl::DirectoryItem item;
48 if( dir.getNextItem( item ) != osl::Directory::E_None )
49 break;
50 osl::FileStatus status( osl_FileStatus_Mask_FileURL );
51 if( item.getFileStatus( status ) == osl::File::E_None )
52 osl::File::remove( status.getFileURL());
57 void EmbeddedFontsHelper::clearTemporaryFontFiles()
59 OUString path = "${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE( "bootstrap") "::UserInstallation}";
60 rtl::Bootstrap::expandMacros( path );
61 path += "/user/temp/embeddedfonts/";
62 clearDir( path + "fromdocs/" );
63 clearDir( path + "fromsystem/" );
66 bool EmbeddedFontsHelper::addEmbeddedFont( uno::Reference< io::XInputStream > stream, const OUString& fontName,
67 const char* extra, std::vector< unsigned char > key, bool eot )
69 OUString fileUrl = EmbeddedFontsHelper::fileUrlForTemporaryFont( fontName, extra );
70 osl::File file( fileUrl );
71 switch( file.open( osl_File_OpenFlag_Create | osl_File_OpenFlag_Write ))
73 case osl::File::E_None:
74 break; // ok
75 case osl::File::E_EXIST:
76 return true; // Assume it's already been added correctly.
77 default:
78 SAL_WARN( "vcl.fonts", "Cannot open file for temporary font" );
79 return false;
81 size_t keyPos = 0;
82 std::vector< char > fontData;
83 fontData.reserve( 1000000 );
84 for(;;)
86 uno::Sequence< sal_Int8 > buffer;
87 sal_uInt64 read = stream->readBytes( buffer, 1024 );
88 for( sal_uInt64 pos = 0;
89 pos < read && keyPos < key.size();
90 ++pos )
91 buffer[ pos ] ^= key[ keyPos++ ];
92 // if eot, don't write the file out yet, since we need to unpack it first.
93 if( !eot && read > 0 )
95 sal_uInt64 writtenTotal = 0;
96 while( writtenTotal < read )
98 sal_uInt64 written;
99 file.write( buffer.getConstArray(), read, written );
100 writtenTotal += written;
103 fontData.insert( fontData.end(), buffer.getConstArray(), buffer.getConstArray() + read );
104 if( read <= 0 )
105 break;
107 bool sufficientFontRights(false);
108 #if ENABLE_EOT
109 if( eot )
111 unsigned uncompressedFontSize = 0;
112 unsigned char *nakedPointerToUncompressedFont = NULL;
113 libeot::EOTMetadata eotMetadata;
114 libeot::EOTError uncompressError =
115 libeot::EOT2ttf_buffer( reinterpret_cast<unsigned char *>(&fontData[0]), fontData.size(), &eotMetadata, &nakedPointerToUncompressedFont, &uncompressedFontSize );
116 std::shared_ptr<unsigned char> uncompressedFont( nakedPointerToUncompressedFont, libeot::EOTfreeBuffer );
117 if( uncompressError != libeot::EOT_SUCCESS )
119 SAL_WARN( "vcl.fonts", "Failed to uncompress font" );
120 osl::File::remove( fileUrl );
121 return false;
123 sal_uInt64 writtenTotal = 0;
124 while( writtenTotal < uncompressedFontSize )
126 sal_uInt64 written;
127 if( file.write( uncompressedFont.get() + writtenTotal, uncompressedFontSize - writtenTotal, written ) != osl::File::E_None )
129 SAL_WARN( "vcl.fonts", "Error writing temporary font file" );
130 osl::File::remove( fileUrl );
131 return false;
133 writtenTotal += written;
135 sufficientFontRights = libeot::EOTcanLegallyEdit( &eotMetadata );
136 libeot::EOTfreeMetadata( &eotMetadata );
138 #endif
140 if( file.close() != osl::File::E_None )
142 SAL_WARN( "vcl.fonts", "Writing temporary font file failed" );
143 osl::File::remove( fileUrl );
144 return false;
146 if( !eot )
148 sufficientFontRights = sufficientTTFRights( &fontData.front(), fontData.size(), EditingAllowed );
150 if( !sufficientFontRights )
152 // It would be actually better to open the document in read-only mode in this case,
153 // warn the user about this, and provide a button to drop the font(s) in order
154 // to switch to editing.
155 SAL_INFO( "vcl.fonts", "Ignoring embedded font that is not usable for editing" );
156 osl::File::remove( fileUrl );
157 return false;
159 EmbeddedFontsHelper::activateFont( fontName, fileUrl );
160 return true;
163 OUString EmbeddedFontsHelper::fileUrlForTemporaryFont( const OUString& fontName, const char* extra )
165 OUString path = "${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE( "bootstrap") "::UserInstallation}";
166 rtl::Bootstrap::expandMacros( path );
167 path += "/user/temp/embeddedfonts/fromdocs/";
168 osl::Directory::createPath( path );
169 OUString filename = fontName;
170 static int uniqueCounter = 0;
171 if( strcmp( extra, "?" ) == 0 )
172 filename += OUString::number( uniqueCounter++ );
173 else
174 filename += OStringToOUString( extra, RTL_TEXTENCODING_ASCII_US );
175 filename += ".ttf"; // TODO is it always ttf?
176 return path + filename;
179 void EmbeddedFontsHelper::activateFont( const OUString& fontName, const OUString& fileUrl )
181 OutputDevice *pDevice = Application::GetDefaultDevice();
182 pDevice->AddTempDevFont(fileUrl, fontName);
185 // Check if it's (legally) allowed to embed the font file into a document
186 // (ttf has a flag allowing this). PhysicalFontFace::IsEmbeddable() appears
187 // to have a different meaning (guessing from code, IsSubsettable() might
188 // possibly mean it's ttf, while IsEmbeddable() might mean it's type1).
189 // So just try to open the data as ttf and see.
190 bool EmbeddedFontsHelper::sufficientTTFRights( const void* data, long size, FontRights rights )
192 TrueTypeFont* font;
193 if( OpenTTFontBuffer( data, size, 0 /*TODO*/, &font ) == SF_OK )
195 TTGlobalFontInfo info;
196 GetTTGlobalFontInfo( font, &info );
197 CloseTTFont( font );
198 // http://www.microsoft.com/typography/tt/ttf_spec/ttch02.doc
199 int copyright = info.typeFlags & TYPEFLAG_COPYRIGHT_MASK;
200 switch( rights )
202 case ViewingAllowed:
203 // Embedding not restricted completely.
204 return ( copyright & 0x02 ) != 0x02;
205 case EditingAllowed:
206 // Font is installable or editable.
207 return copyright == 0 || ( copyright & 0x08 );
210 return true; // no known restriction
213 OUString EmbeddedFontsHelper::fontFileUrl( const OUString& familyName, FontFamily family, FontItalic italic,
214 FontWeight weight, FontPitch pitch, rtl_TextEncoding, FontRights rights )
216 OUString path = "${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE( "bootstrap") "::UserInstallation}";
217 rtl::Bootstrap::expandMacros( path );
218 path += "/user/temp/embeddedfonts/fromsystem/";
219 osl::Directory::createPath( path );
220 OUString filename = familyName + "_" + OUString::number( family ) + "_" + OUString::number( italic )
221 + "_" + OUString::number( weight ) + "_" + OUString::number( pitch );
222 filename += ".ttf"; // TODO is it always ttf?
223 OUString url = path + filename;
224 if( osl::File( url ).open( osl_File_OpenFlag_Read ) == osl::File::E_None ) // = exists()
226 // File with contents of the font file already exists, assume it's been created by a previous call.
227 return url;
229 bool ok = false;
230 SalGraphics* graphics = Application::GetDefaultDevice()->GetGraphics();
231 PhysicalFontCollection fonts;
232 graphics->GetDevFontList( &fonts );
233 std::unique_ptr< ImplGetDevFontList > fontInfo( fonts.GetDevFontList());
234 PhysicalFontFace* selected = NULL;
235 for( int i = 0;
236 i < fontInfo->Count();
237 ++i )
239 PhysicalFontFace* f = fontInfo->Get( i );
240 if( f->GetFamilyName() == familyName )
242 // Ignore comparing text encodings, at least for now. They cannot be trivially compared
243 // (e.g. UCS2 and UTF8 are technically the same characters, just have different encoding,
244 // and just having a unicode font doesn't say what glyphs it actually contains).
245 // It is possible that it still may be needed to do at least some checks here
246 // for some encodings (can one font have more font files for more encodings?).
247 if(( family == FAMILY_DONTKNOW || f->GetFamilyType() == family )
248 && ( italic == ITALIC_DONTKNOW || f->GetSlant() == italic )
249 && ( weight == WEIGHT_DONTKNOW || f->GetWeight() == weight )
250 && ( pitch == PITCH_DONTKNOW || f->GetPitch() == pitch ))
251 { // Exact match, return it immediately.
252 selected = f;
253 break;
255 if(( f->GetFamilyType() == FAMILY_DONTKNOW || family == FAMILY_DONTKNOW || f->GetFamilyType() == family )
256 && ( f->GetSlant() == ITALIC_DONTKNOW || italic == ITALIC_DONTKNOW || f->GetSlant() == italic )
257 && ( f->GetWeight() == WEIGHT_DONTKNOW || weight == WEIGHT_DONTKNOW || f->GetWeight() == weight )
258 && ( f->GetPitch() == PITCH_DONTKNOW || pitch == PITCH_DONTKNOW || f->GetPitch() == pitch ))
259 { // Some fonts specify 'DONTKNOW' for some things, still a good match, if we don't find a better one.
260 selected = f;
264 if( selected != NULL )
266 FontSubsetInfo info;
267 long size;
268 if( const void* data = graphics->GetEmbedFontData( selected, NULL, NULL, 0, info, &size ))
270 if( sufficientTTFRights( data, size, rights ))
272 osl::File file( url );
273 if( file.open( osl_File_OpenFlag_Write | osl_File_OpenFlag_Create ) == osl::File::E_None )
275 sal_uInt64 written = 0;
276 sal_uInt64 totalSize = size;
277 bool error = false;
278 while( written < totalSize && !error)
280 sal_uInt64 nowWritten;
281 switch( file.write( static_cast< const char* >( data ) + written, size - written, nowWritten ))
283 case osl::File::E_None:
284 written += nowWritten;
285 break;
286 case osl::File::E_AGAIN:
287 case osl::File::E_INTR:
288 break;
289 default:
290 error = true;
291 break;
294 file.close();
295 if( error )
296 osl::File::remove( url );
297 else
298 ok = true;
301 graphics->FreeEmbedFontData( data, size );
304 return ok ? url : "";
307 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */