Exemple #1
0
void PPDFile::close()
{
    if (!_ppd)
        return;
    ppdClose(_ppd);
    _ppd = NULL;
}
Exemple #2
0
static void
list_options(cups_dest_t *dest)		/* I - Destination to list */
{
  int		i;			/* Looping var */
  const char	*filename;		/* PPD filename */
  ppd_file_t	*ppd;			/* PPD data */
  ppd_group_t	*group;			/* Current group */


  if ((filename = cupsGetPPD(dest->name)) == NULL)
  {
    _cupsLangPrintf(stderr, _("lpoptions: Unable to get PPD file for %s: %s"),
		    dest->name, cupsLastErrorString());
    return;
  }

  if ((ppd = ppdOpenFile(filename)) == NULL)
  {
    unlink(filename);
    _cupsLangPrintf(stderr, _("lpoptions: Unable to open PPD file for %s."),
		    dest->name);
    return;
  }

  ppdMarkDefaults(ppd);
  cupsMarkOptions(ppd, dest->num_options, dest->options);

  for (i = ppd->num_groups, group = ppd->groups; i > 0; i --, group ++)
    list_group(ppd, group);

  ppdClose(ppd);
  unlink(filename);
}
static void read_config_ppd() {
  ppd_option_t *option;
  ppd_file_t *ppd_file;
  char * ppd_name;

  ppd_name = getenv("PPD");
  if (ppd_name == NULL) {
    log_event(CPERROR, "Could not retrieve PPD name");
    return;
  }
  ppd_file = ppdOpenFile(ppd_name);
  if (ppd_file == NULL) {
    log_event(CPERROR, "Could not open PPD file: %s", ppd_name);
    return;
  }
  ppdMarkDefaults(ppd_file);

  option = ppdFirstOption(ppd_file);
  while (option != NULL) {
    _assign_value(SEC_PPD, option->keyword, option->defchoice);
    option = ppdNextOption(ppd_file);
  }
  ppdClose(ppd_file);

  return;
}
Exemple #4
0
/*
 * Ouverture et fermeture du fichier PPD
 * Opening or closing PPD file
 */
bool PPDFile::open(const char *file, const char *version, const char *useropts)
{
    const char *fileVersion;
    cups_option_t *options;
    int nr;

    // Check if a PPD file was previously opened
    if (_ppd) {
        ERRORMSG(_("Internal warning: a PPD file was previously opened. Please "
            "close it before opening a new one."));
        close();
    }

    // Open the PPD file
    _ppd = ppdOpenFile(file);
    if (!_ppd) {
        ERRORMSG(_("Cannot open PPD file %s"), file);
        return false;
    }

    // Mark the default values and the user options
    ppdMarkDefaults(_ppd);
    nr = cupsParseOptions(useropts, 0, &options);
    cupsMarkOptions(_ppd, nr, options);
    cupsFreeOptions(nr, options);

    // Check if the PPD version is compatible with this filter
    fileVersion = get("FileVersion");
    if (!fileVersion) { 
        ERRORMSG(_("No FileVersion found in the PPD file: invalid "
            "PPD file"));
        ppdClose(_ppd);
        _ppd = NULL;
        return false;
    }
    if (strcmp(fileVersion, version)) {
        ERRORMSG(_("Invalid PPD file version: %s but the PPD file "
            "is designed for SpliX V. %s"), version, fileVersion);
        ppdClose(_ppd);
        _ppd = NULL;
        return false;
    }

    return true;
}
QPpdPrintDevice::~QPpdPrintDevice()
{
    if (m_ppd)
        ppdClose(m_ppd);
    if (m_cupsDest)
        cupsFreeDests(1, m_cupsDest);
    m_cupsDest = 0;
    m_ppd = 0;
}
void HPCupsFilter::cleanup()
{
    if (m_pPrinterBuffer) {
        delete [] m_pPrinterBuffer;
    }

    if(m_ppd){
       ppdClose(m_ppd);
       m_ppd = NULL;
    }
}
static
int	make_lgmon_command( char *command, char *option, int utilbyte, short is_direct )	/* Ver.3.20 add param */
{
	char		model_name[MODEL_NAME_STR_LEN] ;
	int			status = CANON_STS_SUCCESS ;
	/* Ver.3.20 */
	short		add_direct = 0;
	char		*p_ppd_name = getenv("PPD");
	ppd_file_t	*p_ppd;

	/* Ver.3.20 */
	add_direct = is_direct;
	if( (p_ppd = ppdOpenFile(p_ppd_name)) == NULL )
		return CANON_STS_NG;
	
	if( p_ppd->model_number < 356 ) add_direct = 0;
	fprintf(stderr,"DEBUG: (cnijusb)p_ppd->model_number=(%d)\n",p_ppd->model_number);
	ppdClose(p_ppd);

										/* model name buffer initialization */
	memset( model_name, 0x00, sizeof( model_name ) ) ;

										/* model neme get 					*/
	if	( ( status = get_model_name( model_name ) ) == CANON_STS_SUCCESS ) { 

										/* making lgmon command 			*/
		if( utilbyte > 0 ){
			if( add_direct == 1 ){		/* Ver.3.20 */
				sprintf( command, "%s%s %s %s %s %s %d",	LGMON_CMD_BASE_STR,
					 model_name,
					 LGMON_CMD_GUI_OPTIN_STR,
					 LGMON_CMD_CUPS_OPTIN_STR,
					 LGMON_CMD_DIRECT_OPTIN_STR,
					 LGMON_CMD_UTIL_OPTIN_STR,
					 utilbyte) ;
			}
			else{
				sprintf( command, "%s%s %s %s %s %d",	LGMON_CMD_BASE_STR,
					 model_name,
					 LGMON_CMD_GUI_OPTIN_STR,
					 LGMON_CMD_CUPS_OPTIN_STR,
					 LGMON_CMD_UTIL_OPTIN_STR,
					 utilbyte) ;	
			}
		}
		else{		/* in this case, CNBjDirect is never specified. */
			sprintf( command, "%s%s %s %s",	LGMON_CMD_BASE_STR,
					 model_name, LGMON_CMD_GUI_OPTIN_STR,
					 LGMON_CMD_CUPS_OPTIN_STR) ;
		}
	}
	return( status ) ;
}
Exemple #8
0
static void
list_options(cups_dest_t *dest)		/* I - Destination to list */
{
  http_t	*http;			/* Connection to destination */
  char		resource[1024];		/* Resource path */
  int		i;			/* Looping var */
  const char	*filename;		/* PPD filename */
  ppd_file_t	*ppd;			/* PPD data */
  ppd_group_t	*group;			/* Current group */


  if ((http = cupsConnectDest(dest, CUPS_DEST_FLAGS_NONE, 30000, NULL, resource, sizeof(resource), NULL, NULL)) == NULL)
  {
    _cupsLangPrintf(stderr, _("lpoptions: Unable to get PPD file for %s: %s"),
		    dest->name, cupsLastErrorString());
    return;
  }

  if ((filename = cupsGetPPD2(http, dest->name)) == NULL)
  {
    httpClose(http);

    _cupsLangPrintf(stderr, _("lpoptions: Unable to get PPD file for %s: %s"),
		    dest->name, cupsLastErrorString());
    return;
  }

  httpClose(http);

  if ((ppd = ppdOpenFile(filename)) == NULL)
  {
    unlink(filename);
    _cupsLangPrintf(stderr, _("lpoptions: Unable to open PPD file for %s."),
		    dest->name);
    return;
  }

  ppdMarkDefaults(ppd);
  cupsMarkOptions(ppd, dest->num_options, dest->options);

  for (i = ppd->num_groups, group = ppd->groups; i > 0; i --, group ++)
    list_group(ppd, group);

  ppdClose(ppd);
  unlink(filename);
}
///////////////////////////////////////////////////////////////////////////////////////////
//
// CS     : PUBLIC gint getProductName(gchar *pDestName, gchar *pProductName)
// IN     : gchar *pDestName : Printer name.
// OUT    : gchar *pProductName : Product name. ( ModelName )
// RETURN : ID_ERR_NO_ERROR : No error.
//          ID_ERR_UNKNOWN_PRINTER : Getting product name failed.
//
PUBLIC gint getProductName(gchar *pDestName, gchar *pProductName)
{
/*** Parameters start ***/
	const gchar	*pPPDName = NULL;					// Pointer to PPD file name.
	ppd_file_t	*pPPD;								// Pointer to PPD file.
	gint		retVal = ID_ERR_UNKNOWN_PRINTER;	// Return value.
/*** Parameters start ***/

	// Get PPD file name.
	pPPDName = cupsGetPPD(pDestName);
	if (pPPDName != NULL) {
		if ((pPPD = ppdOpenFile(pPPDName)) != NULL) {
			if (strcmp(pPPD->manufacturer, STR_MANUFACTURER_NAME) == 0) {
				strncpy(pProductName, pPPD->modelname, strlen(pPPD->modelname));	// use modelname from 22th Jan.'03
				retVal = ID_ERR_NO_ERROR;
			}
			ppdClose(pPPD);
		}
		unlink(pPPDName);	// Tora 020418: You should remove the copy of the PPD file.
	}

	return(retVal);
}// End getProductName
/*----------------------------------------------------------------------------*
 * This function is carrying out processing which acquires 
 * the model name of a device (printer) from the product key of a PPD file.
 */
static
int     get_model_name( char *model_name )
{
	ppd_file_t	*p_file  ;
	int	status = CANON_STS_SUCCESS ;

									/* ppd file key get 					*/
	if  ( ( p_file = ppdOpenFile( getenv( "PPD" ) ) ) != NULL ) {
									/* product key length check				*/
		if  ( strlen( p_file->product ) > 0 ) {
			char product[MODEL_NAME_STR_LEN];
			char *p_product;
			char *p_tail;

			memset( product, 0, MODEL_NAME_STR_LEN );
			strncpy( product, p_file->product, MODEL_NAME_STR_LEN - 1 ) ;
			p_product = product;

			while( *p_product == '(' )
				p_product++;
			p_tail = p_product;
			while( *p_tail != ')' && *p_tail != '\0' )
				p_tail++;
			*p_tail = '\0';
			strcpy( model_name, p_product ) ;
		}
		else { 						/* product key (*products:) is not set	*/
			status = CANON_STS_PPD_KEY_SET_ERR ;
		}
		ppdClose( p_file ) ;
	}
	else {							/* ppd file open eror	r				*/ 
			status = CANON_STS_PPD_FILE_OPEN_ERR ;
	}

	return( status ) ;
}
Exemple #11
0
GList *dt_get_media_type(const dt_printer_info_t *printer)
{
  const char *printer_name = printer->name;
  GList *result = NULL;

  // check now PPD media type

  const char *PPDFile = cupsGetPPD(printer_name);
  ppd_file_t *ppd = ppdOpenFile(PPDFile);

  if (ppd)
  {
      ppd_option_t *opt = ppdFindOption(ppd, "MediaType");

      if (opt)
      {
        ppd_choice_t *choice = opt->choices;

        for (int k=0; k<opt->num_choices; k++)
        {
          dt_medium_info_t *media = (dt_medium_info_t*)malloc(sizeof(dt_medium_info_t));
          g_strlcpy(media->name, choice->choice, MAX_NAME);
          g_strlcpy(media->common_name, choice->text, MAX_NAME);
          result = g_list_append (result, media);

          dt_print(DT_DEBUG_PRINT, "[print] new media %2d (%s) (%s)\n", k, media->name, media->common_name);
          choice++;
        }
      }
  }

  ppdClose(ppd);
  g_unlink(PPDFile);

  return result;
}
const char *				/* O - Device URI or @code NULL@ */
cupsBackendDeviceURI(char **argv)	/* I - Command-line arguments */
{
  const char	*device_uri,		/* Device URI */
		*auth_info_required;	/* AUTH_INFO_REQUIRED env var */
  _cups_globals_t *cg = _cupsGlobals();	/* Global info */
  int		options;		/* Resolve options */
  ppd_file_t	*ppd;			/* PPD file */
  ppd_attr_t	*ppdattr;		/* PPD attribute */


  if ((device_uri = getenv("DEVICE_URI")) == NULL)
  {
    if (!argv || !argv[0] || !strchr(argv[0], ':'))
      return (NULL);

    device_uri = argv[0];
  }

  options = _HTTP_RESOLVE_STDERR;
  if ((auth_info_required = getenv("AUTH_INFO_REQUIRED")) != NULL &&
      !strcmp(auth_info_required, "negotiate"))
    options |= _HTTP_RESOLVE_FQDN;

  if ((ppd = ppdOpenFile(getenv("PPD"))) != NULL)
  {
    if ((ppdattr = ppdFindAttr(ppd, "cupsIPPFaxOut", NULL)) != NULL &&
        !_cups_strcasecmp(ppdattr->value, "true"))
      options |= _HTTP_RESOLVE_FAXOUT;

    ppdClose(ppd);
  }

  return (_httpResolveURI(device_uri, cg->resolved_uri,
                          sizeof(cg->resolved_uri), options, NULL, NULL));
}
Exemple #13
0
bool PrinterUtil::getPrinterMarginValues(const QString& printerName, const QString& pageSize, double& ptsTopMargin, double& ptsBottomMargin, double& ptsLeftMargin, double& ptsRightMargin)
{
	bool retVal=false;
#if defined(HAVE_CUPS)
	const char *filename; // tmp PPD filename
	filename=cupsGetPPD(printerName.toLocal8Bit().constData());
	if (filename!=NULL)
	{
		ppd_file_t *ppd; // PPD data
		ppd = ppdOpenFile(filename);
		if (ppd!=NULL)
		{
			ppd_size_t *size; // page size data, null if printer doesnt support selected size
			size = ppdPageSize(ppd, pageSize.toLocal8Bit().constData());
			if (size!=NULL)
			{
				//Store in pts for returning via getNewPrinterMargins in pts
				retVal=true;
				ptsTopMargin=size->length-size->top;
				ptsBottomMargin=size->bottom;
				ptsLeftMargin=size->left;
				ptsRightMargin=size->width-size->right;
			}
			ppdClose(ppd);
		}
	}
#elif defined(_WIN32)
	DWORD nPaper;
	DWORD nPaperNames;
	typedef WCHAR wchar64[64];
	nPaper = DeviceCapabilitiesW( (LPCWSTR) printerName.utf16(), NULL, DC_PAPERS, NULL, NULL );
	nPaperNames = DeviceCapabilitiesW( (LPCWSTR) printerName.utf16(), NULL, DC_PAPERNAMES, NULL, NULL );
	if ( (nPaper > 0) && (nPaperNames > 0) && (nPaper == nPaperNames) )
	{
		int paperIndex = -1;
		DWORD   *papers = new DWORD[nPaper];
		wchar64 *paperNames = new wchar64[nPaperNames];
		DWORD s1 = DeviceCapabilitiesW( (LPCWSTR) printerName.utf16(), NULL, DC_PAPERS, (LPWSTR) papers, NULL );
		DWORD s2 = DeviceCapabilitiesW( (LPCWSTR) printerName.utf16(), NULL, DC_PAPERNAMES, (LPWSTR) paperNames, NULL );
		for ( uint i = 0; i < nPaperNames; i++ )
		{
			if ( pageSize == QString::fromUtf16((const ushort*) paperNames[i]) )
			{
				paperIndex = i;
				break;
			}
		}
		if ( paperIndex >= 0 )
		{
			Qt::HANDLE handle = NULL;
			if( OpenPrinterW( (LPWSTR) printerName.utf16(), &handle, NULL ) )
			{
				// Retrieve DEVMODE structure for selected device
				uint size = DocumentPropertiesW( ScCore->primaryMainWindow()->winId(), handle, (LPWSTR) printerName.utf16(), NULL, NULL, 0);
				QByteArray devModeW(size, 0);
				DEVMODEW* devMode = (DEVMODEW*) devModeW.data();
				DocumentPropertiesW( ScCore->primaryMainWindow()->winId(), handle, (LPWSTR) printerName.utf16(), devMode, NULL, DM_OUT_BUFFER);
				ClosePrinter( handle );
				// Set paper size
				devMode->dmPaperSize = papers[paperIndex];
				// Create device context
				HDC printerDC = CreateDCW( NULL, (LPWSTR) printerName.utf16(), NULL, devMode );
				if( printerDC )
				{
					retVal = true;
					int logPixelsX = GetDeviceCaps( printerDC, LOGPIXELSX );
					int logPixelsY = GetDeviceCaps( printerDC, LOGPIXELSY );
					int physicalOffsetX = GetDeviceCaps( printerDC, PHYSICALOFFSETX );
					int physicalOffsetY = GetDeviceCaps( printerDC, PHYSICALOFFSETY );
					ptsLeftMargin = ptsRightMargin = ( physicalOffsetX / (double) logPixelsX * 72 );
					ptsTopMargin = ptsBottomMargin = ( physicalOffsetY / (double) logPixelsY * 72 );
					DeleteDC(printerDC);
				}
			}
		}
		delete[] papers;
		delete[] paperNames;
	}
#endif
	return retVal;
}
Exemple #14
0
CupsOptions::CupsOptions(QWidget* parent, QString Geraet) : QDialog( parent )
{
	FlagsOpt.clear();
	setModal(true);
	setWindowTitle( tr( "Printer Options" ) );
	setWindowIcon(QIcon(loadIcon ( "AppIcon.png" )));
	prefs = PrefsManager::instance()->prefsFile->getContext("cups_options");
	setSizeGripEnabled(true);
	CupsOptionsLayout = new QVBoxLayout( this );
	CupsOptionsLayout->setSpacing( 5 );
	CupsOptionsLayout->setMargin( 10 );
	Table = new QTableWidget(0, 2, this);
	Table->setSortingEnabled(false);
	Table->setSelectionMode(QAbstractItemView::NoSelection);
	Table->verticalHeader()->hide();
	Table->setHorizontalHeaderItem(0, new QTableWidgetItem( tr("Option")));
	Table->setHorizontalHeaderItem(1, new QTableWidgetItem( tr("Value")));
	QHeaderView* headerH = Table->horizontalHeader();
	headerH->setStretchLastSection(true);
	headerH->setMovable(false);
	headerH->setClickable(false);
	headerH->setResizeMode(QHeaderView::Fixed);
	Table->setMinimumSize(300, 100);
#ifdef HAVE_CUPS
	int i;
	cups_dest_t *dests;
	cups_dest_t *dest;
	int num_dests;
	const char	*filename;	/* PPD filename */
	ppd_file_t	*ppd;				/* PPD data */
	ppd_group_t	*group;			/* Current group */
	num_dests = cupsGetDests(&dests);
	dest = cupsGetDest(Geraet.toLocal8Bit().constData(), NULL, num_dests, dests);
	if (!(dest == NULL || (filename = cupsGetPPD(dest->name)) == NULL || (ppd = ppdOpenFile(filename)) == NULL))
	{
		ppdMarkDefaults(ppd);
		cupsMarkOptions(ppd, dest->num_options, dest->options);
		QStringList opts;
		QString Marked = "";
		KeyToText.clear();
		KeyToDefault.clear();
		for (i = ppd->num_groups, group = ppd->groups; i > 0; i --, ++group)
		{
			int ix;
			ppd_option_t	*option;	/* Current option */
			ppd_choice_t	*choice;	/* Current choice */
			for (ix = group->num_options, option = group->options; ix > 0; ix --, ++option)
			{
				int j;
				Marked = "";
				struct OpData Daten;
				opts.clear();
				for (j = option->num_choices, choice = option->choices;
						j > 0; j --, ++choice)
				{
					opts.append(QString(choice->choice));
					if (choice->marked)
						Marked = QString(choice->choice);
				}
				if (!Marked.isEmpty())
				{
					Table->setRowCount(Table->rowCount()+1);
					Table->setItem(Table->rowCount()-1, 0, new QTableWidgetItem(QString(option->text)));
					QComboBox *item = new QComboBox( this );
					item->setEditable(false);
					FlagsOpt.append(item);
					Daten.Cnum = static_cast<int>(FlagsOpt.count()-1);
					Daten.KeyW = QString(option->keyword);
					KeyToText[QString(option->text)] = Daten;
					item->addItems(opts);
					int lastSelected = prefs->getInt(QString(option->text), 0);
					if (lastSelected >= static_cast<int>(opts.count()))
						lastSelected = 0;
					item->setCurrentIndex(lastSelected);
					KeyToDefault[QString(option->text)] = Marked;
					Table->setCellWidget(Table->rowCount()-1, 1, item);
				}
			}
		}
		ppdClose(ppd);
		cupsFreeDests(num_dests, dests);
	}
	struct OpData Daten;

	Table->setRowCount(Table->rowCount()+1);
	Table->setItem(Table->rowCount()-1, 0, new QTableWidgetItem(QString( tr("Page Set"))));
	QComboBox *item4 = new QComboBox( this );
	item4->setEditable(false);
	FlagsOpt.append(item4);
	Daten.Cnum = static_cast<int>(FlagsOpt.count()-1);
	Daten.KeyW = "page-set";
	KeyToText["Page Set"] = Daten;
	item4->addItem( tr("All Pages"));
	item4->addItem( tr("Even Pages only"));
	item4->addItem( tr("Odd Pages only"));
	int lastSelected = prefs->getInt( tr("Page Set"), 0);
	if (lastSelected >= 3)
		lastSelected = 0;
	item4->setCurrentIndex(lastSelected);
	KeyToDefault["Page Set"] = tr("All Pages");
	Table->setCellWidget(Table->rowCount()-1, 1, item4);
	Table->setRowCount(Table->rowCount()+1);
	Table->setItem(Table->rowCount()-1, 0, new QTableWidgetItem(QString( tr("Mirror"))));
	QComboBox *item2 = new QComboBox( this );
	item2->setEditable(false);
	FlagsOpt.append(item2);
	Daten.Cnum = static_cast<int>(FlagsOpt.count()-1);
	Daten.KeyW = "mirror";
	KeyToText["Mirror"] = Daten;
	item2->addItem(CommonStrings::trNo);
	item2->addItem(CommonStrings::trYes);
	item2->setCurrentIndex(0);
	lastSelected = prefs->getInt( tr("Mirror"), 0);
	if (lastSelected >= 2)
		lastSelected = 0;
	item2->setCurrentIndex(lastSelected);
	KeyToDefault["Mirror"] = CommonStrings::trNo;
	Table->setCellWidget(Table->rowCount()-1, 1, item2);
	Table->setRowCount(Table->rowCount()+1);
	Table->setItem(Table->rowCount()-1, 0, new QTableWidgetItem(QString( tr("Orientation"))));
	QComboBox *item5 = new QComboBox( this );
	item5->setEditable(false);
	FlagsOpt.append(item5);
	Daten.Cnum = static_cast<int>(FlagsOpt.count()-1);
	Daten.KeyW = "orientation";
	KeyToText["Orientation"] = Daten;
	item5->addItem( tr("Portrait"));
	item5->addItem( tr("Landscape"));
	item5->setCurrentIndex(0);
	lastSelected = prefs->getInt( tr("Orientation"), 0);
	if (lastSelected >= 2)
		lastSelected = 0;
	item5->setCurrentIndex(lastSelected);
	KeyToDefault["Orientation"] = tr("Portrait");
	Table->setCellWidget(Table->rowCount()-1, 1, item5);
	Table->setRowCount(Table->rowCount()+1);
	Table->setItem(Table->rowCount()-1, 0, new QTableWidgetItem(QString( tr("N-Up Printing"))));
	QComboBox *item3 = new QComboBox( this );
	item3->setEditable(false);
	FlagsOpt.append(item3);
	Daten.Cnum = static_cast<int>(FlagsOpt.count()-1);
	Daten.KeyW = "number-up";
	KeyToText["N-Up Printing"] = Daten;
	item3->addItem("1 "+ tr("Page per Sheet"));
	item3->addItem("2 "+ tr("Pages per Sheet"));
	item3->addItem("4 "+ tr("Pages per Sheet"));
	item3->addItem("6 "+ tr("Pages per Sheet"));
	item3->addItem("9 "+ tr("Pages per Sheet"));
	item3->addItem("16 "+ tr("Pages per Sheet"));
	lastSelected = prefs->getInt( tr("N-Up Printing"), 0);
	if (lastSelected >= 6)
		lastSelected = 0;
	item3->setCurrentIndex(lastSelected);
	KeyToDefault["N-Up Printing"] = "1 "+ tr("Page per Sheet");
	Table->setCellWidget(Table->rowCount()-1, 1, item3);
#endif
	Table->resizeColumnsToContents();
	CupsOptionsLayout->addWidget( Table );

	Layout2 = new QHBoxLayout;
	Layout2->setSpacing( 5 );
	Layout2->setMargin( 0 );
	QSpacerItem* spacer = new QSpacerItem( 2, 2, QSizePolicy::Expanding, QSizePolicy::Minimum );
	Layout2->addItem( spacer );
	PushButton1 = new QPushButton( CommonStrings::tr_OK, this );
	PushButton1->setDefault( true );
	Layout2->addWidget( PushButton1 );
	PushButton2 = new QPushButton( CommonStrings::tr_Cancel, this );
	PushButton2->setDefault( false );
	PushButton1->setFocus();
	Layout2->addWidget( PushButton2 );
	CupsOptionsLayout->addLayout( Layout2 );
	setMinimumSize( sizeHint() );
	resize(minimumSizeHint().expandedTo(QSize(300, 100)));

//tooltips
	Table->setToolTip( "<qt>" + tr( "This panel displays various CUPS options when printing. The exact parameters available will depend on your printer driver. You can confirm CUPS support by selecting Help > About. Look for the listings: C-C-T These equate to C=CUPS C=littlecms T=TIFF support. Missing library support is indicated by a *" ) + "</qt>" );

    // signals and slots connections
	connect( PushButton2, SIGNAL( clicked() ), this, SLOT( reject() ) );
	connect( PushButton1, SIGNAL( clicked() ), this, SLOT( accept() ) );
}
Exemple #15
0
int					/* O - Exit status */
main(int  argc,				/* I - Number of command-line arguments */
     char *argv[])			/* I - Command-line arguments */
{
  int			fd;		/* File descriptor */
  cups_raster_t		*ras;		/* Raster stream for printing */
  cups_page_header2_t	header;		/* Page header from file */
  unsigned		y;		/* Current line */
  ppd_file_t		*ppd;		/* PPD file */
  int			num_options;	/* Number of options */
  cups_option_t		*options;	/* Options */
#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
  struct sigaction action;		/* Actions for POSIX signals */
#endif /* HAVE_SIGACTION && !HAVE_SIGSET */


 /*
  * Make sure status messages are not buffered...
  */

  setbuf(stderr, NULL);

 /*
  * Check command-line...
  */

  if (argc < 6 || argc > 7)
  {
   /*
    * We don't have the correct number of arguments; write an error message
    * and return.
    */

    _cupsLangPrintFilter(stderr, "ERROR",
                         _("%s job-id user title copies options [file]"),
			 "rastertolabel");
    return (1);
  }

 /*
  * Open the page stream...
  */

  if (argc == 7)
  {
    if ((fd = open(argv[6], O_RDONLY)) == -1)
    {
      _cupsLangPrintError("ERROR", _("Unable to open raster file"));
      sleep(1);
      return (1);
    }
  }
  else
    fd = 0;

  ras = cupsRasterOpen(fd, CUPS_RASTER_READ);

 /*
  * Register a signal handler to eject the current page if the
  * job is cancelled.
  */

  Canceled = 0;

#ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
  sigset(SIGTERM, CancelJob);
#elif defined(HAVE_SIGACTION)
  memset(&action, 0, sizeof(action));

  sigemptyset(&action.sa_mask);
  action.sa_handler = CancelJob;
  sigaction(SIGTERM, &action, NULL);
#else
  signal(SIGTERM, CancelJob);
#endif /* HAVE_SIGSET */

 /*
  * Open the PPD file and apply options...
  */

  num_options = cupsParseOptions(argv[5], 0, &options);

  ppd = ppdOpenFile(getenv("PPD"));
  if (!ppd)
  {
    ppd_status_t	status;		/* PPD error */
    int			linenum;	/* Line number */

    _cupsLangPrintFilter(stderr, "ERROR",
                         _("The PPD file could not be opened."));

    status = ppdLastError(&linenum);

    fprintf(stderr, "DEBUG: %s on line %d.\n", ppdErrorString(status), linenum);

    return (1);
  }

  ppdMarkDefaults(ppd);
  cupsMarkOptions(ppd, num_options, options);

 /*
  * Initialize the print device...
  */

  Setup(ppd);

 /*
  * Process pages as needed...
  */

  Page = 0;

  while (cupsRasterReadHeader2(ras, &header))
  {
   /*
    * Write a status message with the page number and number of copies.
    */

    if (Canceled)
      break;

    Page ++;

    fprintf(stderr, "PAGE: %d 1\n", Page);
    _cupsLangPrintFilter(stderr, "INFO", _("Starting page %d."), Page);

   /*
    * Start the page...
    */

    StartPage(ppd, &header);

   /*
    * Loop for each line on the page...
    */

    for (y = 0; y < header.cupsHeight && !Canceled; y ++)
    {
     /*
      * Let the user know how far we have progressed...
      */

      if (Canceled)
	break;

      if ((y & 15) == 0)
      {
        _cupsLangPrintFilter(stderr, "INFO",
	                     _("Printing page %d, %u%% complete."),
			     Page, 100 * y / header.cupsHeight);
        fprintf(stderr, "ATTR: job-media-progress=%u\n",
		100 * y / header.cupsHeight);
      }

     /*
      * Read a line of graphics...
      */

      if (cupsRasterReadPixels(ras, Buffer, header.cupsBytesPerLine) < 1)
        break;

     /*
      * Write it to the printer...
      */

      OutputLine(ppd, &header, y);
    }

   /*
    * Eject the page...
    */

    _cupsLangPrintFilter(stderr, "INFO", _("Finished page %d."), Page);

    EndPage(ppd, &header);

    if (Canceled)
      break;
  }

 /*
  * Close the raster stream...
  */

  cupsRasterClose(ras);
  if (fd != 0)
    close(fd);

 /*
  * Close the PPD file and free the options...
  */

  ppdClose(ppd);
  cupsFreeOptions(num_options, options);

 /*
  * If no pages were printed, send an error message...
  */

  if (Page == 0)
  {
    _cupsLangPrintFilter(stderr, "ERROR", _("No pages were found."));
    return (1);
  }
  else
    return (0);
}
Exemple #16
0
DRIVER_ERROR HPCupsFilter::startPage (cups_page_header2_t *cups_header)
{
    DRIVER_ERROR        err = NO_ERROR;
    ppd_attr_t          *attr;
    int                 xoverspray = 120;
    int                 yoverspray = 60;

/*
 *  Check for invalid data
 */
    if (cups_header->HWResolution[0] == 100 && cups_header->HWResolution[1] == 100)
    {

/*
 *      Something went wrong, cups is defaulting to 100 dpi.
 *      Some inkjet printers do not support 100 dpi. Return error.
 */

        dbglog("ERROR: Unsupported resolution\n");
        return JOB_CANCELED;
    }

//  XOverSpray and YOverSpray are entered as fractional value * 1000

    if (((attr = ppdFindAttr(m_ppd, "HPXOverSpray", NULL)) != NULL) &&
        (attr && attr->value != NULL)) {
           xoverspray = atoi(attr->value);
    }
    if (((attr = ppdFindAttr(m_ppd, "HPYOverSpray", NULL)) != NULL) &&
        (attr && attr->value != NULL)) {
           yoverspray = atoi(attr->value);
    }

    if (m_iLogLevel & BASIC_LOG) {
        printCupsHeaderInfo(cups_header);
    }

    m_JA.quality_attributes.media_type = cups_header->cupsMediaType;
    m_JA.quality_attributes.print_quality = atoi(cups_header->OutputType);
    m_JA.quality_attributes.horizontal_resolution = cups_header->HWResolution[0];
    m_JA.quality_attributes.vertical_resolution   = cups_header->HWResolution[1];
    m_JA.quality_attributes.actual_vertical_resolution   = cups_header->HWResolution[1];

//  Get the printer's actual resolution, may be different than what is reported
    char   *p;
    if ((p = strstr (cups_header->OutputType, "_"))) {
        int    x = 0, y = 0;
        p++;
        x = atoi(p);
        while (*p && *p != 'x')
            p++;
        if (*p && *p == 'x') {
            p++;
            y = atoi(p);
        }
//      Currently, there is one printer with one printmode that supports lower y-resolution
        if (y != 0) {
            m_JA.quality_attributes.actual_vertical_resolution = y;
        }
    }
    m_JA.color_mode = cups_header->cupsRowStep;
    m_JA.media_source = cups_header->MediaPosition;

    m_JA.print_borderless = (cups_header->ImagingBoundingBox[0] == 0) ? true : false;
    if (cups_header->Duplex) {
        m_JA.e_duplex_mode  = (cups_header->Tumble == 0) ? DUPLEXMODE_BOOK : DUPLEXMODE_TABLET;
    }
    else {
        m_JA.e_duplex_mode = DUPLEXMODE_NONE;
    }
    m_JA.krgb_mode = (cups_header->cupsColorSpace == CUPS_CSPACE_RGBW) ? true : false;

    /*
     *  Cups PageSize dimensions are in PostScript units, which are 72 units to an inch
     *  and is stored as <width, height>
     *  The ImagingBoundingBox is in PostScript units and are stored as <lower_left> <upper_right>
     *  and <0, 0> is at the bottom left
     *      lower_left_x = ImagingBoundingBox[0]
     *      lower_left_y = ImagingBoundingBox[1]
     *      upper_right_x = ImagingBoundingBox[2]
     *      upper_right_y = ImagingBoundingBox[3]
     *  We require <top_left> <bottom_right> values and <0, 0> is top left
     *  So,
     *      PrintableStartX = lower_left_x
     *      PrintableStartY = PhysicalPageHeight - upper_right_y
     */

    int    horz_res = cups_header->HWResolution[0];
    int    vert_res = cups_header->HWResolution[1];
    m_JA.media_attributes.pcl_id = cups_header->cupsInteger[0];
    m_JA.media_attributes.printable_start_x = (cups_header->Margins[0] * horz_res) / 72;
    m_JA.media_attributes.printable_start_y = ((cups_header->PageSize[1] - cups_header->ImagingBoundingBox[3]) * vert_res) / 72;
    m_JA.media_attributes.horizontal_overspray = (xoverspray * horz_res) / 1000;
    m_JA.media_attributes.vertical_overspray   = (yoverspray * vert_res) / 1000;

    /*
     * Left and top overspray in dots. We haven't defined ovespray for all classes in the drv.
     * Hence using default values in the case of older classes.
     */
    m_JA.media_attributes.left_overspray = cups_header->cupsReal[0] ? (cups_header->cupsReal[0] * horz_res) : m_JA.media_attributes.horizontal_overspray / 2;
    m_JA.media_attributes.top_overspray  = cups_header->cupsReal[1] ? (cups_header->cupsReal[1] * vert_res) : m_JA.media_attributes.vertical_overspray / 2;

    if (((attr = ppdFindAttr(m_ppd, "HPMechOffset", NULL)) != NULL) &&
        (attr && attr->value != NULL)) {
        m_JA.mech_offset = atoi(attr->value);
    }

    if(cups_header->PageSize[0] > 612) // Check for B size paper. B Size paper has width > 8.5 inch (612 points)
    {
        //Check if HPMechOffsetBSize attribute is defined. If it is defined then use this offset value.
        if (((attr = ppdFindAttr(m_ppd, "HPMechOffsetBSize", NULL)) != NULL) && (attr && attr->value != NULL)) 
        {
            m_JA.mech_offset = atoi(attr->value);
        }

    }

//  Get printer platform name
    if (((attr = ppdFindAttr(m_ppd, "hpPrinterPlatform", NULL)) != NULL) && (attr->value != NULL)) {

        strncpy(m_JA.printer_platform, attr->value, sizeof(m_JA.printer_platform)-1);

        if (m_iLogLevel & BASIC_LOG) {
            dbglog("HPCUPS: found Printer Platform, it is - %s\n", attr->value);
        }	

        if (strcmp(m_JA.printer_platform, "ljzjscolor") == 0) {
            if (((attr = ppdFindAttr(m_ppd, "hpLJZjsColorVersion", NULL)) != NULL) && 
                 (attr->value != NULL)) 
            {
                 m_JA.printer_platform_version = atoi(attr->value);
            }
        }
    }

//Get Raster Preprocessing status
    if (((attr = ppdFindAttr(m_ppd, "hpReverseRasterPages", NULL)) != NULL) && 
         (attr->value != NULL)) 
    {
          m_JA.pre_process_raster = atoi(attr->value);
    }

    if (((attr = ppdFindAttr(m_ppd, "HPSPDClass", NULL)) == NULL) ||
         (attr && attr->value == NULL)) 
    {
        m_JA.HPSPDClass = 0;
    }
    else
    {
        m_JA.HPSPDClass = atoi(attr->value);
    }
    

// Get the encapsulation technology from ppd

    if (((attr = ppdFindAttr(m_ppd, "hpPrinterLanguage", NULL)) == NULL) ||
         (attr && attr->value == NULL)) 
    {
            dbglog("DEBUG: Bad PPD - hpPrinterLanguage not found\n");
            ppdClose(m_ppd);
            m_ppd = NULL;
            return SYSTEM_ERROR;
    }
    strncpy(m_JA.printer_language, attr->value, sizeof(m_JA.printer_language)-1);

    if (strcmp(m_JA.printer_language, "hbpl1") == 0) {
        m_JA.media_attributes.physical_width = cups_header->PageSize[0];
        m_JA.media_attributes.physical_height = cups_header->PageSize[1];
        m_JA.media_attributes.printable_width = ((cups_header->ImagingBoundingBox[2]-cups_header->ImagingBoundingBox[0]) * horz_res) / 72;
        m_JA.media_attributes.printable_height = ((cups_header->ImagingBoundingBox[3]-cups_header->ImagingBoundingBox[1]) * vert_res) / 72;
        strncpy(m_JA.media_attributes.PageSizeName, &cups_header->cupsString[0][0], sizeof(m_JA.media_attributes.PageSizeName));
        strncpy(m_JA.media_attributes.MediaTypeName, cups_header->MediaType, sizeof(m_JA.media_attributes.MediaTypeName));
        strncpy(m_JA.quality_attributes.hbpl1_print_quality, cups_header->OutputType, sizeof(m_JA.quality_attributes.hbpl1_print_quality));
        m_JA.color_mode = cups_header->cupsRowStep;
    }
    else {
        m_JA.media_attributes.physical_width   = (cups_header->PageSize[0] * horz_res) / 72;
        m_JA.media_attributes.physical_height  = (cups_header->PageSize[1] * vert_res) / 72;
        m_JA.media_attributes.printable_width  = cups_header->cupsWidth;
        m_JA.media_attributes.printable_height = cups_header->cupsHeight;
    }

    if (m_iLogLevel & BASIC_LOG) {
        dbglog("HPCUPS: found Printer Language, it is - %s\n", attr->value);
    }

//  Fill in the other PCL header info

    struct utsname  uts_name;
    uname(&uts_name);
    strncpy(m_JA.job_title, m_argv[3], sizeof(m_JA.job_title)-1);
    strncpy(m_JA.user_name, m_argv[2], sizeof(m_JA.user_name)-1);
    strncpy(m_JA.host_name, uts_name.nodename, sizeof(m_JA.host_name)-1);
    strncpy(m_JA.os_name, uts_name.sysname, sizeof(m_JA.os_name)-1);
    getdomainname(m_JA.domain_name, sizeof(m_JA.domain_name) - 1);
    int i = strlen(m_argv[0]) - 1;
    while (i >= 0 && m_argv[0][i] != '/') {
        i--;
    }
    snprintf(m_JA.driver_name, sizeof(m_JA.driver_name), "%s; %s", &m_argv[0][i+1], HP_FILE_VERSION_STR);
    char    *ptr = getenv("DEVICE_URI");
    i = 0;
    if (ptr) {
        while (*ptr) {
            if (*ptr == '%') {
                ptr += 3;
                m_JA.printer_name[i++] = ' ';
            }
            m_JA.printer_name[i++] = *ptr++;
        }
    }

    string strPrinterURI="" , strPrinterName= "";
    if (getenv("DEVICE_URI"))
        m_DBusComm.initDBusComm(DBUS_PATH,DBUS_INTERFACE, getenv("DEVICE_URI"), m_JA.printer_name);

    ptr = strstr(m_argv[5], "job-uuid");
    if (ptr) {
        strncpy(m_JA.uuid, ptr + strlen("job-uuid=urn:uuid:"), sizeof(m_JA.uuid)-1);
    }

    for (i = 0; i < 16; i++)
        m_JA.integer_values[i] = cups_header->cupsInteger[i];

    if (cups_header->cupsString[0]) {
        strncpy(m_JA.quality_attributes.print_mode_name, &cups_header->cupsString[0][0],
                sizeof(m_JA.quality_attributes.print_mode_name)-1);
    }

    Encapsulator *encap_interface = EncapsulatorFactory::GetEncapsulator(m_JA.printer_language);

    if ((err = m_Job.Init(m_pSys, &m_JA, encap_interface)) != NO_ERROR)
    {
        if (err == PLUGIN_LIBRARY_MISSING)
        {
            fputs ("STATE: +hplip.plugin-error\n", stderr);

            m_DBusComm.sendEvent(EVENT_PRINT_FAILED_MISSING_PLUGIN, "Plugin missing", m_JA.job_id, m_JA.user_name);

        }
        dbglog ("m_Job initialization failed with error = %d\n", err);
        ppdClose(m_ppd);
        m_ppd = NULL;
        return err;
    }

    if (m_iLogLevel & BASIC_LOG) {
        dbglog("HPCUPS: returning NO_ERROR from startPage\n");
    }

    m_pPrinterBuffer = new BYTE[cups_header->cupsWidth * 4 + 32];

    return NO_ERROR;
}
Exemple #17
0
int					/* O - Exit status */
main(int  argc,				/* I - Number of command-line arguments */
     char *argv[])			/* I - Command-line arguments */
{
  int		status = 0,		/* Exit status */
		i,			/* Looping var */
		num_dests;		/* Number of destinations */
  cups_dest_t	*dests,			/* Destinations */
		*dest,			/* Current destination */
		*named_dest;		/* Current named destination */
  const char	*ppdfile;		/* PPD file */
  ppd_file_t	*ppd;			/* PPD file data */
  int		num_jobs;		/* Number of jobs for queue */
  cups_job_t	*jobs;			/* Jobs for queue */


  if (argc > 1)
  {
    if (!strcmp(argv[1], "enum"))
    {
      cups_ptype_t	mask = CUPS_PRINTER_LOCAL,
					/* Printer type mask */
			type = CUPS_PRINTER_LOCAL;
					/* Printer type */
      int		msec = 0;	/* Timeout in milliseconds */


      for (i = 2; i < argc; i ++)
        if (isdigit(argv[i][0] & 255) || argv[i][0] == '.')
          msec = (int)(atof(argv[i]) * 1000);
        else if (!_cups_strcasecmp(argv[i], "bw"))
        {
          mask |= CUPS_PRINTER_BW;
          type |= CUPS_PRINTER_BW;
        }
        else if (!_cups_strcasecmp(argv[i], "color"))
        {
          mask |= CUPS_PRINTER_COLOR;
          type |= CUPS_PRINTER_COLOR;
        }
        else if (!_cups_strcasecmp(argv[i], "mono"))
        {
          mask |= CUPS_PRINTER_COLOR;
        }
        else if (!_cups_strcasecmp(argv[i], "duplex"))
        {
          mask |= CUPS_PRINTER_DUPLEX;
          type |= CUPS_PRINTER_DUPLEX;
        }
        else if (!_cups_strcasecmp(argv[i], "simplex"))
        {
          mask |= CUPS_PRINTER_DUPLEX;
        }
        else if (!_cups_strcasecmp(argv[i], "staple"))
        {
          mask |= CUPS_PRINTER_STAPLE;
          type |= CUPS_PRINTER_STAPLE;
        }
        else if (!_cups_strcasecmp(argv[i], "copies"))
        {
          mask |= CUPS_PRINTER_COPIES;
          type |= CUPS_PRINTER_COPIES;
        }
        else if (!_cups_strcasecmp(argv[i], "collate"))
        {
          mask |= CUPS_PRINTER_COLLATE;
          type |= CUPS_PRINTER_COLLATE;
        }
        else if (!_cups_strcasecmp(argv[i], "punch"))
        {
          mask |= CUPS_PRINTER_PUNCH;
          type |= CUPS_PRINTER_PUNCH;
        }
        else if (!_cups_strcasecmp(argv[i], "cover"))
        {
          mask |= CUPS_PRINTER_COVER;
          type |= CUPS_PRINTER_COVER;
        }
        else if (!_cups_strcasecmp(argv[i], "bind"))
        {
          mask |= CUPS_PRINTER_BIND;
          type |= CUPS_PRINTER_BIND;
        }
        else if (!_cups_strcasecmp(argv[i], "sort"))
        {
          mask |= CUPS_PRINTER_SORT;
          type |= CUPS_PRINTER_SORT;
        }
        else if (!_cups_strcasecmp(argv[i], "mfp"))
        {
          mask |= CUPS_PRINTER_MFP;
          type |= CUPS_PRINTER_MFP;
        }
        else if (!_cups_strcasecmp(argv[i], "printer"))
        {
          mask |= CUPS_PRINTER_MFP;
        }
        else if (!_cups_strcasecmp(argv[i], "large"))
        {
          mask |= CUPS_PRINTER_LARGE;
          type |= CUPS_PRINTER_LARGE;
        }
        else if (!_cups_strcasecmp(argv[i], "medium"))
        {
          mask |= CUPS_PRINTER_MEDIUM;
          type |= CUPS_PRINTER_MEDIUM;
        }
        else if (!_cups_strcasecmp(argv[i], "small"))
        {
          mask |= CUPS_PRINTER_SMALL;
          type |= CUPS_PRINTER_SMALL;
        }
        else
          fprintf(stderr, "Unknown argument \"%s\" ignored...\n", argv[i]);

      cupsEnumDests(CUPS_DEST_FLAGS_NONE, msec, NULL, type, mask, enum_cb, NULL);
    }
    else if (!strcmp(argv[1], "password"))
    {
      const char *pass = cupsGetPassword("Password:"******"Password entered: %s\n", pass);
      else
	puts("No password entered.");
    }
    else if (!strcmp(argv[1], "ppd") && argc == 3)
    {
     /*
      * ./testcups ppd printer
      */

      http_status_t	http_status;	/* Status */
      char		buffer[1024];	/* PPD filename */
      time_t		modtime = 0;	/* Last modified */

      if ((http_status = cupsGetPPD3(CUPS_HTTP_DEFAULT, argv[2], &modtime,
                                     buffer, sizeof(buffer))) != HTTP_STATUS_OK)
        printf("Unable to get PPD: %d (%s)\n", (int)http_status,
               cupsLastErrorString());
      else
        puts(buffer);
    }
    else if (!strcmp(argv[1], "print") && argc == 5)
    {
     /*
      * ./testcups print printer file interval
      */

      int		interval,	/* Interval between writes */
			job_id;		/* Job ID */
      cups_file_t	*fp;		/* Print file */
      char		buffer[16384];	/* Read/write buffer */
      ssize_t		bytes;		/* Bytes read/written */

      if ((fp = cupsFileOpen(argv[3], "r")) == NULL)
      {
	printf("Unable to open \"%s\": %s\n", argv[2], strerror(errno));
	return (1);
      }

      if ((job_id = cupsCreateJob(CUPS_HTTP_DEFAULT, argv[2], "testcups", 0,
				  NULL)) <= 0)
      {
	printf("Unable to create print job on %s: %s\n", argv[1],
	       cupsLastErrorString());
	return (1);
      }

      interval = atoi(argv[4]);

      if (cupsStartDocument(CUPS_HTTP_DEFAULT, argv[1], job_id, argv[2],
			    CUPS_FORMAT_AUTO, 1) != HTTP_STATUS_CONTINUE)
      {
	puts("Unable to start document!");
	return (1);
      }

      while ((bytes = cupsFileRead(fp, buffer, sizeof(buffer))) > 0)
      {
	printf("Writing %d bytes...\n", (int)bytes);

	if (cupsWriteRequestData(CUPS_HTTP_DEFAULT, buffer,
				 bytes) != HTTP_STATUS_CONTINUE)
	{
	  puts("Unable to write bytes!");
	  return (1);
	}

        if (interval > 0)
	  sleep(interval);
      }

      cupsFileClose(fp);

      if (cupsFinishDocument(CUPS_HTTP_DEFAULT,
                             argv[1]) > IPP_STATUS_OK_IGNORED_OR_SUBSTITUTED)
      {
	puts("Unable to finish document!");
	return (1);
      }
    }
    else
    {
      puts("Usage:");
      puts("");
      puts("Run basic unit tests:");
      puts("");
      puts("    ./testcups");
      puts("");
      puts("Enumerate printers (for N seconds, -1 for indefinitely):");
      puts("");
      puts("    ./testcups enum [seconds]");
      puts("");
      puts("Ask for a password:"******"");
      puts("    ./testcups password");
      puts("");
      puts("Get the PPD file:");
      puts("");
      puts("    ./testcups ppd printer");
      puts("");
      puts("Print a file (interval controls delay between buffers in seconds):");
      puts("");
      puts("    ./testcups print printer file interval");
      return (1);
    }

    return (0);
  }

 /*
  * cupsGetDests()
  */

  fputs("cupsGetDests: ", stdout);
  fflush(stdout);

  num_dests = cupsGetDests(&dests);

  if (num_dests == 0)
  {
    puts("FAIL");
    return (1);
  }
  else
  {
    printf("PASS (%d dests)\n", num_dests);

    for (i = num_dests, dest = dests; i > 0; i --, dest ++)
    {
      printf("    %s", dest->name);

      if (dest->instance)
        printf("    /%s", dest->instance);

      if (dest->is_default)
        puts(" ***DEFAULT***");
      else
        putchar('\n');
    }
  }

 /*
  * cupsGetDest(NULL)
  */

  fputs("cupsGetDest(NULL): ", stdout);
  fflush(stdout);

  if ((dest = cupsGetDest(NULL, NULL, num_dests, dests)) == NULL)
  {
    for (i = num_dests, dest = dests; i > 0; i --, dest ++)
      if (dest->is_default)
        break;

    if (i)
    {
      status = 1;
      puts("FAIL");
    }
    else
      puts("PASS (no default)");

    dest = NULL;
  }
  else
    printf("PASS (%s)\n", dest->name);

 /*
  * cupsGetNamedDest(NULL, NULL, NULL)
  */

  fputs("cupsGetNamedDest(NULL, NULL, NULL): ", stdout);
  fflush(stdout);

  if ((named_dest = cupsGetNamedDest(NULL, NULL, NULL)) == NULL ||
      !dests_equal(dest, named_dest))
  {
    if (!dest)
      puts("PASS (no default)");
    else if (named_dest)
    {
      puts("FAIL (different values)");
      show_diffs(dest, named_dest);
      status = 1;
    }
    else
    {
      puts("FAIL (no default)");
      status = 1;
    }
  }
  else
    printf("PASS (%s)\n", named_dest->name);

  if (named_dest)
    cupsFreeDests(1, named_dest);

 /*
  * cupsGetDest(printer)
  */

  printf("cupsGetDest(\"%s\"): ", dests[num_dests / 2].name);
  fflush(stdout);

  if ((dest = cupsGetDest(dests[num_dests / 2].name, NULL, num_dests,
                          dests)) == NULL)
  {
    puts("FAIL");
    return (1);
  }
  else
    puts("PASS");

 /*
  * cupsGetNamedDest(NULL, printer, instance)
  */

  printf("cupsGetNamedDest(NULL, \"%s\", \"%s\"): ", dest->name,
         dest->instance ? dest->instance : "(null)");
  fflush(stdout);

  if ((named_dest = cupsGetNamedDest(NULL, dest->name,
                                     dest->instance)) == NULL ||
      !dests_equal(dest, named_dest))
  {
    if (named_dest)
    {
      puts("FAIL (different values)");
      show_diffs(dest, named_dest);
    }
    else
      puts("FAIL (no destination)");


    status = 1;
  }
  else
    puts("PASS");

  if (named_dest)
    cupsFreeDests(1, named_dest);

 /*
  * cupsPrintFile()
  */

  fputs("cupsPrintFile: ", stdout);
  fflush(stdout);

  if (cupsPrintFile(dest->name, "../data/testprint", "Test Page",
                    dest->num_options, dest->options) <= 0)
  {
    printf("FAIL (%s)\n", cupsLastErrorString());
    return (1);
  }
  else
    puts("PASS");

 /*
  * cupsGetPPD(printer)
  */

  fputs("cupsGetPPD(): ", stdout);
  fflush(stdout);

  if ((ppdfile = cupsGetPPD(dest->name)) == NULL)
  {
    puts("FAIL");
  }
  else
  {
    puts("PASS");

   /*
    * ppdOpenFile()
    */

    fputs("ppdOpenFile(): ", stdout);
    fflush(stdout);

    if ((ppd = ppdOpenFile(ppdfile)) == NULL)
    {
      puts("FAIL");
      return (1);
    }
    else
      puts("PASS");

    ppdClose(ppd);
    unlink(ppdfile);
  }

 /*
  * cupsGetJobs()
  */

  fputs("cupsGetJobs: ", stdout);
  fflush(stdout);

  num_jobs = cupsGetJobs(&jobs, NULL, 0, -1);

  if (num_jobs == 0)
  {
    puts("FAIL");
    return (1);
  }
  else
    puts("PASS");

  cupsFreeJobs(num_jobs, jobs);
  cupsFreeDests(num_dests, dests);

  return (status);
}
Exemple #18
0
dt_printer_info_t *dt_get_printer_info(const char *printer_name)
{
  cups_dest_t *dests;
  int num_dests = cupsGetDests(&dests);
  cups_dest_t *dest = cupsGetDest(printer_name, NULL, num_dests, dests);
  dt_printer_info_t *result = NULL;

  if (dest)
  {
    const char *PPDFile = cupsGetPPD (printer_name);
    result = (dt_printer_info_t *)malloc(sizeof(dt_printer_info_t));
    g_strlcpy(result->name, dest->name, MAX_NAME);
    ppd_file_t *ppd = ppdOpenFile(PPDFile);

    if (ppd)
    {
      ppdMarkDefaults(ppd);
      cupsMarkOptions(ppd, dest->num_options, dest->options);

      // hardware margins

      ppd_attr_t *attr = ppdFindAttr(ppd, "HWMargins", NULL);

      if (attr)
      {
        sscanf(attr->value, "%lf %lf %lf %lf",
               &result->hw_margin_left, &result->hw_margin_bottom,
               &result->hw_margin_right, &result->hw_margin_top);

        result->hw_margin_left   = dt_pdf_point_to_mm (result->hw_margin_left);
        result->hw_margin_bottom = dt_pdf_point_to_mm (result->hw_margin_bottom);
        result->hw_margin_right  = dt_pdf_point_to_mm (result->hw_margin_right);
        result->hw_margin_top    = dt_pdf_point_to_mm (result->hw_margin_top);
      }

      // default resolution

      attr = ppdFindAttr(ppd, "DefaultResolution", NULL);

      if (attr)
      {
        char *x = strstr(attr->value, "x");

        if (x)
          sscanf (x+1, "%ddpi", &result->resolution);
        else
          sscanf (attr->value, "%ddpi", &result->resolution);
      }
      else
        result->resolution = 300;

      while(result->resolution>360)
        result->resolution /= 2.0;

      ppdClose(ppd);
      unlink(PPDFile);
    }
  }

  cupsFreeDests(num_dests, dests);
  return result;
}
Exemple #19
0
static void
colord_register_printer(
    cupsd_printer_t *p)			/* I - printer */
{
  char		ppdfile[1024],		/* PPD filename */
		iccfile[1024];		/* ICC filename */
  ppd_file_t	*ppd;			/* PPD file */
  cups_array_t	*profiles;		/* Profile paths array */
  ppd_attr_t	*attr;			/* Profile attributes */
  const char	*device_colorspace;	/* Device colorspace */
  char		*format[3];		/* Qualifier format tuple */


 /*
  * Ensure we have a D-Bus connection...
  */

  if (!colord_con)
    return;

 /*
  * Try opening the PPD file for this printer...
  */

  snprintf(ppdfile, sizeof(ppdfile), "%s/ppd/%s.ppd", ServerRoot, p->name);
  if ((ppd = _ppdOpenFile(ppdfile, _PPD_LOCALIZATION_ICC_PROFILES)) == NULL)
    return;

 /*
  * Find out the qualifier format
  */

  colord_get_qualifier_format(ppd, format);

 /*
  * See if we have any embedded profiles...
  */

  profiles = cupsArrayNew3(NULL, NULL, NULL, 0, (cups_acopy_func_t)strdup,
			   (cups_afree_func_t)free);
  for (attr = ppdFindAttr(ppd, "cupsICCProfile", NULL);
       attr;
       attr = ppdFindNextAttr(ppd, "cupsICCProfile", NULL))
    if (attr->spec[0] && attr->value && attr->value[0])
    {
      if (attr->value[0] != '/')
        snprintf(iccfile, sizeof(iccfile), "%s/profiles/%s", DataDir,
                 attr->value);
      else
        strlcpy(iccfile, attr->value, sizeof(iccfile));

      if (_cupsFileCheck(iccfile, _CUPS_FILE_CHECK_FILE, !RunUser,
			 cupsdLogFCMessage, p))
	continue;

      colord_create_profile(profiles, p->name, attr->spec, COLORD_SPACE_UNKNOWN,
			    format, iccfile, COLORD_SCOPE_TEMP);
    }

 /*
  * Add the grayscale profile first.  We always have a grayscale profile.
  */

  colord_create_profile(profiles, p->name, "Gray..", COLORD_SPACE_GRAY,
                        format, NULL, COLORD_SCOPE_TEMP);

 /*
  * Then add the RGB/CMYK/DeviceN color profile...
  */

  device_colorspace = "unknown";
  switch (ppd->colorspace)
  {
    case PPD_CS_RGB :
    case PPD_CS_CMY :
        device_colorspace = COLORD_SPACE_RGB;
        colord_create_profile(profiles, p->name, "RGB..", COLORD_SPACE_RGB,
			      format, NULL, COLORD_SCOPE_TEMP);
        break;

    case PPD_CS_RGBK :
    case PPD_CS_CMYK :
        device_colorspace = COLORD_SPACE_CMYK;
        colord_create_profile(profiles, p->name, "CMYK..", COLORD_SPACE_CMYK,
                              format, NULL, COLORD_SCOPE_TEMP);
        break;

    case PPD_CS_GRAY :
        device_colorspace = COLORD_SPACE_GRAY;
        break;

    case PPD_CS_N :
        colord_create_profile(profiles, p->name, "DeviceN..",
                              COLORD_SPACE_UNKNOWN, format, NULL,
			      COLORD_SCOPE_TEMP);
        break;
  }

 /*
  * Register the device with colord.
  */

  cupsdLogMessage(CUPSD_LOG_INFO, "Registering ICC color profiles for \"%s\".",
                  p->name);
  colord_create_device(p, ppd, profiles, device_colorspace, format,
		       COLORD_RELATION_SOFT, COLORD_SCOPE_TEMP);

 /*
  * Free any memory we used...
  */

  cupsArrayDelete(profiles);

  free(format[0]);
  free(format[1]);
  free(format[2]);

  ppdClose(ppd);
}
Exemple #20
0
void GetOptionStringFromCups (char *pPrinter, int fd)
{
    int            i, j;
    int            iJS;
    int            num_dests;
    cups_dest_t    *dests;
    cups_dest_t    *dest;
    char           *opt;
    char           *ppdFileName;
    ppd_file_t     *ppdFile;
    char           szJSOptionString[1024];

fprintf (stderr, "DEBUG: In GetOption.... printer = %s, fd = %d\n", pPrinter, fd);
    ppdFileName = (char *) cupsGetPPD (pPrinter);
    if (!ppdFileName)
    {
fprintf (stderr, "DEBUG: did not get ppdfilename\n");
        return;
    }
fprintf (stderr, "DEBUG: ppdFileName = %s\n", ppdFileName);
    ppdFile = ppdOpenFile (ppdFileName);
fprintf (stderr, "DEBUG: ppdFileName = %s\n", ppdFileName);
    if (ppdFile == NULL)
    {
fprintf (stderr, "DEBUG: unable to open ppdfile, %s\n", ppdFileName);
        return;
    }
    num_dests = cupsGetDests (&dests);
    if (num_dests == 0)
    {
fprintf (stderr, "DEBUG: num_dests is zero\n");
        ppdClose (ppdFile);
        return;
    }
    dest = cupsGetDest (pPrinter, NULL, num_dests, dests);
    if (dest == NULL)
    {
fprintf (stderr, "DEBUG: did not get dest for printer %s\n", pPrinter);
        ppdClose (ppdFile);
        return;
    }
    ppdMarkDefaults (ppdFile);
    cupsMarkOptions (ppdFile, dest->num_options, dest->options);
    iJS = sizeof (szJSStrings) / sizeof (szJSStrings[0]);
    if ((opt = (char *) cupsGetOption ("HOLD", dest->num_options, dest->options)) == NULL)
    {
fprintf (stderr, "DEBUG: did not see HOLD option\nOptions in the list are:\n");
for (i = 0; i < dest->num_options; i++)
{
    fprintf (stderr, "DEBUG: Option = %s : value = %s\n", dest->options[i].name, dest->options[i].value);
}

        ppdClose (ppdFile);
        return;
    }
    memset (szJSOptionString, 0, sizeof (szJSOptionString));
    j = sprintf (szJSOptionString, "HOLD=%s", opt);
    for (i = 0; i < iJS; i++)
    {
        if ((opt = (char *) cupsGetOption (szJSStrings[i], dest->num_options, dest->options)))
        {
fprintf (stderr, "DEBUG: cupsGetOption returned %s = %s\n", szJSStrings[i], opt);
            j += sprintf (szJSOptionString + j, " %s=%s", szJSStrings[i], opt);
        }
    }
    ppdClose (ppdFile);
    cupsFreeDests (num_dests, dests);
fprintf (stderr, "DEBUG: Calling SendJobHoldCommands with %s\n", szJSOptionString);
    SendJobHoldCommands (szJSOptionString, fd);
}
Exemple #21
0
int gapp_init_print(RunTime *rt)
{
#ifdef HAVE_CUPS
    int i;
    cups_dest_t *dests;
    
    rt->print_dest = 0;
    
    rt->num_print_dests = cupsGetDests(&dests);
    if (!rt->num_print_dests) {
        /* no CUPS printers defined or CUPS not running */
        rt->use_cups = FALSE;
    } else {
        rt->print_dests = xcalloc(rt->num_print_dests, sizeof(PrintDest));
        if (rt->print_dests == NULL) {
            return RETURN_FAILURE;
        }
    }
    
    for (i = 0; i < rt->num_print_dests; i++) {
        cups_dest_t *dest = &dests[i];
        PrintDest *pd = &rt->print_dests[i];

        char *printer;
        int           j;
        const char    *filename;        /* PPD filename */
        ppd_file_t    *ppd;             /* PPD data */
        ppd_group_t   *group;           /* Current group */
        
        printer = copy_string(NULL, dest->name);
        if (dest->instance) {
            printer = concat_strings(printer, "/");
            printer = concat_strings(printer, dest->instance);
        }
        
        pd->name    = copy_string(NULL, dest->name);
        pd->inst    = copy_string(NULL, dest->instance);
        pd->printer = printer;
        
        if (dest->is_default) {
            rt->print_dest = i;
        }
        
        if ((filename = cupsGetPPD(dest->name)) == NULL) {
            continue;
        }

        if ((ppd = ppdOpenFile(filename)) == NULL) {
            remove(filename);
            continue;
        }

        ppdMarkDefaults(ppd);
        cupsMarkOptions(ppd, dest->num_options, dest->options);

        for (j = 0, group = ppd->groups; j < ppd->num_groups; j++, group++) {
            parse_group(pd, group);
        }

        ppdClose(ppd);
        remove(filename);
    }
    cupsFreeDests(rt->num_print_dests, dests);
#else
    rt->print_dest = 0;
    rt->num_print_dests = 0;
#endif

    return RETURN_SUCCESS;
}
Exemple #22
0
int					/* O - Exit status */
main(int  argc,				/* I - Number of command-line arguments */
     char *argv[])			/* I - Command-line arguments */
{
  int			i;		/* Looping var */
  int			errors = 0;	/* Number of errors */
  cups_lang_t		*language;	/* Message catalog */
  cups_lang_t		*language2;	/* Message catalog */
  struct lconv		*loc;		/* Locale data */
  char			buffer[1024];	/* String buffer */
  double		number;		/* Number */
  static const char * const tests[] =	/* Test strings */
  {
    "1",
    "-1",
    "3",
    "5.125"
  };


  if (argc == 1)
  {
    language  = cupsLangDefault();
    language2 = cupsLangDefault();
  }
  else
  {
    language  = cupsLangGet(argv[1]);
    language2 = cupsLangGet(argv[1]);

    setenv("LANG", argv[1], 1);
    setenv("SOFTWARE", "CUPS/" CUPS_SVERSION, 1);
  }

  _cupsSetLocale(argv);

  if (language != language2)
  {
    errors ++;

    puts("**** ERROR: Language cache did not work! ****");
    puts("First result from cupsLangGet:");
  }

  printf("Language = \"%s\"\n", language->language);
  printf("Encoding = \"%s\"\n", _cupsEncodingName(language->encoding));
  printf("No       = \"%s\"\n", _cupsLangString(language, "No"));
  printf("Yes      = \"%s\"\n", _cupsLangString(language, "Yes"));

  if (language != language2)
  {
    puts("Second result from cupsLangGet:");

    printf("Language = \"%s\"\n", language2->language);
    printf("Encoding = \"%s\"\n", _cupsEncodingName(language2->encoding));
    printf("No       = \"%s\"\n", _cupsLangString(language2, "No"));
    printf("Yes      = \"%s\"\n", _cupsLangString(language2, "Yes"));
  }

  loc = localeconv();

  for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i ++)
  {
    number = _cupsStrScand(tests[i], NULL, loc);

    printf("_cupsStrScand(\"%s\") number=%f\n", tests[i], number);

    _cupsStrFormatd(buffer, buffer + sizeof(buffer), number, loc);

    printf("_cupsStrFormatd(%f) buffer=\"%s\"\n", number, buffer);

    if (strcmp(buffer, tests[i]))
    {
      errors ++;
      puts("**** ERROR: Bad formatted number! ****");
    }
  }

  if (argc == 3)
  {
    ppd_file_t		*ppd;		/* PPD file */
    ppd_option_t	*option;	/* PageSize option */
    ppd_choice_t	*choice;	/* PageSize/Letter choice */

    if ((ppd = ppdOpenFile(argv[2])) == NULL)
    {
      printf("Unable to open PPD file \"%s\".\n", argv[2]);
      errors ++;
    }
    else
    {
      ppdLocalize(ppd);

      if ((option = ppdFindOption(ppd, "PageSize")) == NULL)
      {
        puts("No PageSize option.");
        errors ++;
      }
      else
      {
        printf("PageSize: %s\n", option->text);

        if ((choice = ppdFindChoice(option, "Letter")) == NULL)
        {
	  puts("No Letter PageSize choice.");
	  errors ++;
        }
        else
        {
	  printf("Letter: %s\n", choice->text);
        }
      }

      ppdClose(ppd);
    }
  }

  return (errors > 0);
}
Exemple #23
0
static void
apple_register_profiles(
    cupsd_printer_t *p)			/* I - Printer */
{
  int			i;		/* Looping var */
  char			ppdfile[1024],	/* PPD filename */
			iccfile[1024],	/* ICC filename */
			selector[PPD_MAX_NAME];
					/* Profile selection string */
  ppd_file_t		*ppd;		/* PPD file */
  ppd_attr_t		*attr,		/* Profile attributes */
			*profileid_attr,/* cupsProfileID attribute */
			*q1_attr,	/* ColorModel (or other) qualifier */
			*q2_attr,	/* MediaType (or other) qualifier */
			*q3_attr;	/* Resolution (or other) qualifier */
  char			q_keyword[PPD_MAX_NAME];
					/* Qualifier keyword */
  const char		*q1_choice,	/* ColorModel (or other) choice */
			*q2_choice,	/* MediaType (or other) choice */
			*q3_choice;	/* Resolution (or other) choice */
  ppd_option_t		*cm_option;	/* Color model option */
  ppd_choice_t		*cm_choice;	/* Color model choice */
  int			num_profiles;	/* Number of profiles */
  OSStatus		error = 0;	/* Last error */
  unsigned		device_id,	/* Printer device ID */
			profile_id = 0,	/* Profile ID */
			default_profile_id = 0;
					/* Default profile ID */
  CFMutableDictionaryRef device_name;	/* Printer device name dictionary */
  CFStringRef		printer_name;	/* Printer name string */
  cups_array_t		*languages;	/* Languages array */
  CFMutableDictionaryRef profiles,	/* Dictionary of profiles */
			profile;	/* Current profile info dictionary */
  CFStringRef		dict_key;	/* Key in factory profile dictionary */


 /*
  * Make sure ColorSync is available...
  */

  if (&ColorSyncRegisterDevice == NULL)
    return;

 /*
  * Try opening the PPD file for this printer...
  */

  snprintf(ppdfile, sizeof(ppdfile), "%s/ppd/%s.ppd", ServerRoot, p->name);
  if ((ppd = _ppdOpenFile(ppdfile, _PPD_LOCALIZATION_ICC_PROFILES)) == NULL)
    return;

 /*
  * See if we have any profiles...
  */

  for (num_profiles = 0, attr = ppdFindAttr(ppd, "cupsICCProfile", NULL);
       attr;
       attr = ppdFindNextAttr(ppd, "cupsICCProfile", NULL))
    if (attr->spec[0] && attr->value && attr->value[0])
    {
      if (attr->value[0] != '/')
	snprintf(iccfile, sizeof(iccfile), "%s/profiles/%s", DataDir,
		 attr->value);
      else
	strlcpy(iccfile, attr->value, sizeof(iccfile));

      if (access(iccfile, 0))
      {
        cupsdLogMessage(CUPSD_LOG_ERROR,
                        "%s: ICC Profile \"%s\" does not exist.", p->name,
                        iccfile);
        cupsdSetPrinterReasons(p, "+cups-missing-filter-warning");
	continue;
      }

      num_profiles ++;
    }

 /*
  * Create a dictionary for the factory profiles...
  */

  profiles = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
				       &kCFTypeDictionaryKeyCallBacks,
				       &kCFTypeDictionaryValueCallBacks);
  if (!profiles)
  {
    cupsdLogMessage(CUPSD_LOG_ERROR,
		    "Unable to allocate memory for factory profiles.");
    ppdClose(ppd);
    return;
  }

 /*
  * If we have profiles, add them...
  */

  if (num_profiles > 0)
  {
   /*
    * For CUPS PPDs, figure out the default profile selector values...
    */

    if ((attr = ppdFindAttr(ppd, "cupsICCQualifier1", NULL)) != NULL &&
	attr->value && attr->value[0])
    {
      snprintf(q_keyword, sizeof(q_keyword), "Default%s", attr->value);
      q1_attr = ppdFindAttr(ppd, q_keyword, NULL);
    }
    else if ((q1_attr = ppdFindAttr(ppd, "DefaultColorModel", NULL)) == NULL)
      q1_attr = ppdFindAttr(ppd, "DefaultColorSpace", NULL);

    if (q1_attr && q1_attr->value && q1_attr->value[0])
      q1_choice = q1_attr->value;
    else
      q1_choice = "";

    if ((attr = ppdFindAttr(ppd, "cupsICCQualifier2", NULL)) != NULL &&
	attr->value && attr->value[0])
    {
      snprintf(q_keyword, sizeof(q_keyword), "Default%s", attr->value);
      q2_attr = ppdFindAttr(ppd, q_keyword, NULL);
    }
    else
      q2_attr = ppdFindAttr(ppd, "DefaultMediaType", NULL);

    if (q2_attr && q2_attr->value && q2_attr->value[0])
      q2_choice = q2_attr->value;
    else
      q2_choice = NULL;

    if ((attr = ppdFindAttr(ppd, "cupsICCQualifier3", NULL)) != NULL &&
	attr->value && attr->value[0])
    {
      snprintf(q_keyword, sizeof(q_keyword), "Default%s", attr->value);
      q3_attr = ppdFindAttr(ppd, q_keyword, NULL);
    }
    else
      q3_attr = ppdFindAttr(ppd, "DefaultResolution", NULL);

    if (q3_attr && q3_attr->value && q3_attr->value[0])
      q3_choice = q3_attr->value;
    else
      q3_choice = NULL;

   /*
    * Loop through the profiles listed in the PPD...
    */

    languages = _ppdGetLanguages(ppd);

    for (attr = ppdFindAttr(ppd, "cupsICCProfile", NULL);
	 attr;
	 attr = ppdFindNextAttr(ppd, "cupsICCProfile", NULL))
      if (attr->spec[0] && attr->value && attr->value[0])
      {
       /*
        * Add this profile...
	*/

        if (attr->value[0] != '/')
	  snprintf(iccfile, sizeof(iccfile), "%s/profiles/%s", DataDir,
	           attr->value);
        else
	  strlcpy(iccfile, attr->value, sizeof(iccfile));

        if (_cupsFileCheck(iccfile, _CUPS_FILE_CHECK_FILE, !RunUser,
	                   cupsdLogFCMessage, p))
	  iccfile[0] = '\0';

	cupsArraySave(ppd->sorted_attrs);

	if ((profileid_attr = ppdFindAttr(ppd, "cupsProfileID",
					  attr->spec)) != NULL &&
	    profileid_attr->value && isdigit(profileid_attr->value[0] & 255))
	  profile_id = (unsigned)strtoul(profileid_attr->value, NULL, 10);
	else
	  profile_id = _ppdHashName(attr->spec);

	cupsArrayRestore(ppd->sorted_attrs);

	profile = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
					    &kCFTypeDictionaryKeyCallBacks,
					    &kCFTypeDictionaryValueCallBacks);
	if (!profile)
	{
	  cupsdLogMessage(CUPSD_LOG_ERROR,
	                  "Unable to allocate memory for color profile.");
	  CFRelease(profiles);
	  ppdClose(ppd);
	  return;
	}

	apple_init_profile(ppd, languages, profile, profile_id, attr->spec,
	                   attr->text[0] ? attr->text : attr->spec, iccfile);

	dict_key = CFStringCreateWithFormat(kCFAllocatorDefault, NULL,
	                                    CFSTR("%u"), profile_id);
	if (dict_key)
	{
	  CFDictionarySetValue(profiles, dict_key, profile);
	  CFRelease(dict_key);
	}

	CFRelease(profile);

       /*
        * See if this is the default profile...
	*/

        if (!default_profile_id && q1_choice && q2_choice && q3_choice)
	{
	  snprintf(selector, sizeof(selector), "%s.%s.%s", q1_choice, q2_choice,
	           q3_choice);
	  if (!strcmp(selector, attr->spec))
	    default_profile_id = profile_id;
	}

        if (!default_profile_id && q1_choice && q2_choice)
	{
	  snprintf(selector, sizeof(selector), "%s.%s.", q1_choice, q2_choice);
	  if (!strcmp(selector, attr->spec))
	    default_profile_id = profile_id;
	}

        if (!default_profile_id && q1_choice && q3_choice)
	{
	  snprintf(selector, sizeof(selector), "%s..%s", q1_choice, q3_choice);
	  if (!strcmp(selector, attr->spec))
	    default_profile_id = profile_id;
	}

        if (!default_profile_id && q1_choice)
	{
	  snprintf(selector, sizeof(selector), "%s..", q1_choice);
	  if (!strcmp(selector, attr->spec))
	    default_profile_id = profile_id;
	}

        if (!default_profile_id && q2_choice && q3_choice)
	{
	  snprintf(selector, sizeof(selector), ".%s.%s", q2_choice, q3_choice);
	  if (!strcmp(selector, attr->spec))
	    default_profile_id = profile_id;
	}

        if (!default_profile_id && q2_choice)
	{
	  snprintf(selector, sizeof(selector), ".%s.", q2_choice);
	  if (!strcmp(selector, attr->spec))
	    default_profile_id = profile_id;
	}

        if (!default_profile_id && q3_choice)
	{
	  snprintf(selector, sizeof(selector), "..%s", q3_choice);
	  if (!strcmp(selector, attr->spec))
	    default_profile_id = profile_id;
	}
      }

    _ppdFreeLanguages(languages);
  }
  else if ((cm_option = ppdFindOption(ppd, "ColorModel")) != NULL)
  {
   /*
    * Extract profiles from ColorModel option...
    */

    const char *profile_name;		/* Name of generic profile */


    num_profiles = cm_option->num_choices;

    for (i = cm_option->num_choices, cm_choice = cm_option->choices;
         i > 0;
	 i --, cm_choice ++)
    {
      if (!strcmp(cm_choice->choice, "Gray") ||
          !strcmp(cm_choice->choice, "Black"))
        profile_name = "Gray";
      else if (!strcmp(cm_choice->choice, "RGB") ||
               !strcmp(cm_choice->choice, "CMY"))
        profile_name = "RGB";
      else if (!strcmp(cm_choice->choice, "CMYK") ||
               !strcmp(cm_choice->choice, "KCMY"))
        profile_name = "CMYK";
      else
        profile_name = "DeviceN";

      snprintf(selector, sizeof(selector), "%s..", profile_name);
      profile_id = _ppdHashName(selector);

      profile = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
					  &kCFTypeDictionaryKeyCallBacks,
					  &kCFTypeDictionaryValueCallBacks);
      if (!profile)
      {
	cupsdLogMessage(CUPSD_LOG_ERROR,
			"Unable to allocate memory for color profile.");
	CFRelease(profiles);
	ppdClose(ppd);
	return;
      }

      apple_init_profile(ppd, NULL, profile, profile_id, cm_choice->choice,
                         cm_choice->text, NULL);

      dict_key = CFStringCreateWithFormat(kCFAllocatorDefault, NULL,
                                          CFSTR("%u"), profile_id);
      if (dict_key)
      {
	CFDictionarySetValue(profiles, dict_key, profile);
	CFRelease(dict_key);
      }

      CFRelease(profile);

      if (cm_choice->marked)
        default_profile_id = profile_id;
    }
  }
  else
  {
   /*
    * Use the default colorspace...
    */

    attr = ppdFindAttr(ppd, "DefaultColorSpace", NULL);

    num_profiles = (attr && ppd->colorspace == PPD_CS_GRAY) ? 1 : 2;

   /*
    * Add the grayscale profile first.  We always have a grayscale profile.
    */

    profile = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
				        &kCFTypeDictionaryKeyCallBacks,
				        &kCFTypeDictionaryValueCallBacks);

    if (!profile)
    {
      cupsdLogMessage(CUPSD_LOG_ERROR,
                      "Unable to allocate memory for color profile.");
      CFRelease(profiles);
      ppdClose(ppd);
      return;
    }

    profile_id = _ppdHashName("Gray..");
    apple_init_profile(ppd, NULL, profile, profile_id, "Gray", "Gray", NULL);

    dict_key = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"),
                                        profile_id);
    if (dict_key)
    {
      CFDictionarySetValue(profiles, dict_key, profile);
      CFRelease(dict_key);
    }

    CFRelease(profile);

   /*
    * Then add the RGB/CMYK/DeviceN color profile...
    */

    profile = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
				        &kCFTypeDictionaryKeyCallBacks,
				        &kCFTypeDictionaryValueCallBacks);

    if (!profile)
    {
      cupsdLogMessage(CUPSD_LOG_ERROR,
                      "Unable to allocate memory for color profile.");
      CFRelease(profiles);
      ppdClose(ppd);
      return;
    }

    switch (ppd->colorspace)
    {
      default :
      case PPD_CS_RGB :
      case PPD_CS_CMY :
          profile_id = _ppdHashName("RGB..");
          apple_init_profile(ppd, NULL, profile, profile_id, "RGB", "RGB",
	                     NULL);
          break;

      case PPD_CS_RGBK :
      case PPD_CS_CMYK :
          profile_id = _ppdHashName("CMYK..");
          apple_init_profile(ppd, NULL, profile, profile_id, "CMYK", "CMYK",
	                     NULL);
          break;

      case PPD_CS_GRAY :
          if (attr)
            break;

      case PPD_CS_N :
          profile_id = _ppdHashName("DeviceN..");
          apple_init_profile(ppd, NULL, profile, profile_id, "DeviceN",
	                     "DeviceN", NULL);
          break;
    }

    if (CFDictionaryGetCount(profile) > 0)
    {
      dict_key = CFStringCreateWithFormat(kCFAllocatorDefault, NULL,
                                          CFSTR("%u"), profile_id);
      if (dict_key)
      {
        CFDictionarySetValue(profiles, dict_key, profile);
        CFRelease(dict_key);
      }
    }

    CFRelease(profile);
  }

  if (num_profiles > 0)
  {
   /*
    * Make sure we have a default profile ID...
    */

    if (!default_profile_id)
      default_profile_id = profile_id;	/* Last profile */

    dict_key = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"),
                                        default_profile_id);
    if (dict_key)
    {
      CFDictionarySetValue(profiles, kColorSyncDeviceDefaultProfileID,
                           dict_key);
      CFRelease(dict_key);
    }

   /*
    * Get the device ID hash and pathelogical name dictionary.
    */

    cupsdLogMessage(CUPSD_LOG_INFO, "Registering ICC color profiles for \"%s\"",
		    p->name);

    device_id    = _ppdHashName(p->name);
    device_name  = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
					     &kCFTypeDictionaryKeyCallBacks,
					     &kCFTypeDictionaryValueCallBacks);
    printer_name = CFStringCreateWithCString(kCFAllocatorDefault,
                                             p->name, kCFStringEncodingUTF8);

    if (device_name && printer_name)
    {
     /*
      * Register the device with ColorSync...
      */

      CFTypeRef		deviceDictKeys[] =
      {					/* Device keys */
        kColorSyncDeviceDescriptions,
	kColorSyncFactoryProfiles,
	kColorSyncDeviceUserScope,
	kColorSyncDeviceHostScope
      };
      CFTypeRef 	deviceDictVals[] =
      {					/* Device values */
        device_name,
	profiles,
	kCFPreferencesAnyUser,
	kCFPreferencesCurrentHost
      };
      CFDictionaryRef	deviceDict;	/* Device dictionary */
      CFUUIDRef		deviceUUID;	/* Device UUID */

      CFDictionarySetValue(device_name, CFSTR("en_US"), printer_name);

      deviceDict = CFDictionaryCreate(kCFAllocatorDefault,
				      (const void **)deviceDictKeys,
				      (const void **)deviceDictVals,
				      sizeof(deviceDictKeys) /
				          sizeof(deviceDictKeys[0]),
				      &kCFTypeDictionaryKeyCallBacks,
				      &kCFTypeDictionaryValueCallBacks);
      deviceUUID = ColorSyncCreateUUIDFromUInt32(device_id);

      if (!deviceDict || !deviceUUID ||
	  !ColorSyncRegisterDevice(kColorSyncPrinterDeviceClass, deviceUUID,
				   deviceDict))
	error = 1001;

      if (deviceUUID)
        CFRelease(deviceUUID);

      if (deviceDict)
        CFRelease(deviceDict);
    }
    else
      error = 1000;

   /*
    * Clean up...
    */

    if (error != noErr)
      cupsdLogMessage(CUPSD_LOG_ERROR,
		      "Unable to register ICC color profiles for \"%s\": %d",
		      p->name, (int)error);

    if (printer_name)
      CFRelease(printer_name);

    if (device_name)
      CFRelease(device_name);
  }

 /*
  * Free any memory we used...
  */

  CFRelease(profiles);

  ppdClose(ppd);
}
Exemple #24
0
static void
backend_init_supplies(
    int         snmp_fd,		/* I - SNMP socket */
    http_addr_t *addr)			/* I - Printer address */
{
  int		i,			/* Looping var */
		type;			/* Current marker type */
  cups_file_t	*cachefile;		/* Cache file */
  const char	*cachedir;		/* CUPS_CACHEDIR value */
  char		addrstr[1024],		/* Address string */
		cachefilename[1024],	/* Cache filename */
		description[CUPS_SNMP_MAX_STRING],
					/* Device description string */
		value[CUPS_MAX_SUPPLIES * (CUPS_SNMP_MAX_STRING * 4 + 3)],
					/* Value string */
		*ptr,			/* Pointer into value string */
		*name_ptr;		/* Pointer into name string */
  cups_snmp_t	packet;			/* SNMP response packet */
  ppd_file_t	*ppd;			/* PPD file for this queue */
  ppd_attr_t	*ppdattr;		/* cupsSNMPSupplies attribute */
  static const char * const types[] =	/* Supply types */
		{
		  "other",
		  "unknown",
		  "toner",
		  "waste-toner",
		  "ink",
		  "ink-cartridge",
		  "ink-ribbon",
		  "waste-ink",
		  "opc",
		  "developer",
		  "fuser-oil",
		  "solid-wax",
		  "ribbon-wax",
		  "waste-wax",
		  "fuser",
		  "corona-wire",
		  "fuser-oil-wick",
		  "cleaner-unit",
		  "fuser-cleaning-pad",
		  "transfer-unit",
		  "toner-cartridge",
		  "fuser-oiler",
		  "water",
		  "waste-water",
		  "glue-water-additive",
		  "waste-paper",
		  "binding-supply",
		  "banding-supply",
		  "stitching-wire",
		  "shrink-wrap",
		  "paper-wrap",
		  "staples",
		  "inserts",
		  "covers"
		};


 /*
  * Reset state information...
  */

  current_addr  = *addr;
  current_state = -1;
  num_supplies  = -1;
  charset       = -1;

  memset(supplies, 0, sizeof(supplies));

 /*
  * See if we should be getting supply levels via SNMP...
  */

  if ((ppd = ppdOpenFile(getenv("PPD"))) == NULL ||
      ((ppdattr = ppdFindAttr(ppd, "cupsSNMPSupplies", NULL)) != NULL &&
       ppdattr->value && _cups_strcasecmp(ppdattr->value, "true")))
  {
    ppdClose(ppd);
    return;
  }

  if ((ppdattr = ppdFindAttr(ppd, "cupsSNMPQuirks", NULL)) != NULL)
  {
    if (!_cups_strcasecmp(ppdattr->value, "capacity"))
      quirks |= CUPS_SNMP_CAPACITY;
  }

  ppdClose(ppd);

 /*
  * Get the device description...
  */

  if (!_cupsSNMPWrite(snmp_fd, addr, CUPS_SNMP_VERSION_1,
		     _cupsSNMPDefaultCommunity(), CUPS_ASN1_GET_REQUEST, 1,
		     hrDeviceDescr))
    return;

  if (!_cupsSNMPRead(snmp_fd, &packet, CUPS_SUPPLY_TIMEOUT) ||
      packet.object_type != CUPS_ASN1_OCTET_STRING)
  {
    strlcpy(description, "Unknown", sizeof(description));
    num_supplies = 0;
  }
  else
    strlcpy(description, (char *)packet.object_value.string.bytes,
            sizeof(description));

  fprintf(stderr, "DEBUG2: hrDeviceDesc=\"%s\"\n", description);

 /*
  * See if we have already queried this device...
  */

  httpAddrString(addr, addrstr, sizeof(addrstr));

  if ((cachedir = getenv("CUPS_CACHEDIR")) == NULL)
    cachedir = CUPS_CACHEDIR;

  snprintf(cachefilename, sizeof(cachefilename), "%s/%s.snmp", cachedir,
           addrstr);

  if ((cachefile = cupsFileOpen(cachefilename, "r")) != NULL)
  {
   /*
    * Yes, read the cache file:
    *
    *     3 num_supplies charset
    *     device description
    *     supply structures...
    */

    if (cupsFileGets(cachefile, value, sizeof(value)))
    {
      if (sscanf(value, "3 %d%d", &num_supplies, &charset) == 2 &&
          num_supplies <= CUPS_MAX_SUPPLIES &&
          cupsFileGets(cachefile, value, sizeof(value)))
      {
        if (!strcmp(description, value))
	  cupsFileRead(cachefile, (char *)supplies,
	               (size_t)num_supplies * sizeof(backend_supplies_t));
        else
	{
	  num_supplies = -1;
	  charset      = -1;
	}
      }
      else
      {
        num_supplies = -1;
	charset      = -1;
      }
    }

    cupsFileClose(cachefile);
  }

 /*
  * If the cache information isn't correct, scan for supplies...
  */

  if (charset < 0)
  {
   /*
    * Get the configured character set...
    */

    int	oid[CUPS_SNMP_MAX_OID];		/* OID for character set */


    if (!_cupsSNMPWrite(snmp_fd, &current_addr, CUPS_SNMP_VERSION_1,
			_cupsSNMPDefaultCommunity(), CUPS_ASN1_GET_REQUEST, 1,
			prtGeneralCurrentLocalization))
      return;

    if (!_cupsSNMPRead(snmp_fd, &packet, CUPS_SUPPLY_TIMEOUT) ||
	packet.object_type != CUPS_ASN1_INTEGER)
    {
      fprintf(stderr,
              "DEBUG: prtGeneralCurrentLocalization type is %x, expected %x!\n",
	      packet.object_type, CUPS_ASN1_INTEGER);
      return;
    }

    fprintf(stderr, "DEBUG2: prtGeneralCurrentLocalization=%d\n",
            packet.object_value.integer);

    _cupsSNMPCopyOID(oid, prtLocalizationCharacterSet, CUPS_SNMP_MAX_OID);
    oid[prtLocalizationCharacterSetOffset - 2] = packet.object_value.integer;


    if (!_cupsSNMPWrite(snmp_fd, &current_addr, CUPS_SNMP_VERSION_1,
			_cupsSNMPDefaultCommunity(), CUPS_ASN1_GET_REQUEST, 1,
			oid))
      return;

    if (!_cupsSNMPRead(snmp_fd, &packet, CUPS_SUPPLY_TIMEOUT) ||
	packet.object_type != CUPS_ASN1_INTEGER)
    {
      fprintf(stderr,
              "DEBUG: prtLocalizationCharacterSet type is %x, expected %x!\n",
	      packet.object_type, CUPS_ASN1_INTEGER);
      return;
    }

    fprintf(stderr, "DEBUG2: prtLocalizationCharacterSet=%d\n",
	    packet.object_value.integer);
    charset = packet.object_value.integer;
  }

  if (num_supplies < 0)
  {
   /*
    * Walk the printer configuration information...
    */

    _cupsSNMPWalk(snmp_fd, &current_addr, CUPS_SNMP_VERSION_1,
		  _cupsSNMPDefaultCommunity(), prtMarkerSuppliesEntry,
		  CUPS_SUPPLY_TIMEOUT, backend_walk_cb, NULL);
  }

 /*
  * Save the cached information...
  */

  if (num_supplies < 0)
    num_supplies = 0;

  if ((cachefile = cupsFileOpen(cachefilename, "w")) != NULL)
  {
    cupsFilePrintf(cachefile, "3 %d %d\n", num_supplies, charset);
    cupsFilePrintf(cachefile, "%s\n", description);

    if (num_supplies > 0)
      cupsFileWrite(cachefile, (char *)supplies,
                    (size_t)num_supplies * sizeof(backend_supplies_t));

    cupsFileClose(cachefile);
  }

  if (num_supplies <= 0)
    return;

 /*
  * Get the colors...
  */

  for (i = 0; i < num_supplies; i ++)
    strlcpy(supplies[i].color, "none", sizeof(supplies[i].color));

  _cupsSNMPWalk(snmp_fd, &current_addr, CUPS_SNMP_VERSION_1,
                _cupsSNMPDefaultCommunity(), prtMarkerColorantValue,
	        CUPS_SUPPLY_TIMEOUT, backend_walk_cb, NULL);

 /*
  * Output the marker-colors attribute...
  */

  for (i = 0, ptr = value; i < num_supplies; i ++, ptr += strlen(ptr))
  {
    if (i)
      *ptr++ = ',';

    strlcpy(ptr, supplies[i].color, sizeof(value) - (size_t)(ptr - value));
  }

  fprintf(stderr, "ATTR: marker-colors=%s\n", value);

 /*
  * Output the marker-names attribute (the double quoting is necessary to deal
  * with embedded quotes and commas in the marker names...)
  */

  for (i = 0, ptr = value; i < num_supplies; i ++)
  {
    if (i)
      *ptr++ = ',';

    *ptr++ = '\'';
    *ptr++ = '\"';
    for (name_ptr = supplies[i].name; *name_ptr;)
    {
      if (*name_ptr == '\\' || *name_ptr == '\"' || *name_ptr == '\'')
      {
        *ptr++ = '\\';
        *ptr++ = '\\';
        *ptr++ = '\\';
      }

      *ptr++ = *name_ptr++;
    }
    *ptr++ = '\"';
    *ptr++ = '\'';
  }

  *ptr = '\0';

  fprintf(stderr, "ATTR: marker-names=%s\n", value);

 /*
  * Output the marker-types attribute...
  */

  for (i = 0, ptr = value; i < num_supplies; i ++, ptr += strlen(ptr))
  {
    if (i)
      *ptr++ = ',';

    type = supplies[i].type;

    if (type < CUPS_TC_other || type > CUPS_TC_covers)
      strlcpy(ptr, "unknown", sizeof(value) - (size_t)(ptr - value));
    else
      strlcpy(ptr, types[type - CUPS_TC_other], sizeof(value) - (size_t)(ptr - value));
  }

  fprintf(stderr, "ATTR: marker-types=%s\n", value);
}
static void
populate_options_real (PpOptionsDialog *dialog)
{
  GtkTreeSelection *selection;
  GtkTreeModel     *model;
  GtkTreeView      *treeview;
  GtkTreeIter       iter;
  ppd_file_t       *ppd_file;
  GtkWidget        *notebook;
  GtkWidget        *grid;
  GtkWidget        *general_tab_grid = tab_grid_new ();
  GtkWidget        *page_setup_tab_grid = tab_grid_new ();
  GtkWidget        *installable_options_tab_grid = tab_grid_new ();
  GtkWidget        *job_tab_grid = tab_grid_new ();
  GtkWidget        *image_quality_tab_grid = tab_grid_new ();
  GtkWidget        *color_tab_grid = tab_grid_new ();
  GtkWidget        *finishing_tab_grid = tab_grid_new ();
  GtkWidget        *advanced_tab_grid = tab_grid_new ();
  GtkWidget        *widget;
  gint              i, j;

  widget = (GtkWidget*)
    gtk_builder_get_object (dialog->builder, "options-spinner");
  gtk_widget_hide (widget);
  gtk_spinner_stop (GTK_SPINNER (widget));

  widget = (GtkWidget*)
    gtk_builder_get_object (dialog->builder, "progress-label");
  gtk_widget_hide (widget);

  treeview = (GtkTreeView *)
    gtk_builder_get_object (dialog->builder, "options-categories-treeview");

  notebook = (GtkWidget *)
    gtk_builder_get_object (dialog->builder, "options-notebook");

  if (dialog->ipp_attributes)
    {
      /* Add number-up option to Page Setup tab */
      ipp_option_add (g_hash_table_lookup (dialog->ipp_attributes,
                                           "number-up-supported"),
                      g_hash_table_lookup (dialog->ipp_attributes,
                                           "number-up-default"),
                      "number-up",
                      /* Translators: This option sets number of pages printed on one sheet */
                      _("Pages per side"),
                      dialog->printer_name,
                      page_setup_tab_grid,
                      dialog->sensitive);

      /* Add sides option to Page Setup tab */
      ipp_option_add (g_hash_table_lookup (dialog->ipp_attributes,
                                           "sides-supported"),
                      g_hash_table_lookup (dialog->ipp_attributes,
                                           "sides-default"),
                      "sides",
                      /* Translators: This option sets whether to print on both sides of paper */
                      _("Two-sided"),
                      dialog->printer_name,
                      page_setup_tab_grid,
                      dialog->sensitive);

      /* Add orientation-requested option to Page Setup tab */
      ipp_option_add (g_hash_table_lookup (dialog->ipp_attributes,
                                           "orientation-requested-supported"),
                      g_hash_table_lookup (dialog->ipp_attributes,
                                           "orientation-requested-default"),
                      "orientation-requested",
                      /* Translators: This option sets orientation of print (portrait, landscape...) */
                      _("Orientation"),
                      dialog->printer_name,
                      page_setup_tab_grid,
                      dialog->sensitive);
    }

  if (dialog->destination && dialog->ppd_filename)
    {
      ppd_file = ppdOpenFile (dialog->ppd_filename);
      ppdLocalize (ppd_file);

      if (ppd_file)
        {
          ppdMarkDefaults (ppd_file);
          cupsMarkOptions (ppd_file,
                           dialog->destination->num_options,
                           dialog->destination->options);

          for (i = 0; i < ppd_file->num_groups; i++)
            {
              for (j = 0; j < ppd_file->groups[i].num_options; j++)
                {
                  grid = NULL;

                  if (STRING_IN_TABLE (ppd_file->groups[i].name,
                                       color_group_whitelist))
                    grid = color_tab_grid;
                  else if (STRING_IN_TABLE (ppd_file->groups[i].name,
                                            image_quality_group_whitelist))
                    grid = image_quality_tab_grid;
                  else if (STRING_IN_TABLE (ppd_file->groups[i].name,
                                            job_group_whitelist))
                    grid = job_tab_grid;
                  else if (STRING_IN_TABLE (ppd_file->groups[i].name,
                                            finishing_group_whitelist))
                    grid = finishing_tab_grid;
                  else if (STRING_IN_TABLE (ppd_file->groups[i].name,
                                            installable_options_group_whitelist))
                    grid = installable_options_tab_grid;
                  else if (STRING_IN_TABLE (ppd_file->groups[i].name,
                                            page_setup_group_whitelist))
                    grid = page_setup_tab_grid;

                  if (!STRING_IN_TABLE (ppd_file->groups[i].options[j].keyword,
                                        ppd_option_blacklist))
                    {
                      if (!grid && STRING_IN_TABLE (ppd_file->groups[i].options[j].keyword,
                                                    color_option_whitelist))
                        grid = color_tab_grid;
                      else if (!grid && STRING_IN_TABLE (ppd_file->groups[i].options[j].keyword,
                                                         image_quality_option_whitelist))
                        grid = image_quality_tab_grid;
                      else if (!grid && STRING_IN_TABLE (ppd_file->groups[i].options[j].keyword,
                                                         finishing_option_whitelist))
                        grid = finishing_tab_grid;
                      else if (!grid && STRING_IN_TABLE (ppd_file->groups[i].options[j].keyword,
                                                         page_setup_option_whitelist))
                        grid = page_setup_tab_grid;

                      if (!grid)
                        grid = advanced_tab_grid;

                      ppd_option_add (ppd_file->groups[i].options[j],
                                      dialog->printer_name,
                                      grid,
                                      dialog->sensitive);
                    }
                }
            }

          ppdClose (ppd_file);
        }
    }

  dialog->ppd_filename_set = FALSE;
  if (dialog->ppd_filename)
    {
      g_unlink (dialog->ppd_filename);
      g_free (dialog->ppd_filename);
      dialog->ppd_filename = NULL;
    }

  dialog->destination_set = FALSE;
  if (dialog->destination)
    {
      cupsFreeDests (1, dialog->destination);
      dialog->destination = NULL;
    }

  dialog->ipp_attributes_set = FALSE;
  if (dialog->ipp_attributes)
    {
      g_hash_table_unref (dialog->ipp_attributes);
      dialog->ipp_attributes = NULL;
    }

  /* Translators: "General" tab contains general printer options */
  tab_add (C_("Printer Option Group", "General"), notebook, treeview, general_tab_grid);

  /* Translators: "Page Setup" tab contains settings related to pages (page size, paper source, etc.) */
  tab_add (C_("Printer Option Group", "Page Setup"), notebook, treeview, page_setup_tab_grid);

  /* Translators: "Installable Options" tab contains settings of presence of installed options (amount of RAM, duplex unit, etc.) */
  tab_add (C_("Printer Option Group", "Installable Options"), notebook, treeview, installable_options_tab_grid);

  /* Translators: "Job" tab contains settings for jobs */
  tab_add (C_("Printer Option Group", "Job"), notebook, treeview, job_tab_grid);

  /* Translators: "Image Quality" tab contains settings for quality of output print (e.g. resolution) */
  tab_add (C_("Printer Option Group", "Image Quality"), notebook, treeview, image_quality_tab_grid);

  /* Translators: "Color" tab contains color settings (e.g. color printing) */
  tab_add (C_("Printer Option Group", "Color"), notebook, treeview, color_tab_grid);

  /* Translators: "Finishing" tab contains finishing settings (e.g. booklet printing) */
  tab_add (C_("Printer Option Group", "Finishing"), notebook, treeview, finishing_tab_grid);

  /* Translators: "Advanced" tab contains all others settings */
  tab_add (C_("Printer Option Group", "Advanced"), notebook, treeview, advanced_tab_grid);

  gtk_widget_show_all (GTK_WIDGET (notebook));

  /* Select the first option group */
  if ((selection = gtk_tree_view_get_selection (treeview)) != NULL)
    {
      g_signal_connect (selection,
                        "changed",
                        G_CALLBACK (category_selection_changed_cb), dialog);

      if ((model = gtk_tree_view_get_model (treeview)) != NULL &&
          gtk_tree_model_get_iter_first (model, &iter))
        gtk_tree_selection_select_iter (selection, &iter);
    }

  dialog->populating_dialog = FALSE;
  if (dialog->response != GTK_RESPONSE_NONE)
    {
      dialog->user_callback (GTK_DIALOG (dialog->dialog), dialog->response, dialog->user_data);
    }
}
Exemple #26
0
static
char* make_cmd_param(cups_option_t *p_cups_opt, int num_opt,
	ParamList *p_param, char *p_product, int len)
{
#ifdef DEBUG_PPD
	char *p_ppd_name = "debug.ppd";
#else
	char *p_ppd_name = getenv("PPD");
#endif
	ppd_file_t *p_ppd;
	char *cmd_buf = NULL;
	ppd_choice_t *p_choice;
	ppd_size_t *p_size;
	ppd_size_t *p_default_size;
	int reso;
	char gs_exec_buf[256];
	char gs_cmd_buf[1024];
	char *flt_cmd_buf = NULL;

//For InkJet
	long minw_mm, maxw_mm;
	long minl_mm, maxl_mm;
	PpdToOptKey *p_opt_key_table = alloc_opt_key_table(p_ppd_name);
	PpdToOptKey *p_table = p_opt_key_table;
	ParamList *p_list = NULL;

	if( (p_ppd = ppdOpenFile(p_ppd_name)) == NULL )
		return NULL;

	if( p_opt_key_table == NULL)
		return NULL;

	ppdMarkDefaults(p_ppd);

	// Obtain default page size setting.
	p_choice = ppdFindMarkedChoice(p_ppd, "PageSize");
	p_default_size = ppdPageSize(p_ppd, p_choice->choice);

	mark_ps_param_options(p_ppd, p_param);
	cupsMarkOptions(p_ppd, num_opt, p_cups_opt);

	// Obtain page size setting.
	p_choice = ppdFindMarkedChoice(p_ppd, "PageSize");
	p_size = ppdPageSize(p_ppd, p_choice->choice);

	if (!p_size || ((int)(p_size->width == 0)) || ((int)(p_size->length == 0))) {
	    p_size = p_default_size;
	}

	// Obtain resolution setting.
	p_choice = ppdFindMarkedChoice(p_ppd, "Resolution");
	reso = atoi(p_choice->choice);

	//Obtain product name.
	parse_product_name(p_ppd->product, p_product, len);

	get_min_max_width_length(p_opt_key_table, p_cups_opt, num_opt,
		&minw_mm, &maxw_mm, &minl_mm, &maxl_mm);

// gs command
	strncpy(gs_exec_buf, GS_PATH, 256);
	strncat(gs_exec_buf, "/", 1);
	strncat(gs_exec_buf, GS_BIN, strlen(GS_BIN));
	snprintf(gs_cmd_buf, 1023,
	"%s -r%d -g%dx%d -q -dNOPROMPT -dSAFER -sDEVICE=ppmraw -sOutputFile=- -| ",
			gs_exec_buf, reso, (int)(p_size->width * (float)reso / 72.0),
			(int)(p_size->length * (float)reso / 72.0));

// For InkJet bjfilter Command 
	while( p_table->ppd_key != NULL )
	{
		p_choice = ppdFindMarkedChoice(p_ppd, p_table->ppd_key);
		if( p_choice != NULL )
		{
			char choice[256];

			strncpy(choice, p_choice->choice, 256);

			if( !strcmp(p_table->ppd_key, "PageSize")
			 && !strcmp(choice, "Custom") )
			{
				char pw[256];
				char pl[256];
				long pw_mm, pl_mm;
				pw_mm = (long)((double)p_size->width * 2540.0 / 72.0);
				pl_mm = (long)((double)p_size->length * 2540.0 / 72.0);
				if( minw_mm != -1 && pw_mm < minw_mm )
					pw_mm = minw_mm;
				if( maxw_mm != -1 && pw_mm > maxw_mm )
					pw_mm = maxw_mm;
				if( minl_mm != -1 && pl_mm < minl_mm )
					pl_mm = minl_mm;
				if( maxl_mm != -1 && pl_mm > maxl_mm )
					pl_mm = maxw_mm;
				snprintf(pw, 255, "%ld", pw_mm);
				snprintf(pl, 255, "%ld", pl_mm);
				param_list_add(&p_list, p_table->opt_key, "user", 5);
				param_list_add(&p_list,
					"--paperwidth", pw, strlen(pw) + 1);
				param_list_add(&p_list,
					"--paperheight", pl, strlen(pl) + 1);
			}
			else
			{
				if( !strcmp(p_table->ppd_key, "PageSize")
				 && is_borderless(choice) )
				{
					param_list_add(&p_list, "--borderless", "", 1);
				}
				param_list_add(&p_list, p_table->opt_key,
					choice, strlen(choice) + 1);
			}
		}
		p_table++;
	}

	while( num_opt-- > 0 )
	{
		char *opt_key = ppd_to_opt_key(p_opt_key_table, p_cups_opt->name);
		if( opt_key != NULL )
		{
			char *value = p_cups_opt->value;
			param_list_add(&p_list, opt_key, value, strlen(value) + 1);
		}
		p_cups_opt++;
	}

	{
		char bbox_buf[256];
		float dd = 1.0 - 36.0 / (float)reso;
		int left   = (int)p_size->left;
		int top    = (int)(p_size->top + dd);
		int right  = left + (int)(p_size->right - p_size->left + dd);
		int bottom = top - (int)(p_size->top - p_size->bottom + dd);

		snprintf(bbox_buf, 255, "%-d,%-d,%-d,%-d", left, bottom, right, top);
		param_list_add(&p_list, "--bbox",
				bbox_buf, strlen(bbox_buf) + 1);
	}

	flt_cmd_buf = make_filter_param_line(p_product, reso, p_list);

	if( p_list != NULL ){
		param_list_free(p_list);
		free_opt_key_table(p_opt_key_table);
	}

	ppdClose(p_ppd);

	if( flt_cmd_buf )
	{
		int buf_len;			
		
		buf_len = strlen(gs_cmd_buf) + strlen(flt_cmd_buf) + 1;

		if( (cmd_buf = (char*)malloc(buf_len)) != NULL )
		{
			strcpy(cmd_buf, gs_cmd_buf);
			strcat(cmd_buf, flt_cmd_buf);
		}
		free(flt_cmd_buf);
fprintf(stderr, "pstocanonbj: %s\n", cmd_buf);
		return cmd_buf;
	}
	else
		return NULL;
}
Exemple #27
0
GList *dt_get_papers(const dt_printer_info_t *printer)
{
  const char *printer_name = printer->name;
  GList *result = NULL;

#if ((CUPS_VERSION_MAJOR == 1) && (CUPS_VERSION_MINOR >= 7)) || CUPS_VERSION_MAJOR > 1
#if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_9
  if (cupsConnectDest != NULL && cupsCopyDestInfo != NULL && cupsGetDestMediaCount != NULL &&
      cupsGetDestMediaByIndex != NULL && cupsFreeDestInfo != NULL)
#endif
  {
    cups_dest_t *dests;
    int num_dests = cupsGetDests(&dests);
    cups_dest_t *dest = cupsGetDest(printer_name, NULL, num_dests, dests);

    int cancel = 0; // important

    char resource[1024];

    if (dest)
    {
      http_t *hcon = cupsConnectDest(dest, 0, 2000, &cancel, resource, sizeof(resource), NULL, (void *)NULL);

      if (hcon)
      {
        cups_size_t size;
        cups_dinfo_t *info = cupsCopyDestInfo (hcon, dest);
        const int count = cupsGetDestMediaCount(hcon, dest, info, CUPS_MEDIA_FLAGS_DEFAULT);
        for (int k=0; k<count; k++)
        {
          if (cupsGetDestMediaByIndex(hcon, dest, info, k, CUPS_MEDIA_FLAGS_DEFAULT, &size))
          {
            if (size.width!=0 && size.length!=0 && !paper_exists(result, size.media))
            {
              pwg_media_t *med = pwgMediaForPWG (size.media);
              char common_name[MAX_NAME] = { 0 };

              if (med->ppd)
                g_strlcpy(common_name, med->ppd, sizeof(common_name));
              else
                g_strlcpy(common_name, size.media, sizeof(common_name));

              dt_paper_info_t *paper = (dt_paper_info_t*)malloc(sizeof(dt_paper_info_t));
              g_strlcpy(paper->name, size.media, sizeof(paper->name));
              g_strlcpy(paper->common_name, common_name, sizeof(paper->common_name));
              paper->width = (double)size.width / 100.0;
              paper->height = (double)size.length / 100.0;
              result = g_list_append (result, paper);

              dt_print(DT_DEBUG_PRINT,
                       "[print] new media paper %4d %6.2f x %6.2f (%s) (%s)\n",
                       k, paper->width, paper->height, paper->name, paper->common_name);
            }
          }
        }

        cupsFreeDestInfo(info);
        httpClose(hcon);
      }
      else
        dt_print(DT_DEBUG_PRINT, "[print] cannot connect to printer %s (cancel=%d)\n", printer_name, cancel);
    }

    cupsFreeDests(num_dests, dests);
  }
#endif

  // check now PPD page sizes

  const char *PPDFile = cupsGetPPD(printer_name);
  ppd_file_t *ppd = ppdOpenFile(PPDFile);

  if (ppd)
  {
    ppd_size_t *size = ppd->sizes;

    for (int k=0; k<ppd->num_sizes; k++)
    {
      if (size->width!=0 && size->length!=0 && !paper_exists(result, size->name))
      {
        dt_paper_info_t *paper = (dt_paper_info_t*)malloc(sizeof(dt_paper_info_t));
        g_strlcpy(paper->name, size->name, MAX_NAME);
        g_strlcpy(paper->common_name, size->name, MAX_NAME);
        paper->width = (double)dt_pdf_point_to_mm(size->width);
        paper->height = (double)dt_pdf_point_to_mm(size->length);
        result = g_list_append (result, paper);

        dt_print(DT_DEBUG_PRINT,
                 "[print] new ppd paper %4d %6.2f x %6.2f (%s) (%s)\n",
                 k, paper->width, paper->height, paper->name, paper->common_name);
      }
      size++;
    }

    ppdClose(ppd);
    g_unlink(PPDFile);
  }

  result = g_list_sort_with_data (result, (GCompareDataFunc)sort_papers, NULL);
  return result;
}
Exemple #28
0
static int				/* O - 0 on success, 1 on fail */
set_printer_options(
    http_t        *http,		/* I - Server connection */
    char          *printer,		/* I - Printer */
    int           num_options,		/* I - Number of options */
    cups_option_t *options,		/* I - Options */
    char          *file)		/* I - PPD file/interface script */
{
  ipp_t		*request;		/* IPP Request */
  const char	*ppdfile;		/* PPD filename */
  int		ppdchanged;		/* PPD changed? */
  ppd_file_t	*ppd;			/* PPD file */
  ppd_choice_t	*choice;		/* Marked choice */
  char		uri[HTTP_MAX_URI],	/* URI for printer/class */
		line[1024],		/* Line from PPD file */
		keyword[1024],		/* Keyword from Default line */
		*keyptr,		/* Pointer into keyword... */
		tempfile[1024];		/* Temporary filename */
  cups_file_t	*in,			/* PPD file */
		*out;			/* Temporary file */
  const char	*protocol,		/* Old protocol option */
		*customval,		/* Custom option value */
		*boolval;		/* Boolean value */
  int		wrote_ipp_supplies = 0,	/* Wrote cupsIPPSupplies keyword? */
		wrote_snmp_supplies = 0;/* Wrote cupsSNMPSupplies keyword? */


  DEBUG_printf(("set_printer_options(http=%p, printer=\"%s\", num_options=%d, "
                "options=%p, file=\"%s\")\n", http, printer, num_options,
		options, file));

 /*
  * Build a CUPS_ADD_MODIFY_PRINTER or CUPS_ADD_MODIFY_CLASS request, which
  * requires the following attributes:
  *
  *    attributes-charset
  *    attributes-natural-language
  *    printer-uri
  *    requesting-user-name
  *    other options
  */

  if (get_printer_type(http, printer, uri, sizeof(uri)) & CUPS_PRINTER_CLASS)
    request = ippNewRequest(CUPS_ADD_MODIFY_CLASS);
  else
    request = ippNewRequest(CUPS_ADD_MODIFY_PRINTER);

  ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI,
               "printer-uri", NULL, uri);
  ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
               "requesting-user-name", NULL, cupsUser());

 /*
  * Add the options...
  */

  cupsEncodeOptions2(request, num_options, options, IPP_TAG_PRINTER);

  if ((protocol = cupsGetOption("protocol", num_options, options)) != NULL)
  {
    if (!_cups_strcasecmp(protocol, "bcp"))
      ippAddString(request, IPP_TAG_PRINTER, IPP_TAG_NAME, "port-monitor",
                   NULL, "bcp");
    else if (!_cups_strcasecmp(protocol, "tbcp"))
      ippAddString(request, IPP_TAG_PRINTER, IPP_TAG_NAME, "port-monitor",
                   NULL, "tbcp");
  }

  if (file)
    ppdfile = file;
  else if (request->request.op.operation_id == CUPS_ADD_MODIFY_PRINTER)
    ppdfile = cupsGetPPD(printer);
  else
    ppdfile = NULL;

  if (ppdfile != NULL)
  {
   /*
    * Set default options in the PPD file...
    */

    ppd = ppdOpenFile(ppdfile);
    ppdMarkDefaults(ppd);
    cupsMarkOptions(ppd, num_options, options);

    if ((out = cupsTempFile2(tempfile, sizeof(tempfile))) == NULL)
    {
      _cupsLangPrintError(NULL, _("lpadmin: Unable to create temporary file"));
      ippDelete(request);
      if (ppdfile != file)
        unlink(ppdfile);
      return (1);
    }

    if ((in = cupsFileOpen(ppdfile, "r")) == NULL)
    {
      _cupsLangPrintf(stderr,
                      _("lpadmin: Unable to open PPD file \"%s\" - %s"),
        	      ppdfile, strerror(errno));
      ippDelete(request);
      if (ppdfile != file)
	unlink(ppdfile);
      cupsFileClose(out);
      unlink(tempfile);
      return (1);
    }

    ppdchanged = 0;

    while (cupsFileGets(in, line, sizeof(line)))
    {
      if (!strncmp(line, "*cupsIPPSupplies:", 17) &&
	  (boolval = cupsGetOption("cupsIPPSupplies", num_options,
	                           options)) != NULL)
      {
        wrote_ipp_supplies = 1;
        cupsFilePrintf(out, "*cupsIPPSupplies: %s\n",
	               (!_cups_strcasecmp(boolval, "true") ||
		        !_cups_strcasecmp(boolval, "yes") ||
		        !_cups_strcasecmp(boolval, "on")) ? "True" : "False");
      }
      else if (!strncmp(line, "*cupsSNMPSupplies:", 18) &&
	       (boolval = cupsGetOption("cupsSNMPSupplies", num_options,
	                                options)) != NULL)
      {
        wrote_snmp_supplies = 1;
        cupsFilePrintf(out, "*cupsSNMPSupplies: %s\n",
	               (!_cups_strcasecmp(boolval, "true") ||
		        !_cups_strcasecmp(boolval, "yes") ||
		        !_cups_strcasecmp(boolval, "on")) ? "True" : "False");
      }
      else if (strncmp(line, "*Default", 8))
        cupsFilePrintf(out, "%s\n", line);
      else
      {
       /*
        * Get default option name...
	*/

        strlcpy(keyword, line + 8, sizeof(keyword));

	for (keyptr = keyword; *keyptr; keyptr ++)
	  if (*keyptr == ':' || isspace(*keyptr & 255))
	    break;

        *keyptr++ = '\0';
        while (isspace(*keyptr & 255))
	  keyptr ++;

        if (!strcmp(keyword, "PageRegion") ||
	    !strcmp(keyword, "PageSize") ||
	    !strcmp(keyword, "PaperDimension") ||
	    !strcmp(keyword, "ImageableArea"))
	{
	  if ((choice = ppdFindMarkedChoice(ppd, "PageSize")) == NULL)
	    choice = ppdFindMarkedChoice(ppd, "PageRegion");
        }
	else
	  choice = ppdFindMarkedChoice(ppd, keyword);

        if (choice && strcmp(choice->choice, keyptr))
	{
	  if (strcmp(choice->choice, "Custom"))
	  {
	    cupsFilePrintf(out, "*Default%s: %s\n", keyword, choice->choice);
	    ppdchanged = 1;
	  }
	  else if ((customval = cupsGetOption(keyword, num_options,
	                                      options)) != NULL)
	  {
	    cupsFilePrintf(out, "*Default%s: %s\n", keyword, customval);
	    ppdchanged = 1;
	  }
	  else
	    cupsFilePrintf(out, "%s\n", line);
	}
	else
	  cupsFilePrintf(out, "%s\n", line);
      }
    }

    if (!wrote_ipp_supplies &&
	(boolval = cupsGetOption("cupsIPPSupplies", num_options,
				 options)) != NULL)
    {
      cupsFilePrintf(out, "*cupsIPPSupplies: %s\n",
		     (!_cups_strcasecmp(boolval, "true") ||
		      !_cups_strcasecmp(boolval, "yes") ||
		      !_cups_strcasecmp(boolval, "on")) ? "True" : "False");
    }

    if (!wrote_snmp_supplies &&
        (boolval = cupsGetOption("cupsSNMPSupplies", num_options,
			         options)) != NULL)
    {
      cupsFilePrintf(out, "*cupsSNMPSupplies: %s\n",
		     (!_cups_strcasecmp(boolval, "true") ||
		      !_cups_strcasecmp(boolval, "yes") ||
		      !_cups_strcasecmp(boolval, "on")) ? "True" : "False");
    }

    cupsFileClose(in);
    cupsFileClose(out);
    ppdClose(ppd);

   /*
    * Do the request...
    */

    ippDelete(cupsDoFileRequest(http, request, "/admin/",
                                ppdchanged ? tempfile : file));

   /*
    * Clean up temp files... (TODO: catch signals in case we CTRL-C during
    * lpadmin)
    */

    if (ppdfile != file)
      unlink(ppdfile);
    unlink(tempfile);
  }
  else
  {
   /*
    * No PPD file - just set the options...
    */

    ippDelete(cupsDoRequest(http, request, "/admin/"));
  }

 /*
  * Check the response...
  */

  if (cupsLastError() > IPP_OK_CONFLICT)
  {
    _cupsLangPrintf(stderr, _("%s: %s"), "lpadmin", cupsLastErrorString());

    return (1);
  }
  else
    return (0);
}
Exemple #29
0
void dt_get_printer_info(const char *printer_name, dt_printer_info_t *pinfo)
{
  cups_dest_t *dests;
  int num_dests = cupsGetDests(&dests);
  cups_dest_t *dest = cupsGetDest(printer_name, NULL, num_dests, dests);

  if (dest)
  {
    const char *PPDFile = cupsGetPPD (printer_name);
    g_strlcpy(pinfo->name, dest->name, MAX_NAME);
    ppd_file_t *ppd = ppdOpenFile(PPDFile);

    if (ppd)
    {
      ppdMarkDefaults(ppd);
      cupsMarkOptions(ppd, dest->num_options, dest->options);

      // first check if this is turboprint drived printer, two solutions:
      // 1. ModelName constains TurboPrint
      // 2. zedoPrinterDriver exists
      ppd_attr_t *attr = ppdFindAttr(ppd, "ModelName", NULL);

      if (attr)
      {
        pinfo->is_turboprint = strstr(attr->value, "TurboPrint") != NULL;
      }

      // hardware margins

      attr = ppdFindAttr(ppd, "HWMargins", NULL);

      if (attr)
      {
        sscanf(attr->value, "%lf %lf %lf %lf",
               &pinfo->hw_margin_left, &pinfo->hw_margin_bottom,
               &pinfo->hw_margin_right, &pinfo->hw_margin_top);

        pinfo->hw_margin_left   = dt_pdf_point_to_mm (pinfo->hw_margin_left);
        pinfo->hw_margin_bottom = dt_pdf_point_to_mm (pinfo->hw_margin_bottom);
        pinfo->hw_margin_right  = dt_pdf_point_to_mm (pinfo->hw_margin_right);
        pinfo->hw_margin_top    = dt_pdf_point_to_mm (pinfo->hw_margin_top);
      }

      // default resolution

      attr = ppdFindAttr(ppd, "DefaultResolution", NULL);

      if (attr)
      {
        char *x = strstr(attr->value, "x");

        if (x)
          sscanf (x+1, "%ddpi", &pinfo->resolution);
        else
          sscanf (attr->value, "%ddpi", &pinfo->resolution);
      }
      else
        pinfo->resolution = 300;

      while(pinfo->resolution>360)
        pinfo->resolution /= 2.0;

      ppdClose(ppd);
      g_unlink(PPDFile);
    }
  }

  cupsFreeDests(num_dests, dests);
}
int					/* O - Exit status */
imagetops_main(int  argc,				/* I - Number of command-line arguments */
     char *argv[])			/* I - Command-line arguments */
{
  cups_image_t	*img;			/* Image to print */
  float		xprint,			/* Printable area */
		yprint,
		xinches,		/* Total size in inches */
		yinches;
  float		xsize,			/* Total size in points */
		ysize,
		xsize2,
		ysize2;
  float		aspect;			/* Aspect ratio */
  int		xpages,			/* # x pages */
		ypages,			/* # y pages */
		xpage,			/* Current x page */
		ypage,			/* Current y page */
		page;			/* Current page number */
  int		xc0, yc0,			/* Corners of the page in image coords */
		xc1, yc1;
  cups_ib_t	*row;			/* Current row */
  int		y;			/* Current Y coordinate in image */
  int		colorspace;		/* Output colorspace */
  int		out_offset,		/* Offset into output buffer */
		out_length;		/* Length of output buffer */
  ppd_file_t	*ppd;			/* PPD file */
  ppd_choice_t	*choice;		/* PPD option choice */
  int		num_options;		/* Number of print options */
  cups_option_t	*options;		/* Print options */
  const char	*val;			/* Option value */
  int		slowcollate;		/* Collate copies the slow way */
  float		g;			/* Gamma correction value */
  float		b;			/* Brightness factor */
  float		zoom;			/* Zoom facter */
  int		xppi, yppi;		/* Pixels-per-inch */
  int		hue, sat;		/* Hue and saturation adjustment */
  int		realcopies,		/* Real copies being printed */
		emit_jcl;		/* Emit JCL? */
  float		left, top;		/* Left and top of image */
  char		filename[1024];		/* Name of file to print */
  time_t	curtime;		/* Current time */
  struct tm	*curtm;			/* Current date */
  char		curdate[255];		/* Current date string */
  int psFileMode = 0; //0:CREATE New ; 1: Append
  int outColorDevice = 1; //0 : monochrome print , 1:color print
  int count = 0,numFiles=1;
  int defout,outfd;
 /*
  * Make sure status messages are not buffered...
  */

	int ii=0;
	for(;ii<argc;ii++)
		LOGI("imagetops : argv:%s",argv[ii]);

  fflush(stdout);

  Copies = 1;	
  
  setbuf(stderr, NULL);

 /*
  * Ignore broken pipe signals...
  */

  signal(SIGPIPE, SIG_IGN);

 	
 /*
  * Process command-line options and write the prolog...
  */

  zoom = 0.0;
  xppi = 0;
  yppi = 0;
  hue  = 0;
  sat  = 100;
  g    = 1.0;
  b    = 1.0;

  Copies = atoi(argv[4]);

  options     = NULL;
  num_options = cupsParseOptions(argv[5], 0, &options);

  ppdFilePath = argv[6];
  ContentType= argv[7];
  psFilePath = argv[8];
  outColorDevice = atoi(argv[9]);
  numFiles = argc - 10;
  LOGI("imagetops : numFiles=%d",numFiles);
  
  
  ppd = SetCommonOptions(num_options, options, 0);
  
  if ((val = cupsGetOption("multiple-document-handling", num_options, options)) != NULL)
  {
   /*
    * This IPP attribute is unnecessarily complicated...
    *
    *   single-document, separate-documents-collated-copies, and
    *   single-document-new-sheet all require collated copies.
    *
    *   separate-documents-uncollated-copies allows for uncollated copies.
    */

    Collate = _cups_strcasecmp(val, "separate-documents-uncollated-copies") != 0;
  }

  if ((val = cupsGetOption("Collate", num_options, options)) != NULL &&
      _cups_strcasecmp(val, "True") == 0)
    Collate = 1;

  if ((val = cupsGetOption("gamma", num_options, options)) != NULL)
  {
   /*
    * Get gamma value from 1 to 10000...
    */

    g = atoi(val) * 0.001f;

    if (g < 0.001f)
      g = 0.001f;
    else if (g > 10.0f)
      g = 10.0f;
  }

  if ((val = cupsGetOption("brightness", num_options, options)) != NULL)
  {
   /*
    * Get brightness value from 10 to 1000.
    */

    b = atoi(val) * 0.01f;

    if (b < 0.1f)
      b = 0.1f;
    else if (b > 10.0f)
      b = 10.0f;
  }

  if ((val = cupsGetOption("scaling", num_options, options)) != NULL)
		zoom = atoi(val) * 0.01;
  else if ((val = cupsGetOption("fitplot", num_options, options)) != NULL &&
           !_cups_strcasecmp(val, "true"))
		zoom = 1.0;
  else if ((val = cupsGetOption("fit-to-page", num_options, options)) != NULL &&
           !_cups_strcasecmp(val, "true"))
    zoom = 1.0;

  if ((val = cupsGetOption("ppi", num_options, options)) != NULL)
    if (sscanf(val, "%dx%d", &xppi, &yppi) < 2)
      yppi = xppi;

  if ((val = cupsGetOption("position", num_options, options)) != NULL)
  {
    if (_cups_strcasecmp(val, "center") == 0)
    {
      XPosition = 0;
      YPosition = 0;
    }
    else if (_cups_strcasecmp(val, "top") == 0)
    {
      XPosition = 0;
      YPosition = 1;
    }
    else if (_cups_strcasecmp(val, "left") == 0)
    {
      XPosition = -1;
      YPosition = 0;
    }
    else if (_cups_strcasecmp(val, "right") == 0)
    {
      XPosition = 1;
      YPosition = 0;
    }
    else if (_cups_strcasecmp(val, "top-left") == 0)
    {
      XPosition = -1;
      YPosition = 1;
    }
    else if (_cups_strcasecmp(val, "top-right") == 0)
    {
      XPosition = 1;
      YPosition = 1;
    }
    else if (_cups_strcasecmp(val, "bottom") == 0)
    {
      XPosition = 0;
      YPosition = -1;
    }
    else if (_cups_strcasecmp(val, "bottom-left") == 0)
    {
      XPosition = -1;
      YPosition = -1;
    }
    else if (_cups_strcasecmp(val, "bottom-right") == 0)
    {
      XPosition = 1;
      YPosition = -1;
    }
  }

  if ((val = cupsGetOption("saturation", num_options, options)) != NULL)
    sat = atoi(val);

  if ((val = cupsGetOption("hue", num_options, options)) != NULL)
    hue = atoi(val);

  if ((choice = ppdFindMarkedChoice(ppd, "MirrorPrint")) != NULL)
  {
    val = choice->choice;
    choice->marked = 0;
  }
  else
    val = cupsGetOption("mirror", num_options, options);

  if (val && (!_cups_strcasecmp(val, "true") || !_cups_strcasecmp(val, "on") ||
              !_cups_strcasecmp(val, "yes")))
    Flip = 1;

  if ((val = cupsGetOption("emit-jcl", num_options, options)) != NULL &&
      (!_cups_strcasecmp(val, "false") || !_cups_strcasecmp(val, "off") ||
       !_cups_strcasecmp(val, "no") || !strcmp(val, "0")))
    emit_jcl = 0;
  else
    emit_jcl = 1;

  LOGI("imagetops/Copies=%d , Collate=%d, gamma=%f, brightness=%f, zoom=%f",Copies,Collate,g,b,zoom);
  LOGI("imagetops/xppi=%d,yppi=%d,XPosition=%d,YPosition=%d,sat=%d,hue=%d,flip=%d,emit_jcl=%d",xppi,yppi,XPosition,YPosition,sat,hue,Flip,emit_jcl);
 /*
  * Open the input image to print...
  */
  
	if(outColorDevice == 1) //added @ grv
		colorspace = CUPS_IMAGE_RGB_CMYK;
	else
		colorspace = CUPS_IMAGE_WHITE;

	LOGI("imagetops/ colorspace = %d",colorspace);
		
	for(count=0;count<numFiles;count++){
		Copies = atoi(argv[4]);
		//do everything for both image files
		strlcpy(filename, argv[(10 + count)], sizeof(filename)); 
		LOGI("imagetops : count=%d , filename=%s",count,filename);
		img = cupsImageOpen(filename, colorspace, CUPS_IMAGE_WHITE, sat, hue, NULL);
		if (img == NULL)
		{
			LOGI("imagetops:error:The print file could not be opened.");
			_cupsLangPrintFilter(stderr, "ERROR",
							 _("The print file could not be opened."));
			ppdClose(ppd);
			return (1);
		}
		colorspace = cupsImageGetColorSpace(img);
		LOGI("imagetops: cupsImageGetColorSpace finished : colorspace :%d",colorspace);
		/*
		* Scale as necessary...
		*/
			
		if (zoom == 0.0 && xppi == 0)
		{
			xppi = cupsImageGetXPPI(img);
			yppi = cupsImageGetYPPI(img);
		}
		LOGI("imagetops:xppi=%d",xppi);
		LOGI("imagetops:yppi=%d",yppi);
		if (yppi == 0)
			yppi = xppi;

		fprintf(stderr, "DEBUG: Before scaling: xppi=%d, yppi=%d, zoom=%.2f\n",
			  xppi, yppi, zoom);
		if (xppi > 0)
		{
			/*
			* Scale the image as neccesary to match the desired pixels-per-inch.
			*/

			if (Orientation & 1)
			{
				xprint = (PageTop - PageBottom) / 72.0;
				yprint = (PageRight - PageLeft) / 72.0;
			}
			else
			{
				xprint = (PageRight - PageLeft) / 72.0;
				yprint = (PageTop - PageBottom) / 72.0;
			}

			fprintf(stderr, "DEBUG: Before scaling: xprint=%.1f, yprint=%.1f\n",
				xprint, yprint);

			xinches = (float)cupsImageGetWidth(img) / (float)xppi;
			yinches = (float)cupsImageGetHeight(img) / (float)yppi;

			fprintf(stderr, "DEBUG: Image size is %.1f x %.1f inches...\n",
				xinches, yinches);

			if ((val = cupsGetOption("natural-scaling", num_options, options)) != NULL)
			{
				xinches = xinches * atoi(val) / 100;
				yinches = yinches * atoi(val) / 100;
			}

			if (cupsGetOption("orientation-requested", num_options, options) == NULL &&
				cupsGetOption("landscape", num_options, options) == NULL)
			{
				/*
				* Rotate the image if it will fit landscape but not portrait...
				*/

				fputs("DEBUG: Auto orientation...\n", stderr);
				LOGI("imagetops.c : Auto orientation...");
				if ((xinches > xprint || yinches > yprint) && xinches <= yprint && yinches <= xprint)
				{
					/*
					* Rotate the image as needed...
					*/

					fputs("DEBUG: Using landscape orientation...\n", stderr);
					LOGI("imagetops.c : Auto orientation : Using landscape orientation");
					Orientation = (Orientation + 1) & 3;
					xsize       = yprint;
					yprint      = xprint;
					xprint      = xsize;
				}
			}
		}else{
			/*
			* Scale percentage of page size...
			*/

			xprint = (PageRight - PageLeft) / 72.0;
			yprint = (PageTop - PageBottom) / 72.0;
			aspect = (float)cupsImageGetYPPI(img) / (float)cupsImageGetXPPI(img);

			fprintf(stderr, "DEBUG: Before scaling: xprint=%.1f, yprint=%.1f\n",
            xprint, yprint);

			fprintf(stderr, "DEBUG: cupsImageGetXPPI(img) = %d, cupsImageGetYPPI(img) = %d, aspect = %f\n",
            cupsImageGetXPPI(img), cupsImageGetYPPI(img), aspect);

			xsize = xprint * zoom;
			ysize = xsize * cupsImageGetHeight(img) / cupsImageGetWidth(img) / aspect;

			if (ysize > (yprint * zoom))
			{
				ysize = yprint * zoom;
				xsize = ysize * cupsImageGetWidth(img) * aspect / cupsImageGetHeight(img);
			}

			xsize2 = yprint * zoom;
			ysize2 = xsize2 * cupsImageGetHeight(img) / cupsImageGetWidth(img) / aspect;

			if (ysize2 > (xprint * zoom))
			{
				ysize2 = xprint * zoom;
				xsize2 = ysize2 * cupsImageGetWidth(img) * aspect / cupsImageGetHeight(img);
			}

			fprintf(stderr, "DEBUG: Portrait size is %.2f x %.2f inches\n", xsize, ysize);
			fprintf(stderr, "DEBUG: Landscape size is %.2f x %.2f inches\n", xsize2, ysize2);

			if (cupsGetOption("orientation-requested", num_options, options) == NULL &&	cupsGetOption("landscape", num_options, options) == NULL)
			{
				/*
				* Choose the rotation with the largest area, but prefer
				* portrait if they are equal...
				*/

				fputs("DEBUG: Auto orientation...\n", stderr);

				if ((xsize * ysize) < (xsize2 * xsize2))
				{
					/*
					* Do landscape orientation...
					*/

					fputs("DEBUG: Using landscape orientation...\n", stderr);

					Orientation = 1;
					xinches     = xsize2;
					yinches     = ysize2;
					xprint      = (PageTop - PageBottom) / 72.0;
					yprint      = (PageRight - PageLeft) / 72.0;
				}
				else
				{
					/*
					* Do portrait orientation...
					*/

					fputs("DEBUG: Using portrait orientation...\n", stderr);

					Orientation = 0;
					xinches     = xsize;
					yinches     = ysize;
				}
			}
			else if (Orientation & 1)
			{
				fputs("DEBUG: Using landscape orientation...\n", stderr);

				xinches     = xsize2;
				yinches     = ysize2;
				xprint      = (PageTop - PageBottom) / 72.0;
				yprint      = (PageRight - PageLeft) / 72.0;
			}
			else
			{
				fputs("DEBUG: Using portrait orientation...\n", stderr);

				xinches     = xsize;
				yinches     = ysize;
				xprint      = (PageRight - PageLeft) / 72.0;
				yprint      = (PageTop - PageBottom) / 72.0;
			}
		}
		
		/*
		* Compute the number of pages to print and the size of the image on each
		* page...
		*/

		xpages = ceil(xinches / xprint);
		ypages = ceil(yinches / yprint);

		xprint = xinches / xpages;
		yprint = yinches / ypages;

		fprintf(stderr, "DEBUG: xpages = %dx%.2fin, ypages = %dx%.2fin\n",xpages, xprint, ypages, yprint);
		
		 
		/*
		* Update the page size for custom sizes...
		*/

		if ((choice = ppdFindMarkedChoice(ppd, "PageSize")) != NULL && _cups_strcasecmp(choice->choice, "Custom") == 0)
		{
			float	width,		/* New width in points */
			length;		/* New length in points */
			char	s[255];		/* New custom page size... */


			/*
			* Use the correct width and length for the current orientation...
			*/

			if (Orientation & 1)
			{
				width  = yprint * 72.0;
				length = xprint * 72.0;
			}
			else
			{
				width  = xprint * 72.0;
				length = yprint * 72.0;
			}

			/*
			* Add margins to page size...
			*/

			width  += ppd->custom_margins[0] + ppd->custom_margins[2];
			length += ppd->custom_margins[1] + ppd->custom_margins[3];

			/*
			* Enforce minimums...
			*/

			if (width < ppd->custom_min[0])
				width = ppd->custom_min[0];

			if (length < ppd->custom_min[1])
				length = ppd->custom_min[1];

			fprintf(stderr, "DEBUG: Updated custom page size to %.2f x %.2f inches...\n",width / 72.0, length / 72.0);

			/*
			* Set the new custom size...
			*/

			sprintf(s, "Custom.%.0fx%.0f", width, length);
			ppdMarkOption(ppd, "PageSize", s);

			/*
			* Update page variables...
			*/

			PageWidth  = width;
			PageLength = length;
			PageLeft   = ppd->custom_margins[0];
			PageRight  = width - ppd->custom_margins[2];
			PageBottom = ppd->custom_margins[1];
			PageTop    = length - ppd->custom_margins[3];
		}

		/*
		* See if we need to collate, and if so how we need to do it...
		*/

		if (xpages == 1 && ypages == 1)
			Collate = 0;

		slowcollate = Collate && ppdFindOption(ppd, "Collate") == NULL;

		if (Copies > 1 && !slowcollate)
		{
			realcopies = Copies;
			Copies     = 1;
		}
		else
			realcopies = 1;

		/*
		* Write any "exit server" options that have been selected...
		*/

		//Changes to create ps file -- start
		
		if(count == 0){//single side print
			defout = dup(1);
			outfd = open(psFilePath,O_RDWR | O_CREAT,S_IRWXU |S_IRWXG | S_IRWXO);
			dup2(outfd,1);
		}
		//Changes to create ps file -- end
		ppdEmit(ppd, stdout, PPD_ORDER_EXIT);
		/*
		* Write any JCL commands that are needed to print PostScript code...
		*/

		if (emit_jcl)
			ppdEmitJCL(ppd, stdout, atoi(argv[1]), argv[2], argv[3]);

		/*
		* Start sending the document with any commands needed...
		*/
		  
		curtime = time(NULL);
		curtm   = localtime(&curtime);
		//////////////////
		if(count == 0){
			puts("%!PS-Adobe-3.0");
			printf("%%%%BoundingBox: %.0f %.0f %.0f %.0f\n", PageLeft, PageBottom,PageRight, PageTop);
			printf("%%%%LanguageLevel: %d\n", LanguageLevel);
		
			printf("%%%%Pages: %d\n", xpages * ypages * Copies * numFiles);
			puts("%%DocumentData: Clean7Bit");
			puts("%%DocumentNeededResources: font Helvetica-Bold");
			puts("%%Creator: imagetops/" CUPS_SVERSION);
			strftime(curdate, sizeof(curdate), "%c", curtm);
			printf("%%%%CreationDate: %s\n", curdate);
			WriteTextComment("Title", argv[3]);
			WriteTextComment("For", argv[2]);
			if (Orientation & 1)
				puts("%%Orientation: Landscape");
			else
				puts("%%Orientation: Portrait");
			puts("%%EndComments");
			puts("%%BeginProlog");

			if (ppd != NULL && ppd->patches != NULL)
				puts(ppd->patches);

			ppdEmit(ppd, stdout, PPD_ORDER_DOCUMENT);
			ppdEmit(ppd, stdout, PPD_ORDER_ANY);
			ppdEmit(ppd, stdout, PPD_ORDER_PROLOG);

			if (g != 1.0 || b != 1.0)
				printf("{ neg 1 add dup 0 lt { pop 1 } { %.3f exp neg 1 add } "
					"ifelse %.3f mul } bind settransfer\n", g, b);

			WriteCommon();
			switch (Orientation)
			{
				case 0 :
					WriteLabelProlog(cupsGetOption("page-label", num_options, options),
						PageBottom, PageTop, PageWidth);
				break;

				case 1 :
					WriteLabelProlog(cupsGetOption("page-label", num_options, options),
						 PageLeft, PageRight, PageLength);
				break;

				case 2 :
					WriteLabelProlog(cupsGetOption("page-label", num_options, options),
						 PageLength - PageTop, PageLength - PageBottom, PageWidth);
				break;

				case 3 :
					WriteLabelProlog(cupsGetOption("page-label", num_options, options),
						 PageWidth - PageRight, PageWidth - PageLeft,PageLength);
				break;
			}

			if (realcopies > 1)
			{
				if (ppd == NULL || ppd->language_level == 1)
					printf("/#copies %d def\n", realcopies);
				else
					printf("<</NumCopies %d>>setpagedevice\n", realcopies);
			}

			puts("%%EndProlog");
		}
		/*
		* Output the pages...
		*/

		row = malloc(cupsImageGetWidth(img) * abs(colorspace) + 3);

		fprintf(stderr, "DEBUG: XPosition=%d, YPosition=%d, Orientation=%d\n",XPosition, YPosition, Orientation);
		fprintf(stderr, "DEBUG: xprint=%.0f, yprint=%.0f\n", xprint, yprint);
		fprintf(stderr, "DEBUG: PageLeft=%.0f, PageRight=%.0f, PageWidth=%.0f\n",PageLeft, PageRight, PageWidth);
		fprintf(stderr, "DEBUG: PageBottom=%.0f, PageTop=%.0f, PageLength=%.0f\n",PageBottom, PageTop, PageLength);

		switch (Orientation)
		{
			default :
				switch (XPosition)
				{
					case -1 :
						left = PageLeft;
					break;
					default :
						left = (PageRight + PageLeft - xprint * 72) / 2;
					break;
					case 1 :
						left = PageRight - xprint * 72;
					break;
				}

				switch (YPosition)
				{
					case -1 :
						top = PageBottom + yprint * 72;
					break;
					default :
						top = (PageTop + PageBottom + yprint * 72) / 2;
					break;
					case 1 :
						top = PageTop;
					break;
				}
			break;

			case 1 :
				switch (XPosition)
				{
					case -1 :
						left = PageBottom;
					break;
					default :
						left = (PageTop + PageBottom - xprint * 72) / 2;
					break;
					case 1 :
						left = PageTop - xprint * 72;
					break;
				}

				switch (YPosition)
				{
					case -1 :
						top = PageLeft + yprint * 72;
					break;
					default :
						top = (PageRight + PageLeft + yprint * 72) / 2;
					break;
					case 1 :
						top = PageRight;
					break;
				}
			break;

			case 2 :
				switch (XPosition)
				{
					case 1 :
						left = PageLeft;
					break;
					default :
						left = (PageRight + PageLeft - xprint * 72) / 2;
					break;
					case -1 :
						left = PageRight - xprint * 72;
					break;
				}

				switch (YPosition)
				{
					case 1 :
						top = PageBottom + yprint * 72;
					break;
					default :
						top = (PageTop + PageBottom + yprint * 72) / 2;
					break;
					case -1 :
						top = PageTop;
					break;
				}
			break;

			case 3 :
				switch (XPosition)
				{
					case 1 :
						left = PageBottom;
					break;
					default :
						left = (PageTop + PageBottom - xprint * 72) / 2;
					break;
					case -1 :
						left = PageTop - xprint * 72;
					break;
				}

				switch (YPosition)
				{
					case 1 :
						top = PageLeft + yprint * 72;
					break;
					default :
						top = (PageRight + PageLeft + yprint * 72) / 2;
					break;
					case -1 :
						top = PageRight;
					break;
				}
			break;
		}

		fprintf(stderr, "DEBUG: left=%.2f, top=%.2f\n", left, top);
		
		for (page = 1; Copies > 0; Copies --)
			for (xpage = 0; xpage < xpages; xpage ++)
				for (ypage = 0; ypage < ypages; ypage ++, page ++)
				{
					if (ppd && ppd->num_filters == 0)
						fprintf(stderr, "PAGE: %d %d\n", page, realcopies);

					_cupsLangPrintFilter(stderr, "INFO", _("Printing page %d."), page);

					printf("%%%%Page: %d %d\n", (page * (count+1)), (page*(count+1)));
					//TEST_TODO
					if(count>=1){
						puts("%%BeginPageSetup");
						if (Orientation & 1)
							puts("%%PageOrientation: Landscape");
						else
							puts("%%PageOrientation: Portrait");
						puts("%%EndPageSetup");
					}
					ppdEmit(ppd, stdout, PPD_ORDER_PAGE);

					puts("gsave");

					if (Flip)
						printf("%.0f 0 translate -1 1 scale\n", PageWidth);

					switch (Orientation)
					{
						case 1 : /* Landscape */
							printf("%.0f 0 translate 90 rotate\n", PageWidth);
						break;
						case 2 : /* Reverse Portrait */
							printf("%.0f %.0f translate 180 rotate\n", PageWidth, PageLength);
						break;
						case 3 : /* Reverse Landscape */
							printf("0 %.0f translate -90 rotate\n", PageLength);
						break;
					}

					puts("gsave");

					xc0 = cupsImageGetWidth(img) * xpage / xpages;
					xc1 = cupsImageGetWidth(img) * (xpage + 1) / xpages - 1;
					yc0 = cupsImageGetHeight(img) * ypage / ypages;
					yc1 = cupsImageGetHeight(img) * (ypage + 1) / ypages - 1;

					printf("%.1f %.1f translate\n", left, top);

					printf("%.3f %.3f scale\n\n",xprint * 72.0 / (xc1 - xc0 + 1),yprint * 72.0 / (yc1 - yc0 + 1));

					if (LanguageLevel == 1)
					{
						printf("/picture %d string def\n", (xc1 - xc0 + 1) * abs(colorspace));
						printf("%d %d 8[1 0 0 -1 0 1]", (xc1 - xc0 + 1), (yc1 - yc0 + 1));

						if (colorspace == CUPS_IMAGE_WHITE)
							puts("{currentfile picture readhexstring pop} image");
						else
							printf("{currentfile picture readhexstring pop} false %d colorimage\n",abs(colorspace));

						for (y = yc0; y <= yc1; y ++)
						{
							cupsImageGetRow(img, xc0, y, xc1 - xc0 + 1, row);
							ps_hex(row, (xc1 - xc0 + 1) * abs(colorspace), y == yc1);
						}
					}
					else
					{
						switch (colorspace)
						{
							case CUPS_IMAGE_WHITE :
								puts("/DeviceGray setcolorspace");
							break;
							case CUPS_IMAGE_RGB :
								puts("/DeviceRGB setcolorspace");
							break;
							case CUPS_IMAGE_CMYK :
								puts("/DeviceCMYK setcolorspace");
							break;
						}

						printf("<<"
							"/ImageType 1"
							"/Width %d"
							"/Height %d"
							"/BitsPerComponent 8",
							xc1 - xc0 + 1, yc1 - yc0 + 1);

						switch (colorspace)
						{
							case CUPS_IMAGE_WHITE :
								fputs("/Decode[0 1]", stdout);
							break;
							case CUPS_IMAGE_RGB :
								fputs("/Decode[0 1 0 1 0 1]", stdout);
							break;
							case CUPS_IMAGE_CMYK :
								fputs("/Decode[0 1 0 1 0 1 0 1]", stdout);
							break;
						}

						fputs("\n/DataSource currentfile/ASCII85Decode filter", stdout);

						if (((xc1 - xc0 + 1) / xprint) < 100.0)
							fputs("/Interpolate true", stdout);

						puts("/ImageMatrix[1 0 0 -1 0 1]>>image");

						for (y = yc0, out_offset = 0; y <= yc1; y ++)
						{
							cupsImageGetRow(img, xc0, y, xc1 - xc0 + 1, row + out_offset);

							out_length = (xc1 - xc0 + 1) * abs(colorspace) + out_offset;
							out_offset = out_length & 3;

							ps_ascii85(row, out_length, y == yc1);

							if (out_offset > 0)
								memcpy(row, row + out_length - out_offset, out_offset);
						}
					}

					if(count==1){
						puts("grestore");
						WriteLabels(0);
						puts("grestore");
					}
					puts("showpage");
					puts("%%PageTrailer");
				}
		
	} //end of big for loop
  
   
   	puts("%%EOF");
 
	/*
	* End the job with the appropriate JCL command or CTRL-D otherwise.
	*/

	if (emit_jcl)
	{
		if (ppd && ppd->jcl_end)
			ppdEmitJCLEnd(ppd, stdout);
		else
		putchar(0x04);
	}

	fflush(stdout);
	dup2(defout,1);
	close(outfd);
	close(defout);

	/*
	* Close files...
	*/
	LOGI("imagetops:Close files");
	cupsImageClose(img);
	ppdClose(ppd);

  return (0);
}