Bump version to 4.1-6
[LibreOffice.git] / vcl / generic / print / printerjob.cxx
blob5d61ff90a9bf51215acee1dc95d884831604f9ec
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 .
21 #include <stdio.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <fcntl.h>
25 #include <unistd.h>
27 #include "psputil.hxx"
28 #include "glyphset.hxx"
30 #include "generic/printerjob.hxx"
31 #include "generic/printergfx.hxx"
32 #include "vcl/ppdparser.hxx"
33 #include "vcl/strhelper.hxx"
34 #include "vcl/printerinfomanager.hxx"
36 #include "rtl/ustring.hxx"
37 #include "rtl/strbuf.hxx"
38 #include "rtl/ustrbuf.hxx"
40 #include <osl/thread.h>
41 #include <osl/security.hxx>
42 #include <sal/alloca.h>
43 #include <sal/macros.h>
45 #include <algorithm>
46 #include <vector>
48 using namespace psp;
51 // forward declaration
53 #define nBLOCKSIZE 0x2000
55 namespace psp
58 sal_Bool
59 AppendPS (FILE* pDst, osl::File* pSrc, sal_uChar* pBuffer,
60 sal_uInt32 nBlockSize = nBLOCKSIZE)
62 if ((pDst == NULL) || (pSrc == NULL))
63 return sal_False;
65 if (pSrc->setPos(osl_Pos_Absolut, 0) != osl::FileBase::E_None)
66 return sal_False;
68 if (nBlockSize == 0)
69 nBlockSize = nBLOCKSIZE;
70 if (pBuffer == NULL)
71 pBuffer = (sal_uChar*)alloca (nBlockSize);
73 sal_uInt64 nIn = 0;
74 sal_uInt64 nOut = 0;
77 pSrc->read (pBuffer, nBlockSize, nIn);
78 if (nIn > 0)
79 nOut = fwrite (pBuffer, 1, sal::static_int_cast<sal_uInt32>(nIn), pDst);
81 while ((nIn > 0) && (nIn == nOut));
83 return sal_True;
86 } // namespace psp
89 * private convenience routines for file handling
92 osl::File*
93 PrinterJob::CreateSpoolFile (const OUString& rName, const OUString& rExtension)
95 osl::File* pFile = NULL;
97 OUString aFile = rName + rExtension;
98 OUString aFileURL;
99 osl::File::RC nError = osl::File::getFileURLFromSystemPath( aFile, aFileURL );
100 if (nError != osl::File::E_None)
101 return NULL;
102 aFileURL = maSpoolDirName + OUString("/") + aFileURL;
104 pFile = new osl::File (aFileURL);
105 nError = pFile->open (osl_File_OpenFlag_Read | osl_File_OpenFlag_Write | osl_File_OpenFlag_Create);
106 if (nError != osl::File::E_None)
108 delete pFile;
109 return NULL;
112 pFile->setAttributes (aFileURL,
113 osl_File_Attribute_OwnWrite | osl_File_Attribute_OwnRead);
114 return pFile;
118 * public methods of PrinterJob: for use in PrinterGfx
121 void
122 PrinterJob::GetScale (double &rXScale, double &rYScale) const
124 rXScale = mfXScale;
125 rYScale = mfYScale;
128 sal_uInt16
129 PrinterJob::GetDepth () const
131 sal_Int32 nLevel = GetPostscriptLevel();
132 sal_Bool bColor = IsColorPrinter ();
134 return nLevel > 1 && bColor ? 24 : 8;
137 sal_uInt16
138 PrinterJob::GetPostscriptLevel (const JobData *pJobData) const
140 sal_uInt16 nPSLevel = 2;
142 if( pJobData == NULL )
143 pJobData = &m_aLastJobData;
145 if( pJobData->m_nPSLevel )
146 nPSLevel = pJobData->m_nPSLevel;
147 else
148 if( pJobData->m_pParser )
149 nPSLevel = pJobData->m_pParser->getLanguageLevel();
151 return nPSLevel;
154 sal_Bool
155 PrinterJob::IsColorPrinter () const
157 sal_Bool bColor = sal_False;
159 if( m_aLastJobData.m_nColorDevice )
160 bColor = m_aLastJobData.m_nColorDevice == -1 ? sal_False : sal_True;
161 else if( m_aLastJobData.m_pParser )
162 bColor = m_aLastJobData.m_pParser->isColorDevice() ? sal_True : sal_False;
164 return bColor;
167 osl::File*
168 PrinterJob::GetCurrentPageHeader ()
170 return maHeaderList.back();
173 osl::File*
174 PrinterJob::GetCurrentPageBody ()
176 return maPageList.back();
180 * public methods of PrinterJob: the actual job / spool handling
183 PrinterJob::PrinterJob () :
184 mpJobHeader( NULL ),
185 mpJobTrailer( NULL ),
186 m_bQuickJob( false )
190 /* remove all our temporary files, uses external program "rm", since
191 osl functionality is inadequate */
192 void
193 removeSpoolDir (const OUString& rSpoolDir)
195 OUString aSysPath;
196 if( osl::File::E_None != osl::File::getSystemPathFromFileURL( rSpoolDir, aSysPath ) )
198 // Conversion did not work, as this is quite a dangerous action,
199 // we should abort here ....
200 OSL_FAIL( "psprint: couldn't remove spool directory" );
201 return;
203 OString aSysPathByte =
204 OUStringToOString (aSysPath, osl_getThreadTextEncoding());
205 sal_Char pSystem [128];
206 sal_Int32 nChar = 0;
208 nChar = psp::appendStr ("rm -rf ", pSystem);
209 nChar += psp::appendStr (aSysPathByte.getStr(), pSystem + nChar);
211 if (system (pSystem) == -1)
212 OSL_FAIL( "psprint: couldn't remove spool directory" );
215 /* creates a spool directory with a "pidgin random" value based on
216 current system time */
217 OUString
218 createSpoolDir ()
220 TimeValue aCur;
221 osl_getSystemTime( &aCur );
222 sal_Int32 nRand = aCur.Seconds ^ (aCur.Nanosec/1000);
224 OUString aTmpDir;
225 osl_getTempDirURL( &aTmpDir.pData );
229 OUStringBuffer aDir( aTmpDir.getLength() + 16 );
230 aDir.append( aTmpDir );
231 aDir.appendAscii( "/psp" );
232 aDir.append(nRand);
233 OUString aResult = aDir.makeStringAndClear();
234 if( osl::Directory::create( aResult ) == osl::FileBase::E_None )
236 osl::File::setAttributes( aResult,
237 osl_File_Attribute_OwnWrite
238 | osl_File_Attribute_OwnRead
239 | osl_File_Attribute_OwnExe );
240 return aResult;
242 nRand++;
243 } while( nRand );
244 return OUString();
247 PrinterJob::~PrinterJob ()
249 std::list< osl::File* >::iterator pPage;
250 for (pPage = maPageList.begin(); pPage != maPageList.end(); ++pPage)
252 //(*pPage)->remove();
253 delete *pPage;
255 for (pPage = maHeaderList.begin(); pPage != maHeaderList.end(); ++pPage)
257 //(*pPage)->remove();
258 delete *pPage;
260 // mpJobHeader->remove();
261 delete mpJobHeader;
262 // mpJobTrailer->remove();
263 delete mpJobTrailer;
265 // XXX should really call osl::remove routines
266 if( !maSpoolDirName.isEmpty() )
267 removeSpoolDir (maSpoolDirName);
269 // osl::Directory::remove (maSpoolDirName);
272 static void WriteLocalTimePS( osl::File *rFile )
274 TimeValue m_start_time, tLocal;
275 oslDateTime date_time;
276 if (osl_getSystemTime( &m_start_time ) &&
277 osl_getLocalTimeFromSystemTime( &m_start_time, &tLocal ) &&
278 osl_getDateTimeFromTimeValue( &tLocal, &date_time ))
280 char ar[ 256 ];
281 snprintf(
282 ar, sizeof (ar),
283 "%04d-%02d-%02d %02d:%02d:%02d ",
284 date_time.Year, date_time.Month, date_time.Day,
285 date_time.Hours, date_time.Minutes, date_time.Seconds );
286 WritePS( rFile, ar );
288 else
289 WritePS( rFile, "Unknown-Time" );
292 static bool isAscii( const OUString& rStr )
294 sal_Int32 nLen = rStr.getLength();
295 for( sal_Int32 i = 0; i < nLen; i++ )
296 if( rStr[i] > 127 )
297 return false;
298 return true;
301 sal_Bool
302 PrinterJob::StartJob (
303 const OUString& rFileName,
304 int nMode,
305 const OUString& rJobName,
306 const OUString& rAppName,
307 const JobData& rSetupData,
308 PrinterGfx* pGraphics,
309 bool bIsQuickJob
312 m_bQuickJob = bIsQuickJob;
313 mnMaxWidthPt = mnMaxHeightPt = 0;
314 mnLandscapes = mnPortraits = 0;
315 m_pGraphics = pGraphics;
316 InitPaperSize (rSetupData);
318 // create file container for document header and trailer
319 maFileName = rFileName;
320 mnFileMode = nMode;
321 maSpoolDirName = createSpoolDir ();
322 maJobTitle = rJobName;
324 OUString aExt(".ps");
325 mpJobHeader = CreateSpoolFile (OUString("psp_head"), aExt);
326 mpJobTrailer = CreateSpoolFile (OUString("psp_tail"), aExt);
327 if( ! (mpJobHeader && mpJobTrailer) ) // existing files are removed in destructor
328 return sal_False;
330 // write document header according to Document Structuring Conventions (DSC)
331 WritePS (mpJobHeader,
332 "%!PS-Adobe-3.0\n"
333 "%%BoundingBox: (atend)\n" );
335 OUString aFilterWS;
337 // Creator (this application)
338 aFilterWS = WhitespaceToSpace( rAppName, sal_False );
339 WritePS (mpJobHeader, "%%Creator: (");
340 WritePS (mpJobHeader, aFilterWS);
341 WritePS (mpJobHeader, ")\n");
343 // For (user name)
344 osl::Security aSecurity;
345 OUString aUserName;
346 if( aSecurity.getUserName( aUserName ) )
348 WritePS (mpJobHeader, "%%For: (");
349 WritePS (mpJobHeader, aUserName);
350 WritePS (mpJobHeader, ")\n");
353 // Creation Date (locale independent local time)
354 WritePS (mpJobHeader, "%%CreationDate: (");
355 WriteLocalTimePS (mpJobHeader);
356 WritePS (mpJobHeader, ")\n");
358 // Document Title
359 /* #i74335#
360 * The title should be clean ascii; rJobName however may
361 * contain any Unicode character. So implement the following
362 * algorithm:
363 * use rJobName, if it contains only ascii
364 * use the filename, if it contains only ascii
365 * else omit %%Title
367 aFilterWS = WhitespaceToSpace( rJobName, sal_False );
368 OUString aTitle( aFilterWS );
369 if( ! isAscii( aTitle ) )
371 sal_Int32 nIndex = 0;
372 while( nIndex != -1 )
373 aTitle = rFileName.getToken( 0, '/', nIndex );
374 aTitle = WhitespaceToSpace( aTitle, sal_False );
375 if( ! isAscii( aTitle ) )
376 aTitle = OUString();
379 maJobTitle = aFilterWS;
380 if( !aTitle.isEmpty() )
382 WritePS (mpJobHeader, "%%Title: (");
383 WritePS (mpJobHeader, aTitle);
384 WritePS (mpJobHeader, ")\n");
387 // Language Level
388 sal_Char pLevel[16];
389 sal_Int32 nSz = getValueOf(GetPostscriptLevel(&rSetupData), pLevel);
390 pLevel[nSz++] = '\n';
391 pLevel[nSz ] = '\0';
392 WritePS (mpJobHeader, "%%LanguageLevel: ");
393 WritePS (mpJobHeader, pLevel);
395 // Other
396 WritePS (mpJobHeader, "%%DocumentData: Clean7Bit\n");
397 WritePS (mpJobHeader, "%%Pages: (atend)\n");
398 WritePS (mpJobHeader, "%%Orientation: (atend)\n");
399 WritePS (mpJobHeader, "%%PageOrder: Ascend\n");
400 WritePS (mpJobHeader, "%%EndComments\n");
402 // write Prolog
403 writeProlog (mpJobHeader, rSetupData);
405 // mark last job setup as not set
406 m_aLastJobData.m_pParser = NULL;
407 m_aLastJobData.m_aContext.setParser( NULL );
409 return sal_True;
412 sal_Bool
413 PrinterJob::EndJob ()
415 // no pages ? that really means no print job
416 if( maPageList.empty() )
417 return sal_False;
419 // write document setup (done here because it
420 // includes the accumulated fonts
421 if( mpJobHeader )
422 writeSetup( mpJobHeader, m_aDocumentJobData );
423 m_pGraphics->OnEndJob();
424 if( ! (mpJobHeader && mpJobTrailer) )
425 return sal_False;
427 // write document trailer according to Document Structuring Conventions (DSC)
428 OStringBuffer aTrailer(512);
429 aTrailer.append( "%%Trailer\n" );
430 aTrailer.append( "%%BoundingBox: 0 0 " );
431 aTrailer.append( (sal_Int32)mnMaxWidthPt );
432 aTrailer.append( " " );
433 aTrailer.append( (sal_Int32)mnMaxHeightPt );
434 if( mnLandscapes > mnPortraits )
435 aTrailer.append("\n%%Orientation: Landscape");
436 else
437 aTrailer.append("\n%%Orientation: Portrait");
438 aTrailer.append( "\n%%Pages: " );
439 aTrailer.append( (sal_Int32)maPageList.size() );
440 aTrailer.append( "\n%%EOF\n" );
441 WritePS (mpJobTrailer, aTrailer.getStr());
444 * spool the set of files to their final destination, this is U**X dependent
447 FILE* pDestFILE = NULL;
449 /* create a destination either as file or as a pipe */
450 sal_Bool bSpoolToFile = !maFileName.isEmpty();
451 if (bSpoolToFile)
453 const OString aFileName = OUStringToOString (maFileName,
454 osl_getThreadTextEncoding());
455 if( mnFileMode )
457 int nFile = open( aFileName.getStr(), O_CREAT | O_EXCL | O_RDWR, mnFileMode );
458 if( nFile != -1 )
460 pDestFILE = fdopen( nFile, "w" );
461 if( pDestFILE == NULL )
463 close( nFile );
464 unlink( aFileName.getStr() );
465 return sal_False;
468 else
469 chmod( aFileName.getStr(), mnFileMode );
471 if (pDestFILE == NULL)
472 pDestFILE = fopen (aFileName.getStr(), "w");
474 if (pDestFILE == NULL)
475 return sal_False;
477 else
479 PrinterInfoManager& rPrinterInfoManager = PrinterInfoManager::get ();
480 pDestFILE = rPrinterInfoManager.startSpool( m_aLastJobData.m_aPrinterName, m_bQuickJob );
481 if (pDestFILE == NULL)
482 return sal_False;
485 /* spool the document parts to the destination */
487 sal_uChar pBuffer[ nBLOCKSIZE ];
489 AppendPS (pDestFILE, mpJobHeader, pBuffer);
490 mpJobHeader->close();
492 sal_Bool bSuccess = sal_True;
493 std::list< osl::File* >::iterator pPageBody;
494 std::list< osl::File* >::iterator pPageHead;
495 for (pPageBody = maPageList.begin(), pPageHead = maHeaderList.begin();
496 pPageBody != maPageList.end() && pPageHead != maHeaderList.end();
497 ++pPageBody, ++pPageHead)
499 if( *pPageHead )
501 osl::File::RC nError = (*pPageHead)->open(osl_File_OpenFlag_Read);
502 if (nError == osl::File::E_None)
504 AppendPS (pDestFILE, *pPageHead, pBuffer);
505 (*pPageHead)->close();
508 else
509 bSuccess = sal_False;
510 if( *pPageBody )
512 osl::File::RC nError = (*pPageBody)->open(osl_File_OpenFlag_Read);
513 if (nError == osl::File::E_None)
515 AppendPS (pDestFILE, *pPageBody, pBuffer);
516 (*pPageBody)->close();
519 else
520 bSuccess = sal_False;
523 AppendPS (pDestFILE, mpJobTrailer, pBuffer);
524 mpJobTrailer->close();
526 /* well done */
528 if (bSpoolToFile)
529 fclose (pDestFILE);
530 else
532 PrinterInfoManager& rPrinterInfoManager = PrinterInfoManager::get();
533 if (0 == rPrinterInfoManager.endSpool( m_aLastJobData.m_aPrinterName,
534 maJobTitle, pDestFILE, m_aDocumentJobData, true ))
536 bSuccess = sal_False;
540 return bSuccess;
543 sal_Bool
544 PrinterJob::AbortJob ()
546 m_pGraphics->OnEndJob();
547 return sal_False;
550 void
551 PrinterJob::InitPaperSize (const JobData& rJobSetup)
553 int nRes = rJobSetup.m_aContext.getRenderResolution ();
555 OUString aPaper;
556 int nWidth, nHeight;
557 rJobSetup.m_aContext.getPageSize (aPaper, nWidth, nHeight);
559 int nLeft = 0, nRight = 0, nUpper = 0, nLower = 0;
560 const PPDParser* pParser = rJobSetup.m_aContext.getParser();
561 if (pParser != NULL)
562 pParser->getMargins (aPaper, nLeft, nRight, nUpper, nLower);
564 mnResolution = nRes;
566 mnWidthPt = nWidth;
567 mnHeightPt = nHeight;
569 if( mnWidthPt > mnMaxWidthPt )
570 mnMaxWidthPt = mnWidthPt;
571 if( mnHeightPt > mnMaxHeightPt )
572 mnMaxHeightPt = mnHeightPt;
574 mnLMarginPt = nLeft;
575 mnRMarginPt = nRight;
576 mnTMarginPt = nUpper;
577 mnBMarginPt = nLower;
579 mfXScale = (double)72.0 / (double)mnResolution;
580 mfYScale = -1.0 * (double)72.0 / (double)mnResolution;
584 sal_Bool
585 PrinterJob::StartPage (const JobData& rJobSetup)
587 InitPaperSize (rJobSetup);
589 OUString aPageNo = OUString::valueOf ((sal_Int32)maPageList.size()+1); // sequential page number must start with 1
590 OUString aExt = aPageNo + OUString(".ps");
592 osl::File* pPageHeader = CreateSpoolFile ( OUString("psp_pghead"), aExt);
593 osl::File* pPageBody = CreateSpoolFile ( OUString("psp_pgbody"), aExt);
595 maHeaderList.push_back (pPageHeader);
596 maPageList.push_back (pPageBody);
598 if( ! (pPageHeader && pPageBody) )
599 return sal_False;
601 // write page header according to Document Structuring Conventions (DSC)
602 WritePS (pPageHeader, "%%Page: ");
603 WritePS (pPageHeader, aPageNo);
604 WritePS (pPageHeader, " ");
605 WritePS (pPageHeader, aPageNo);
606 WritePS (pPageHeader, "\n");
608 if( rJobSetup.m_eOrientation == orientation::Landscape )
610 WritePS (pPageHeader, "%%PageOrientation: Landscape\n");
611 mnLandscapes++;
613 else
615 WritePS (pPageHeader, "%%PageOrientation: Portrait\n");
616 mnPortraits++;
619 sal_Char pBBox [256];
620 sal_Int32 nChar = 0;
622 nChar = psp::appendStr ("%%PageBoundingBox: ", pBBox);
623 nChar += psp::getValueOf (mnLMarginPt, pBBox + nChar);
624 nChar += psp::appendStr (" ", pBBox + nChar);
625 nChar += psp::getValueOf (mnBMarginPt, pBBox + nChar);
626 nChar += psp::appendStr (" ", pBBox + nChar);
627 nChar += psp::getValueOf (mnWidthPt - mnRMarginPt, pBBox + nChar);
628 nChar += psp::appendStr (" ", pBBox + nChar);
629 nChar += psp::getValueOf (mnHeightPt - mnTMarginPt, pBBox + nChar);
630 nChar += psp::appendStr ("\n", pBBox + nChar);
632 WritePS (pPageHeader, pBBox);
634 /* #i7262# #i65491# write setup only before first page
635 * (to %%Begin(End)Setup, instead of %%Begin(End)PageSetup)
636 * don't do this in StartJob since the jobsetup there may be
637 * different.
639 bool bWriteFeatures = true;
640 if( 1 == maPageList.size() )
642 m_aDocumentJobData = rJobSetup;
643 bWriteFeatures = false;
646 if ( writePageSetup( pPageHeader, rJobSetup, bWriteFeatures ) )
648 m_aLastJobData = rJobSetup;
649 return true;
652 return false;
655 sal_Bool
656 PrinterJob::EndPage ()
658 m_pGraphics->OnEndPage();
660 osl::File* pPageHeader = maHeaderList.back();
661 osl::File* pPageBody = maPageList.back();
663 if( ! (pPageBody && pPageHeader) )
664 return sal_False;
666 // copy page to paper and write page trailer according to DSC
668 sal_Char pTrailer[256];
669 sal_Int32 nChar = 0;
670 nChar = psp::appendStr ("grestore grestore\n", pTrailer);
671 nChar += psp::appendStr ("showpage\n", pTrailer + nChar);
672 nChar += psp::appendStr ("%%PageTrailer\n\n", pTrailer + nChar);
673 WritePS (pPageBody, pTrailer);
675 // this page is done for now, close it to avoid having too many open fd's
677 pPageHeader->close();
678 pPageBody->close();
680 return sal_True;
683 struct less_ppd_key : public ::std::binary_function<double, double, bool>
685 bool operator()(const PPDKey* left, const PPDKey* right)
686 { return left->getOrderDependency() < right->getOrderDependency(); }
689 static bool writeFeature( osl::File* pFile, const PPDKey* pKey, const PPDValue* pValue, bool bUseIncluseFeature )
691 if( ! pKey || ! pValue )
692 return true;
694 OStringBuffer aFeature(256);
695 aFeature.append( "[{\n" );
696 if( bUseIncluseFeature )
697 aFeature.append( "%%IncludeFeature:" );
698 else
699 aFeature.append( "%%BeginFeature:" );
700 aFeature.append( " *" );
701 aFeature.append( OUStringToOString( pKey->getKey(), RTL_TEXTENCODING_ASCII_US ) );
702 aFeature.append( ' ' );
703 aFeature.append( OUStringToOString( pValue->m_aOption, RTL_TEXTENCODING_ASCII_US ) );
704 if( !bUseIncluseFeature )
706 aFeature.append( '\n' );
707 aFeature.append( OUStringToOString( pValue->m_aValue, RTL_TEXTENCODING_ASCII_US ) );
708 aFeature.append( "\n%%EndFeature" );
710 aFeature.append( "\n} stopped cleartomark\n" );
711 sal_uInt64 nWritten = 0;
712 return pFile->write( aFeature.getStr(), aFeature.getLength(), nWritten )
713 || nWritten != (sal_uInt64)aFeature.getLength() ? false : true;
716 bool PrinterJob::writeFeatureList( osl::File* pFile, const JobData& rJob, bool bDocumentSetup )
718 bool bSuccess = true;
720 // emit features ordered to OrderDependency
721 // ignore features that are set to default
723 // sanity check
724 if( rJob.m_pParser == rJob.m_aContext.getParser() &&
725 rJob.m_pParser &&
726 ( m_aLastJobData.m_pParser == rJob.m_pParser || m_aLastJobData.m_pParser == NULL )
729 int i;
730 int nKeys = rJob.m_aContext.countValuesModified();
731 ::std::vector< const PPDKey* > aKeys( nKeys );
732 for( i = 0; i < nKeys; i++ )
733 aKeys[i] = rJob.m_aContext.getModifiedKey( i );
734 ::std::sort( aKeys.begin(), aKeys.end(), less_ppd_key() );
736 for( i = 0; i < nKeys && bSuccess; i++ )
738 const PPDKey* pKey = aKeys[i];
739 bool bEmit = false;
740 if( bDocumentSetup )
742 if( pKey->getSetupType() == PPDKey::DocumentSetup )
743 bEmit = true;
745 if( pKey->getSetupType() == PPDKey::PageSetup ||
746 pKey->getSetupType() == PPDKey::AnySetup )
747 bEmit = true;
748 if( bEmit )
750 const PPDValue* pValue = rJob.m_aContext.getValue( pKey );
751 if( pValue
752 && pValue->m_eType == eInvocation
753 && ( m_aLastJobData.m_pParser == NULL
754 || m_aLastJobData.m_aContext.getValue( pKey ) != pValue
755 || bDocumentSetup
759 // try to avoid PS level 2 feature commands if level is set to 1
760 if( GetPostscriptLevel( &rJob ) == 1 )
762 bool bHavePS2 =
763 ( pValue->m_aValue.SearchAscii( "<<" ) != STRING_NOTFOUND )
765 ( pValue->m_aValue.SearchAscii( ">>" ) != STRING_NOTFOUND );
766 if( bHavePS2 )
767 continue;
769 bSuccess = writeFeature( pFile, pKey, pValue, PrinterInfoManager::get().getUseIncludeFeature() );
774 else
775 bSuccess = false;
777 return bSuccess;
780 bool PrinterJob::writePageSetup( osl::File* pFile, const JobData& rJob, bool bWriteFeatures )
782 bool bSuccess = true;
784 WritePS (pFile, "%%BeginPageSetup\n%\n");
785 if ( bWriteFeatures )
786 bSuccess = writeFeatureList( pFile, rJob, false );
787 WritePS (pFile, "%%EndPageSetup\n");
789 sal_Char pTranslate [128];
790 sal_Int32 nChar = 0;
792 if( rJob.m_eOrientation == orientation::Portrait )
794 nChar = psp::appendStr ("gsave\n[", pTranslate);
795 nChar += psp::getValueOfDouble ( pTranslate + nChar, mfXScale, 5);
796 nChar += psp::appendStr (" 0 0 ", pTranslate + nChar);
797 nChar += psp::getValueOfDouble ( pTranslate + nChar, mfYScale, 5);
798 nChar += psp::appendStr (" ", pTranslate + nChar);
799 nChar += psp::getValueOf (mnRMarginPt, pTranslate + nChar);
800 nChar += psp::appendStr (" ", pTranslate + nChar);
801 nChar += psp::getValueOf (mnHeightPt-mnTMarginPt,
802 pTranslate + nChar);
803 nChar += psp::appendStr ("] concat\ngsave\n",
804 pTranslate + nChar);
806 else
808 nChar = psp::appendStr ("gsave\n", pTranslate);
809 nChar += psp::appendStr ("[ 0 ", pTranslate + nChar);
810 nChar += psp::getValueOfDouble ( pTranslate + nChar, -mfYScale, 5);
811 nChar += psp::appendStr (" ", pTranslate + nChar);
812 nChar += psp::getValueOfDouble ( pTranslate + nChar, mfXScale, 5);
813 nChar += psp::appendStr (" 0 ", pTranslate + nChar );
814 nChar += psp::getValueOfDouble ( pTranslate + nChar, mnLMarginPt, 5 );
815 nChar += psp::appendStr (" ", pTranslate + nChar);
816 nChar += psp::getValueOf (mnBMarginPt, pTranslate + nChar );
817 nChar += psp::appendStr ("] concat\ngsave\n",
818 pTranslate + nChar);
821 WritePS (pFile, pTranslate);
823 return bSuccess;
826 void PrinterJob::writeJobPatch( osl::File* pFile, const JobData& rJobData )
828 if( ! PrinterInfoManager::get().getUseJobPatch() )
829 return;
831 const PPDKey* pKey = NULL;
833 if( rJobData.m_pParser )
834 pKey = rJobData.m_pParser->getKey( OUString( "JobPatchFile" ) );
835 if( ! pKey )
836 return;
838 // order the patch files
839 // according to PPD spec the JobPatchFile options must be int
840 // and should be emitted in order
841 std::list< sal_Int32 > patch_order;
842 int nValueCount = pKey->countValues();
843 for( int i = 0; i < nValueCount; i++ )
845 const PPDValue* pVal = pKey->getValue( i );
846 patch_order.push_back( pVal->m_aOption.ToInt32() );
847 if( patch_order.back() == 0 && ! pVal->m_aOption.EqualsAscii( "0" ) )
849 WritePS( pFile, "% Warning: left out JobPatchFile option \"" );
850 OString aOption = OUStringToOString( pVal->m_aOption, RTL_TEXTENCODING_ASCII_US );
851 WritePS( pFile, aOption.getStr() );
852 WritePS( pFile,
853 "\"\n% as it violates the PPD spec;\n"
854 "% JobPatchFile options need to be numbered for ordering.\n" );
858 patch_order.sort();
859 patch_order.unique();
861 while( patch_order.begin() != patch_order.end() )
863 // note: this discards patch files not adhering to the "int" scheme
864 // as there won't be a value for them
865 writeFeature( pFile, pKey, pKey->getValue( OUString::valueOf( patch_order.front() ) ), false );
866 patch_order.pop_front();
870 bool PrinterJob::writeProlog (osl::File* pFile, const JobData& rJobData )
872 WritePS( pFile, "%%BeginProlog\n" );
874 // JobPatchFile feature needs to be emitted at begin of prolog
875 writeJobPatch( pFile, rJobData );
877 static const sal_Char pProlog[] = {
878 "%%BeginResource: procset PSPrint-Prolog 1.0 0\n"
879 "/ISO1252Encoding [\n"
880 "/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef\n"
881 "/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef\n"
882 "/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef\n"
883 "/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef\n"
884 "/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle\n"
885 "/parenleft /parenright /asterisk /plus /comma /hyphen /period /slash\n"
886 "/zero /one /two /three /four /five /six /seven\n"
887 "/eight /nine /colon /semicolon /less /equal /greater /question\n"
888 "/at /A /B /C /D /E /F /G\n"
889 "/H /I /J /K /L /M /N /O\n"
890 "/P /Q /R /S /T /U /V /W\n"
891 "/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore\n"
892 "/grave /a /b /c /d /e /f /g\n"
893 "/h /i /j /k /l /m /n /o\n"
894 "/p /q /r /s /t /u /v /w\n"
895 "/x /y /z /braceleft /bar /braceright /asciitilde /unused\n"
896 "/Euro /unused /quotesinglbase /florin /quotedblbase /ellipsis /dagger /daggerdbl\n"
897 "/circumflex /perthousand /Scaron /guilsinglleft /OE /unused /Zcaron /unused\n"
898 "/unused /quoteleft /quoteright /quotedblleft /quotedblright /bullet /endash /emdash\n"
899 "/tilde /trademark /scaron /guilsinglright /oe /unused /zcaron /Ydieresis\n"
900 "/space /exclamdown /cent /sterling /currency /yen /brokenbar /section\n"
901 "/dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron\n"
902 "/degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered\n"
903 "/cedilla /onesuperior /ordmasculine /guillemotright /onequarter /onehalf /threequarters /questiondown\n"
904 "/Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla\n"
905 "/Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis\n"
906 "/Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply\n"
907 "/Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls\n"
908 "/agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla\n"
909 "/egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis\n"
910 "/eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide\n"
911 "/oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis] def\n"
912 "\n"
913 "/psp_definefont { exch dup findfont dup length dict begin { 1 index /FID ne\n"
914 "{ def } { pop pop } ifelse } forall /Encoding 3 -1 roll def\n"
915 "currentdict end exch pop definefont pop } def\n"
916 "\n"
917 "/pathdict dup 8 dict def load begin\n"
918 "/rcmd { { currentfile 1 string readstring pop 0 get dup 32 gt { exit }\n"
919 "{ pop } ifelse } loop dup 126 eq { pop exit } if 65 sub dup 16#3 and 1\n"
920 "add exch dup 16#C and -2 bitshift 16#3 and 1 add exch 16#10 and 16#10\n"
921 "eq 3 1 roll exch } def\n"
922 "/rhex { dup 1 sub exch currentfile exch string readhexstring pop dup 0\n"
923 "get dup 16#80 and 16#80 eq dup 3 1 roll { 16#7f and } if 2 index 0 3\n"
924 "-1 roll put 3 1 roll 0 0 1 5 -1 roll { 2 index exch get add 256 mul }\n"
925 "for 256 div exch pop exch { neg } if } def\n"
926 "/xcmd { rcmd exch rhex exch rhex exch 5 -1 roll add exch 4 -1 roll add\n"
927 "1 index 1 index 5 -1 roll { moveto } { lineto } ifelse } def end\n"
928 "/readpath { 0 0 pathdict begin { xcmd } loop end pop pop } def\n"
929 "\n"
930 "systemdict /languagelevel known not {\n"
931 "/xshow { exch dup length 0 1 3 -1 roll 1 sub { dup 3 index exch get\n"
932 "exch 2 index exch get 1 string dup 0 4 -1 roll put currentpoint 3 -1\n"
933 "roll show moveto 0 rmoveto } for pop pop } def\n"
934 "/rectangle { 4 -2 roll moveto 1 index 0 rlineto 0 exch rlineto neg 0\n"
935 "rlineto closepath } def\n"
936 "/rectfill { rectangle fill } def\n"
937 "/rectstroke { rectangle stroke } def } if\n"
938 "/bshow { currentlinewidth 3 1 roll currentpoint 3 index show moveto\n"
939 "setlinewidth false charpath stroke setlinewidth } def\n"
940 "/bxshow { currentlinewidth 4 1 roll setlinewidth exch dup length 1 sub\n"
941 "0 1 3 -1 roll { 1 string 2 index 2 index get 1 index exch 0 exch put dup\n"
942 "currentpoint 3 -1 roll show moveto currentpoint 3 -1 roll false charpath\n"
943 "stroke moveto 2 index exch get 0 rmoveto } for pop pop setlinewidth } def\n"
944 "\n"
945 "/psp_lzwfilter { currentfile /ASCII85Decode filter /LZWDecode filter } def\n"
946 "/psp_ascii85filter { currentfile /ASCII85Decode filter } def\n"
947 "/psp_lzwstring { psp_lzwfilter 1024 string readstring } def\n"
948 "/psp_ascii85string { psp_ascii85filter 1024 string readstring } def\n"
949 "/psp_imagedict {\n"
950 "/psp_bitspercomponent { 3 eq { 1 }{ 8 } ifelse } def\n"
951 "/psp_decodearray { [ [0 1 0 1 0 1] [0 255] [0 1] [0 255] ] exch get }\n"
952 "def 7 dict dup\n"
953 "/ImageType 1 put dup\n"
954 "/Width 7 -1 roll put dup\n"
955 "/Height 5 index put dup\n"
956 "/BitsPerComponent 4 index psp_bitspercomponent put dup\n"
957 "/Decode 5 -1 roll psp_decodearray put dup\n"
958 "/ImageMatrix [1 0 0 1 0 0] dup 5 8 -1 roll put put dup\n"
959 "/DataSource 4 -1 roll 1 eq { psp_lzwfilter } { psp_ascii85filter } ifelse put\n"
960 "} def\n"
961 "%%EndResource\n"
962 "%%EndProlog\n"
964 WritePS (pFile, pProlog);
966 return true;
969 bool PrinterJob::writeSetup( osl::File* pFile, const JobData& rJob )
971 WritePS (pFile, "%%BeginSetup\n%\n");
973 // download fonts
974 std::list< OString > aFonts[2];
975 m_pGraphics->writeResources( pFile, aFonts[0], aFonts[1] );
977 for( int i = 0; i < 2; i++ )
979 if( !aFonts[i].empty() )
981 std::list< OString >::const_iterator it = aFonts[i].begin();
982 OStringBuffer aLine( 256 );
983 if( i == 0 )
984 aLine.append( "%%DocumentSuppliedResources: font " );
985 else
986 aLine.append( "%%DocumentNeededResources: font " );
987 aLine.append( *it );
988 aLine.append( "\n" );
989 WritePS ( pFile, aLine.getStr() );
990 while( (++it) != aFonts[i].end() )
992 aLine.setLength(0);
993 aLine.append( "%%+ font " );
994 aLine.append( *it );
995 aLine.append( "\n" );
996 WritePS ( pFile, aLine.getStr() );
1001 bool bSuccess = true;
1002 // in case of external print dialog the number of copies is prepended
1003 // to the job, let us not complicate things by emitting our own copy count
1004 bool bExternalDialog = PrinterInfoManager::get().checkFeatureToken( GetPrinterName(), "external_dialog" );
1005 if( ! bExternalDialog && rJob.m_nCopies > 1 )
1007 // setup code
1008 OStringBuffer aLine("/#copies ");
1009 aLine.append(static_cast<sal_Int32>(rJob.m_nCopies));
1010 aLine.append(" def\n");
1011 sal_uInt64 nWritten = 0;
1012 bSuccess = pFile->write(aLine.getStr(), aLine.getLength(), nWritten)
1013 || nWritten != static_cast<sal_uInt64>(aLine.getLength()) ?
1014 false : true;
1016 if( bSuccess && GetPostscriptLevel( &rJob ) >= 2 )
1017 WritePS (pFile, "<< /NumCopies null /Policies << /NumCopies 1 >> >> setpagedevice\n" );
1020 bool bFeatureSuccess = writeFeatureList( pFile, rJob, true );
1022 WritePS (pFile, "%%EndSetup\n");
1024 return bSuccess && bFeatureSuccess;
1027 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */