Branch libreoffice-5-0-4
[LibreOffice.git] / vcl / generic / print / printerjob.cxx
blob30b51f3062e10e4006a966fc0363bd81683b735f
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/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <stdio.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <fcntl.h>
24 #include <unistd.h>
26 #include "psputil.hxx"
27 #include "glyphset.hxx"
29 #include "generic/printerjob.hxx"
30 #include "generic/printergfx.hxx"
31 #include "vcl/ppdparser.hxx"
32 #include "vcl/strhelper.hxx"
33 #include "vcl/printerinfomanager.hxx"
35 #include "rtl/ustring.hxx"
36 #include "rtl/strbuf.hxx"
37 #include "rtl/ustrbuf.hxx"
39 #include <osl/thread.h>
40 #include <osl/security.hxx>
41 #include <sal/alloca.h>
42 #include <sal/macros.h>
44 #include <algorithm>
45 #include <vector>
47 using namespace psp;
49 #define nBLOCKSIZE 0x2000
51 namespace psp
54 bool
55 AppendPS (FILE* pDst, osl::File* pSrc, unsigned char* pBuffer,
56 sal_uInt32 nBlockSize = nBLOCKSIZE)
58 if ((pDst == NULL) || (pSrc == NULL))
59 return false;
61 if (pSrc->setPos(osl_Pos_Absolut, 0) != osl::FileBase::E_None)
62 return false;
64 if (nBlockSize == 0)
65 nBlockSize = nBLOCKSIZE;
66 if (pBuffer == NULL)
67 pBuffer = static_cast<unsigned char*>(alloca (nBlockSize));
69 sal_uInt64 nIn = 0;
70 sal_uInt64 nOut = 0;
73 pSrc->read (pBuffer, nBlockSize, nIn);
74 if (nIn > 0)
75 nOut = fwrite (pBuffer, 1, sal::static_int_cast<sal_uInt32>(nIn), pDst);
77 while ((nIn > 0) && (nIn == nOut));
79 return true;
82 } // namespace psp
85 * private convenience routines for file handling
88 osl::File*
89 PrinterJob::CreateSpoolFile (const OUString& rName, const OUString& rExtension)
91 osl::File* pFile = NULL;
93 OUString aFile = rName + rExtension;
94 OUString aFileURL;
95 osl::File::RC nError = osl::File::getFileURLFromSystemPath( aFile, aFileURL );
96 if (nError != osl::File::E_None)
97 return NULL;
98 aFileURL = maSpoolDirName + "/" + aFileURL;
100 pFile = new osl::File (aFileURL);
101 nError = pFile->open (osl_File_OpenFlag_Read | osl_File_OpenFlag_Write | osl_File_OpenFlag_Create);
102 if (nError != osl::File::E_None)
104 delete pFile;
105 return NULL;
108 osl::File::setAttributes (aFileURL,
109 osl_File_Attribute_OwnWrite | osl_File_Attribute_OwnRead);
110 return pFile;
114 * public methods of PrinterJob: for use in PrinterGfx
117 void
118 PrinterJob::GetScale (double &rXScale, double &rYScale) const
120 rXScale = mfXScale;
121 rYScale = mfYScale;
124 sal_uInt16
125 PrinterJob::GetDepth () const
127 sal_Int32 nLevel = GetPostscriptLevel();
128 bool bColor = IsColorPrinter ();
130 return nLevel > 1 && bColor ? 24 : 8;
133 sal_uInt16
134 PrinterJob::GetPostscriptLevel (const JobData *pJobData) const
136 sal_uInt16 nPSLevel = 2;
138 if( pJobData == NULL )
139 pJobData = &m_aLastJobData;
141 if( pJobData->m_nPSLevel )
142 nPSLevel = pJobData->m_nPSLevel;
143 else
144 if( pJobData->m_pParser )
145 nPSLevel = pJobData->m_pParser->getLanguageLevel();
147 return nPSLevel;
150 bool
151 PrinterJob::IsColorPrinter () const
153 bool bColor = false;
155 if( m_aLastJobData.m_nColorDevice )
156 bColor = m_aLastJobData.m_nColorDevice != -1;
157 else if( m_aLastJobData.m_pParser )
158 bColor = m_aLastJobData.m_pParser->isColorDevice();
160 return bColor;
163 osl::File*
164 PrinterJob::GetCurrentPageHeader ()
166 return maHeaderList.back();
169 osl::File*
170 PrinterJob::GetCurrentPageBody ()
172 return maPageList.back();
176 * public methods of PrinterJob: the actual job / spool handling
178 PrinterJob::PrinterJob()
179 : mnFileMode(0)
180 , mpJobHeader(NULL)
181 , mpJobTrailer(NULL)
182 , m_pGraphics(NULL)
183 , mnResolution(96)
184 , mnWidthPt(0)
185 , mnHeightPt(0)
186 , mnMaxWidthPt(0)
187 , mnMaxHeightPt(0)
188 , mnLandscapes(0)
189 , mnPortraits(0)
190 , mnLMarginPt(0)
191 , mnRMarginPt(0)
192 , mnTMarginPt(0)
193 , mnBMarginPt(0)
194 , mfXScale(1)
195 , mfYScale(1)
196 , m_bQuickJob(false)
200 /* remove all our temporary files, uses external program "rm", since
201 osl functionality is inadequate */
202 void
203 removeSpoolDir (const OUString& rSpoolDir)
205 OUString aSysPath;
206 if( osl::File::E_None != osl::File::getSystemPathFromFileURL( rSpoolDir, aSysPath ) )
208 // Conversion did not work, as this is quite a dangerous action,
209 // we should abort here ....
210 OSL_FAIL( "psprint: couldn't remove spool directory" );
211 return;
213 OString aSysPathByte =
214 OUStringToOString (aSysPath, osl_getThreadTextEncoding());
215 sal_Char pSystem [128];
216 sal_Int32 nChar = 0;
218 nChar = psp::appendStr ("rm -rf ", pSystem);
219 nChar += psp::appendStr (aSysPathByte.getStr(), pSystem + nChar);
221 if (system (pSystem) == -1)
222 OSL_FAIL( "psprint: couldn't remove spool directory" );
225 /* creates a spool directory with a "pidgin random" value based on
226 current system time */
227 OUString
228 createSpoolDir ()
230 TimeValue aCur;
231 osl_getSystemTime( &aCur );
232 sal_Int32 nRand = aCur.Seconds ^ (aCur.Nanosec/1000);
234 OUString aTmpDir;
235 osl_getTempDirURL( &aTmpDir.pData );
239 OUStringBuffer aDir( aTmpDir.getLength() + 16 );
240 aDir.append( aTmpDir );
241 aDir.appendAscii( "/psp" );
242 aDir.append(nRand);
243 OUString aResult = aDir.makeStringAndClear();
244 if( osl::Directory::create( aResult ) == osl::FileBase::E_None )
246 osl::File::setAttributes( aResult,
247 osl_File_Attribute_OwnWrite
248 | osl_File_Attribute_OwnRead
249 | osl_File_Attribute_OwnExe );
250 return aResult;
252 nRand++;
253 } while( nRand );
254 return OUString();
257 PrinterJob::~PrinterJob ()
259 std::list< osl::File* >::iterator pPage;
260 for (pPage = maPageList.begin(); pPage != maPageList.end(); ++pPage)
262 //(*pPage)->remove();
263 delete *pPage;
265 for (pPage = maHeaderList.begin(); pPage != maHeaderList.end(); ++pPage)
267 //(*pPage)->remove();
268 delete *pPage;
270 // mpJobHeader->remove();
271 delete mpJobHeader;
272 // mpJobTrailer->remove();
273 delete mpJobTrailer;
275 // XXX should really call osl::remove routines
276 if( !maSpoolDirName.isEmpty() )
277 removeSpoolDir (maSpoolDirName);
279 // osl::Directory::remove (maSpoolDirName);
282 static void WriteLocalTimePS( osl::File *rFile )
284 TimeValue m_start_time, tLocal;
285 oslDateTime date_time;
286 if (osl_getSystemTime( &m_start_time ) &&
287 osl_getLocalTimeFromSystemTime( &m_start_time, &tLocal ) &&
288 osl_getDateTimeFromTimeValue( &tLocal, &date_time ))
290 char ar[ 256 ];
291 snprintf(
292 ar, sizeof (ar),
293 "%04d-%02d-%02d %02d:%02d:%02d ",
294 date_time.Year, date_time.Month, date_time.Day,
295 date_time.Hours, date_time.Minutes, date_time.Seconds );
296 WritePS( rFile, ar );
298 else
299 WritePS( rFile, "Unknown-Time" );
302 static bool isAscii( const OUString& rStr )
304 sal_Int32 nLen = rStr.getLength();
305 for( sal_Int32 i = 0; i < nLen; i++ )
306 if( rStr[i] > 127 )
307 return false;
308 return true;
311 bool
312 PrinterJob::StartJob (
313 const OUString& rFileName,
314 int nMode,
315 const OUString& rJobName,
316 const OUString& rAppName,
317 const JobData& rSetupData,
318 PrinterGfx* pGraphics,
319 bool bIsQuickJob
322 m_bQuickJob = bIsQuickJob;
323 mnMaxWidthPt = mnMaxHeightPt = 0;
324 mnLandscapes = mnPortraits = 0;
325 m_pGraphics = pGraphics;
326 InitPaperSize (rSetupData);
328 // create file container for document header and trailer
329 maFileName = rFileName;
330 mnFileMode = nMode;
331 maSpoolDirName = createSpoolDir ();
332 maJobTitle = rJobName;
334 OUString aExt(".ps");
335 mpJobHeader = CreateSpoolFile (OUString("psp_head"), aExt);
336 mpJobTrailer = CreateSpoolFile (OUString("psp_tail"), aExt);
337 if( ! (mpJobHeader && mpJobTrailer) ) // existing files are removed in destructor
338 return false;
340 // write document header according to Document Structuring Conventions (DSC)
341 WritePS (mpJobHeader,
342 "%!PS-Adobe-3.0\n"
343 "%%BoundingBox: (atend)\n" );
345 OUString aFilterWS;
347 // Creator (this application)
348 aFilterWS = WhitespaceToSpace( rAppName, false );
349 WritePS (mpJobHeader, "%%Creator: (");
350 WritePS (mpJobHeader, aFilterWS);
351 WritePS (mpJobHeader, ")\n");
353 // For (user name)
354 osl::Security aSecurity;
355 OUString aUserName;
356 if( aSecurity.getUserName( aUserName ) )
358 WritePS (mpJobHeader, "%%For: (");
359 WritePS (mpJobHeader, aUserName);
360 WritePS (mpJobHeader, ")\n");
363 // Creation Date (locale independent local time)
364 WritePS (mpJobHeader, "%%CreationDate: (");
365 WriteLocalTimePS (mpJobHeader);
366 WritePS (mpJobHeader, ")\n");
368 // Document Title
369 /* #i74335#
370 * The title should be clean ascii; rJobName however may
371 * contain any Unicode character. So implement the following
372 * algorithm:
373 * use rJobName, if it contains only ascii
374 * use the filename, if it contains only ascii
375 * else omit %%Title
377 aFilterWS = WhitespaceToSpace( rJobName, false );
378 OUString aTitle( aFilterWS );
379 if( ! isAscii( aTitle ) )
381 sal_Int32 nIndex = 0;
382 while( nIndex != -1 )
383 aTitle = rFileName.getToken( 0, '/', nIndex );
384 aTitle = WhitespaceToSpace( aTitle, false );
385 if( ! isAscii( aTitle ) )
386 aTitle.clear();
389 maJobTitle = aFilterWS;
390 if( !aTitle.isEmpty() )
392 WritePS (mpJobHeader, "%%Title: (");
393 WritePS (mpJobHeader, aTitle);
394 WritePS (mpJobHeader, ")\n");
397 // Language Level
398 sal_Char pLevel[16];
399 sal_Int32 nSz = getValueOf(GetPostscriptLevel(&rSetupData), pLevel);
400 pLevel[nSz++] = '\n';
401 pLevel[nSz ] = '\0';
402 WritePS (mpJobHeader, "%%LanguageLevel: ");
403 WritePS (mpJobHeader, pLevel);
405 // Other
406 WritePS (mpJobHeader, "%%DocumentData: Clean7Bit\n");
407 WritePS (mpJobHeader, "%%Pages: (atend)\n");
408 WritePS (mpJobHeader, "%%Orientation: (atend)\n");
409 WritePS (mpJobHeader, "%%PageOrder: Ascend\n");
410 WritePS (mpJobHeader, "%%EndComments\n");
412 // write Prolog
413 writeProlog (mpJobHeader, rSetupData);
415 // mark last job setup as not set
416 m_aLastJobData.m_pParser = NULL;
417 m_aLastJobData.m_aContext.setParser( NULL );
419 return true;
422 bool
423 PrinterJob::EndJob()
425 // no pages ? that really means no print job
426 if( maPageList.empty() )
427 return false;
429 // write document setup (done here because it
430 // includes the accumulated fonts
431 if( mpJobHeader )
432 writeSetup( mpJobHeader, m_aDocumentJobData );
433 m_pGraphics->OnEndJob();
434 if( ! (mpJobHeader && mpJobTrailer) )
435 return false;
437 // write document trailer according to Document Structuring Conventions (DSC)
438 OStringBuffer aTrailer(512);
439 aTrailer.append( "%%Trailer\n" );
440 aTrailer.append( "%%BoundingBox: 0 0 " );
441 aTrailer.append( (sal_Int32)mnMaxWidthPt );
442 aTrailer.append( " " );
443 aTrailer.append( (sal_Int32)mnMaxHeightPt );
444 if( mnLandscapes > mnPortraits )
445 aTrailer.append("\n%%Orientation: Landscape");
446 else
447 aTrailer.append("\n%%Orientation: Portrait");
448 aTrailer.append( "\n%%Pages: " );
449 aTrailer.append( (sal_Int32)maPageList.size() );
450 aTrailer.append( "\n%%EOF\n" );
451 WritePS (mpJobTrailer, aTrailer.getStr());
454 * spool the set of files to their final destination, this is U**X dependent
457 FILE* pDestFILE = NULL;
459 /* create a destination either as file or as a pipe */
460 bool bSpoolToFile = !maFileName.isEmpty();
461 if (bSpoolToFile)
463 const OString aFileName = OUStringToOString (maFileName,
464 osl_getThreadTextEncoding());
465 if( mnFileMode )
467 int nFile = open( aFileName.getStr(), O_CREAT | O_EXCL | O_RDWR, mnFileMode );
468 if( nFile != -1 )
470 pDestFILE = fdopen( nFile, "w" );
471 if( pDestFILE == NULL )
473 close( nFile );
474 unlink( aFileName.getStr() );
475 return false;
478 else
480 (void)chmod( aFileName.getStr(), mnFileMode );
483 if (pDestFILE == NULL)
484 pDestFILE = fopen (aFileName.getStr(), "w");
486 if (pDestFILE == NULL)
487 return false;
489 else
491 PrinterInfoManager& rPrinterInfoManager = PrinterInfoManager::get ();
492 pDestFILE = rPrinterInfoManager.startSpool( m_aLastJobData.m_aPrinterName, m_bQuickJob );
493 if (pDestFILE == NULL)
494 return false;
497 /* spool the document parts to the destination */
499 unsigned char pBuffer[ nBLOCKSIZE ];
501 AppendPS (pDestFILE, mpJobHeader, pBuffer);
502 mpJobHeader->close();
504 bool bSuccess = true;
505 std::list< osl::File* >::iterator pPageBody;
506 std::list< osl::File* >::iterator pPageHead;
507 for (pPageBody = maPageList.begin(), pPageHead = maHeaderList.begin();
508 pPageBody != maPageList.end() && pPageHead != maHeaderList.end();
509 ++pPageBody, ++pPageHead)
511 if( *pPageHead )
513 osl::File::RC nError = (*pPageHead)->open(osl_File_OpenFlag_Read);
514 if (nError == osl::File::E_None)
516 AppendPS (pDestFILE, *pPageHead, pBuffer);
517 (*pPageHead)->close();
520 else
521 bSuccess = false;
522 if( *pPageBody )
524 osl::File::RC nError = (*pPageBody)->open(osl_File_OpenFlag_Read);
525 if (nError == osl::File::E_None)
527 AppendPS (pDestFILE, *pPageBody, pBuffer);
528 (*pPageBody)->close();
531 else
532 bSuccess = false;
535 AppendPS (pDestFILE, mpJobTrailer, pBuffer);
536 mpJobTrailer->close();
538 /* well done */
540 if (bSpoolToFile)
541 fclose (pDestFILE);
542 else
544 PrinterInfoManager& rPrinterInfoManager = PrinterInfoManager::get();
545 if (!rPrinterInfoManager.endSpool( m_aLastJobData.m_aPrinterName,
546 maJobTitle, pDestFILE, m_aDocumentJobData, true, OUString()))
548 bSuccess = false;
552 return bSuccess;
555 bool
556 PrinterJob::AbortJob ()
558 m_pGraphics->OnEndJob();
559 return false;
562 void
563 PrinterJob::InitPaperSize (const JobData& rJobSetup)
565 int nRes = rJobSetup.m_aContext.getRenderResolution ();
567 OUString aPaper;
568 int nWidth, nHeight;
569 rJobSetup.m_aContext.getPageSize (aPaper, nWidth, nHeight);
571 int nLeft = 0, nRight = 0, nUpper = 0, nLower = 0;
572 const PPDParser* pParser = rJobSetup.m_aContext.getParser();
573 if (pParser != NULL)
574 pParser->getMargins (aPaper, nLeft, nRight, nUpper, nLower);
576 mnResolution = nRes;
578 mnWidthPt = nWidth;
579 mnHeightPt = nHeight;
581 if( mnWidthPt > mnMaxWidthPt )
582 mnMaxWidthPt = mnWidthPt;
583 if( mnHeightPt > mnMaxHeightPt )
584 mnMaxHeightPt = mnHeightPt;
586 mnLMarginPt = nLeft;
587 mnRMarginPt = nRight;
588 mnTMarginPt = nUpper;
589 mnBMarginPt = nLower;
591 mfXScale = (double)72.0 / (double)mnResolution;
592 mfYScale = -1.0 * (double)72.0 / (double)mnResolution;
595 bool
596 PrinterJob::StartPage (const JobData& rJobSetup)
598 InitPaperSize (rJobSetup);
600 OUString aPageNo = OUString::number ((sal_Int32)maPageList.size()+1); // sequential page number must start with 1
601 OUString aExt = aPageNo + ".ps";
603 osl::File* pPageHeader = CreateSpoolFile ( OUString("psp_pghead"), aExt);
604 osl::File* pPageBody = CreateSpoolFile ( OUString("psp_pgbody"), aExt);
606 maHeaderList.push_back (pPageHeader);
607 maPageList.push_back (pPageBody);
609 if( ! (pPageHeader && pPageBody) )
610 return false;
612 // write page header according to Document Structuring Conventions (DSC)
613 WritePS (pPageHeader, "%%Page: ");
614 WritePS (pPageHeader, aPageNo);
615 WritePS (pPageHeader, " ");
616 WritePS (pPageHeader, aPageNo);
617 WritePS (pPageHeader, "\n");
619 if( rJobSetup.m_eOrientation == orientation::Landscape )
621 WritePS (pPageHeader, "%%PageOrientation: Landscape\n");
622 mnLandscapes++;
624 else
626 WritePS (pPageHeader, "%%PageOrientation: Portrait\n");
627 mnPortraits++;
630 sal_Char pBBox [256];
631 sal_Int32 nChar = 0;
633 nChar = psp::appendStr ("%%PageBoundingBox: ", pBBox);
634 nChar += psp::getValueOf (mnLMarginPt, pBBox + nChar);
635 nChar += psp::appendStr (" ", pBBox + nChar);
636 nChar += psp::getValueOf (mnBMarginPt, pBBox + nChar);
637 nChar += psp::appendStr (" ", pBBox + nChar);
638 nChar += psp::getValueOf (mnWidthPt - mnRMarginPt, pBBox + nChar);
639 nChar += psp::appendStr (" ", pBBox + nChar);
640 nChar += psp::getValueOf (mnHeightPt - mnTMarginPt, pBBox + nChar);
641 nChar += psp::appendStr ("\n", pBBox + nChar);
643 WritePS (pPageHeader, pBBox);
645 /* #i7262# #i65491# write setup only before first page
646 * (to %%Begin(End)Setup, instead of %%Begin(End)PageSetup)
647 * don't do this in StartJob since the jobsetup there may be
648 * different.
650 bool bWriteFeatures = true;
651 if( 1 == maPageList.size() )
653 m_aDocumentJobData = rJobSetup;
654 bWriteFeatures = false;
657 if ( writePageSetup( pPageHeader, rJobSetup, bWriteFeatures ) )
659 m_aLastJobData = rJobSetup;
660 return true;
663 return false;
666 bool
667 PrinterJob::EndPage ()
669 osl::File* pPageHeader = maHeaderList.back();
670 osl::File* pPageBody = maPageList.back();
672 if( ! (pPageBody && pPageHeader) )
673 return false;
675 // copy page to paper and write page trailer according to DSC
677 sal_Char pTrailer[256];
678 sal_Int32 nChar = 0;
679 nChar = psp::appendStr ("grestore grestore\n", pTrailer);
680 nChar += psp::appendStr ("showpage\n", pTrailer + nChar);
681 nChar += psp::appendStr ("%%PageTrailer\n\n", pTrailer + nChar);
682 WritePS (pPageBody, pTrailer);
684 // this page is done for now, close it to avoid having too many open fd's
686 pPageHeader->close();
687 pPageBody->close();
689 return true;
692 struct less_ppd_key : public ::std::binary_function<double, double, bool>
694 bool operator()(const PPDKey* left, const PPDKey* right)
695 { return left->getOrderDependency() < right->getOrderDependency(); }
698 static bool writeFeature( osl::File* pFile, const PPDKey* pKey, const PPDValue* pValue, bool bUseIncluseFeature )
700 if( ! pKey || ! pValue )
701 return true;
703 OStringBuffer aFeature(256);
704 aFeature.append( "[{\n" );
705 if( bUseIncluseFeature )
706 aFeature.append( "%%IncludeFeature:" );
707 else
708 aFeature.append( "%%BeginFeature:" );
709 aFeature.append( " *" );
710 aFeature.append( OUStringToOString( pKey->getKey(), RTL_TEXTENCODING_ASCII_US ) );
711 aFeature.append( ' ' );
712 aFeature.append( OUStringToOString( pValue->m_aOption, RTL_TEXTENCODING_ASCII_US ) );
713 if( !bUseIncluseFeature )
715 aFeature.append( '\n' );
716 aFeature.append( OUStringToOString( pValue->m_aValue, RTL_TEXTENCODING_ASCII_US ) );
717 aFeature.append( "\n%%EndFeature" );
719 aFeature.append( "\n} stopped cleartomark\n" );
720 sal_uInt64 nWritten = 0;
721 return !(pFile->write( aFeature.getStr(), aFeature.getLength(), nWritten )
722 || nWritten != (sal_uInt64)aFeature.getLength());
725 bool PrinterJob::writeFeatureList( osl::File* pFile, const JobData& rJob, bool bDocumentSetup )
727 bool bSuccess = true;
729 // emit features ordered to OrderDependency
730 // ignore features that are set to default
732 // sanity check
733 if( rJob.m_pParser == rJob.m_aContext.getParser() &&
734 rJob.m_pParser &&
735 ( m_aLastJobData.m_pParser == rJob.m_pParser || m_aLastJobData.m_pParser == NULL )
738 int i;
739 int nKeys = rJob.m_aContext.countValuesModified();
740 ::std::vector< const PPDKey* > aKeys( nKeys );
741 for( i = 0; i < nKeys; i++ )
742 aKeys[i] = rJob.m_aContext.getModifiedKey( i );
743 ::std::sort( aKeys.begin(), aKeys.end(), less_ppd_key() );
745 for( i = 0; i < nKeys && bSuccess; i++ )
747 const PPDKey* pKey = aKeys[i];
748 bool bEmit = false;
749 if( bDocumentSetup )
751 if( pKey->getSetupType() == PPDKey::DocumentSetup )
752 bEmit = true;
754 if( pKey->getSetupType() == PPDKey::PageSetup ||
755 pKey->getSetupType() == PPDKey::AnySetup )
756 bEmit = true;
757 if( bEmit )
759 const PPDValue* pValue = rJob.m_aContext.getValue( pKey );
760 if( pValue
761 && pValue->m_eType == eInvocation
762 && ( m_aLastJobData.m_pParser == NULL
763 || m_aLastJobData.m_aContext.getValue( pKey ) != pValue
764 || bDocumentSetup
768 // try to avoid PS level 2 feature commands if level is set to 1
769 if( GetPostscriptLevel( &rJob ) == 1 )
771 bool bHavePS2 =
772 ( pValue->m_aValue.indexOf( "<<" ) != -1 )
774 ( pValue->m_aValue.indexOf( ">>" ) != -1 );
775 if( bHavePS2 )
776 continue;
778 bSuccess = writeFeature( pFile, pKey, pValue, PrinterInfoManager::get().getUseIncludeFeature() );
783 else
784 bSuccess = false;
786 return bSuccess;
789 bool PrinterJob::writePageSetup( osl::File* pFile, const JobData& rJob, bool bWriteFeatures )
791 bool bSuccess = true;
793 WritePS (pFile, "%%BeginPageSetup\n%\n");
794 if ( bWriteFeatures )
795 bSuccess = writeFeatureList( pFile, rJob, false );
796 WritePS (pFile, "%%EndPageSetup\n");
798 sal_Char pTranslate [128];
799 sal_Int32 nChar = 0;
801 if( rJob.m_eOrientation == orientation::Portrait )
803 nChar = psp::appendStr ("gsave\n[", pTranslate);
804 nChar += psp::getValueOfDouble ( pTranslate + nChar, mfXScale, 5);
805 nChar += psp::appendStr (" 0 0 ", pTranslate + nChar);
806 nChar += psp::getValueOfDouble ( pTranslate + nChar, mfYScale, 5);
807 nChar += psp::appendStr (" ", pTranslate + nChar);
808 nChar += psp::getValueOf (mnRMarginPt, pTranslate + nChar);
809 nChar += psp::appendStr (" ", pTranslate + nChar);
810 nChar += psp::getValueOf (mnHeightPt-mnTMarginPt,
811 pTranslate + nChar);
812 nChar += psp::appendStr ("] concat\ngsave\n",
813 pTranslate + nChar);
815 else
817 nChar = psp::appendStr ("gsave\n", pTranslate);
818 nChar += psp::appendStr ("[ 0 ", pTranslate + nChar);
819 nChar += psp::getValueOfDouble ( pTranslate + nChar, -mfYScale, 5);
820 nChar += psp::appendStr (" ", pTranslate + nChar);
821 nChar += psp::getValueOfDouble ( pTranslate + nChar, mfXScale, 5);
822 nChar += psp::appendStr (" 0 ", pTranslate + nChar );
823 nChar += psp::getValueOfDouble ( pTranslate + nChar, mnLMarginPt, 5 );
824 nChar += psp::appendStr (" ", pTranslate + nChar);
825 nChar += psp::getValueOf (mnBMarginPt, pTranslate + nChar );
826 nChar += psp::appendStr ("] concat\ngsave\n",
827 pTranslate + nChar);
830 WritePS (pFile, pTranslate);
832 return bSuccess;
835 void PrinterJob::writeJobPatch( osl::File* pFile, const JobData& rJobData )
837 if( ! PrinterInfoManager::get().getUseJobPatch() )
838 return;
840 const PPDKey* pKey = NULL;
842 if( rJobData.m_pParser )
843 pKey = rJobData.m_pParser->getKey( OUString( "JobPatchFile" ) );
844 if( ! pKey )
845 return;
847 // order the patch files
848 // according to PPD spec the JobPatchFile options must be int
849 // and should be emitted in order
850 std::list< sal_Int32 > patch_order;
851 int nValueCount = pKey->countValues();
852 for( int i = 0; i < nValueCount; i++ )
854 const PPDValue* pVal = pKey->getValue( i );
855 patch_order.push_back( pVal->m_aOption.toInt32() );
856 if( patch_order.back() == 0 && pVal->m_aOption != "0" )
858 WritePS( pFile, "% Warning: left out JobPatchFile option \"" );
859 OString aOption = OUStringToOString( pVal->m_aOption, RTL_TEXTENCODING_ASCII_US );
860 WritePS( pFile, aOption.getStr() );
861 WritePS( pFile,
862 "\"\n% as it violates the PPD spec;\n"
863 "% JobPatchFile options need to be numbered for ordering.\n" );
867 patch_order.sort();
868 patch_order.unique();
870 while( patch_order.begin() != patch_order.end() )
872 // note: this discards patch files not adhering to the "int" scheme
873 // as there won't be a value for them
874 writeFeature( pFile, pKey, pKey->getValue( OUString::number( patch_order.front() ) ), false );
875 patch_order.pop_front();
879 bool PrinterJob::writeProlog (osl::File* pFile, const JobData& rJobData )
881 WritePS( pFile, "%%BeginProlog\n" );
883 // JobPatchFile feature needs to be emitted at begin of prolog
884 writeJobPatch( pFile, rJobData );
886 static const sal_Char pProlog[] = {
887 "%%BeginResource: procset PSPrint-Prolog 1.0 0\n"
888 "/ISO1252Encoding [\n"
889 "/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef\n"
890 "/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef\n"
891 "/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef\n"
892 "/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef\n"
893 "/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle\n"
894 "/parenleft /parenright /asterisk /plus /comma /hyphen /period /slash\n"
895 "/zero /one /two /three /four /five /six /seven\n"
896 "/eight /nine /colon /semicolon /less /equal /greater /question\n"
897 "/at /A /B /C /D /E /F /G\n"
898 "/H /I /J /K /L /M /N /O\n"
899 "/P /Q /R /S /T /U /V /W\n"
900 "/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore\n"
901 "/grave /a /b /c /d /e /f /g\n"
902 "/h /i /j /k /l /m /n /o\n"
903 "/p /q /r /s /t /u /v /w\n"
904 "/x /y /z /braceleft /bar /braceright /asciitilde /unused\n"
905 "/Euro /unused /quotesinglbase /florin /quotedblbase /ellipsis /dagger /daggerdbl\n"
906 "/circumflex /perthousand /Scaron /guilsinglleft /OE /unused /Zcaron /unused\n"
907 "/unused /quoteleft /quoteright /quotedblleft /quotedblright /bullet /endash /emdash\n"
908 "/tilde /trademark /scaron /guilsinglright /oe /unused /zcaron /Ydieresis\n"
909 "/space /exclamdown /cent /sterling /currency /yen /brokenbar /section\n"
910 "/dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron\n"
911 "/degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered\n"
912 "/cedilla /onesuperior /ordmasculine /guillemotright /onequarter /onehalf /threequarters /questiondown\n"
913 "/Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla\n"
914 "/Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis\n"
915 "/Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply\n"
916 "/Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls\n"
917 "/agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla\n"
918 "/egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis\n"
919 "/eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide\n"
920 "/oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis] def\n"
921 "\n"
922 "/psp_definefont { exch dup findfont dup length dict begin { 1 index /FID ne\n"
923 "{ def } { pop pop } ifelse } forall /Encoding 3 -1 roll def\n"
924 "currentdict end exch pop definefont pop } def\n"
925 "\n"
926 "/pathdict dup 8 dict def load begin\n"
927 "/rcmd { { currentfile 1 string readstring pop 0 get dup 32 gt { exit }\n"
928 "{ pop } ifelse } loop dup 126 eq { pop exit } if 65 sub dup 16#3 and 1\n"
929 "add exch dup 16#C and -2 bitshift 16#3 and 1 add exch 16#10 and 16#10\n"
930 "eq 3 1 roll exch } def\n"
931 "/rhex { dup 1 sub exch currentfile exch string readhexstring pop dup 0\n"
932 "get dup 16#80 and 16#80 eq dup 3 1 roll { 16#7f and } if 2 index 0 3\n"
933 "-1 roll put 3 1 roll 0 0 1 5 -1 roll { 2 index exch get add 256 mul }\n"
934 "for 256 div exch pop exch { neg } if } def\n"
935 "/xcmd { rcmd exch rhex exch rhex exch 5 -1 roll add exch 4 -1 roll add\n"
936 "1 index 1 index 5 -1 roll { moveto } { lineto } ifelse } def end\n"
937 "/readpath { 0 0 pathdict begin { xcmd } loop end pop pop } def\n"
938 "\n"
939 "systemdict /languagelevel known not {\n"
940 "/xshow { exch dup length 0 1 3 -1 roll 1 sub { dup 3 index exch get\n"
941 "exch 2 index exch get 1 string dup 0 4 -1 roll put currentpoint 3 -1\n"
942 "roll show moveto 0 rmoveto } for pop pop } def\n"
943 "/rectangle { 4 -2 roll moveto 1 index 0 rlineto 0 exch rlineto neg 0\n"
944 "rlineto closepath } def\n"
945 "/rectfill { rectangle fill } def\n"
946 "/rectstroke { rectangle stroke } def } if\n"
947 "/bshow { currentlinewidth 3 1 roll currentpoint 3 index show moveto\n"
948 "setlinewidth false charpath stroke setlinewidth } def\n"
949 "/bxshow { currentlinewidth 4 1 roll setlinewidth exch dup length 1 sub\n"
950 "0 1 3 -1 roll { 1 string 2 index 2 index get 1 index exch 0 exch put dup\n"
951 "currentpoint 3 -1 roll show moveto currentpoint 3 -1 roll false charpath\n"
952 "stroke moveto 2 index exch get 0 rmoveto } for pop pop setlinewidth } def\n"
953 "\n"
954 "/psp_lzwfilter { currentfile /ASCII85Decode filter /LZWDecode filter } def\n"
955 "/psp_ascii85filter { currentfile /ASCII85Decode filter } def\n"
956 "/psp_lzwstring { psp_lzwfilter 1024 string readstring } def\n"
957 "/psp_ascii85string { psp_ascii85filter 1024 string readstring } def\n"
958 "/psp_imagedict {\n"
959 "/psp_bitspercomponent { 3 eq { 1 }{ 8 } ifelse } def\n"
960 "/psp_decodearray { [ [0 1 0 1 0 1] [0 255] [0 1] [0 255] ] exch get }\n"
961 "def 7 dict dup\n"
962 "/ImageType 1 put dup\n"
963 "/Width 7 -1 roll put dup\n"
964 "/Height 5 index put dup\n"
965 "/BitsPerComponent 4 index psp_bitspercomponent put dup\n"
966 "/Decode 5 -1 roll psp_decodearray put dup\n"
967 "/ImageMatrix [1 0 0 1 0 0] dup 5 8 -1 roll put put dup\n"
968 "/DataSource 4 -1 roll 1 eq { psp_lzwfilter } { psp_ascii85filter } ifelse put\n"
969 "} def\n"
970 "%%EndResource\n"
971 "%%EndProlog\n"
973 WritePS (pFile, pProlog);
975 return true;
978 bool PrinterJob::writeSetup( osl::File* pFile, const JobData& rJob )
980 WritePS (pFile, "%%BeginSetup\n%\n");
982 // download fonts
983 std::list< OString > aFonts;
984 m_pGraphics->writeResources( pFile, aFonts );
986 if( !aFonts.empty() )
988 std::list< OString >::const_iterator it = aFonts.begin();
989 OStringBuffer aLine( 256 );
990 aLine.append( "%%DocumentSuppliedResources: font " );
991 aLine.append( *it );
992 aLine.append( "\n" );
993 WritePS ( pFile, aLine.getStr() );
994 while( (++it) != aFonts.end() )
996 aLine.setLength(0);
997 aLine.append( "%%+ font " );
998 aLine.append( *it );
999 aLine.append( "\n" );
1000 WritePS ( pFile, aLine.getStr() );
1004 bool bSuccess = true;
1005 // in case of external print dialog the number of copies is prepended
1006 // to the job, let us not complicate things by emitting our own copy count
1007 bool bExternalDialog = PrinterInfoManager::get().checkFeatureToken( GetPrinterName(), "external_dialog" );
1008 if( ! bExternalDialog && rJob.m_nCopies > 1 )
1010 // setup code
1011 OStringBuffer aLine("/#copies ");
1012 aLine.append(static_cast<sal_Int32>(rJob.m_nCopies));
1013 aLine.append(" def\n");
1014 sal_uInt64 nWritten = 0;
1015 bSuccess = !(pFile->write(aLine.getStr(), aLine.getLength(), nWritten)
1016 || nWritten != static_cast<sal_uInt64>(aLine.getLength()));
1018 if( bSuccess && GetPostscriptLevel( &rJob ) >= 2 )
1019 WritePS (pFile, "<< /NumCopies null /Policies << /NumCopies 1 >> >> setpagedevice\n" );
1022 bool bFeatureSuccess = writeFeatureList( pFile, rJob, true );
1024 WritePS (pFile, "%%EndSetup\n");
1026 return bSuccess && bFeatureSuccess;
1029 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */