diff options
Diffstat (limited to 'kdeprint/cups')
118 files changed, 15449 insertions, 0 deletions
diff --git a/kdeprint/cups/Makefile.am b/kdeprint/cups/Makefile.am new file mode 100644 index 000000000..60bd22c08 --- /dev/null +++ b/kdeprint/cups/Makefile.am @@ -0,0 +1,49 @@ +AM_CPPFLAGS = -D_KDEPRINT_COMPILE + +SUBDIRS = cupsdconf2 + +INCLUDES= -I$(top_srcdir) -I$(top_srcdir)/kio -I$(top_srcdir)/kfile -I$(top_srcdir)/kdeprint -I$(top_srcdir)/kdeprint/management -I$(top_srcdir)/kdecore/network $(all_includes) + +kde_module_LTLIBRARIES = kdeprint_cups.la + +kdeprint_cups_la_SOURCES = cupsinfos.cpp ipprequest.cpp kmcupsfactory.cpp kmcupsjobmanager.cpp \ + kmcupsmanager.cpp kmcupsuimanager.cpp kmpropbanners.cpp kmwbanners.cpp kmwipp.cpp \ + kmwippselect.cpp kcupsprinterimpl.cpp kmcupsconfigwidget.cpp \ + kmconfigcups.cpp kmconfigcupsdir.cpp kmwippprinter.cpp kmwfax.cpp kmwquota.cpp \ + kmpropquota.cpp kmwusers.cpp kmpropusers.cpp kpschedulepage.cpp image.cpp \ + imagepreview.cpp imageposition.cpp kpimagepage.cpp \ + kptextpage.cpp kphpgl2page.cpp cupsaddsmb2.cpp kmwother.cpp ippreportdlg.cpp \ + kptagspage.cpp +kdeprint_cups_la_LDFLAGS = $(all_libraries) -module -avoid-version -no-undefined +kdeprint_cups_la_LIBADD = $(top_builddir)/kdeprint/management/libkdeprint_management.la $(LIB_KIO) $(LIB_CUPS) $(top_builddir)/kdecore/libkdefakes.la +kdeprint_cups_la_METASOURCES = AUTO + +noinst_HEADERS = cupsinfos.h ipprequest.h kmcupsjobmanager.h kmcupsmanager.h kmcupsuimanager.h \ + kmpropbanners.h kmwbanners.h kmwipp.h kmwippselect.h kcupsprinterimpl.h \ + kmcupsconfigwidget.h kmconfigcups.h kmconfigcupsdir.h kmwippprinter.h kmwfax.h kmwquota.h \ + kmpropquota.h kmwusers.h kmpropusers.h kpschedulepage.h imagepreview.h imageposition.h \ + kpimagepage.h kptextpage.h kphpgl2page.h cupsaddsmb2.h \ + kmwother.h ippreportdlg.h kptagspage.h + +bin_PROGRAMS = make_driver_db_cups cupsdoprint +make_driver_db_cups_SOURCES = make_driver_db_cups.c +make_driver_db_cups_LDADD = ../libdriverparse.a $(top_builddir)/kdecore/libkdefakes.la $(LIBDL) $(LIBZ) +make_driver_db_cups_LDFLAGS = $(all_libraries) + +cupsdoprint_SOURCES = cupsdoprint.c +cupsdoprint_LDADD = $(LIB_CUPS) $(top_builddir)/kdecore/libkdefakes.la +cupsdoprint_LDFLAGS = $(all_libraries) + +entry_DATA = cups.print +entrydir = $(kde_datadir)/kdeprint/plugins + +misc_DATA = preview.png preview-mini.png +miscdir = $(kde_datadir)/kdeprint + +EXTRA_DIST = postscript.ppd.gz + +install-data-local: + if test -n "$(cups_modeldir)"; then \ + $(INSTALL_DATA) $(srcdir)/postscript.ppd.gz $(DESTDIR)$(cups_modeldir)/postscript.ppd.gz || true ;\ + fi + diff --git a/kdeprint/cups/configure.in.in b/kdeprint/cups/configure.in.in new file mode 100644 index 000000000..b37ba67a1 --- /dev/null +++ b/kdeprint/cups/configure.in.in @@ -0,0 +1,18 @@ +dnl Whether to install the PostScript driver +AC_MSG_CHECKING([installation of PS driver needed]) +ac_cups_share_test="/usr/share/cups /usr/local/share/cups /opt/share/cups /opt/local/share/cups" +cups_modeldir="" +for d in $ac_cups_share_test; do + if test -d $d && test -d $d/model; then + cups_modeldir=$d/model + break + fi +done + +AC_SUBST(cups_modeldir) + +if test -n "$cups_modeldir"; then + AC_MSG_RESULT(yes) +else + AC_MSG_RESULT(no) +fi diff --git a/kdeprint/cups/cups.print b/kdeprint/cups/cups.print new file mode 100644 index 000000000..03b2474ee --- /dev/null +++ b/kdeprint/cups/cups.print @@ -0,0 +1,68 @@ +[KDE Print Entry] +PrintSystem=cups +Comment=CUPS (Common UNIX Print System) +Comment[af]=Cups (Gemeenskaplike Unix Druk Stelsel) +Comment[ar]=CUPS (نظام طباعة يونيكس الشائع) +Comment[az]=CUPS (Ümumi UNIX Çap Sistemi) +Comment[be]=CUPS (Агульная сістэма друку UNIX) +Comment[bn]=কাপ্স (Common UNIX Print System) +Comment[ca]=CUPS (Sistema d'impressió comú de Unix) +Comment[cs]=CUPS (Common Unix Print System) +Comment[csb]=CUPS (Zbiérnô Systema Drëkù dlô Uniksa) +Comment[cy]=CUPS (Cysawd Argraffu UNIX Cyffredinol) +Comment[da]=CUPS (Common UNIX Print System = Fælles UNIX-udskriftssystem) +Comment[el]=CUPS (Κοινό σύστημα εκτύπωσης του UNIX) +Comment[eo]=CUPS (Kapabla Uniks-pressistemo) +Comment[es]=CUPS (sistema de impresión común para Unix) +Comment[eu]=CUPS (Common UNIX Print System) +Comment[fa]=CUPS)سیستم چاپ مشترک یونیکس( +Comment[fr]=CUPS (Common Unix Print System) +Comment[fy]=CUPS (Common Unix Print System) +Comment[gl]=CUPS (Sistema Comun de Impresión para UNIX) +Comment[he]=מערכת הדפסה נפוצה ליוניקס (CUPS) +Comment[hi]=CUPS (सामान्य यूनिक्स प्रिंट सिस्टम) +Comment[hr]=CUPS (Common Unix Print System) +Comment[is]=CUPS (Common Unix Print System) +Comment[ja]=CUPS (Common UNIX Printing System) +Comment[ka]=CUPS (საერთო Unix ბეჭდვის სიტემა) +Comment[kk]=CUPS (Common UNIX Print System) басып шығару жүйесі +Comment[ko]=CUPS (공통 유닉스 인쇄 시스템) +Comment[lt]=CUPS (Bendra Unix Spausdinimo Sistema) +Comment[mn]=CUPS (Юниксын Ерөнхий Хэвлэх Систем) +Comment[mt]=CUPS (Common Unix Print System) +Comment[ne]=CUPS (साझा UNIX मुद्रण प्रणाली) +Comment[nn]=CUPS («Common Unix Print System», utskriftssystem) +Comment[nso]=CUPS (System yago Swana ya Kgatiso ya UNIX) +Comment[pa]=CUPS (ਕਾਮਨ UNIX ਪ੍ਰਿੰਟਰ ਸਿਸਟਮ) +Comment[pl]=CUPS (Wspólny System Drukowania dla Uniksa) +Comment[pt]=CUPS (Common Unix Print System) +Comment[pt_BR]=Servidor de Impressão CUPS (Common Unix Print System) +Comment[ro]=CUPS (Sistem de tipărire Unix comun) +Comment[ru]=Система печати CUPS (Common Unix Print System) +Comment[rw]=CUPS (Sisitemu Rusange yo Gucapa ya UNIX ) +Comment[se]=CUPS («Common Unix Print System», čálihanvuogádat) +Comment[sl]=CUPS (skupni tiskalniški sistem za Unix) +Comment[sr]=CUPS (Common Unix Print System) +Comment[sr@Latn]=CUPS (Common Unix Print System) +Comment[ss]=CUPS (Umshini lovamile wekushicelela we UNIX) +Comment[sv]=Cups (Common Unix print system) +Comment[ta]=CUPS (பொது யுனிக்ஸ் அச்சுத் தொகுதி) +Comment[te]=కెయుపిఎస్ (సామాన్య యునిక్స్ ప్రచురణ వ్యవస్థ) +Comment[tg]=Системаи чопи CUPS (Common UNIX Print System) +Comment[th]=CUPS (ระบบการพิมพ์พื้นฐานของยูนิกซ์) +Comment[tr]=CUPS (Common Unix Print System - Genel Unix Yazdırma Sistemi) +Comment[tt]=CUPS atlı bastıru sisteme (Common UNIX Print System) +Comment[uz]=CUPS (UNIX uchun umumiy bosib chiqarish tizimi) +Comment[uz@cyrillic]=CUPS (UNIX учун умумий босиб чиқариш тизими) +Comment[ven]=CUPS (Maitele au phirintha a UNIX zwao) +Comment[vi]=CUPS (hệ thống in UNIX dùng chung) +Comment[wa]=CUPS (Comon Sistinme d' Imprimaedje po UNIX) +Comment[xh]=CUPS (Indlela Elula Yoshicilelo lwe UNIX) +Comment[zh_CN]=CUPS (通用 Unix 打印系统) +Comment[zh_HK]=CUPS (通用 Unix 列印系統) +Comment[zh_TW]=CUPS (通用 Unix 列印系統) +Comment[zu]=CUPS (Isistimu Yokushicilela ye-Unix Eyejwayelekile) +DetectUris=service:/ipp,config:/cups/cupsd.conf +DetectPrecedence=10 +MimeTypes=application/postscript,application/pdf,image/gif,image/jpeg,image/png,image/x-bmp,image/x-xpm +PrimaryMimeType=application/postscript diff --git a/kdeprint/cups/cupsaddsmb2.cpp b/kdeprint/cups/cupsaddsmb2.cpp new file mode 100644 index 000000000..993a72c9b --- /dev/null +++ b/kdeprint/cups/cupsaddsmb2.cpp @@ -0,0 +1,476 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "cupsaddsmb2.h" +#include "cupsinfos.h" +#include "sidepixmap.h" + +#include <qtimer.h> +#include <qprogressbar.h> +#include <qlabel.h> +#include <qlayout.h> +#include <qlineedit.h> +#include <klocale.h> +#include <kmessagebox.h> +#include <qmessagebox.h> +#include <qfile.h> +#include <kio/passdlg.h> +#include <kdebug.h> +#include <kseparator.h> +#include <kactivelabel.h> +#include <qwhatsthis.h> +#include <kpushbutton.h> +#include <kstdguiitem.h> + +#include <cups/cups.h> +#include <ctype.h> + +CupsAddSmb::CupsAddSmb(QWidget *parent, const char *name) +: KDialog(parent, name) +{ + m_state = None; + m_status = false; + m_actionindex = 0; + connect(&m_proc, SIGNAL(receivedStdout(KProcess*,char*,int)), SLOT(slotReceived(KProcess*,char*,int))); + connect(&m_proc, SIGNAL(receivedStderr(KProcess*,char*,int)), SLOT(slotReceived(KProcess*,char*,int))); + connect(&m_proc, SIGNAL(processExited(KProcess*)), SLOT(slotProcessExited(KProcess*))); + + m_side = new SidePixmap(this); + m_doit = new QPushButton(i18n("&Export"), this); + m_cancel = new KPushButton(KStdGuiItem::cancel(), this); + connect(m_cancel, SIGNAL(clicked()), SLOT(reject())); + connect(m_doit, SIGNAL(clicked()), SLOT(slotActionClicked())); + m_bar = new QProgressBar(this); + m_text = new KActiveLabel(this); + QLabel *m_title = new QLabel(i18n("Export Printer Driver to Windows Clients"), this); + setCaption(m_title->text()); + QFont f(m_title->font()); + f.setBold(true); + m_title->setFont(f); + KSeparator *m_sep = new KSeparator(Qt::Horizontal, this); + m_textinfo = new QLabel( this ); + m_logined = new QLineEdit( this ); + m_passwded = new QLineEdit( this ); + m_passwded->setEchoMode( QLineEdit::Password ); + m_servered = new QLineEdit( this ); + QLabel *m_loginlab = new QLabel( i18n( "&Username:" ), this ); + QLabel *m_serverlab = new QLabel( i18n( "&Samba server:" ), this ); + QLabel *m_passwdlab = new QLabel( i18n( "&Password:" ), this ); + m_loginlab->setBuddy( m_logined ); + m_serverlab->setBuddy( m_servered ); + m_passwdlab->setBuddy( m_passwded ); + + QString txt = i18n( "<p><b>Samba server</b></p>" + "Adobe Windows PostScript driver files plus the CUPS printer PPD will be " + "exported to the <tt>[print$]</tt> special share of the Samba server (to change " + "the source CUPS server, use the <nobr><i>Configure Manager -> CUPS server</i></nobr> first). " + "The <tt>[print$]</tt> share must exist on the Samba side prior to clicking the " + "<b>Export</b> button below." ); + QWhatsThis::add( m_serverlab, txt ); + QWhatsThis::add( m_servered, txt ); + + txt = i18n( "<p><b>Samba username</b></p>" + "User needs to have write access to the <tt>[print$]</tt> share on the Samba server. " + "<tt>[print$]</tt> holds printer drivers prepared for download to Windows clients. " + "This dialog does not work for Samba servers configured with <tt>security = share</tt> " + "(but works fine with <tt>security = user</tt>)." ); + QWhatsThis::add( m_loginlab, txt ); + QWhatsThis::add( m_logined, txt ); + + txt = i18n( "<p><b>Samba password</b></p>" + "The Samba setting <tt>encrypt passwords = yes</tt> " + "(default) requires prior use of <tt>smbpasswd -a [username]</tt> command, " + "to create an encrypted Samba password and have Samba recognize it." ); + QWhatsThis::add( m_passwdlab, txt ); + QWhatsThis::add( m_passwded, txt ); + + QHBoxLayout *l0 = new QHBoxLayout(this, 10, 10); + QVBoxLayout *l1 = new QVBoxLayout(0, 0, 10); + l0->addWidget(m_side); + l0->addLayout(l1); + l1->addWidget(m_title); + l1->addWidget(m_sep); + l1->addWidget(m_text); + QGridLayout *l3 = new QGridLayout( 0, 3, 2, 0, 10 ); + l1->addLayout( l3 ); + l3->addWidget( m_loginlab, 1, 0 ); + l3->addWidget( m_passwdlab, 2, 0 ); + l3->addWidget( m_serverlab, 0, 0 ); + l3->addWidget( m_logined, 1, 1 ); + l3->addWidget( m_passwded, 2, 1 ); + l3->addWidget( m_servered, 0, 1 ); + l3->setColStretch( 1, 1 ); + l1->addSpacing( 10 ); + l1->addWidget(m_bar); + l1->addWidget( m_textinfo ); + l1->addSpacing(30); + QHBoxLayout *l2 = new QHBoxLayout(0, 0, 10); + l1->addLayout(l2); + l2->addStretch(1); + l2->addWidget(m_doit); + l2->addWidget(m_cancel); + + m_logined->setText( CupsInfos::self()->login() ); + m_passwded->setText( CupsInfos::self()->password() ); + m_servered->setText( cupsServer() ); + + setMinimumHeight(400); +} + +CupsAddSmb::~CupsAddSmb() +{ +} + +void CupsAddSmb::slotActionClicked() +{ + if (m_state == None) + doExport(); + else if (m_proc.isRunning()) + m_proc.kill(); +} + +void CupsAddSmb::slotReceived(KProcess*, char *buf, int buflen) +{ + QString line; + int index(0); + bool partial(false); + static bool incomplete(false); + + kdDebug(500) << "slotReceived()" << endl; + while (1) + { + // read a line + line = QString::fromLatin1(""); + partial = true; + while (index < buflen) + { + QChar c(buf[index++]); + if (c == '\n') + { + partial = false; + break; + } + else if (c.isPrint()) + line += c; + } + + if (line.isEmpty()) + { + kdDebug(500) << "NOTHING TO READ" << endl; + return; + } + + kdDebug(500) << "ANSWER = " << line << " (END = " << line.length() << ")" << endl; + if (!partial) + { + if (incomplete && m_buffer.count() > 0) + m_buffer[m_buffer.size()-1].append(line); + else + m_buffer << line; + incomplete = false; + kdDebug(500) << "COMPLETE LINE READ (" << m_buffer.count() << ")" << endl; + } + else + { + if (line.startsWith("smb:") || line.startsWith("rpcclient $")) + { + kdDebug(500) << "END OF ACTION" << endl; + checkActionStatus(); + if (m_status) + nextAction(); + else + { + // quit program + kdDebug(500) << "EXITING PROGRAM..." << endl; + m_proc.writeStdin("quit\n", 5); + kdDebug(500) << "SENT" << endl; + } + return; + } + else + { + if (incomplete && m_buffer.count() > 0) + m_buffer[m_buffer.size()-1].append(line); + else + m_buffer << line; + incomplete = true; + kdDebug(500) << "INCOMPLETE LINE READ (" << m_buffer.count() << ")" << endl; + } + } + } +} + +void CupsAddSmb::checkActionStatus() +{ + m_status = false; + // when checking the status, we need to take into account the + // echo of the command in the output buffer. + switch (m_state) + { + case None: + case Start: + m_status = true; + break; + case Copy: + m_status = (m_buffer.count() == 0); + break; + case MkDir: + m_status = (m_buffer.count() == 1 || m_buffer[1].find("ERRfilexists") != -1); + break; + case AddDriver: + case AddPrinter: + m_status = (m_buffer.count() == 1 || !m_buffer[1].startsWith("result")); + break; + } + kdDebug(500) << "ACTION STATUS = " << m_status << endl; +} + +void CupsAddSmb::nextAction() +{ + if (m_actionindex < (int)(m_actions.count())) + QTimer::singleShot(1, this, SLOT(doNextAction())); +} + +void CupsAddSmb::doNextAction() +{ + m_buffer.clear(); + m_state = None; + if (m_proc.isRunning()) + { + QCString s = m_actions[m_actionindex++].latin1(); + m_bar->setProgress(m_bar->progress()+1); + kdDebug(500) << "NEXT ACTION = " << s << endl; + if (s == "quit") + { + // do nothing + } + else if (s == "mkdir") + { + m_state = MkDir; + //m_text->setText(i18n("Creating directory %1").arg(m_actions[m_actionindex])); + m_textinfo->setText(i18n("Creating folder %1").arg(m_actions[m_actionindex])); + s.append(" ").append(m_actions[m_actionindex].latin1()); + m_actionindex++; + } + else if (s == "put") + { + m_state = Copy; + //m_text->setText(i18n("Uploading %1").arg(m_actions[m_actionindex+1])); + m_textinfo->setText(i18n("Uploading %1").arg(m_actions[m_actionindex+1])); + s.append(" ").append(QFile::encodeName(m_actions[m_actionindex]).data()).append(" ").append(m_actions[m_actionindex+1].latin1()); + m_actionindex += 2; + } + else if (s == "adddriver") + { + m_state = AddDriver; + //m_text->setText(i18n("Installing driver for %1").arg(m_actions[m_actionindex])); + m_textinfo->setText(i18n("Installing driver for %1").arg(m_actions[m_actionindex])); + s.append(" \"").append(m_actions[m_actionindex].latin1()).append("\" \"").append(m_actions[m_actionindex+1].latin1()).append("\""); + m_actionindex += 2; + } + else if (s == "addprinter" || s == "setdriver") + { + m_state = AddPrinter; + //m_text->setText(i18n("Installing printer %1").arg(m_actions[m_actionindex])); + m_textinfo->setText(i18n("Installing printer %1").arg(m_actions[m_actionindex])); + QCString dest = m_actions[m_actionindex].local8Bit(); + if (s == "addprinter") + s.append(" ").append(dest).append(" ").append(dest).append(" \"").append(dest).append("\" \"\""); + else + s.append(" ").append(dest).append(" ").append(dest); + m_actionindex++; + } + else + { + kdDebug(500) << "ACTION = unknown action" << endl; + m_proc.kill(); + return; + } + // send action + kdDebug(500) << "ACTION = " << s << endl; + s.append("\n"); + m_proc.writeStdin(s.data(), s.length()); + } +} + +void CupsAddSmb::slotProcessExited(KProcess*) +{ + kdDebug(500) << "PROCESS EXITED (" << m_state << ")" << endl; + if (m_proc.normalExit() && m_state != Start && m_status) + { + // last process went OK. If it was smbclient, then switch to rpcclient + if (qstrncmp(m_proc.args().first(), "smbclient", 9) == 0) + { + doInstall(); + return; + } + else + { + m_doit->setEnabled(false); + m_cancel->setEnabled(true); + m_cancel->setText(i18n("&Close")); + m_cancel->setDefault(true); + m_cancel->setFocus(); + m_logined->setEnabled( true ); + m_servered->setEnabled( true ); + m_passwded->setEnabled( true ); + m_text->setText(i18n("Driver successfully exported.")); + m_bar->reset(); + m_textinfo->setText( QString::null ); + return; + } + } + + if (m_proc.normalExit()) + { + showError( + i18n("Operation failed. Possible reasons are: permission denied " + "or invalid Samba configuration (see <a href=\"man:/cupsaddsmb\">" + "cupsaddsmb</a> manual page for detailed information, you need " + "<a href=\"http://www.cups.org\">CUPS</a> version 1.1.11 or higher). " + "You may want to try again with another login/password.")); + + } + else + { + showError(i18n("Operation aborted (process killed).")); + } +} + +void CupsAddSmb::showError(const QString& msg) +{ + m_text->setText(i18n("<h3>Operation failed.</h3><p>%1</p>").arg(msg)); + m_cancel->setEnabled(true); + m_logined->setEnabled( true ); + m_servered->setEnabled( true ); + m_passwded->setEnabled( true ); + m_doit->setText(i18n("&Export")); + m_state = None; +} + +bool CupsAddSmb::exportDest(const QString &dest, const QString& datadir) +{ + CupsAddSmb dlg; + dlg.m_dest = dest; + dlg.m_datadir = datadir; + dlg.m_text->setText( + i18n( "You are about to prepare the <b>%1</b> driver to be " + "shared out to Windows clients through Samba. This operation " + "requires the <a href=\"http://www.adobe.com/products/printerdrivers/main.html\">Adobe PostScript Driver</a>, a recent version of " + "Samba 2.2.x and a running SMB service on the target server. " + "Click <b>Export</b> to start the operation. Read the <a href=\"man:/cupsaddsmb\">cupsaddsmb</a> " + "manual page in Konqueror or type <tt>man cupsaddsmb</tt> in a " + "console window to learn more about this functionality." ).arg( dest ) ); + dlg.exec(); + return dlg.m_status; +} + +bool CupsAddSmb::doExport() +{ + m_status = false; + m_state = None; + + if (!QFile::exists(m_datadir+"/drivers/ADOBEPS5.DLL") || + !QFile::exists(m_datadir+"/drivers/ADOBEPS4.DRV")) + { + showError( + i18n("Some driver files are missing. You can get them on " + "<a href=\"http://www.adobe.com\">Adobe</a> web site. " + "See <a href=\"man:/cupsaddsmb\">cupsaddsmb</a> manual " + "page for more details (you need <a href=\"http://www.cups.org\">CUPS</a> " + "version 1.1.11 or higher).")); + return false; + } + + m_bar->setTotalSteps(18); + m_bar->setProgress(0); + //m_text->setText(i18n("<p>Preparing to upload driver to host <b>%1</b>").arg(m_servered->text())); + m_textinfo->setText(i18n("Preparing to upload driver to host %1").arg(m_servered->text())); + m_cancel->setEnabled(false); + m_logined->setEnabled( false ); + m_servered->setEnabled( false ); + m_passwded->setEnabled( false ); + m_doit->setText(i18n("&Abort")); + + const char *ppdfile; + + if ((ppdfile = cupsGetPPD(m_dest.local8Bit())) == NULL) + { + showError(i18n("The driver for printer <b>%1</b> could not be found.").arg(m_dest)); + return false; + } + + m_actions.clear(); + m_actions << "mkdir" << "W32X86"; + m_actions << "put" << ppdfile << "W32X86/"+m_dest+".PPD"; + m_actions << "put" << m_datadir+"/drivers/ADOBEPS5.DLL" << "W32X86/ADOBEPS5.DLL"; + m_actions << "put" << m_datadir+"/drivers/ADOBEPSU.DLL" << "W32X86/ADOBEPSU.DLL"; + m_actions << "put" << m_datadir+"/drivers/ADOBEPSU.HLP" << "W32X86/ADOBEPSU.HLP"; + m_actions << "mkdir" << "WIN40"; + m_actions << "put" << ppdfile << "WIN40/"+m_dest+".PPD"; + m_actions << "put" << m_datadir+"/drivers/ADFONTS.MFM" << "WIN40/ADFONTS.MFM"; + m_actions << "put" << m_datadir+"/drivers/ADOBEPS4.DRV" << "WIN40/ADOBEPS4.DRV"; + m_actions << "put" << m_datadir+"/drivers/ADOBEPS4.HLP" << "WIN40/ADOBEPS4.HLP"; + m_actions << "put" << m_datadir+"/drivers/DEFPRTR2.PPD" << "WIN40/DEFPRTR2.PPD"; + m_actions << "put" << m_datadir+"/drivers/ICONLIB.DLL" << "WIN40/ICONLIB.DLL"; + m_actions << "put" << m_datadir+"/drivers/PSMON.DLL" << "WIN40/PSMON.DLL"; + m_actions << "quit"; + + m_proc.clearArguments(); + m_proc << "smbclient" << QString::fromLatin1("//")+m_servered->text()+"/print$"; + return startProcess(); +} + +bool CupsAddSmb::doInstall() +{ + m_status = false; + m_state = None; + + m_actions.clear(); + m_actions << "adddriver" << "Windows NT x86" << m_dest+":ADOBEPS5.DLL:"+m_dest+".PPD:ADOBEPSU.DLL:ADOBEPSU.HLP:NULL:RAW:NULL"; + // seems to be wrong with newer versions of Samba + //m_actions << "addprinter" << m_dest; + m_actions << "adddriver" << "Windows 4.0" << m_dest+":ADOBEPS4.DRV:"+m_dest+".PPD:NULL:ADOBEPS4.HLP:PSMON.DLL:RAW:ADFONTS.MFM,DEFPRTR2.PPD,ICONLIB.DLL"; + // seems to be ok with newer versions of Samba + m_actions << "setdriver" << m_dest; + m_actions << "quit"; + + //m_text->setText(i18n("Preparing to install driver on host <b>%1</b>").arg(m_servered->text())); + m_textinfo->setText(i18n("Preparing to install driver on host %1").arg(m_servered->text())); + + m_proc.clearArguments(); + m_proc << "rpcclient" << m_servered->text(); + return startProcess(); +} + +bool CupsAddSmb::startProcess() +{ + m_proc << "-d" << "0" << "-N" << "-U"; + if (m_passwded->text().isEmpty()) + m_proc << m_logined->text(); + else + m_proc << m_logined->text()+"%"+m_passwded->text(); + m_state = Start; + m_actionindex = 0; + m_buffer.clear(); + kdDebug(500) << "PROCESS STARTED = " << m_proc.args()[0] << endl; + return m_proc.start(KProcess::NotifyOnExit, KProcess::All); +} + +#include "cupsaddsmb2.moc" diff --git a/kdeprint/cups/cupsaddsmb2.h b/kdeprint/cups/cupsaddsmb2.h new file mode 100644 index 000000000..1f364fc26 --- /dev/null +++ b/kdeprint/cups/cupsaddsmb2.h @@ -0,0 +1,77 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef CUPSADDSMB_H +#define CUPSADDSMB_H + +#include <qobject.h> +#include <qstringlist.h> +#include <kprocess.h> +#include <kdialog.h> + +class QProgressBar; +class SidePixmap; +class QPushButton; +class QLabel; +class KActiveLabel; +class QLineEdit; + +class CupsAddSmb : public KDialog +{ + Q_OBJECT + +public: + enum State { None, Start, MkDir, Copy, AddDriver, AddPrinter }; + CupsAddSmb(QWidget *parent = 0, const char *name = 0); + ~CupsAddSmb(); + + static bool exportDest(const QString& dest, const QString& datadir); + +protected slots: + void slotReceived(KProcess*, char*, int); + void doNextAction(); + void slotProcessExited(KProcess*); + void slotActionClicked(); + +protected: + void checkActionStatus(); + void nextAction(); + bool startProcess(); + bool doExport(); + bool doInstall(); + void showError(const QString& msg); + +private: + KProcess m_proc; + QStringList m_buffer; + int m_state; + QStringList m_actions; + int m_actionindex; + bool m_status; + QProgressBar *m_bar; + QString m_dest; + SidePixmap *m_side; + QPushButton *m_doit, *m_cancel; + KActiveLabel *m_text; + QLabel *m_textinfo; + QLineEdit *m_logined, *m_passwded, *m_servered; + QString m_datadir; +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/Makefile.am b/kdeprint/cups/cupsdconf2/Makefile.am new file mode 100644 index 000000000..84c68ae98 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/Makefile.am @@ -0,0 +1,35 @@ +#$Id$ + +INCLUDES= -I$(top_srcdir) -I$(top_srcdir)/kio -I$(top_srcdir)/kfile $(all_includes) + +bin_PROGRAMS = +lib_LTLIBRARIES = +kdeinit_LTLIBRARIES = cupsdconf.la + +# library creation +cupsdconf_la_SOURCES = cupsdconf.cpp cupsddialog.cpp cupsdpage.cpp cupsdcomment.cpp cupsdsplash.cpp \ + cupsdserverpage.cpp cupsdlogpage.cpp cupsdjobspage.cpp cupsdfilterpage.cpp \ + qdirlineedit.cpp cupsddirpage.cpp portdialog.cpp cupsdnetworkpage.cpp \ + editlist.cpp cupsdbrowsingpage.cpp browsedialog.cpp cupsdsecuritypage.cpp \ + locationdialog.cpp addressdialog.cpp cups-util.c \ + qdirmultilineedit.cpp sizewidget.cpp main.cpp +cupsdconf_la_METASOURCES = AUTO +cupsdconf_la_LDFLAGS = -avoid-version -module $(all_libraries) $(KDE_RPATH) +cupsdconf_la_LIBADD = $(LIB_KIO) $(LIB_CUPS) + +noinst_HEADERS = cupsdconf.h cupsdpage.h cupsddialog.h cupsdcomment.h cupsdsplash.h \ + cupsdserverpage.h cupsdlogpage.h cupsdjobspage.h cupsdfilterpage.h \ + qdirlineedit.h cupsddirpage.h portdialog.h cupsdnetworkpage.h \ + editlist.h cupsdbrowsingpage.h browsedialog.h cupsdsecuritypage.h \ + locationdialog.h addressdialog.h cups-util.h qdirmultilineedit.h \ + sizewidget.h + +# Data +cupsdconfdata_DATA = kde_logo.png cups_logo.png cupsd.conf.template +cupsdconfdatadir = $(kde_datadir)/kdeprint + +# Translations +messages: + perl cupsdcomment.pl < cupsd.conf.template > cupsd.conf.template.cpp + $(XGETTEXT) *.cpp -o $(podir)/cupsdconf.pot + rm -f cupsd.conf.template.cpp diff --git a/kdeprint/cups/cupsdconf2/addressdialog.cpp b/kdeprint/cups/cupsdconf2/addressdialog.cpp new file mode 100644 index 000000000..b7472c5a4 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/addressdialog.cpp @@ -0,0 +1,89 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "addressdialog.h" + +#include <qcombobox.h> +#include <qlineedit.h> +#include <qlabel.h> +#include <qlayout.h> + +#include <klocale.h> + +AddressDialog::AddressDialog(QWidget *parent, const char *name) + : KDialogBase(Swallow, i18n("ACL Address"), Ok|Cancel, Ok, parent, name, true, true) +{ + QWidget *w = new QWidget(this); + type_ = new QComboBox(w); + address_ = new QLineEdit(w); + + type_->insertItem(i18n("Allow")); + type_->insertItem(i18n("Deny")); + + QLabel *l1 = new QLabel(i18n("Type:"), w); + QLabel *l2 = new QLabel(i18n("Address:"), w); + + QGridLayout *m1 = new QGridLayout(w, 2, 2, 0, 5); + m1->setColStretch(1, 1); + m1->addWidget(l1, 0, 0, Qt::AlignRight); + m1->addWidget(l2, 1, 0, Qt::AlignRight); + m1->addWidget(type_, 0, 1); + m1->addWidget(address_, 1, 1); + + setMainWidget(w); + resize(300, 100); +} + +QString AddressDialog::addressString() +{ + QString s; + if (type_->currentItem() == 0) + s.append("Allow "); + else + s.append("Deny "); + if (address_->text().isEmpty()) + s.append("All"); + else + s.append(address_->text()); + return s; +} + +QString AddressDialog::newAddress(QWidget *parent) +{ + AddressDialog dlg(parent); + if (dlg.exec()) + return dlg.addressString(); + else + return QString::null; +} + +QString AddressDialog::editAddress(const QString& addr, QWidget *parent) +{ + AddressDialog dlg(parent); + int p = addr.find(' '); + if (p != -1) + { + dlg.type_->setCurrentItem(addr.left(p).lower() == "deny" ? 1 : 0); + dlg.address_->setText(addr.mid(p+1)); + } + if (dlg.exec()) + return dlg.addressString(); + else + return QString::null; +} diff --git a/kdeprint/cups/cupsdconf2/addressdialog.h b/kdeprint/cups/cupsdconf2/addressdialog.h new file mode 100644 index 000000000..4560dd72b --- /dev/null +++ b/kdeprint/cups/cupsdconf2/addressdialog.h @@ -0,0 +1,42 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef ADDRESSDIALOG_H +#define ADDRESSDIALOG_H + +#include <kdialogbase.h> + +class QComboBox; +class QLineEdit; + +class AddressDialog : public KDialogBase +{ +public: + AddressDialog(QWidget *parent = 0, const char *name = 0); + + QString addressString(); + static QString newAddress(QWidget *parent = 0); + static QString editAddress(const QString& s, QWidget *parent = 0); + +private: + QComboBox *type_; + QLineEdit *address_; +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/browsedialog.cpp b/kdeprint/cups/cupsdconf2/browsedialog.cpp new file mode 100644 index 000000000..846ea41a5 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/browsedialog.cpp @@ -0,0 +1,150 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "browsedialog.h" +#include "cupsdconf.h" + +#include <qlineedit.h> +#include <qpushbutton.h> +#include <qcombobox.h> +#include <qlabel.h> +#include <qlayout.h> +#include <qwhatsthis.h> +#include <qregexp.h> + +#include <klocale.h> + +BrowseDialog::BrowseDialog(QWidget *parent, const char *name) + : KDialogBase(parent, name, true, QString::null, Ok|Cancel, Ok, true) +{ + QWidget *dummy = new QWidget(this); + setMainWidget(dummy); + type_ = new QComboBox(dummy); + from_ = new QLineEdit(dummy); + to_ = new QLineEdit(dummy); + type_->insertItem(i18n("Send")); + type_->insertItem(i18n("Allow")); + type_->insertItem(i18n("Deny")); + type_->insertItem(i18n("Relay")); + type_->insertItem(i18n("Poll")); + + QLabel *l1 = new QLabel(i18n("Type:"), dummy); + QLabel *l2 = new QLabel(i18n("From:"), dummy); + QLabel *l3 = new QLabel(i18n("To:"), dummy); + + QGridLayout *m1 = new QGridLayout(dummy, 3, 2, 0, 5); + m1->addWidget(l1, 0, 0, Qt::AlignRight); + m1->addWidget(l2, 1, 0, Qt::AlignRight); + m1->addWidget(l3, 2, 0, Qt::AlignRight); + m1->addWidget(type_, 0, 1); + m1->addWidget(from_, 1, 1); + m1->addWidget(to_, 2, 1); + + connect(type_, SIGNAL(activated(int)), SLOT(slotTypeChanged(int))); + slotTypeChanged(type_->currentItem()); + + setCaption(i18n("Browse Address")); + resize(250, 100); +} + +QString BrowseDialog::addressString() +{ + QString s; + switch (type_->currentItem()) + { + case 0: + s.append("Send"); + break; + case 1: + s.append("Allow"); + break; + case 2: + s.append("Deny"); + break; + case 3: + s.append("Relay"); + break; + case 4: + s.append("Poll"); + break; + } + if (from_->isEnabled()) + s.append(" ").append(from_->text()); + if (to_->isEnabled()) + s.append(" ").append(to_->text()); + return s; +} + +void BrowseDialog::setInfos(CupsdConf *conf) +{ + QWhatsThis::add(type_, conf->comments_.toolTip("browsetype")); +} + +QString BrowseDialog::newAddress(QWidget *parent, CupsdConf *conf) +{ + BrowseDialog dlg(parent); + dlg.setInfos(conf); + if (dlg.exec()) + { + return dlg.addressString(); + } + return QString::null; +} + +QString BrowseDialog::editAddress(const QString& s, QWidget *parent, CupsdConf *conf) +{ + BrowseDialog dlg(parent); + dlg.setInfos(conf); + QStringList l = QStringList::split(QRegExp("\\s"), s, false); + if (l.count() > 1) + { + if (l[0] == "Send") dlg.type_->setCurrentItem(0); + else if (l[0] == "Allow") dlg.type_->setCurrentItem(1); + else if (l[0] == "Deny") dlg.type_->setCurrentItem(2); + else if (l[0] == "Relay") dlg.type_->setCurrentItem(3); + else if (l[0] == "Poll") dlg.type_->setCurrentItem(4); + dlg.slotTypeChanged(dlg.type_->currentItem()); + int index(1); + if (dlg.from_->isEnabled()) + dlg.from_->setText(l[index++]); + if (dlg.to_->isEnabled()) + dlg.to_->setText(l[index]); + } + if (dlg.exec()) + { + return dlg.addressString(); + } + return QString::null; +} + +void BrowseDialog::slotTypeChanged(int index) +{ + bool useFrom(true), useTo(true); + switch (index) + { + case 0: useFrom = false; break; + case 1: + case 4: + case 2: useTo = false; break; + } + from_->setEnabled(useFrom); + to_->setEnabled(useTo); +} + +#include "browsedialog.moc" diff --git a/kdeprint/cups/cupsdconf2/browsedialog.h b/kdeprint/cups/cupsdconf2/browsedialog.h new file mode 100644 index 000000000..ac5be55b7 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/browsedialog.h @@ -0,0 +1,49 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef BROWSEDIALOG_H +#define BROWSEDIALOG_H + +#include <kdialogbase.h> + +class QLineEdit; +class QComboBox; +struct CupsdConf; + +class BrowseDialog : public KDialogBase +{ + Q_OBJECT + +public: + BrowseDialog(QWidget *parent = 0, const char *name = 0); + + QString addressString(); + void setInfos(CupsdConf*); + static QString newAddress(QWidget *parent = 0, CupsdConf *conf = 0); + static QString editAddress(const QString& s, QWidget *parent = 0, CupsdConf *conf = 0); + +protected slots: + void slotTypeChanged(int); + +private: + QComboBox *type_; + QLineEdit *from_, *to_; +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/cups-util.c b/kdeprint/cups/cupsdconf2/cups-util.c new file mode 100644 index 000000000..cb6ddcf92 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cups-util.c @@ -0,0 +1,556 @@ +#include <cups/ipp.h> +#include <cups/http.h> +#include <cups/cups.h> +#include <stdlib.h> +#include <fcntl.h> +#include <sys/stat.h> +#include <unistd.h> + +#define CUPS_SERVERROOT "/etc/cups" +static http_t *cups_server; +static ipp_status_t last_error; +static char authstring[HTTP_MAX_VALUE]; +static char pwdstring[33]; +static int cups_local_auth(http_t *http); + +const char* cupsGetConf( void ); +int cupsPutConf( const char* ); + +const char * /* O - Filename for PPD file */ +cupsGetConf(void) +{ + int fd; /* PPD file */ + int bytes; /* Number of bytes read */ + char buffer[8192]; /* Buffer for file */ + char resource[HTTP_MAX_URI]; /* Resource name */ + const char *password; /* Password string */ + char realm[HTTP_MAX_VALUE], /* realm="xyz" string */ + nonce[HTTP_MAX_VALUE], /* nonce="xyz" string */ + plain[255], /* Plaintext username:password */ + encode[512]; /* Encoded username:password */ + http_status_t status; /* HTTP status from server */ + char prompt[1024]; /* Prompt string */ + int digest_tries; /* Number of tries with Digest */ + static char filename[HTTP_MAX_URI]; /* Local filename */ +#if CUPS_VERSION_MAJOR - 0 <= 1 && CUPS_VERSION_MINOR - 0 < 2 + const char *fqdn = 0; +#else + char fqdn[ HTTP_MAX_URI ]; /* Server name buffer */ +#endif + + + /* + * Connect to the correct server as needed... + */ + + if ((cups_server = httpConnectEncrypt(cupsServer(), ippPort(), + cupsEncryption())) == NULL) + { + last_error = IPP_SERVICE_UNAVAILABLE; + return (NULL); + } + + /* + * Get a temp file... + */ + + if ((fd = cupsTempFd(filename, sizeof(filename))) < 0) + { + /* + * Can't open file; close the server connection and return NULL... + */ + + httpFlush(cups_server); + httpClose(cups_server); + cups_server = NULL; + return (NULL); + } + + /* + * And send a request to the HTTP server... + */ + + snprintf(resource, sizeof(resource), "/admin/conf/cupsd.conf"); + + digest_tries = 0; + + do + { + httpClearFields(cups_server); + httpSetField(cups_server, HTTP_FIELD_HOST, cupsServer()); + httpSetField(cups_server, HTTP_FIELD_AUTHORIZATION, authstring); + + if (httpGet(cups_server, resource)) + { + if (httpReconnect(cups_server)) + { + status = HTTP_ERROR; + break; + } + else + { + status = HTTP_UNAUTHORIZED; + continue; + } + } + + while ((status = httpUpdate(cups_server)) == HTTP_CONTINUE); + + if (status == HTTP_UNAUTHORIZED) + { + const char *www_authenticate; + fprintf(stderr,"cupsGetConf: unauthorized...\n"); + + /* + * Flush any error message... + */ + + httpFlush(cups_server); + + /* + * See if we can do local authentication... + */ + + if (cups_local_auth(cups_server)) + continue; + + /* + * See if we should retry the current digest password... + */ + +#if CUPS_VERSION_MAJOR - 0 <= 1 && CUPS_VERSION_MINOR - 0 < 2 + www_authenticate = cups_server->fields[HTTP_FIELD_WWW_AUTHENTICATE]; +#else + www_authenticate = httpGetField( cups_server, HTTP_FIELD_WWW_AUTHENTICATE ); +#endif + if (strncmp(www_authenticate, "Basic", 5) == 0 || + digest_tries > 1 || !pwdstring[0]) + { + /* + * Nope - get a password from the user... + */ +#if CUPS_VERSION_MAJOR - 0 <= 1 && CUPS_VERSION_MINOR - 0 < 2 + fqdn = cups_server->hostname; +#else + httpGetHostname( cups_server, fqdn, sizeof( fqdn ) ); +#endif + + snprintf(prompt, sizeof(prompt), "Password for %s on %s? ", cupsUser(), fqdn ); + + if ((password = cupsGetPassword(prompt)) == NULL) + break; + if (!password[0]) + break; + + strncpy(pwdstring, password, sizeof(pwdstring) - 1); + pwdstring[sizeof(pwdstring) - 1] = '\0'; + + digest_tries = 0; + } + else + digest_tries ++; + + /* + * Got a password; encode it for the server... + */ + +#if CUPS_VERSION_MAJOR - 0 <= 1 && CUPS_VERSION_MINOR - 0 < 2 + www_authenticate = cups_server->fields[HTTP_FIELD_WWW_AUTHENTICATE]; +#else + www_authenticate = httpGetField( cups_server, HTTP_FIELD_WWW_AUTHENTICATE ); +#endif + if (strncmp(www_authenticate, "Basic", 5) == 0) + { + /* + * Basic authentication... + */ + + snprintf(plain, sizeof(plain), "%s:%s", cupsUser(), pwdstring); +#if CUPS_VERSION_MAJOR == 1 && CUPS_VERSION_MINOR >= 2 + httpEncode64_2(encode, sizeof(encode), plain, sizeof(plain)); +#else + httpEncode64(encode, plain); +#endif + snprintf(authstring, sizeof(authstring), "Basic %s", encode); + } + else + { + /* + * Digest authentication... + */ + + httpGetSubField(cups_server, HTTP_FIELD_WWW_AUTHENTICATE, "realm", realm); + httpGetSubField(cups_server, HTTP_FIELD_WWW_AUTHENTICATE, "nonce", nonce); + + httpMD5(cupsUser(), realm, pwdstring, encode); + httpMD5Final(nonce, "GET", resource, encode); + snprintf(authstring, sizeof(authstring), + "Digest username=\"%s\", realm=\"%s\", nonce=\"%s\", " + "response=\"%s\"", cupsUser(), realm, nonce, encode); + } + + continue; + } +#ifdef HAVE_LIBSSL + else if (status == HTTP_UPGRADE_REQUIRED) + { + /* + * Flush any error message... + */ + + httpFlush(cups_server); + + /* + * Upgrade with encryption... + */ + + httpEncryption(cups_server, HTTP_ENCRYPT_REQUIRED); + + /* + * Try again, this time with encryption enabled... + */ + + continue; + } +#endif /* HAVE_LIBSSL */ + } + while (status == HTTP_UNAUTHORIZED || status == HTTP_UPGRADE_REQUIRED); + + /* + * See if we actually got the file or an error... + */ + + if (status != HTTP_OK) + { + close(fd); + unlink(filename); + httpFlush(cups_server); + httpClose(cups_server); + cups_server = NULL; + return (NULL); + } + + /* + * OK, we need to copy the file... + */ + + while ((bytes = +#if CUPS_VERSION_MAJOR - 0 <= 1 && CUPS_VERSION_MINOR - 0 < 2 + httpRead +#else + httpRead2 +#endif + (cups_server, buffer, sizeof(buffer))) > 0) + { + write(fd, buffer, bytes); + } + + close(fd); + + return (filename); +} + +int /* O - Status of operation */ +cupsPutConf(const char *name) /* I - Name of the config file to send */ +{ + int fd; /* PPD file */ + int bytes; /* Number of bytes read */ + char buffer[8192]; /* Buffer for file */ + char resource[HTTP_MAX_URI]; /* Resource name */ + const char *password; /* Password string */ + char realm[HTTP_MAX_VALUE], /* realm="xyz" string */ + nonce[HTTP_MAX_VALUE], /* nonce="xyz" string */ + plain[255], /* Plaintext username:password */ + encode[512]; /* Encoded username:password */ + http_status_t status; /* HTTP status from server */ + char prompt[1024]; /* Prompt string */ + int digest_tries; /* Number of tries with Digest */ +#if CUPS_VERSION_MAJOR - 0 <= 1 && CUPS_VERSION_MINOR - 0 < 2 + const char *fqdn = 0; +#else + char fqdn[ HTTP_MAX_URI ]; /* Server name buffer */ +#endif + + if (name == NULL) + return 0; + + /* + * Connect to the correct server as needed... + */ + + if ((cups_server = httpConnectEncrypt(cupsServer(), ippPort(), + cupsEncryption())) == NULL) + { + last_error = IPP_SERVICE_UNAVAILABLE; + return 0; + } + + /* + * Open the local config file... + */ + + if ((fd = open(name, O_RDONLY)) < 0) + { + /* + * Can't open file; close the server connection and return NULL... + */ + + httpFlush(cups_server); + httpClose(cups_server); + cups_server = NULL; + return 0; + } + + /* + * And send a request to the HTTP server... + */ + + strncpy(resource, "/admin/conf/cupsd.conf", sizeof(resource)); + + digest_tries = 0; + + do + { + httpClearFields(cups_server); + httpSetField(cups_server, HTTP_FIELD_HOST, cupsServer()); + httpSetField(cups_server, HTTP_FIELD_AUTHORIZATION, authstring); + httpSetField(cups_server, HTTP_FIELD_TRANSFER_ENCODING, "chunked"); + + if (httpPut(cups_server, resource)) + { + if (httpReconnect(cups_server)) + { + status = HTTP_ERROR; + break; + } + else + { + status = HTTP_UNAUTHORIZED; + continue; + } + } + + /* send the file now */ + lseek(fd, 0, SEEK_SET); + status = HTTP_CONTINUE; + while ((bytes = read(fd, buffer, sizeof(buffer))) > 0) + if (httpCheck(cups_server)) + { + if ((status = httpUpdate(cups_server)) != HTTP_CONTINUE) + break; + } + else +#if CUPS_VERSION_MAJOR - 0 <= 1 && CUPS_VERSION_MINOR - 0 < 2 + httpWrite +#else + httpWrite2 +#endif + (cups_server, buffer, bytes); + + if (status == HTTP_CONTINUE) + { +#if CUPS_VERSION_MAJOR - 0 <= 1 && CUPS_VERSION_MINOR - 0 < 2 + httpWrite +#else + httpWrite2 +#endif + (cups_server, buffer, 0); + while ((status = httpUpdate(cups_server)) == HTTP_CONTINUE); + } + + if (status == HTTP_UNAUTHORIZED) + { + const char *www_authenticate; + fprintf(stderr,"cupsPutConf: unauthorized..."); + + /* + * Flush any error message... + */ + + httpFlush(cups_server); + + /* + * See if we can do local authentication... + */ + + if (cups_local_auth(cups_server)) + continue; + + /* + * See if we should retry the current digest password... + */ + +#if CUPS_VERSION_MAJOR - 0 <= 1 && CUPS_VERSION_MINOR - 0 < 2 + www_authenticate = cups_server->fields[HTTP_FIELD_WWW_AUTHENTICATE]; +#else + www_authenticate = httpGetField( cups_server, HTTP_FIELD_WWW_AUTHENTICATE ); +#endif + if (strncmp(www_authenticate, "Basic", 5) == 0 || + digest_tries > 1 || !pwdstring[0]) + { + /* + * Nope - get a password from the user... + */ + + +#if CUPS_VERSION_MAJOR - 0 <= 1 && CUPS_VERSION_MINOR - 0 < 2 + fqdn = cups_server->hostname; +#else + httpGetHostname( cups_server, fqdn, sizeof( fqdn ) ); +#endif + snprintf(prompt, sizeof(prompt), "Password for %s on %s? ", cupsUser(), fqdn ); + + if ((password = cupsGetPassword(prompt)) == NULL) + break; + if (!password[0]) + break; + + strncpy(pwdstring, password, sizeof(pwdstring) - 1); + pwdstring[sizeof(pwdstring) - 1] = '\0'; + + digest_tries = 0; + } + else + digest_tries ++; + + /* + * Got a password; encode it for the server... + */ + +#if CUPS_VERSION_MAJOR - 0 <= 1 && CUPS_VERSION_MINOR - 0 < 2 + www_authenticate = cups_server->fields[HTTP_FIELD_WWW_AUTHENTICATE]; +#else + www_authenticate = httpGetField( cups_server, HTTP_FIELD_WWW_AUTHENTICATE ); +#endif + if (strncmp(www_authenticate, "Basic", 5) == 0) + { + /* + * Basic authentication... + */ + + snprintf(plain, sizeof(plain), "%s:%s", cupsUser(), pwdstring); +#if CUPS_VERSION_MAJOR == 1 && CUPS_VERSION_MINOR >= 2 + httpEncode64_2(encode, sizeof(encode), plain, sizeof(plain)); +#else + httpEncode64(encode, plain); +#endif + snprintf(authstring, sizeof(authstring), "Basic %s", encode); + } + else + { + /* + * Digest authentication... + */ + + httpGetSubField(cups_server, HTTP_FIELD_WWW_AUTHENTICATE, "realm", realm); + httpGetSubField(cups_server, HTTP_FIELD_WWW_AUTHENTICATE, "nonce", nonce); + + httpMD5(cupsUser(), realm, pwdstring, encode); + httpMD5Final(nonce, "GET", resource, encode); + snprintf(authstring, sizeof(authstring), + "Digest username=\"%s\", realm=\"%s\", nonce=\"%s\", " + "response=\"%s\"", cupsUser(), realm, nonce, encode); + } + + continue; + } +#ifdef HAVE_LIBSSL + else if (status == HTTP_UPGRADE_REQUIRED) + { + /* + * Flush any error message... + */ + + httpFlush(cups_server); + + /* + * Upgrade with encryption... + */ + + httpEncryption(cups_server, HTTP_ENCRYPT_REQUIRED); + + /* + * Try again, this time with encryption enabled... + */ + + continue; + } +#endif /* HAVE_LIBSSL */ + } + while (status == HTTP_UNAUTHORIZED || status == HTTP_UPGRADE_REQUIRED); + + /* + * See if we actually got the file or an error... + */ + + if (status != HTTP_CREATED) + { + httpFlush(cups_server); + httpClose(cups_server); + cups_server = NULL; + close(fd); + return 0; + } + + close(fd); + + return 1; +} + +static int /* O - 1 if available, 0 if not */ +cups_local_auth(http_t *http) /* I - Connection */ +{ + int pid; /* Current process ID */ + FILE *fp; /* Certificate file */ + char filename[1024], /* Certificate filename */ + certificate[33];/* Certificate string */ + const char *root; /* Server root directory */ + + + /* + * See if we are accessing localhost... + the struct has changed in newer versions - PiggZ (adam@piggz.co.uk) + */ +#if CUPS_VERSION_MAJOR == 1 && CUPS_VERSION_MINOR >= 2 + if (!httpAddrLocalhost(http)) +#else + if (ntohl(*(int*)&http->hostaddr.sin_addr) != 0x7f000001 && + strcasecmp(http->hostname, "localhost") != 0) +#endif + return (0); + + /* + * Try opening a certificate file for this PID. If that fails, + * try the root certificate... + */ + + if ((root = getenv("CUPS_SERVERROOT")) == NULL) + root = CUPS_SERVERROOT; + + pid = getpid(); + snprintf(filename, sizeof(filename), "%s/certs/%d", root, pid); + if ((fp = fopen(filename, "r")) == NULL && pid > 0) + { + snprintf(filename, sizeof(filename), "%s/certs/0", root); + fp = fopen(filename, "r"); + } + + if (fp == NULL) + return (0); + + /* + * Read the certificate from the file... + */ + + fgets(certificate, sizeof(certificate), fp); + fclose(fp); + + /* + * Set the authorization string and return... + */ + + snprintf(authstring, sizeof(authstring), "Local %s", certificate); + + return (1); +} + diff --git a/kdeprint/cups/cupsdconf2/cups-util.h b/kdeprint/cups/cupsdconf2/cups-util.h new file mode 100644 index 000000000..1daf4050e --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cups-util.h @@ -0,0 +1,26 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef CUPS_UTIL_H +#define CUPS_UTIL_H + +const char* cupsGetConf(void); +int cupsPutConf(const char *filename); + +#endif diff --git a/kdeprint/cups/cupsdconf2/cups_logo.png b/kdeprint/cups/cupsdconf2/cups_logo.png Binary files differnew file mode 100644 index 000000000..e6f9b5919 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cups_logo.png diff --git a/kdeprint/cups/cupsdconf2/cupsd.conf.template b/kdeprint/cups/cupsdconf2/cupsd.conf.template new file mode 100644 index 000000000..c91f0dfa3 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsd.conf.template @@ -0,0 +1,977 @@ +%%header +# CUPS configuration file, generated by CUPS configuration tool. +# This tool is part of KDEPrint, the printing framework for KDE +# since version 2.2.2 and is used by the CUPS supporting module +# in KDEPrint. The predecessors to KDEPrint in former KDE releases +# were KUPS and QtCUPS; they are deprecated and no longer maintained. +# +# Author: Michael Goffioul <kdeprint@swing.be> +# +# Web site: http://printing.kde.org/ +# +######################################################################## +# # +# This is the CUPS configuration file. If you are familiar with # +# Apache or any of the other popular web servers, we've followed the # +# same format. Any configuration variable used here has the same # +# semantics as the corresponding variable in Apache. If we need # +# different functionality then a different name is used to avoid # +# confusion... # +# # +######################################################################## +@@ + +%%servername +# <b>Server name (ServerName)</b> +# <p> +# The hostname of your server, as advertised to the world. +# By default CUPS will use the hostname of the system.</p> +# <p> +# To set the default server used by clients, see the client.conf file.</p> +# <p> +# <i>ex</i>: myhost.domain.com</p> +$$ +#ServerName myhost.domain.com +@@ + +%%serveradmin +# <b>Server administrator (ServerAdmin)</b> +# <p> +# The email address to send all complaints or problems to. +# By default CUPS will use "root@hostname".</p> +# <p> +# <i>ex</i>: root@myhost.com</p> +$$ +#ServerAdmin root@your.domain.com +@@ + +%%accesslog +# <b>Access log (AccessLog)</b> +# <p> +# The access log file; if this does not start with a leading / +# then it is assumed to be relative to ServerRoot. By default set to +# "/var/log/cups/access_log".</p> +# <p> +# You can also use the special name <b>syslog</b> to send the output to the +# syslog file or daemon.</p> +# <p> +# <i>ex</i>: /var/log/cups/access_log</p> +$$ +#AccessLog /var/log/cups/access_log +@@ + +%%datadir +# <b>Data directory (DataDir)</b> +# <p> +# The root directory for the CUPS data files. +# By default /usr/share/cups.</p> +# <p> +# <i>ex</i>: /usr/share/cups</p> +$$ +#DataDir /usr/share/cups +@@ + +%%defaultcharset +# <b>Default character set (DefaultCharset)</b> +# <p> +# The default character set to use. If not specified, +# defaults to utf-8. Note that this can also be overridden in +# HTML documents...</p> +# <p> +# <i>ex</i>: utf-8</p> +$$ +#DefaultCharset utf-8 +@@ + +%%defaultlanguage +# <b>Default language (DefaultLanguage)</b> +# <p> +# The default language if not specified by the browser. +# If not specified, the current locale is used.</p> +# <p> +# <i>ex</i>: en</p> +$$ +#DefaultLanguage en +@@ + +%%documentroot +# <b>Document directory (DocumentRoot)</b> +# <p> +# The root directory for HTTP documents that are served. +# By default the compiled-in directory.</p> +# <p> +# <i>ex</i>: /usr/share/cups/doc</p> +$$ +#DocumentRoot /usr/share/cups/doc +@@ + +%%errorlog +# <b>Error log (ErrorLog)</b> +# <p> +# The error log file; if this does not start with a leading / +# then it is assumed to be relative to ServerRoot. By default set to +# "/var/log/cups/error_log".</p> +# <p> +# You can also use the special name <b>syslog</b> to send the output to the +# syslog file or daemon.</p> +# <p> +# <i>ex</i>: /var/log/cups/error_log</p> +$$ +#ErrorLog /var/log/cups/error_log +@@ + +%%fontpath +# <b>Font path (FontPath)</b> +# <p> +# The path to locate all font files (currently only for pstoraster). +# By default /usr/share/cups/fonts.</p> +# <p> +# <i>ex</i>: /usr/share/cups/fonts</p> +$$ +#FontPath /usr/share/cups/fonts +@@ + +%%loglevel +# <b>Log level (LogLevel)</b> +# <p> +# Controls the number of messages logged to the ErrorLog +# file and can be one of the following:</p> +# <ul type=circle> +# <li><i>debug2</i>: Log everything.</li> +# <li><i>debug</i>: Log almost everything.</li> +# <li><i>info</i>: Log all requests and state changes.</li> +# <li><i>warn</i>: Log errors and warnings.</li> +# <li><i>error</i>: Log only errors.</li> +# <li><i>none</i>: Log nothing.</li> +# </ul><p> +# <i>ex</i>: info</p> +$$ +#LogLevel info +@@ + +%%maxlogsize +# <b>Max log size (MaxLogSize)</b> +# <p> +# Controls the maximum size of each log file before they are +# rotated. Defaults to 1048576 (1MB). Set to 0 to disable log rotating.</p> +# <p> +# <i>ex</i>: 1048576</p> +$$ +#MaxLogSize 0 +@@ + +%%pagelog +# <b>Page log (PageLog)</b> +# <p> +# The page log file; if this does not start with a leading / +# then it is assumed to be relative to ServerRoot. By default set to +# "/var/log/cups/page_log".</p> +# <p> +# You can also use the special name <b>syslog</b> to send the output to the +# syslog file or daemon.</p> +# <p> +# <i>ex</i>: /var/log/cups/page_log</p> +$$ +#PageLog /var/log/cups/page_log +@@ + +%%preservejobhistory +# <b>Preserve job history (PreserveJobHistory)</b> +# <p> +# Whether or not to preserve the job history after a +# job is completed, canceled, or stopped. Default is Yes.</p> +# <p> +# <i>ex</i>: Yes</p> +$$ +#PreserveJobHistory Yes +@@ + +%%preservejobfiles +# <b>Preserve job files (PreserveJobFiles)</b> +# <p> +# Whether or not to preserve the job files after a +# job is completed, canceled, or stopped. Default is No.</p> +# <p> +# <i>ex</i>: No</p> +$$ +#PreserveJobFiles No +@@ + +%%printcap +# <b>Printcap file (Printcap)</b> +# <p> +# The name of the printcap file. Default is no filename. +# Leave blank to disable printcap file generation.</p> +# <p> +# <i>ex</i>: /etc/printcap</p> +$$ +#Printcap /etc/printcap +@@ + +%%requestroot +# <b>Request directory (RequestRoot)</b> +# <p> +# The directory where request files are stored. +# By default /var/spool/cups.</p> +# <p> +# <i>ex</i>: /var/spool/cups</p> +$$ +#RequestRoot /var/spool/cups +@@ + +%%remoteroot +# <b>Remote root user (RemoteRoot)</b> +# <p> +# The name of the user assigned to unauthenticated accesses +# from remote systems. By default "remroot".</p> +# <p> +# <i>ex</i>: remroot</p> +$$ +#RemoteRoot remroot +@@ + +%%serverbin +# <b>Server binaries (ServerBin)</b> +# <p> +# The root directory for the scheduler executables. +# By default /usr/lib/cups or /usr/lib32/cups (IRIX 6.5).</p> +# <p> +# <i>ex</i>: /usr/lib/cups</p> +$$ +#ServerBin /usr/lib/cups +@@ + +%%serverroot +# <b>Server files (ServerRoot)</b> +# <p> +# The root directory for the scheduler. +# By default /etc/cups.</p> +# <p> +# <i>ex</i>: /etc/cups</p> +$$ +#ServerRoot /etc/cups +@@ + +%%user +# <b>User (User)</b> +# <p> +# The user the server runs under. Normally this +# must be <b>lp</b>, however you can configure things for another user +# as needed.</p> +# <p> +# Note: the server must be run initially as root to support the +# default IPP port of 631. It changes users whenever an external +# program is run...</p> +# <p> +# <i>ex</i>: lp</p> +$$ +#User lp +@@ + +%%group +# <b>Group (Group)</b> +# <p> +# The group the server runs under. Normally this +# must be <b>sys</b>, however you can configure things for another +# group as needed.</p> +# <p> +# <i>ex</i>: sys</p> +$$ +#Group sys +@@ + +%%ripcache +# <b>RIP cache (RIPCache)</b> +# <p> +# The amount of memory that each RIP should use to cache +# bitmaps. The value can be any real number followed by "k" for +# kilobytes, "m" for megabytes, "g" for gigabytes, or "t" for tiles +# (1 tile = 256x256 pixels). Defaults to "8m" (8 megabytes).</p> +# <p> +# <i>ex</i>: 8m</p> +$$ +#RIPCache 8m +@@ + +%%tempdir +# <b>Temporary files (TempDir)</b> +# <p> +# The directory to put temporary files in. This directory must be +# writable by the user defined above! Defaults to "/var/spool/cups/tmp" or +# the value of the TMPDIR environment variable.</p> +# <p> +# <i>ex</i>: /var/spool/cups/tmp</p> +$$ +#TempDir /var/spool/cups/tmp +@@ + +%%filterlimit +# <b>Filter limit (FilterLimit)</b> +# <p> +# Sets the maximum cost of all job filters that can be run +# at the same time. A limit of 0 means no limit. A typical job may need +# a filter limit of at least 200; limits less than the minimum required +# by a job force a single job to be printed at any time.</p> +# <p> +# The default limit is 0 (unlimited).</p> +# <p> +# <i>ex</i>: 200</p> +$$ +#FilterLimit 0 +@@ + +%%listen +# <b>Listen to (Port/Listen)</b> +# <p> +# Ports/addresses that are listened to. The default port 631 is reserved +# for the Internet Printing Protocol (IPP) and is what is used here.</p> +# <p> +# You can have multiple Port/Listen lines to listen to more than one +# port or address, or to restrict access.</p> +# <p> +# Note: Unfortunately, most web browsers don't support TLS or HTTP Upgrades +# for encryption. If you want to support web-based encryption you will +# probably need to listen on port 443 (the "HTTPS" port...).</p> +# <p> +# <i>ex</i>: 631, myhost:80, 1.2.3.4:631</p> +$$ +# Port 80 +# Port 631 +# Listen hostname +# Listen hostname:80 +# Listen hostname:631 +# Listen 1.2.3.4 +# Listen 1.2.3.4:631 +# +#Port 631 +@@ + +%%hostnamelookups +# <b>Hostname lookups (HostNameLookups)</b> +# <p> +# Whether or not to do lookups on IP addresses to get a +# fully-qualified hostname. This defaults to Off for performance reasons...</p> +# <p> +# <i>ex</i>: On</p> +$$ +#HostNameLookups On +@@ + +%%keepalive +# <b>Keep alive (KeepAlive)</b> +# <p> +# Whether or not to support the Keep-Alive connection +# option. Default is on.</p> +# <p> +# <i>ex</i>: On</p> +$$ +#KeepAlive On +@@ + +%%keepalivetimeout +# <b>Keep-alive timeout (KeepAliveTimeout)</b> +# <p> +# The timeout (in seconds) before Keep-Alive connections are +# automatically closed. Default is 60 seconds.</p> +# <p> +# <i>ex</i>: 60</p> +$$ +#KeepAliveTimeout 60 +@@ + +%%maxclients +# <b>Max clients (MaxClients)</b> +# <p> +# Controls the maximum number of simultaneous clients that +# will be handled. Defaults to 100.</p> +# <p> +# <i>ex</i>: 100</p> +$$ +#MaxClients 100 +@@ + +%%maxrequestsize +# <b>Max request size (MaxRequestSize)</b> +# <p> +# Controls the maximum size of HTTP requests and print files. +# Set to 0 to disable this feature (defaults to 0).</p> +# <p> +# <i>ex</i>: 0</p> +$$ +#MaxRequestSize 0 +@@ + +%%timeout +# <b>Client timeout (Timeout)</b> +# <p> +# The timeout (in seconds) before requests time out. Default is 300 seconds.</p> +# <p> +# <i>ex</i>: 300</p> +$$ +#Timeout 300 +@@ + +%%browsing +# <b>Use browsing (Browsing)</b> +# <p> +# Whether or not to <b>listen</b> to printer +# information from other CUPS servers. +# </p> +# <p> +# Enabled by default. +# </p> +# <p> +# Note: to enable the <b>sending</b> of browsing +# information from this CUPS server to the LAN, +# specify a valid <i>BrowseAddress</i>. +# </p> +# <p> +# <i>ex</i>: On</p> +$$ +#Browsing On +@@ + +%%browseshortnames +# <b>Use short names (BrowseShortNames)</b> +# <p> +# Whether or not to use "short" names for remote printers +# when possible (e.g. "printer" instead of "printer@host"). Enabled by +# default.</p> +# <p> +# <i>ex</i>: Yes</p> +$$ +#BrowseShortNames Yes +@@ + +%%browseaddress +# <b>Browse addresses (BrowseAddress)</b> +# <p> +# Specifies a broadcast address to be used. By +# default browsing information is broadcast to all active interfaces.</p> +# <p> +# Note: HP-UX 10.20 and earlier do not properly handle broadcast unless +# you have a Class A, B, C, or D netmask (i.e. no CIDR support).</p> +# <p> +# <i>ex</i>: x.y.z.255, x.y.255.255</p> +$$ +#BrowseAddress x.y.z.255 +#BrowseAddress x.y.255.255 +#BrowseAddress x.255.255.255 +@@ + +%%browseallow +# <b>Browse allow/deny (BrowseAllow/BrowseDeny)</b> +# <p> +# <u>BrowseAllow</u>: specifies an address mask to allow for incoming browser +# packets. The default is to allow packets from all addresses.</p> +# <p> +# <u>BrowseDeny</u>: specifies an address mask to deny for incoming browser +# packets. The default is to deny packets from no addresses.</p> +# <p> +# Both "BrowseAllow" and "BrowseDeny" accept the following notations for +# addresses:</p> +# <pre> +# All +# None +# *.domain.com +# .domain.com +# host.domain.com +# nnn.* +# nnn.nnn.* +# nnn.nnn.nnn.* +# nnn.nnn.nnn.nnn +# nnn.nnn.nnn.nnn/mm +# nnn.nnn.nnn.nnn/mmm.mmm.mmm.mmm +# </pre><p> +# The hostname/domainname restrictions only work if you have turned hostname +# lookups on!</p> +$$ +#BrowseAllow address +#BrowseDeny address +@@ + +%%browseinterval +# <b>Browse interval (BrowseInterval)</b> +# <p> +# The time between browsing updates in seconds. Default +# is 30 seconds.</p> +# <p> +# Note that browsing information is sent whenever a printer's state changes +# as well, so this represents the maximum time between updates.</p> +# <p> +# Set this to 0 to disable outgoing broadcasts so your local printers are +# not advertised but you can still see printers on other hosts.</p> +# <p> +# <i>ex</i>: 30</p> +$$ +#BrowseInterval 30 +@@ + +%%browseorder +# <b>Browse order (BrowseOrder)</b> +# <p> +# Specifies the order of BrowseAllow/BrowseDeny comparisons.</p> +# <p> +# <i>ex</i>: allow,deny</p> +$$ +#BrowseOrder allow,deny +#BrowseOrder deny,allow +@@ + +%%browsepoll +# <b>Browse poll (BrowsePoll)</b> +# <p> +# Poll the named server(s) for printers.</p> +# <p> +# <i>ex</i>: myhost:631</p> +$$ +#BrowsePoll address:port +@@ + +%%browseport +# <b>Browse port (BrowsePort)</b> +# <p> +# The port used for UDP broadcasts. By default this is +# the IPP port; if you change this you need to do it on all servers. +# Only one BrowsePort is recognized.</p> +# <p> +# <i>ex</i>: 631</p> +$$ +#BrowsePort 631 +@@ + +%%browserelay +# <b>Browse relay (BrowseRelay)</b> +# <p> +# Relay browser packets from one address/network to another.</p> +# <p> +# <i>ex</i>: src-address dest-address</p> +$$ +#BrowseRelay source-address destination-address +@@ + +%%browsetimeout +# <b>Browse timeout (BrowseTimeout)</b> +# <p> +# The timeout (in seconds) for network printers - if we don't +# get an update within this time the printer will be removed +# from the printer list. This number definitely should not be +# less the BrowseInterval value for obvious reasons. Defaults +# to 300 seconds.</p> +# <p> +# <i>ex</i>: 300</p> +$$ +#BrowseTimeout 300 +@@ + +%%implicitclasses +# <b>Implicit classes (ImplicitClasses)</b> +# <p> +# Whether or not to use implicit classes.</p> +# <p> +# Printer classes can be specified explicitly in the classes.conf +# file, implicitly based upon the printers available on the LAN, or +# both.</p> +# <p> +# When ImplicitClasses is On, printers on the LAN with the same name +# (e.g. Acme-LaserPrint-1000) will be put into a class with the same +# name. This allows you to setup multiple redundant queues on a LAN +# without a lot of administrative difficulties. If a user sends a +# job to Acme-LaserPrint-1000, the job will go to the first available +# queue.</p> +# <p> +# Enabled by default.</p> +$$ +#ImplicitClasses Off +@@ + +%%systemgroup +# <b>System group (SystemGroup)</b> +# <p> +# The group name for "System" (printer administration) +# access. The default varies depending on the operating system, but +# will be <b>sys</b>, <b>system</b>, or <b>root</b> (checked for in that order).</p> +# <p> +# <i>ex</i>: sys</p> +$$ +#SystemGroup sys +@@ + +%%servercertificate +# <b>Encryption certificate (ServerCertificate)</b> +# <p> +# The file to read containing the server's certificate. +# Defaults to "/etc/cups/ssl/server.crt".</p> +# <p> +# <i>ex</i>: /etc/cups/ssl/server.crt</p> +$$ +#ServerCertificate /etc/cups/ssl/server.crt +@@ + +%%serverkey +# <b>Encryption key (ServerKey)</b> +# <p> +# The file to read containing the server's key. +# Defaults to "/etc/cups/ssl/server.key".</p> +# <p> +# <i>ex</i>: /etc/cups/ssl/server.key</p> +$$ +#ServerKey /etc/cups/ssl/server.key +@@ + +%%locations +# Access permissions +# +# Access permissions for each directory served by the scheduler. +# Locations are relative to DocumentRoot... +# +# AuthType: the authorization to use: +# +# None - Perform no authentication +# Basic - Perform authentication using the HTTP Basic method. +# Digest - Perform authentication using the HTTP Digest method. +# +# (Note: local certificate authentication can be substituted by +# the client for Basic or Digest when connecting to the +# localhost interface) +# +# AuthClass: the authorization class; currently only Anonymous, User, +# System (valid user belonging to group SystemGroup), and Group +# (valid user belonging to the specified group) are supported. +# +# AuthGroupName: the group name for "Group" authorization. +# +# Order: the order of Allow/Deny processing. +# +# Allow: allows access from the specified hostname, domain, IP address, or +# network. +# +# Deny: denies access from the specified hostname, domain, IP address, or +# network. +# +# Both "Allow" and "Deny" accept the following notations for addresses: +# +# All +# None +# *.domain.com +# .domain.com +# host.domain.com +# nnn.* +# nnn.nnn.* +# nnn.nnn.nnn.* +# nnn.nnn.nnn.nnn +# nnn.nnn.nnn.nnn/mm +# nnn.nnn.nnn.nnn/mmm.mmm.mmm.mmm +# +# The host and domain address require that you enable hostname lookups +# with "HostNameLookups On" above. +# +# Encryption: whether or not to use encryption; this depends on having +# the OpenSSL library linked into the CUPS library and scheduler. +# +# Possible values: +# +# Always - Always use encryption (SSL) +# Never - Never use encryption +# Required - Use TLS encryption upgrade +# IfRequested - Use encryption if the server requests it +# +# The default value is "IfRequested". +$$ +#<Location [resource_name]> +# +# You may wish to limit access to printers and classes, either with Allow +# and Deny lines, or by requiring a username and password. +# +# +## Anonymous access (default) +#AuthType None +# +## Require a username and password (Basic authentication) +#AuthType Basic +#AuthClass User +# +## Require a username and password (Digest/MD5 authentication) +#AuthType Digest +#AuthClass User +# +## Restrict access to local domain +#Order Deny,Allow +#Deny From All +#Allow From .mydomain.com +# +## Use encryption if requested +#Encryption IfRequested +#</Location> +@@ + +%%authtype +# <b>Authentication (AuthType)</b> +# <p> +# The authorization to use:<p> +# <ul type=circle> +# <li><i>None</i> - Perform no authentication.</li> +# <li><i>Basic</i> - Perform authentication using the HTTP Basic method.</li> +# <li><i>Digest</i> - Perform authentication using the HTTP Digest method.</li> +# </ul><p> +# Note: local certificate authentication can be substituted by +# the client for <i>Basic</i> or <i>Digest</i> when connecting to the +# localhost interface.</p> +@@ + +%%authclass +# <b>Class (AuthClass)</b> +# <p> +# The authorization class; currently only <i>Anonymous</i>, <i>User</i>, +# <i>System</i> (valid user belonging to group SystemGroup), and <i>Group</i> +# (valid user belonging to the specified group) are supported.</p> +@@ + +%%authname +# <p>The user/group names allowed to access the resource. The format is a +# comma separated list.</p> +@@ + +%%satisfy +# <b>Satisfy (Satisfy)</b> +# <p> +# This directive controls whether all specified conditions must +# be satisfied to allow access to the resource. If set to "all", +# then all authentication and access control conditions must be +# satisfied to allow access. +# </p> +# <p> +# Setting Satisfy to "any" allows a user to gain access if the +# authentication <i>or</i> access control requirements are satisfied. +# For example, you might require authentication for remote access, +# but allow local access without authentication. +# </p> +# <p> +# The default is "all". +# </p> +@@ + +%%authgroupname +# <b>Authentication group name (AuthGroupName)</b> +# <p> +# The group name for <i>Group</i> authorization.</p> +@@ + +%%order +# <b>ACL order (Order)</b> +# <p> +# The order of Allow/Deny processing.</p> +@@ + +%%allow +# <b>Allow</b> +# <p> +# Allows access from the specified hostname, domain, IP address, or +# network. Possible values are:</p> +# <pre> +# All +# None +# *.domain.com +# .domain.com +# host.domain.com +# nnn.* +# nnn.nnn.* +# nnn.nnn.nnn.* +# nnn.nnn.nnn.nnn +# nnn.nnn.nnn.nnn/mm +# nnn.nnn.nnn.nnn/mmm.mmm.mmm.mmm +# </pre><p> +# The host and domain address require that you enable hostname lookups +# with "HostNameLookups On" above.</p> +@@ + +%%allowdeny +# <b>ACL addresses (Allow/Deny)</b> +# <p> +# Allows/Denies access from the specified hostname, domain, IP address, or +# network. Possible values are:</p> +# <pre> +# All +# None +# *.domain.com +# .domain.com +# host.domain.com +# nnn.* +# nnn.nnn.* +# nnn.nnn.nnn.* +# nnn.nnn.nnn.nnn +# nnn.nnn.nnn.nnn/mm +# nnn.nnn.nnn.nnn/mmm.mmm.mmm.mmm +# </pre><p> +# The host and domain address require that you enable hostname lookups +# with "HostNameLookups On" above.</p> +@@ + +%%encryption +# <b>Encryption (Encryption)</b> +# <p> +# Whether or not to use encryption; this depends on having +# the OpenSSL library linked into the CUPS library and scheduler.</p> +# <p> +# Possible values:</p> +# <ul type=circle> +# <li><i>Always</i> - Always use encryption (SSL)</li> +# <li><i>Never</i> - Never use encryption</li> +# <li><i>Required</i> - Use TLS encryption upgrade</li> +# <li><i>IfRequested</i> - Use encryption if the server requests it</li> +# </ul><p> +# The default value is "IfRequested".</p> +@@ + +%%locationsshort +# <b>Access permissions</b> +# <p> +# Access permissions for each directory served by the scheduler. +# Locations are relative to DocumentRoot...</p> +@@ + +%%autopurgejobs +# <b>Auto purge jobs (AutoPurgeJobs)</b> +# <p> +# Automatically purge jobs when not needed for quotas. +# Default is No.</p> +$$ +#AutoPurgeJobs No +@@ + +%%browseprotocols +# <b>Browse protocols (BrowseProtocols)</b> +# <p> +# Which protocols to use for browsing. Can be +# any of the following separated by whitespace and/or commas:</p> +# <ul type=circle> +# <li><i>all</i> - Use all supported protocols.</li> +# <li><i>cups</i> - Use the CUPS browse protocol.</li> +# <li><i>slp</i> - Use the SLPv2 protocol.</li> +# </ul><p> +# The default is <b>cups</b>.</p> +# <p> +# Note: If you choose to use SLPv2, it is <b>strongly</b> recommended that +# you have at least one SLP Directory Agent (DA) on your +# network. Otherwise, browse updates can take several seconds, +# during which the scheduler will not response to client +# requests.</p> +$$ +#BrowseProtocols cups +@@ + +%%classification +# <b>Classification (Classification)</b> +# <p> +# The classification level of the server. If set, this +# classification is displayed on all pages, and raw printing is disabled. +# The default is the empty string.</p> +# <p> +# <i>ex</i>: confidential +$$ +#Classification classified +@@ + +%%classifyoverride +# <b>Allow overrides (ClassifyOverride)</b> +# <p> +# Whether to allow users to override the classification +# on printouts. If enabled, users can limit banner pages to before or +# after the job, and can change the classification of a job, but cannot +# completely eliminate the classification or banners.</p> +# <p> +# The default is off.</p> +$$ +#ClassifyOverride off +@@ + +%%hideimplicitmembers +# <b>Hide implicit members (HideImplicitMembers)</b> +# <p> +# Whether or not to show the members of an +# implicit class.</p> +# <p> +# When HideImplicitMembers is On, any remote printers that are +# part of an implicit class are hidden from the user, who will +# then only see a single queue even though many queues will be +# supporting the implicit class.</p> +# <p> +# Enabled by default.</p> +$$ +#HideImplicitMembers On +@@ + +%%implicitanyclasses +# <b>Use "any" classes (ImplicitAnyClasses)</b> +# <p> +# Whether or not to create <b>AnyPrinter</b> implicit +# classes.</p> +# <p> +# When ImplicitAnyClasses is On and a local queue of the same name +# exists, e.g. "printer", "printer@server1", "printer@server1", then +# an implicit class called "Anyprinter" is created instead.</p> +# <p> +# When ImplicitAnyClasses is Off, implicit classes are not created +# when there is a local queue of the same name.</p> +# <p> +# Disabled by default.</p> +$$ +#ImplicitAnyCLasses Off +@@ + +%%maxjobs +# <b>Max jobs (MaxJobs)</b> +# <p> +# Maximum number of jobs to keep in memory (active and completed). +# Default is 0 (no limit).</p> +$$ +#MaxJobs 0 +@@ + +%%maxjobsperuser +# <b>Max jobs per user (MaxJobsPerUser)</b> +# <p> +# The MaxJobsPerUser directive controls the maximum number of <i>active</i> +# jobs that are allowed for each user. Once a user reaches the limit, new +# jobs will be rejected until one of the active jobs is completed, stopped, +# aborted, or canceled.</p> +# <p> +# Setting the maximum to 0 disables this functionality. +# Default is 0 (no limit). +# </p> +$$ +#MaxJobsPerUser 0 +@@ + +%%maxjobsperprinter +# <b>Max jobs per printer (MaxJobsPerPrinter)</b> +# <p> +# The MaxJobsPerPrinter directive controls the maximum number of <i>active</i> +# jobs that are allowed for each printer or class. Once a printer or class +# reaches the limit, new jobs will be rejected until one of the active jobs +# is completed, stopped, aborted, or canceled.</p> +# <p> +# Setting the maximum to 0 disables this functionality. +# Default is 0 (no limit). +# </p> +$$ +#MaxJobsPerPrinter 0 +@@ + +%%port +# <b>Port</b> +# <p> +# The port value that the CUPS daemon is listening to. Default is 631.</p> +@@ + +%%address +# <b>Address</b> +# <p> +# The address that the CUPS daemon is listening at. Leave it empty or use +# an asterisk (*) to specify a port value on the entire subnetwork.</p> +@@ + +%%usessl +# <p>Check this box if you want to use SSL encryption with this address/port. +# </p> +@@ diff --git a/kdeprint/cups/cupsdconf2/cupsdbrowsingpage.cpp b/kdeprint/cups/cupsdconf2/cupsdbrowsingpage.cpp new file mode 100644 index 000000000..a61742458 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdbrowsingpage.cpp @@ -0,0 +1,210 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "cupsdbrowsingpage.h" +#include "cupsdconf.h" +#include "editlist.h" +#include "browsedialog.h" + +#include <qlabel.h> +#include <qlayout.h> +#include <qcheckbox.h> +#include <qcombobox.h> +#include <qwhatsthis.h> + +#include <klocale.h> +#include <knuminput.h> + +CupsdBrowsingPage::CupsdBrowsingPage(QWidget *parent, const char *name) + : CupsdPage(parent, name) +{ + setPageLabel(i18n("Browsing")); + setHeader(i18n("Browsing Settings")); + setPixmap("kdeprint_printer_remote"); + + browseinterval_ = new KIntNumInput(this); + browseport_ = new KIntNumInput(this); + browsetimeout_ = new KIntNumInput(this); + browsing_ = new QCheckBox(i18n("Use browsing"), this); + cups_ = new QCheckBox("CUPS", this); + slp_ = new QCheckBox("SLP", this); + browseaddresses_ = new EditList(this); + browseorder_ = new QComboBox(this); + useimplicitclasses_ = new QCheckBox(i18n("Implicit classes"), this); + hideimplicitmembers_ = new QCheckBox(i18n("Hide implicit members"), this); + useshortnames_ = new QCheckBox(i18n("Use short names"), this); + useanyclasses_ = new QCheckBox(i18n("Use \"any\" classes"), this); + + browseorder_->insertItem(i18n("Allow, Deny")); + browseorder_->insertItem(i18n("Deny, Allow")); + + browseport_->setRange(0, 9999, 1, true); + browseport_->setSteps(1, 5); + browseinterval_->setRange(0, 10000, 1, true); + browseinterval_->setSteps(1, 10); + browseinterval_->setSuffix(i18n(" sec")); + browsetimeout_->setRange(0, 10000, 1, true); + browsetimeout_->setSteps(1, 10); + browsetimeout_->setSuffix(i18n(" sec")); + + QLabel *l1 = new QLabel(i18n("Browse port:"), this); + QLabel *l2 = new QLabel(i18n("Browse interval:"), this); + QLabel *l3 = new QLabel(i18n("Browse timeout:"), this); + QLabel *l4 = new QLabel(i18n("Browse addresses:"), this); + QLabel *l5 = new QLabel(i18n("Browse order:"), this); + QLabel *l6 = new QLabel(i18n("Browse options:"), this); + + QGridLayout *m1 = new QGridLayout(this, 8, 2, 10, 7); + m1->setRowStretch(7, 1); + m1->setColStretch(1, 1); + QHBoxLayout *m2 = new QHBoxLayout(0, 0, 10); + m1->addMultiCellLayout(m2, 0, 0, 0, 1); + m2->addWidget(browsing_); + m2->addWidget(cups_); + m2->addWidget(slp_); + m2->addStretch(1); + m1->addWidget(l1, 1, 0, Qt::AlignRight); + m1->addWidget(l2, 2, 0, Qt::AlignRight); + m1->addWidget(l3, 3, 0, Qt::AlignRight); + m1->addWidget(l4, 4, 0, Qt::AlignRight|Qt::AlignTop); + m1->addWidget(l5, 5, 0, Qt::AlignRight); + m1->addWidget(l6, 6, 0, Qt::AlignRight|Qt::AlignTop); + m1->addWidget(browseport_, 1, 1); + m1->addWidget(browseinterval_, 2, 1); + m1->addWidget(browsetimeout_, 3, 1); + m1->addWidget(browseaddresses_, 4, 1); + m1->addWidget(browseorder_, 5, 1); + QGridLayout *m3 = new QGridLayout(0, 2, 2, 0, 5); + m1->addLayout(m3, 6, 1); + m3->addWidget(useimplicitclasses_, 0, 0); + m3->addWidget(useanyclasses_, 0, 1); + m3->addWidget(hideimplicitmembers_, 1, 0); + m3->addWidget(useshortnames_, 1, 1); + + connect(browsing_, SIGNAL(toggled(bool)), cups_, SLOT(setEnabled(bool))); + connect(browsing_, SIGNAL(toggled(bool)), slp_, SLOT(setEnabled(bool))); + connect(browsing_, SIGNAL(toggled(bool)), browseport_, SLOT(setEnabled(bool))); + connect(browsing_, SIGNAL(toggled(bool)), browseinterval_, SLOT(setEnabled(bool))); + connect(browsing_, SIGNAL(toggled(bool)), browsetimeout_, SLOT(setEnabled(bool))); + connect(browsing_, SIGNAL(toggled(bool)), browseaddresses_, SLOT(setEnabled(bool))); + connect(browsing_, SIGNAL(toggled(bool)), browseorder_, SLOT(setEnabled(bool))); + connect(browsing_, SIGNAL(toggled(bool)), useimplicitclasses_, SLOT(setEnabled(bool))); + connect(browsing_, SIGNAL(toggled(bool)), useanyclasses_, SLOT(setEnabled(bool))); + connect(browsing_, SIGNAL(toggled(bool)), hideimplicitmembers_, SLOT(setEnabled(bool))); + connect(browsing_, SIGNAL(toggled(bool)), useshortnames_, SLOT(setEnabled(bool))); + + connect(browsing_, SIGNAL(toggled(bool)), l1, SLOT(setEnabled(bool))); + connect(browsing_, SIGNAL(toggled(bool)), l2, SLOT(setEnabled(bool))); + connect(browsing_, SIGNAL(toggled(bool)), l3, SLOT(setEnabled(bool))); + connect(browsing_, SIGNAL(toggled(bool)), l4, SLOT(setEnabled(bool))); + connect(browsing_, SIGNAL(toggled(bool)), l5, SLOT(setEnabled(bool))); + connect(browsing_, SIGNAL(toggled(bool)), l6, SLOT(setEnabled(bool))); + + connect(browseaddresses_, SIGNAL(add()), SLOT(slotAdd())); + connect(browseaddresses_, SIGNAL(edit(int)), SLOT(slotEdit(int))); + connect(browseaddresses_, SIGNAL(defaultList()), SLOT(slotDefaultList())); + connect(browseinterval_, SIGNAL(valueChanged(int)), SLOT(intervalChanged(int))); + browsing_->setChecked(true); +} + +bool CupsdBrowsingPage::loadConfig(CupsdConf *conf, QString&) +{ + conf_ = conf; + browsing_->setChecked(conf_->browsing_); + cups_->setChecked(conf_->browseprotocols_.findIndex("CUPS") != -1); + slp_->setChecked(conf_->browseprotocols_.findIndex("SLP") != -1); + browseport_->setValue(conf_->browseport_); + browseinterval_->setValue(conf_->browseinterval_); + browsetimeout_->setValue(conf_->browsetimeout_); + browseaddresses_->insertItems(conf_->browseaddresses_); + browseorder_->setCurrentItem(conf_->browseorder_); + useimplicitclasses_->setChecked(conf_->useimplicitclasses_); + useanyclasses_->setChecked(conf_->useanyclasses_); + hideimplicitmembers_->setChecked(conf_->hideimplicitmembers_); + useshortnames_->setChecked(conf_->useshortnames_); + + return true; +} + +bool CupsdBrowsingPage::saveConfig(CupsdConf *conf, QString&) +{ + conf->browsing_ = browsing_->isChecked(); + QStringList l; + if (cups_->isChecked()) l << "CUPS"; + if (slp_->isChecked()) l << "SLP"; + conf->browseprotocols_ = l; + conf->browseport_ = browseport_->value(); + conf->browseinterval_ = browseinterval_->value(); + conf->browsetimeout_ = browsetimeout_->value(); + conf->browseaddresses_ = browseaddresses_->items(); + conf->browseorder_ = browseorder_->currentItem(); + conf->useimplicitclasses_ = useimplicitclasses_->isChecked(); + conf->useanyclasses_ = useanyclasses_->isChecked(); + conf->hideimplicitmembers_ = hideimplicitmembers_->isChecked(); + conf->useshortnames_ = useshortnames_->isChecked(); + + return true; +} + +void CupsdBrowsingPage::setInfos(CupsdConf *conf) +{ + QWhatsThis::add(browsing_, conf->comments_.toolTip("browsing")); + QWhatsThis::add(cups_, conf->comments_.toolTip("browseprotocols")); + QWhatsThis::add(slp_, conf->comments_.toolTip("browseprotocols")); + QWhatsThis::add(browseinterval_, conf->comments_.toolTip("browseinterval")); + QWhatsThis::add(browseport_, conf->comments_.toolTip("browseport")); + QWhatsThis::add(browsetimeout_, conf->comments_.toolTip("browsetimeout")); + QWhatsThis::add(browseaddresses_, conf->comments_.toolTip("browseaddresses")); + QWhatsThis::add(browseorder_, conf->comments_.toolTip("browseorder")); + QWhatsThis::add(useimplicitclasses_, conf->comments_.toolTip("implicitclasses")); + QWhatsThis::add(useanyclasses_, conf->comments_.toolTip("implicitanyclasses")); + QWhatsThis::add(hideimplicitmembers_, conf->comments_.toolTip("hideimplicitmembers")); + QWhatsThis::add(useshortnames_, conf->comments_.toolTip("browseshortnames")); +} + +void CupsdBrowsingPage::slotAdd() +{ + QString s = BrowseDialog::newAddress(this, conf_); + if (!s.isEmpty()) + browseaddresses_->insertItem(s); +} + +void CupsdBrowsingPage::slotEdit(int index) +{ + QString s = browseaddresses_->text(index); + s = BrowseDialog::editAddress(s, this, conf_); + if (!s.isEmpty()) + browseaddresses_->setText(index, s); +} + +void CupsdBrowsingPage::slotDefaultList() +{ + browseaddresses_->clear(); + QStringList l; + l << "Send 255.255.255.255"; + browseaddresses_->insertItems(l); +} + +void CupsdBrowsingPage::intervalChanged(int val) +{ + browsetimeout_->setRange(val, 10000, 1, true); + browsetimeout_->setSteps(1, 10); +} + +#include "cupsdbrowsingpage.moc" diff --git a/kdeprint/cups/cupsdconf2/cupsdbrowsingpage.h b/kdeprint/cups/cupsdconf2/cupsdbrowsingpage.h new file mode 100644 index 000000000..655998a5e --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdbrowsingpage.h @@ -0,0 +1,55 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef CUPSDBROWSINGPAGE_H +#define CUPSDBROWSINGPAGE_H + +#include "cupsdpage.h" + +class KIntNumInput; +class QCheckBox; +class EditList; +class QComboBox; + +class CupsdBrowsingPage : public CupsdPage +{ + Q_OBJECT + +public: + CupsdBrowsingPage(QWidget *parent = 0, const char *name = 0); + + bool loadConfig(CupsdConf*, QString&); + bool saveConfig(CupsdConf*, QString&); + void setInfos(CupsdConf*); + +protected slots: + void slotAdd(); + void slotEdit(int); + void slotDefaultList(); + void intervalChanged(int); + +private: + KIntNumInput *browseport_, *browseinterval_, *browsetimeout_; + EditList *browseaddresses_; + QComboBox *browseorder_; + QCheckBox *browsing_, *cups_, *slp_; + QCheckBox *useimplicitclasses_, *hideimplicitmembers_, *useshortnames_, *useanyclasses_; +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/cupsdcomment.cpp b/kdeprint/cups/cupsdconf2/cupsdcomment.cpp new file mode 100644 index 000000000..d49a104a3 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdcomment.cpp @@ -0,0 +1,136 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "cupsdcomment.h" + +#include <qfile.h> +#include <qregexp.h> +#include <klocale.h> +#include <kstandarddirs.h> + +QString Comment::comment() +{ + QString str = comment_; + str.replace(QRegExp("<[^>]*>"), ""); + str += ("#\n" + example_); + return str; +} + +QString Comment::toolTip() +{ + QString str = comment_; + str.replace(QRegExp("^#[\\s]*"), "").replace(QRegExp("\n#[\\s]*"), "\n"); + return i18n("Do not translate the keyword between brackets (e.g. ServerName, ServerAdmin, etc.)", str.utf8()); +} + +QString Comment::key() +{ + return key_; +} + +bool Comment::load(QFile *f) +{ + comment_ = ""; + example_ = ""; + key_ = ""; + QString line, *current = &comment_; + while (!f->atEnd()) + { + f->readLine(line, 1024); + if (line.left(2) == "$$") + { + current = &example_; + } + else if (line.left(2) == "%%") + { + key_ = line.mid(2).stripWhiteSpace(); + } + else if (line.left(2) == "@@") + { + return true; + } + else if (line.stripWhiteSpace().isEmpty()) + { + ; // do nothing + } + else + { + if (line[0] != '#') break; + else + { + current->append(line); + } + } + } + return false; +} + +//------------------------------------------------------------------------------------------------------------ + +QString CupsdComment::operator[] (const QString& key) +{ + return comment(key); +} + +QString CupsdComment::comment(const QString& key) +{ + if (comments_.count() != 0 || loadComments()) + { + Comment *comm = comments_.find(key); + if (comm) + return comm->comment(); + } + return QString::null; +} + +QString CupsdComment::toolTip(const QString& key) +{ + if (comments_.count() != 0 || loadComments()) + { + Comment *comm = comments_.find(key); + if (comm) + return comm->toolTip(); + } + return QString::null; +} + +bool CupsdComment::loadComments() +{ + comments_.setAutoDelete(true); + comments_.clear(); + QFile f(locate("data", "kdeprint/cupsd.conf.template")); + if (f.exists() && f.open(IO_ReadOnly)) + { + Comment *comm; + while (!f.atEnd()) + { + comm = new Comment(); + if (!comm->load(&f)) + break; + else + { + if (comm->key().isEmpty()) + delete comm; + else + comments_.insert(comm->key(), comm); + } + } + } + return true; +} diff --git a/kdeprint/cups/cupsdconf2/cupsdcomment.h b/kdeprint/cups/cupsdconf2/cupsdcomment.h new file mode 100644 index 000000000..efe242765 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdcomment.h @@ -0,0 +1,55 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef CUPSDCOMMENT_H +#define CUPSDCOMMENT_H + +#include <qstringlist.h> +#include <qdict.h> + +class QFile; + +class Comment +{ +public: + bool load(QFile* f); + QString toolTip(); + QString comment(); + QString key(); +private: + QString comment_; + QString example_; + QString key_; +}; + +class CupsdComment +{ +public: + QString operator[] (const QString& key); + QString comment(const QString& key); + QString toolTip(const QString& key); + +private: + bool loadComments(); + +private: + QDict<Comment> comments_; +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/cupsdcomment.pl b/kdeprint/cups/cupsdconf2/cupsdcomment.pl new file mode 100644 index 000000000..b3da5ee7e --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdcomment.pl @@ -0,0 +1,61 @@ +#!/usr/bin/perl -w +# +# Filter to extract comments for translation from cupsd.conf.template +# +# This code should produce strings identical to tooltips in cupsdcomment.cpp +# +my ($comment_, $example_); +$example_ = ""; + +load(); # Skip header + +while ( <STDIN> ) +{ + if(load()) + { + print toolTip(); + } +} + +# Corresponds to Comment::load in cupsdcomment.cpp +sub load +{ + $comment_ = ""; + my($current) = \$comment_; + while ( <STDIN> ) + { + if (/^\$\$/) + { + $current = \$example_; + } + elsif (/^\%\%/) + { + next; # Do nothing + } + elsif (/^\@\@/) + { + return 1; + } + elsif (/^[\s]*$/) + { + next; # Do nothing + } + else + { + last if (!/^\#/); + ${$current} = ${$current} . $_; + } + } + return 0; +} + +# Corresponds to Comment::toolTip in cupsdcomment.cpp +sub toolTip +{ + my($str) = $comment_; + $str =~ s/\"/\\\"/g; + $str =~ s/^\#[\s]*/i18n\(\"Do not translate the keyword between brackets \(e\.g\. ServerName, ServerAdmin, etc\.\)\",\"/; + $str =~ s/\n\#[\s]*/\\n\"\n\"/g; + $str =~ s/\n$/\\n\"\n\)\;\n\n/; + return $str; +} diff --git a/kdeprint/cups/cupsdconf2/cupsdconf.cpp b/kdeprint/cups/cupsdconf2/cupsdconf.cpp new file mode 100644 index 000000000..4018ab2fb --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdconf.cpp @@ -0,0 +1,884 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include <config.h> +#include "cupsdconf.h" + +#include <qfile.h> +#include <qregexp.h> +#include <klocale.h> +#include <kdebug.h> +#include <kconfig.h> + +#include <stdlib.h> +#include <cups/cups.h> +#include <cups/ipp.h> +#include <cups/language.h> + +QString findDir(const QStringList& list) +{ + for (QStringList::ConstIterator it=list.begin(); it!=list.end(); ++it) + if (QFile::exists(*it)) + return *it; + // if nothing found, just use the first as default value + return list[0]; +} + +void splitSizeSpec(const QString& s, int& sz, int& suff) +{ + int p = s.find(QRegExp("\\D")); + sz = s.mid(0, p).toInt(); + if (p != -1) + { + switch (s[p].latin1()) + { + case 'k': suff = UNIT_KB; break; + default: + case 'm': suff = UNIT_MB; break; + case 'g': suff = UNIT_GB; break; + case 't': suff = UNIT_TILE; break; + } + } + else + suff = UNIT_MB; +} + +CupsdConf::CupsdConf() +{ + // start by trying to find CUPS directories (useful later) + datadir_ = findDir(QStringList("/usr/share/cups") + << "/usr/local/share/cups" + << "/opt/share/cups" + << "/opt/local/share/cups"); + documentdir_ = findDir(QStringList(datadir_+"/doc") + << datadir_.left(datadir_.length()-5)+"/doc/cups"); + //fontpath_ << (datadir_+"/fonts"); + requestdir_ = findDir(QStringList("/var/spool/cups") + << "/var/cups"); + serverbin_ = findDir(QStringList("/usr/lib" KDELIBSUFF "/cups") + << "/usr/local/lib" KDELIBSUFF "/cups" + << "/opt/lib" KDELIBSUFF "/cups" + << "/opt/local/lib" KDELIBSUFF "/cups"); + serverfiles_ = findDir(QStringList("/etc/cups") + << "/usr/local/etc/cups"); + tmpfiles_ = requestdir_+"/tmp"; + + // other options + servername_ = QString::null; + serveradmin_ = QString::null; + classification_ = CLASS_NONE; + otherclassname_ = QString::null; + classoverride_ = false; + charset_ = "utf-8"; + language_ = "en"; + printcap_ = "/etc/printcap"; + printcapformat_ = PRINTCAP_BSD; + remoteroot_ = "remroot"; + systemgroup_ = "sys"; + encryptcert_ = serverfiles_+"/ssl/server.crt"; + encryptkey_ = serverfiles_+"/ssl/server.key"; + hostnamelookup_ = HOSTNAME_OFF; + keepalive_ = true; + keepalivetimeout_ = 60; + maxclients_ = 100; + maxrequestsize_ = "0"; + clienttimeout_ = 300; + // listenaddresses_ + QString logdir = findDir(QStringList("/var/log/cups") + << "/var/spool/cups/log" + << "/var/cups/log"); + accesslog_ = logdir+"/access_log"; + errorlog_ = logdir+"/error_log"; + pagelog_ = logdir+"/page_log"; + maxlogsize_ = "1m"; + loglevel_ = LOGLEVEL_INFO; + keepjobhistory_ = true; + keepjobfiles_ = false; + autopurgejobs_ = false; + maxjobs_ = 0; + maxjobsperprinter_ = 0; + maxjobsperuser_ = 0; + user_ = "lp"; + group_ = "sys"; + ripcache_ = "8m"; + filterlimit_ = 0; + browsing_ = true; + browseprotocols_ << "CUPS"; + browseport_ = ippPort(); + browseinterval_ = 30; + browsetimeout_ = 300; + // browseaddresses_ + browseorder_ = ORDER_ALLOW_DENY; + useimplicitclasses_ = true; + hideimplicitmembers_ = true; + useshortnames_ = true; + useanyclasses_ = false; + + loadAvailableResources(); +} + +CupsdConf::~CupsdConf() +{ +} + +bool CupsdConf::loadFromFile(const QString& filename) +{ + QFile f(filename); + if (!f.exists() || !f.open(IO_ReadOnly)) return false; + else + { + QTextStream t(&f); + QString line; + bool done(false), value(true); + while (!done && value) + { + line = t.readLine().simplifyWhiteSpace(); + if (line.isEmpty()) + { + if (t.atEnd()) done = true; + else continue; + } + else if (line[0] == '#') continue; + else if (line.left(9).lower() == "<location") + { + CupsLocation *location = new CupsLocation(); + locations_.append(location); + if (!location->parseResource(line) || !parseLocation(location, t)) + value = false; + // search corresponding resource + for (resources_.first();resources_.current();resources_.next()) + if (resources_.current()->path_ == location->resourcename_) + location->resource_ = resources_.current(); + } + else value = parseOption(line); + } + f.close(); + return value; + } +} + +bool CupsdConf::saveToFile(const QString& filename) +{ + QFile f(filename); + if (!f.open(IO_WriteOnly)) + return false; + else + { + QTextStream t(&f); + t << comments_["header"] << endl; + t << "# Server" << endl << endl; + + t << comments_["servername"] << endl; + if ( !servername_.isEmpty() ) + t << "ServerName " << servername_ << endl; + + t << endl << comments_["serveradmin"] << endl; + if ( !serveradmin_.isEmpty() ) + t << "ServerAdmin " << serveradmin_ << endl; + + t << endl << comments_["classification"] << endl; + t << "Classification "; + switch (classification_) + { + default: + case CLASS_NONE: t << "none"; break; + case CLASS_CLASSIFIED: t << "classified"; break; + case CLASS_CONFIDENTIAL: t << "confidential"; break; + case CLASS_SECRET: t << "secret"; break; + case CLASS_TOPSECRET: t << "topsecret"; break; + case CLASS_UNCLASSIFIED: t << "unclassified"; break; + case CLASS_OTHER: t << otherclassname_; break; + } + t << endl; + + t << endl << comments_["classifyoverride"] << endl; + if (classification_ != CLASS_NONE) t << "ClassifyOverride " << (classoverride_ ? "Yes" : "No") << endl; + + t << endl << comments_["defaultcharset"] << endl; + t << "DefaultCharset " << charset_.upper() << endl; + + t << endl << comments_["defaultlanguage"] << endl; + t << "DefaultLanguage " << language_.lower() << endl; + + t << endl << comments_["printcap"] << endl; + t << "Printcap " << printcap_ << endl; + + t << endl << comments_["printcapformat"] << endl; + t << "PrintcapFormat " << (printcapformat_ == PRINTCAP_SOLARIS ? "Solaris" : "BSD") << endl; + + t << endl << "# Security" << endl; + t << endl << comments_["remoteroot"] << endl; + t << "RemoteRoot " << remoteroot_ << endl; + + t << endl << comments_["systemgroup"] << endl; + t << "SystemGroup " << systemgroup_ << endl; + + t << endl << comments_["servercertificate"] << endl; + t << "ServerCertificate " << encryptcert_ << endl; + + t << endl << comments_["serverkey"] << endl; + t << "ServerKey " << encryptkey_ << endl; + + t << endl << comments_["locations"] << endl; + for (locations_.first(); locations_.current(); locations_.next()) + { + CupsLocation *loc = locations_.current(); + t << "<Location " << loc->resourcename_ << ">" << endl; + if (loc->authtype_ != AUTHTYPE_NONE) + { + t << "AuthType "; + switch (loc->authtype_) + { + case AUTHTYPE_BASIC: t << "Basic"; break; + case AUTHTYPE_DIGEST: t << "Digest"; break; + } + t << endl; + } + if (loc->authclass_ != AUTHCLASS_ANONYMOUS) + { + switch (loc->authclass_) + { + case AUTHCLASS_USER: + if (!loc->authname_.isEmpty()) + t << "Require user " << loc->authname_ << endl; + else + t << "AuthClass User" << endl; + break; + case AUTHCLASS_GROUP: + if (!loc->authname_.isEmpty()) + t << "Require group " << loc->authname_ << endl; + else + t << "AuthClass Group" << endl; + break; + case AUTHCLASS_SYSTEM: + t << "AuthClass System" << endl; + break; + } + } + t << "Encryption "; + switch (loc->encryption_) + { + case ENCRYPT_ALWAYS: t << "Always"; break; + case ENCRYPT_NEVER: t << "Never"; break; + case ENCRYPT_REQUIRED: t << "Required"; break; + default: + case ENCRYPT_IFREQUESTED: t << "IfRequested"; break; + } + t << endl; + t << "Satisfy " << (loc->satisfy_ == SATISFY_ALL ? "All" : "Any") << endl; + t << "Order " << (loc->order_ == ORDER_ALLOW_DENY ? "allow,deny" : "deny,allow") << endl; + for (QStringList::ConstIterator it=loc->addresses_.begin(); it!=loc->addresses_.end(); ++it) + t << *it << endl; + t << "</Location>" << endl; + } + + t << endl << "# Network" << endl; + t << endl << comments_["hostnamelookups"] << endl; + t << "HostnameLookups "; + switch (hostnamelookup_) + { + default: + case HOSTNAME_OFF: t << "Off"; break; + case HOSTNAME_ON: t << "On"; break; + case HOSTNAME_DOUBLE: t << "Double"; break; + } + t << endl; + + t << endl << comments_["keepalive"] << endl; + t << "KeepAlive " << (keepalive_ ? "On" : "Off") << endl; + + t << endl << comments_["keepalivetimeout"] << endl; + t << "KeepAliveTimeout " << keepalivetimeout_ << endl; + + t << endl << comments_["maxclients"] << endl; + t << "MaxClients " << maxclients_ << endl; + + t << endl << comments_["maxrequestsize"] << endl; + t << "MaxRequestSize " << maxrequestsize_ << endl; + + t << endl << comments_["timeout"] << endl; + t << "Timeout " << clienttimeout_ << endl; + + t << endl << comments_["listen"] << endl; + for (QStringList::ConstIterator it=listenaddresses_.begin(); it!=listenaddresses_.end(); ++it) + t << *it << endl; + + t << endl << "# Log" << endl; + t << endl << comments_["accesslog"] << endl; + t << "AccessLog " << accesslog_ << endl; + + t << endl << comments_["errorlog"] << endl; + t << "ErrorLog " << errorlog_ << endl; + + t << endl << comments_["pagelog"] << endl; + t << "PageLog " << pagelog_ << endl; + + t << endl << comments_["maxlogsize"] << endl; + //t << "MaxLogSize " << maxlogsize_ << "m" << endl; + t << "MaxLogSize " << maxlogsize_ << endl; + + t << endl << comments_["loglevel"] << endl; + t << "LogLevel "; + switch (loglevel_) + { + case LOGLEVEL_NONE: t << "none"; break; + default: + case LOGLEVEL_INFO: t << "info"; break; + case LOGLEVEL_ERROR: t << "error"; break; + case LOGLEVEL_WARN: t << "warn"; break; + case LOGLEVEL_DEBUG: t << "debug"; break; + case LOGLEVEL_DEBUG2: t << "debug2"; break; + } + t << endl; + + t << endl << "# Jobs" << endl; + t << endl << comments_["preservejobhistory"] << endl; + t << "PreserveJobHistory " << (keepjobhistory_ ? "On" : "Off") << endl; + + t << endl << comments_["preservejobfiles"] << endl; + if (keepjobhistory_) t << "PreserveJobFiles " << (keepjobfiles_ ? "On" : "Off") << endl; + + t << endl << comments_["autopurgejobs"] << endl; + if (keepjobhistory_) t << "AutoPurgeJobs " << (autopurgejobs_ ? "Yes" : "No") << endl; + + t << endl << comments_["maxjobs"] << endl; + t << "MaxJobs " << maxjobs_ << endl; + + t << endl << comments_["maxjobsperprinter"] << endl; + t << "MaxJobsPerPrinter " << maxjobsperprinter_ << endl; + + t << endl << comments_["maxjobsperuser"] << endl; + t << "MaxJobsPerUser " << maxjobsperuser_ << endl; + + t << endl << "# Filter" << endl; + t << endl << comments_["user"] << endl; + t << "User " << user_ << endl; + + t << endl << comments_["group"] << endl; + t << "Group " << group_ << endl; + + t << endl << comments_["ripcache"] << endl; + t << "RIPCache " << ripcache_ << endl; + + t << endl << comments_["filterlimit"] << endl; + t << "FilterLimit " << filterlimit_ << endl; + + t << endl << "# Directories" << endl; + t << endl << comments_["datadir"] << endl; + t << "DataDir " << datadir_ << endl; + + t << endl << comments_["documentroot"] << endl; + t << "DocumentRoot " << documentdir_ << endl; + + t << endl << comments_["fontpath"] << endl; + for (QStringList::ConstIterator it=fontpath_.begin(); it!=fontpath_.end(); ++it) + t << "FontPath " << *it << endl; + + t << endl << comments_["requestroot"] << endl; + t << "RequestRoot " << requestdir_ << endl; + + t << endl << comments_["serverbin"] << endl; + t << "ServerBin " << serverbin_ << endl; + + t << endl << comments_["serverroot"] << endl; + t << "ServerRoot " << serverfiles_ << endl; + + t << endl << comments_["tempdir"] << endl; + t << "TempDir " << tmpfiles_ << endl; + + t << endl << "# Browsing" << endl; + t << endl << comments_["browsing"] << endl; + t << "Browsing " << (browsing_ ? "On" : "Off") << endl; + + t << endl << comments_["browseprotocols"] << endl; + if (browsing_) + { + t << "BrowseProtocols "; + for (QStringList::ConstIterator it=browseprotocols_.begin(); it!=browseprotocols_.end(); ++it) + t << (*it).upper() << " "; + t << endl; + } + + t << endl << comments_["browseport"] << endl; + if (browsing_) t << "BrowsePort " << browseport_ << endl; + + t << endl << comments_["browseinterval"] << endl; + if (browsing_) t << "BrowseInterval " << browseinterval_ << endl; + + t << endl << comments_["browsetimeout"] << endl; + if (browsing_) t << "BrowseTimeout " << browsetimeout_ << endl; + + t << endl << comments_["browseaddress"] << endl; + if (browsing_) + for (QStringList::ConstIterator it=browseaddresses_.begin(); it!=browseaddresses_.end(); ++it) + if ((*it).startsWith("Send")) + t << "BrowseAddress " << (*it).mid(5) << endl; + else + t << "Browse" << (*it) << endl; + + t << endl << comments_["browseorder"] << endl; + if (browsing_) t << "BrowseOrder " << (browseorder_ == ORDER_ALLOW_DENY ? "allow,deny" : "deny,allow") << endl; + + t << endl << comments_["implicitclasses"] << endl; + if (browsing_) t << "ImplicitClasses " << (useimplicitclasses_ ? "On" : "Off") << endl; + + t << endl << comments_["implicitanyclasses"] << endl; + if (browsing_) t << "ImplicitAnyClasses " << (useanyclasses_ ? "On" : "Off") << endl; + + t << endl << comments_["hideimplicitmembers"] << endl; + if (browsing_) t << "HideImplicitMembers " << (hideimplicitmembers_ ? "Yes" : "No") << endl; + + t << endl << comments_["browseshortnames"] << endl; + if (browsing_) t << "BrowseShortNames " << (useshortnames_ ? "Yes" : "No") << endl; + + t << endl << "# Unknown" << endl; + for (QValueList< QPair<QString,QString> >::ConstIterator it=unknown_.begin(); it!=unknown_.end(); ++it) + t << (*it).first << " " << (*it).second << endl; + + return true; + } +} + +bool CupsdConf::parseLocation(CupsLocation *location, QTextStream& file) +{ + QString line; + bool done(false); + bool value(true); + while (!done && value) + { + line = file.readLine().simplifyWhiteSpace(); + if (line.isEmpty()) + { + if (file.atEnd()) + { + value = false; + done = true; + } + else continue; + } + else if (line[0] == '#') continue; + else if (line.lower() == "</location>") done = true; + else value = location->parseOption(line); + } + return value; +} + +bool CupsdConf::parseOption(const QString& line) +{ + int p(-1); + QString keyword, value, l(line.simplifyWhiteSpace()); + + if ((p=l.find(' ')) != -1) + { + keyword = l.left(p).lower(); + value = l.mid(p+1); + } + else + { + keyword = l.lower(); + } + + //kdDebug() << "cupsd.conf keyword=" << keyword << endl; + if (keyword == "accesslog") accesslog_ = value; + else if (keyword == "autopurgejobs") autopurgejobs_ = (value.lower() == "yes"); + else if (keyword == "browseaddress") browseaddresses_.append("Send "+value); + else if (keyword == "browseallow") browseaddresses_.append("Allow "+value); + else if (keyword == "browsedeny") browseaddresses_.append("Deny "+value); + else if (keyword == "browseinterval") browseinterval_ = value.toInt(); + else if (keyword == "browseorder") browseorder_ = (value.lower() == "deny,allow" ? ORDER_DENY_ALLOW : ORDER_ALLOW_DENY); + else if (keyword == "browsepoll") browseaddresses_.append("Poll "+value); + else if (keyword == "browseport") browseport_ = value.toInt(); + else if (keyword == "browseprotocols") + { + browseprotocols_.clear(); + QStringList prots = QStringList::split(QRegExp("\\s"), value, false); + if (prots.find("all") != prots.end()) + browseprotocols_ << "CUPS" << "SLP"; + else + for (QStringList::ConstIterator it=prots.begin(); it!=prots.end(); ++it) + browseprotocols_ << (*it).upper(); + } + else if (keyword == "browserelay") browseaddresses_.append("Relay "+value); + else if (keyword == "browseshortnames") useshortnames_ = (value.lower() != "no"); + else if (keyword == "browsetimeout") browsetimeout_ = value.toInt(); + else if (keyword == "browsing") browsing_ = (value.lower() != "off"); + else if (keyword == "classification") + { + QString cl = value.lower(); + if (cl == "none") classification_ = CLASS_NONE; + else if (cl == "classified") classification_ = CLASS_CLASSIFIED; + else if (cl == "confidential") classification_ = CLASS_CONFIDENTIAL; + else if (cl == "secret") classification_ = CLASS_SECRET; + else if (cl == "topsecret") classification_ = CLASS_TOPSECRET; + else if (cl == "unclassified") classification_ = CLASS_UNCLASSIFIED; + else + { + classification_ = CLASS_OTHER; + otherclassname_ = cl; + } + } + else if (keyword == "classifyoverride") classoverride_ = (value.lower() == "yes"); + else if (keyword == "datadir") datadir_ = value; + else if (keyword == "defaultcharset") charset_ = value; + else if (keyword == "defaultlanguage") language_ = value; + else if (keyword == "documentroot") documentdir_ = value; + else if (keyword == "errorlog") errorlog_ = value; + else if (keyword == "filterlimit") filterlimit_ = value.toInt(); + else if (keyword == "fontpath") fontpath_ += QStringList::split(':', value, false); + else if (keyword == "group") group_ = value; + else if (keyword == "hideimplicitmembers") hideimplicitmembers_ = (value.lower() != "no"); + else if (keyword == "hostnamelookups") + { + QString h = value.lower(); + if (h == "on") hostnamelookup_ = HOSTNAME_ON; + else if (h == "double") hostnamelookup_ = HOSTNAME_DOUBLE; + else hostnamelookup_ = HOSTNAME_OFF; + } + else if (keyword == "implicitclasses") useimplicitclasses_ = (value.lower() != "off"); + else if (keyword == "implicitanyclasses") useanyclasses_ = (value.lower() == "on"); + else if (keyword == "keepalive") keepalive_ = (value.lower() != "off"); + else if (keyword == "keepalivetimeout") keepalivetimeout_ = value.toInt(); + else if (keyword == "listen") listenaddresses_.append("Listen "+value); + else if (keyword == "loglevel") + { + QString ll = value.lower(); + if (ll == "none") loglevel_ = LOGLEVEL_NONE; + else if (ll == "error") loglevel_ = LOGLEVEL_ERROR; + else if (ll == "warn") loglevel_ = LOGLEVEL_WARN; + else if (ll == "info") loglevel_ = LOGLEVEL_INFO; + else if (ll == "debug") loglevel_ = LOGLEVEL_DEBUG; + else if (ll == "debug2") loglevel_ = LOGLEVEL_DEBUG2; + } + else if (keyword == "maxclients") maxclients_ = value.toInt(); + else if (keyword == "maxjobs") maxjobs_ = value.toInt(); + else if (keyword == "maxjobsperprinter") maxjobsperprinter_ = value.toInt(); + else if (keyword == "maxjobsperuser") maxjobsperuser_ = value.toInt(); + else if (keyword == "maxrequestsize") maxrequestsize_ = value; + else if (keyword == "maxlogsize") maxlogsize_ = value; + /*{ + // FIXME: support for suffixes + int suffix; + splitSizeSpec( value, maxlogsize_, suffix ); + }*/ + else if (keyword == "pagelog") pagelog_ = value; + else if (keyword == "port") listenaddresses_.append("Listen *:"+value); + else if (keyword == "preservejobhistory") keepjobhistory_ = (value != "off"); + else if (keyword == "preservejobfiles") keepjobfiles_ = (value == "on"); + else if (keyword == "printcap") printcap_ = value; + else if (keyword == "printcapformat") printcapformat_ = (value.lower() == "solaris" ? PRINTCAP_SOLARIS : PRINTCAP_BSD); + else if (keyword == "requestroot") requestdir_ = value; + else if (keyword == "remoteroot") remoteroot_ = value; + else if (keyword == "ripcache") ripcache_ = value; + else if (keyword == "serveradmin") serveradmin_ = value; + else if (keyword == "serverbin") serverbin_ = value; + else if (keyword == "servercertificate") encryptcert_ = value; + else if (keyword == "serverkey") encryptkey_ = value; + else if (keyword == "servername") servername_ = value; + else if (keyword == "serverroot") serverfiles_ = value; + else if (keyword == "ssllisten") listenaddresses_.append("SSLListen "+value); + else if (keyword == "sslport") listenaddresses_.append("SSLListen *:"+value); + else if (keyword == "systemgroup") systemgroup_ = value; + else if (keyword == "tempdir") tmpfiles_ = value; + else if (keyword == "timeout") clienttimeout_ = value.toInt(); + else if (keyword == "user") user_ = value; + else + { + // unrecognized option + unknown_ << QPair<QString,QString>(keyword, value); + } + return true; +} + +bool CupsdConf::loadAvailableResources() +{ + KConfig conf("kdeprintrc"); + conf.setGroup("CUPS"); + QString host = conf.readEntry("Host",cupsServer()); + int port = conf.readNumEntry("Port",ippPort()); + http_t *http_ = httpConnect(host.local8Bit(),port); + + resources_.clear(); + // standard resources + resources_.append(new CupsResource("/")); + resources_.append(new CupsResource("/admin")); + resources_.append(new CupsResource("/printers")); + resources_.append(new CupsResource("/classes")); + resources_.append(new CupsResource("/jobs")); + + if (!http_) + return false; + + // printer resources + ipp_t *request_ = ippNew(); + cups_lang_t* lang = cupsLangDefault(); + ippAddString(request_, IPP_TAG_OPERATION, IPP_TAG_CHARSET, "attributes-charset", NULL, cupsLangEncoding(lang)); + ippAddString(request_, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE, "attributes-natural-language", NULL, lang->language); + request_->request.op.operation_id = CUPS_GET_PRINTERS; + request_ = cupsDoRequest(http_, request_, "/printers/"); + if (request_) + { + QString name; + int type(0); + ipp_attribute_t *attr = request_->attrs; + while (attr) + { + // check new printer (keep only local non-implicit printers) + if (!attr->name) + { + if (!(type & CUPS_PRINTER_REMOTE) && !(type & CUPS_PRINTER_IMPLICIT) && !name.isEmpty()) + resources_.append(new CupsResource("/printers/"+name)); + name = ""; + type = 0; + } + else if (strcmp(attr->name, "printer-name") == 0) name = attr->values[0].string.text; + else if (strcmp(attr->name, "printer-type") == 0) type = attr->values[0].integer; + attr = attr->next; + } + if (!(type & CUPS_PRINTER_REMOTE) && !(type & CUPS_PRINTER_IMPLICIT) && !name.isEmpty()) + resources_.append(new CupsResource("/printers/"+name)); + ippDelete(request_); + } + // class resources + request_ = ippNew(); + ippAddString(request_, IPP_TAG_OPERATION, IPP_TAG_CHARSET, "attributes-charset", NULL, cupsLangEncoding(lang)); + ippAddString(request_, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE, "attributes-natural-language", NULL, lang->language); + request_->request.op.operation_id = CUPS_GET_CLASSES; + request_ = cupsDoRequest(http_, request_, "/classes/"); + if (request_) + { + QString name; + int type(0); + ipp_attribute_t *attr = request_->attrs; + while (attr) + { + // check new class (keep only local classes) + if (!attr->name) + { + if (!(type & CUPS_PRINTER_REMOTE) && !name.isEmpty()) + resources_.append(new CupsResource("/classes/"+name)); + name = ""; + type = 0; + } + else if (strcmp(attr->name, "printer-name") == 0) name = attr->values[0].string.text; + else if (strcmp(attr->name, "printer-type") == 0) type = attr->values[0].integer; + attr = attr->next; + } + if (!(type & CUPS_PRINTER_REMOTE) && !name.isEmpty()) + resources_.append(new CupsResource("/classes/"+name)); + ippDelete(request_); + } + httpClose(http_); + return true; +} + +//------------------------------------------------------------------------------------------------ + +CupsLocation::CupsLocation() +{ + resource_ = 0; + resourcename_ = ""; + authtype_ = AUTHTYPE_NONE; + authclass_ = AUTHCLASS_ANONYMOUS; + authname_ = QString::null; + encryption_ = ENCRYPT_IFREQUESTED; + satisfy_ = SATISFY_ALL; + order_ = ORDER_ALLOW_DENY; + // addresses_ +} + +CupsLocation::CupsLocation(const CupsLocation& loc) +: resource_(loc.resource_), + resourcename_(loc.resourcename_), + authtype_(loc.authtype_), + authclass_(loc.authclass_), + authname_(loc.authname_), + encryption_(loc.encryption_), + satisfy_(loc.satisfy_), + order_(loc.order_), + addresses_(loc.addresses_) +{ +} + +bool CupsLocation::parseResource(const QString& line) +{ + QString str = line.simplifyWhiteSpace(); + int p1 = line.find(' '), p2 = line.find('>'); + if (p1 != -1 && p2 != -1) + { + resourcename_ = str.mid(p1+1,p2-p1-1); + return true; + } + else return false; +} + +bool CupsLocation::parseOption(const QString& line) +{ + int p(-1); + QString keyword, value, l(line.simplifyWhiteSpace()); + + if ((p=l.find(' ')) != -1) + { + keyword = l.left(p).lower(); + value = l.mid(p+1); + } + else + { + keyword = l.lower(); + } + + if (keyword == "authtype") + { + QString a = value.lower(); + if (a == "basic") authtype_ = AUTHTYPE_BASIC; + else if (a == "digest") authtype_ = AUTHTYPE_DIGEST; + else authtype_ = AUTHTYPE_NONE; + } + else if (keyword == "authclass") + { + QString a = value.lower(); + if (a == "user") authclass_ = AUTHCLASS_USER; + else if (a == "system") authclass_ = AUTHCLASS_SYSTEM; + else if (a == "group") authclass_ = AUTHCLASS_GROUP; + else authclass_ = AUTHCLASS_ANONYMOUS; + } + else if (keyword == "authgroupname") authname_ = value; + else if (keyword == "require") + { + int p = value.find(' '); + if (p != -1) + { + authname_ = value.mid(p+1); + QString cl = value.left(p).lower(); + if (cl == "user") + authclass_ = AUTHCLASS_USER; + else if (cl == "group") + authclass_ = AUTHCLASS_GROUP; + } + } + else if (keyword == "allow") addresses_.append("Allow "+value); + else if (keyword == "deny") addresses_.append("Deny "+value); + else if (keyword == "order") order_ = (value.lower() == "deny,allow" ? ORDER_DENY_ALLOW : ORDER_ALLOW_DENY); + else if (keyword == "encryption") + { + QString e = value.lower(); + if (e == "always") encryption_ = ENCRYPT_ALWAYS; + else if (e == "never") encryption_ = ENCRYPT_NEVER; + else if (e == "required") encryption_ = ENCRYPT_REQUIRED; + else encryption_ = ENCRYPT_IFREQUESTED; + } + else if (keyword == "satisfy") satisfy_ = (value.lower() == "any" ? SATISFY_ANY : SATISFY_ALL); + else return false; + return true; +} + +//------------------------------------------------------------------------------------------------ + +CupsResource::CupsResource() +{ + type_ = RESOURCE_GLOBAL; +} + +CupsResource::CupsResource(const QString& path) +{ + setPath(path); +} + +void CupsResource::setPath(const QString& path) +{ + path_ = path; + type_ = typeFromPath(path_); + text_ = pathToText(path_); +} + +int CupsResource::typeFromText(const QString& text) +{ + if (text == i18n("Base", "Root") || text == i18n("All printers") || text == i18n("All classes") || text == i18n("Print jobs")) return RESOURCE_GLOBAL; + else if (text == i18n("Administration")) return RESOURCE_ADMIN; + else if (text.find(i18n("Class")) == 0) return RESOURCE_CLASS; + else if (text.find(i18n("Printer")) == 0) return RESOURCE_PRINTER; + else return RESOURCE_PRINTER; +} + +int CupsResource::typeFromPath(const QString& path) +{ + if (path == "/admin") return RESOURCE_ADMIN; + else if (path == "/printers" || path == "/classes" || path == "/" || path == "/jobs") return RESOURCE_GLOBAL; + else if (path.left(9) == "/printers") return RESOURCE_PRINTER; + else if (path.left(8) == "/classes") return RESOURCE_CLASS; + else return RESOURCE_GLOBAL; +} + +QString CupsResource::textToPath(const QString& text) +{ + QString path("/"); + if (text == i18n("Administration")) path = "/admin"; + else if (text == i18n("All printers")) path = "/printers"; + else if (text == i18n("All classes")) path = "/classes"; + else if (text == i18n("Print jobs")) path = "/jobs"; + else if (text == i18n("Base", "Root")) path = "/"; + else if (text.find(i18n("Printer")) == 0) + { + path = "/printers/"; + path.append(text.right(text.length()-i18n("Printer").length()-1)); + } + else if (text.find(i18n("Class")) == 0) + { + path = "/classes/"; + path.append(text.right(text.length()-i18n("Class").length()-1)); + } + return path; +} + +QString CupsResource::pathToText(const QString& path) +{ + QString text(i18n("Base", "Root")); + if (path == "/admin") text = i18n("Administration"); + else if (path == "/printers") text = i18n("All printers"); + else if (path == "/classes") text = i18n("All classes"); + else if (path == "/") text = i18n("Root"); + else if (path == "/jobs") text = i18n("Print jobs"); + else if (path.find("/printers/") == 0) + { + text = i18n("Printer"); + text.append(" "); + text.append(path.right(path.length()-10)); + } + else if (path.find("/classes/") == 0) + { + text = i18n("Class"); + text.append(" "); + text.append(path.right(path.length()-9)); + } + return text; +} + +QString CupsResource::typeToIconName(int type) +{ + switch (type) + { + case RESOURCE_ADMIN: + case RESOURCE_GLOBAL: + return QString("folder"); + case RESOURCE_PRINTER: + return QString("kdeprint_printer"); + case RESOURCE_CLASS: + return QString("kdeprint_printer_class"); + } + return QString("folder"); +} diff --git a/kdeprint/cups/cupsdconf2/cupsdconf.h b/kdeprint/cups/cupsdconf2/cupsdconf.h new file mode 100644 index 000000000..3c53c5390 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdconf.h @@ -0,0 +1,181 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef CUPSDCONF_H +#define CUPSDCONF_H + +#include <qstring.h> +#include <qstringlist.h> +#include <qptrlist.h> +#include <qtextstream.h> +#include <qpair.h> + +#include "cupsdcomment.h" + +enum LogLevelType { LOGLEVEL_DEBUG2 = 0, LOGLEVEL_DEBUG, LOGLEVEL_INFO, LOGLEVEL_WARN, LOGLEVEL_ERROR, LOGLEVEL_NONE }; +enum OrderType { ORDER_ALLOW_DENY = 0, ORDER_DENY_ALLOW }; +enum AuthTypeType { AUTHTYPE_NONE = 0, AUTHTYPE_BASIC, AUTHTYPE_DIGEST }; +enum AuthClassType { AUTHCLASS_ANONYMOUS = 0, AUTHCLASS_USER, AUTHCLASS_SYSTEM, AUTHCLASS_GROUP }; +enum EncryptionType { ENCRYPT_ALWAYS = 0, ENCRYPT_NEVER, ENCRYPT_REQUIRED, ENCRYPT_IFREQUESTED }; +enum BrowseProtocolType { BROWSE_ALL = 0, BROWSE_CUPS, BROWSE_SLP }; +enum PrintcapFormatType { PRINTCAP_BSD = 0, PRINTCAP_SOLARIS }; +enum HostnameLookupType { HOSTNAME_OFF = 0, HOSTNAME_ON, HOSTNAME_DOUBLE }; +enum ClassificationType { CLASS_NONE = 0, CLASS_CLASSIFIED, CLASS_CONFIDENTIAL, CLASS_SECRET, CLASS_TOPSECRET, CLASS_UNCLASSIFIED, CLASS_OTHER }; +enum SatisfyType { SATISFY_ALL = 0, SATISFY_ANY }; +enum UnitType { UNIT_KB = 0, UNIT_MB, UNIT_GB, UNIT_TILE }; + +struct CupsLocation; +struct CupsResource; +enum ResourceType { RESOURCE_GLOBAL, RESOURCE_PRINTER, RESOURCE_CLASS, RESOURCE_ADMIN }; + +struct CupsdConf +{ +// functions member + CupsdConf(); + ~CupsdConf(); + + bool loadFromFile(const QString& filename); + bool saveToFile(const QString& filename); + bool parseOption(const QString& line); + bool parseLocation(CupsLocation *location, QTextStream& file); + + bool loadAvailableResources(); + + static CupsdConf* get(); + static void release(); + +// data members + static CupsdConf *unique_; + + // Server + QString servername_; + QString serveradmin_; + int classification_; + QString otherclassname_; + bool classoverride_; + QString charset_; + QString language_; + QString printcap_; + int printcapformat_; + + // Security + QString remoteroot_; + QString systemgroup_; + QString encryptcert_; + QString encryptkey_; + QPtrList<CupsLocation> locations_; + QPtrList<CupsResource> resources_; + + // Network + int hostnamelookup_; + bool keepalive_; + int keepalivetimeout_; + int maxclients_; + QString maxrequestsize_; + int clienttimeout_; + QStringList listenaddresses_; + + // Log + QString accesslog_; + QString errorlog_; + QString pagelog_; + QString maxlogsize_; + int loglevel_; + + // Jobs + bool keepjobhistory_; + bool keepjobfiles_; + bool autopurgejobs_; + int maxjobs_; + int maxjobsperprinter_; + int maxjobsperuser_; + + // Filter + QString user_; + QString group_; + QString ripcache_; + int filterlimit_; + + // Directories + QString datadir_; + QString documentdir_; + QStringList fontpath_; + QString requestdir_; + QString serverbin_; + QString serverfiles_; + QString tmpfiles_; + + // Browsing + bool browsing_; + QStringList browseprotocols_; + int browseport_; + int browseinterval_; + int browsetimeout_; + QStringList browseaddresses_; + int browseorder_; + bool useimplicitclasses_; + bool hideimplicitmembers_; + bool useshortnames_; + bool useanyclasses_; + + // cupsd.conf file comments + CupsdComment comments_; + + // unrecognized options + QValueList< QPair<QString,QString> > unknown_; +}; + +struct CupsLocation +{ + CupsLocation(); + CupsLocation(const CupsLocation& loc); + + bool parseOption(const QString& line); + bool parseResource(const QString& line); + + CupsResource *resource_; + QString resourcename_; + int authtype_; + int authclass_; + QString authname_; + int encryption_; + int satisfy_; + int order_; + QStringList addresses_; +}; + +struct CupsResource +{ + CupsResource(); + CupsResource(const QString& path); + + void setPath(const QString& path); + + int type_; + QString path_; + QString text_; + + static QString textToPath(const QString& text); + static QString pathToText(const QString& path); + static int typeFromPath(const QString& path); + static int typeFromText(const QString& text); + static QString typeToIconName(int type); +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/cupsddialog.cpp b/kdeprint/cups/cupsdconf2/cupsddialog.cpp new file mode 100644 index 000000000..a70b5b59e --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsddialog.cpp @@ -0,0 +1,360 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "cupsddialog.h" + +#include "cupsdpage.h" +#include "cupsdconf.h" +#include "cupsdsplash.h" +#include "cupsdserverpage.h" +#include "cupsdlogpage.h" +#include "cupsdjobspage.h" +#include "cupsdfilterpage.h" +#include "cupsddirpage.h" +#include "cupsdnetworkpage.h" +#include "cupsdbrowsingpage.h" +#include "cupsdsecuritypage.h" + +#include <qdir.h> +#include <qvbox.h> +#include <kmessagebox.h> +#include <klocale.h> +#include <qfile.h> +#include <qfileinfo.h> +#include <kglobal.h> +#include <kiconloader.h> +#include <qstringlist.h> +#include <qwhatsthis.h> +#include <kio/passdlg.h> +#include <kguiitem.h> +#include <kprocess.h> + +#include <signal.h> +#include <cups/cups.h> + +static bool dynamically_loaded = false; +static QString pass_string; + +extern "C" +{ +#include "cups-util.h" + KDEPRINT_EXPORT bool restartServer(QString& msg) + { + return CupsdDialog::restartServer(msg); + } + KDEPRINT_EXPORT bool configureServer(QWidget *parent, QString& msg) + { + dynamically_loaded = true; + bool result = CupsdDialog::configure(QString::null, parent, &msg); + dynamically_loaded = false; + return result; + } +} + +int getServerPid() +{ + QDir dir("/proc",QString::null,QDir::Name,QDir::Dirs); + for (uint i=0;i<dir.count();i++) + { + if (dir[i] == "." || dir[i] == ".." || dir[i] == "self") continue; + QFile f("/proc/" + dir[i] + "/cmdline"); + if (f.exists() && f.open(IO_ReadOnly)) + { + QTextStream t(&f); + QString line; + t >> line; + f.close(); + if (line.right(5) == "cupsd" || + line.right(6).left(5) == "cupsd") // second condition for 2.4.x kernels + // which add a null byte at the end + return dir[i].toInt(); + } + } + return (-1); +} + +const char* getPassword(const char*) +{ + QString user(cupsUser()); + QString pass; + + if (KIO::PasswordDialog::getNameAndPassword(user, pass, NULL) == QDialog::Accepted) + { + cupsSetUser(user.latin1()); + pass_string = pass; + if (pass_string.isEmpty()) + return ""; + else + return pass_string.latin1(); + } + else + return NULL; +} + +//--------------------------------------------------- + +CupsdDialog::CupsdDialog(QWidget *parent, const char *name) + : KDialogBase(IconList, "", Ok|Cancel|User1, Ok, parent, name, true, true, KGuiItem(i18n("Short Help"), "help")) +{ + KGlobal::iconLoader()->addAppDir("kdeprint"); + KGlobal::locale()->insertCatalogue("cupsdconf"); + + setShowIconsInTreeList(true); + setRootIsDecorated(false); + + pagelist_.setAutoDelete(false); + filename_ = ""; + conf_ = 0; + constructDialog(); + + setCaption(i18n("CUPS Server Configuration")); + + //resize(500, 400); +} + +CupsdDialog::~CupsdDialog() +{ + delete conf_; +} + +void CupsdDialog::addConfPage(CupsdPage *page) +{ + QPixmap icon = KGlobal::instance()->iconLoader()->loadIcon( + page->pixmap(), + KIcon::NoGroup, + KIcon::SizeMedium + ); + + QVBox *box = addVBoxPage(page->pageLabel(), page->header(), icon); + page->reparent(box, QPoint(0,0)); + pagelist_.append(page); +} + +void CupsdDialog::constructDialog() +{ + addConfPage(new CupsdSplash(0)); + addConfPage(new CupsdServerPage(0)); + addConfPage(new CupsdNetworkPage(0)); + addConfPage(new CupsdSecurityPage(0)); + addConfPage(new CupsdLogPage(0)); + addConfPage(new CupsdJobsPage(0)); + addConfPage(new CupsdFilterPage(0)); + addConfPage(new CupsdDirPage(0)); + addConfPage(new CupsdBrowsingPage(0)); + + conf_ = new CupsdConf(); + for (pagelist_.first();pagelist_.current();pagelist_.next()) + { + pagelist_.current()->setInfos(conf_); + } +} + +bool CupsdDialog::setConfigFile(const QString& filename) +{ + filename_ = filename; + if (!conf_->loadFromFile(filename_)) + { + KMessageBox::error(this, i18n("Error while loading configuration file!"), i18n("CUPS Configuration Error")); + return false; + } + if (conf_->unknown_.count() > 0) + { + // there were some unknown options, warn the user + QString msg; + for (QValueList< QPair<QString,QString> >::ConstIterator it=conf_->unknown_.begin(); it!=conf_->unknown_.end(); ++it) + msg += ((*it).first + " = " + (*it).second + "<br>"); + msg.prepend("<p>" + i18n("Some options were not recognized by this configuration tool. " + "They will be left untouched and you won't be able to change them.") + "</p>"); + KMessageBox::sorry(this, msg, i18n("Unrecognized Options")); + } + bool ok(true); + QString msg; + for (pagelist_.first();pagelist_.current() && ok;pagelist_.next()) + ok = pagelist_.current()->loadConfig(conf_, msg); + if (!ok) + { + KMessageBox::error(this, msg.prepend("<qt>").append("</qt>"), i18n("CUPS Configuration Error")); + return false; + } + return true; +} + +bool CupsdDialog::restartServer(QString& msg) +{ + int serverPid = getServerPid(); + msg.truncate(0); + if (serverPid <= 0) + { + msg = i18n("Unable to find a running CUPS server"); + } + else + { + bool success = false; + if (getuid() == 0 ) + success = (::kill(serverPid, SIGHUP) == 0); + else + { + KProcess proc; + proc << "kdesu" << "-c" << "kill -SIGHUP " + QString::number( serverPid ); + success = proc.start( KProcess::Block ) && proc.normalExit(); + } + if( !success ) + msg = i18n("Unable to restart CUPS server (pid = %1)").arg(serverPid); + } + return (msg.isEmpty()); +} + +bool CupsdDialog::configure(const QString& filename, QWidget *parent, QString *msg) +{ + bool needUpload(false); + QString errormsg; + bool result = true; + + // init password dialog if needed + if (!dynamically_loaded) + cupsSetPasswordCB(getPassword); + + // load config file from server + QString fn(filename); + if (fn.isEmpty()) + { + fn = cupsGetConf(); + if (fn.isEmpty()) + errormsg = i18n("Unable to retrieve configuration file from the CUPS server. " + "You probably don't have the access permissions to perform this operation."); + else needUpload = true; + } + + // check read state (only if needed) + if (!fn.isEmpty()) + { + QFileInfo fi(fn); + if (!fi.exists() || !fi.isReadable() || !fi.isWritable()) + errormsg = i18n("Internal error: file '%1' not readable/writable!").arg(fn); + // check file size + if (fi.size() == 0) + errormsg = i18n("Internal error: empty file '%1'!").arg(fn); + } + + if (!errormsg.isEmpty()) + { + if ( !dynamically_loaded ) + KMessageBox::error(parent, errormsg.prepend("<qt>").append("</qt>"), i18n("CUPS Configuration Error")); + result = false; + } + else + { + KGlobal::locale()->insertCatalogue("cupsdconf"); // Must be before dialog is created to translate "Short Help" + CupsdDialog dlg(parent); + if (dlg.setConfigFile(fn) && dlg.exec()) + { + QCString encodedFn = QFile::encodeName(fn); + if (!needUpload) + KMessageBox::information(parent, + i18n("The config file has not been uploaded to the " + "CUPS server. The daemon will not be restarted.")); + else if (!cupsPutConf(encodedFn.data())) + { + errormsg = i18n("Unable to upload the configuration file to CUPS server. " + "You probably don't have the access permissions to perform this operation."); + if ( !dynamically_loaded ) + KMessageBox::error(parent, errormsg, i18n("CUPS configuration error")); + result = false; + } + } + + } + if (needUpload) + QFile::remove(fn); + + if ( msg ) + *msg = errormsg; + return result; +} + +void CupsdDialog::slotOk() +{ + if (conf_ && !filename_.isEmpty()) + { // try to save the file + bool ok(true); + QString msg; + CupsdConf newconf_; + for (pagelist_.first();pagelist_.current() && ok;pagelist_.next()) + ok = pagelist_.current()->saveConfig(&newconf_, msg); + // copy unknown options + newconf_.unknown_ = conf_->unknown_; + if (!ok) + { + ; // do nothing + } + else if (!newconf_.saveToFile(filename_)) + { + msg = i18n("Unable to write configuration file %1").arg(filename_); + ok = false; + } + if (!ok) + { + KMessageBox::error(this, msg.prepend("<qt>").append("</qt>"), i18n("CUPS Configuration Error")); + } + else + KDialogBase::slotOk(); + } +} + +void CupsdDialog::slotUser1() +{ + QWhatsThis::enterWhatsThisMode(); +} + +int CupsdDialog::serverPid() +{ + return getServerPid(); +} + +int CupsdDialog::serverOwner() +{ + int pid = getServerPid(); + if (pid > 0) + { + QString str; + str.sprintf("/proc/%d/status",pid); + QFile f(str); + if (f.exists() && f.open(IO_ReadOnly)) + { + QTextStream t(&f); + while (!t.eof()) + { + str = t.readLine(); + if (str.find("Uid:",0,false) == 0) + { + QStringList list = QStringList::split('\t', str, false); + if (list.count() >= 2) + { + bool ok; + int u = list[1].toInt(&ok); + if (ok) return u; + } + } + } + } + } + return (-1); +} + +#include "cupsddialog.moc" diff --git a/kdeprint/cups/cupsdconf2/cupsddialog.h b/kdeprint/cups/cupsdconf2/cupsddialog.h new file mode 100644 index 000000000..4de5cd3dc --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsddialog.h @@ -0,0 +1,58 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef CUPSDDIALOG_H +#define CUPSDDIALOG_H + +#include <kdialogbase.h> +#include <qptrlist.h> + +class CupsdPage; +struct CupsdConf; + +class CupsdDialog : public KDialogBase +{ + Q_OBJECT +public: + CupsdDialog(QWidget *parent = 0, const char *name = 0); + ~CupsdDialog(); + + bool setConfigFile(const QString& filename); + + static bool configure(const QString& filename = QString::null, QWidget *parent = 0, QString *errormsg = 0); + static bool restartServer(QString& msg); + static int serverPid(); + static int serverOwner(); + +protected slots: + void slotOk(); + void slotUser1(); + +protected: + void addConfPage(CupsdPage*); + void constructDialog(); + void restartServer(); + +private: + QPtrList<CupsdPage> pagelist_; + CupsdConf *conf_; + QString filename_; +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/cupsddirpage.cpp b/kdeprint/cups/cupsdconf2/cupsddirpage.cpp new file mode 100644 index 000000000..04a94c30a --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsddirpage.cpp @@ -0,0 +1,109 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "cupsddirpage.h" +#include "cupsdconf.h" +#include "qdirlineedit.h" +#include "qdirmultilineedit.h" + +#include <qlabel.h> +#include <qlayout.h> +#include <qwhatsthis.h> + +#include <klocale.h> + +CupsdDirPage::CupsdDirPage(QWidget *parent, const char *name) + : CupsdPage(parent, name) +{ + setPageLabel(i18n("Folders")); + setHeader(i18n("Folders Settings")); + setPixmap("folder"); + + datadir_ = new QDirLineEdit(false, this); + documentdir_ = new QDirLineEdit(false, this); + fontpath_ = new QDirMultiLineEdit(this); + requestdir_ = new QDirLineEdit(false, this); + serverbin_ = new QDirLineEdit(false, this); + serverfiles_ = new QDirLineEdit(false, this); + tmpfiles_ = new QDirLineEdit(false, this); + + QLabel *l1 = new QLabel(i18n("Data folder:"), this); + QLabel *l2 = new QLabel(i18n("Document folder:"), this); + QLabel *l3 = new QLabel(i18n("Font path:"), this); + QLabel *l4 = new QLabel(i18n("Request folder:"), this); + QLabel *l5 = new QLabel(i18n("Server binaries:"), this); + QLabel *l6 = new QLabel(i18n("Server files:"), this); + QLabel *l7 = new QLabel(i18n("Temporary files:"), this); + + QGridLayout *m1 = new QGridLayout(this, 8, 2, 10, 7); + m1->setRowStretch(7, 1); + m1->setColStretch(1, 1); + m1->addWidget(l1, 0, 0, Qt::AlignRight); + m1->addWidget(l2, 1, 0, Qt::AlignRight); + m1->addWidget(l3, 2, 0, Qt::AlignRight|Qt::AlignTop); + m1->addWidget(l4, 3, 0, Qt::AlignRight); + m1->addWidget(l5, 4, 0, Qt::AlignRight); + m1->addWidget(l6, 5, 0, Qt::AlignRight); + m1->addWidget(l7, 6, 0, Qt::AlignRight); + m1->addWidget(datadir_, 0, 1); + m1->addWidget(documentdir_, 1, 1); + m1->addWidget(fontpath_, 2, 1); + m1->addWidget(requestdir_, 3, 1); + m1->addWidget(serverbin_, 4, 1); + m1->addWidget(serverfiles_, 5, 1); + m1->addWidget(tmpfiles_, 6, 1); +} + +bool CupsdDirPage::loadConfig(CupsdConf *conf, QString&) +{ + conf_ = conf; + datadir_->setURL(conf_->datadir_); + documentdir_->setURL(conf_->documentdir_); + fontpath_->setURLs(conf_->fontpath_); + requestdir_->setURL(conf_->requestdir_); + serverbin_->setURL(conf_->serverbin_); + serverfiles_->setURL(conf_->serverfiles_); + tmpfiles_->setURL(conf_->tmpfiles_); + + return true; +} + +bool CupsdDirPage::saveConfig(CupsdConf *conf, QString&) +{ + conf->datadir_ = datadir_->url(); + conf->documentdir_ = documentdir_->url(); + conf->fontpath_ = fontpath_->urls(); + conf->requestdir_ = requestdir_->url(); + conf->serverbin_ = serverbin_->url(); + conf->serverfiles_ = serverfiles_->url(); + conf->tmpfiles_ = tmpfiles_->url(); + + return true; +} + +void CupsdDirPage::setInfos(CupsdConf *conf) +{ + QWhatsThis::add(datadir_, conf->comments_.toolTip("datadir")); + QWhatsThis::add(documentdir_, conf->comments_.toolTip("documentroot")); + QWhatsThis::add(fontpath_, conf->comments_.toolTip("fontpath")); + QWhatsThis::add(requestdir_, conf->comments_.toolTip("requestroot")); + QWhatsThis::add(serverbin_, conf->comments_.toolTip("serverbin")); + QWhatsThis::add(serverfiles_, conf->comments_.toolTip("serverroot")); + QWhatsThis::add(tmpfiles_, conf->comments_.toolTip("tempdir")); +} diff --git a/kdeprint/cups/cupsdconf2/cupsddirpage.h b/kdeprint/cups/cupsdconf2/cupsddirpage.h new file mode 100644 index 000000000..ffce797e8 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsddirpage.h @@ -0,0 +1,47 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef CUPSDDIRPAGE_H +#define CUPSDDIRPAGE_H + +#include "cupsdpage.h" + +class QDirLineEdit; +class QDirMultiLineEdit; + +class CupsdDirPage : public CupsdPage +{ +public: + CupsdDirPage(QWidget *parent = 0, const char *name = 0); + + bool loadConfig(CupsdConf*, QString&); + bool saveConfig(CupsdConf*, QString&); + void setInfos(CupsdConf*); + +private: + QDirLineEdit *datadir_, + *documentdir_, + *requestdir_, + *serverbin_, + *serverfiles_, + *tmpfiles_; + QDirMultiLineEdit *fontpath_; +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/cupsdfilterpage.cpp b/kdeprint/cups/cupsdconf2/cupsdfilterpage.cpp new file mode 100644 index 000000000..12270bc26 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdfilterpage.cpp @@ -0,0 +1,94 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "cupsdfilterpage.h" +#include "cupsdconf.h" +#include "sizewidget.h" + +#include <qlabel.h> +#include <qlineedit.h> +#include <qlayout.h> +#include <qwhatsthis.h> +#include <qcombobox.h> + +#include <klocale.h> +#include <knuminput.h> + +CupsdFilterPage::CupsdFilterPage(QWidget *parent, const char *name) + : CupsdPage(parent, name) +{ + setPageLabel(i18n("Filter")); + setHeader(i18n("Filter Settings")); + setPixmap("filter"); + + user_ = new QLineEdit(this); + group_ = new QLineEdit(this); + ripcache_ = new SizeWidget(this); + filterlimit_ = new KIntNumInput(this); + + filterlimit_->setRange(0, 1000, 1, true); + filterlimit_->setSpecialValueText(i18n("Unlimited")); + filterlimit_->setSteps(1, 10); + + QLabel *l1 = new QLabel(i18n("User:"), this); + QLabel *l2 = new QLabel(i18n("Group:"), this); + QLabel *l3 = new QLabel(i18n("RIP cache:"), this); + QLabel *l4 = new QLabel(i18n("Filter limit:"), this); + + QGridLayout *m1 = new QGridLayout(this, 5, 2, 10, 7); + m1->setRowStretch(4, 1); + m1->setColStretch(1, 1); + m1->addWidget(l1, 0, 0, Qt::AlignRight); + m1->addWidget(l2, 1, 0, Qt::AlignRight); + m1->addWidget(l3, 2, 0, Qt::AlignRight); + m1->addWidget(l4, 3, 0, Qt::AlignRight); + m1->addWidget(user_, 0, 1); + m1->addWidget(group_, 1, 1); + m1->addWidget(ripcache_, 2, 1); + m1->addWidget(filterlimit_, 3, 1); +} + +bool CupsdFilterPage::loadConfig(CupsdConf *conf, QString&) +{ + conf_ = conf; + user_->setText(conf_->user_); + group_->setText(conf_->group_); + ripcache_->setSizeString(conf_->ripcache_); + filterlimit_->setValue(conf_->filterlimit_); + + return true; +} + +bool CupsdFilterPage::saveConfig(CupsdConf *conf, QString&) +{ + conf->user_ = user_->text(); + conf->group_ = group_->text(); + conf->ripcache_ = ripcache_->sizeString(); + conf->filterlimit_ = filterlimit_->value(); + + return true; +} + +void CupsdFilterPage::setInfos(CupsdConf *conf) +{ + QWhatsThis::add(user_, conf->comments_.toolTip("user")); + QWhatsThis::add(group_, conf->comments_.toolTip("group")); + QWhatsThis::add(ripcache_, conf->comments_.toolTip("ripcache")); + QWhatsThis::add(filterlimit_, conf->comments_.toolTip("filterlimit")); +} diff --git a/kdeprint/cups/cupsdconf2/cupsdfilterpage.h b/kdeprint/cups/cupsdconf2/cupsdfilterpage.h new file mode 100644 index 000000000..894777520 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdfilterpage.h @@ -0,0 +1,45 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef CUPSDFILTERPAGE_H +#define CUPSDFILTERPAGE_H + +#include "cupsdpage.h" + +class SizeWidget; +class QLineEdit; +class QComboBox; +class KIntNumInput; + +class CupsdFilterPage : public CupsdPage +{ +public: + CupsdFilterPage(QWidget *parent = 0, const char *name = 0); + + bool loadConfig(CupsdConf*, QString&); + bool saveConfig(CupsdConf*, QString&); + void setInfos(CupsdConf*); + +private: + QLineEdit *user_, *group_; + KIntNumInput *filterlimit_; + SizeWidget *ripcache_; +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/cupsdjobspage.cpp b/kdeprint/cups/cupsdconf2/cupsdjobspage.cpp new file mode 100644 index 000000000..bfb2832eb --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdjobspage.cpp @@ -0,0 +1,123 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "cupsdjobspage.h" +#include "cupsdconf.h" + +#include <qlabel.h> +#include <qcheckbox.h> +#include <qlayout.h> +#include <qwhatsthis.h> + +#include <klocale.h> +#include <knuminput.h> + +CupsdJobsPage::CupsdJobsPage(QWidget *parent, const char *name) + : CupsdPage(parent, name) +{ + setPageLabel(i18n("Jobs")); + setHeader(i18n("Print Jobs Settings")); + setPixmap("fileprint"); + + keepjobhistory_ = new QCheckBox(i18n("Preserve job history"), this); + keepjobfiles_ = new QCheckBox(i18n("Preserve job files"), this); + autopurgejobs_ = new QCheckBox(i18n("Auto purge jobs"), this); + maxjobs_ = new KIntNumInput(this); + maxjobsperprinter_ = new KIntNumInput(this); + maxjobsperuser_ = new KIntNumInput(this); + + maxjobs_->setRange(0, 1000, 1, true); + maxjobs_->setSteps(1, 10); + maxjobs_->setSpecialValueText(i18n("Unlimited")); + maxjobsperprinter_->setRange(0, 1000, 1, true); + maxjobsperprinter_->setSpecialValueText(i18n("Unlimited")); + maxjobsperprinter_->setSteps(1, 10); + maxjobsperuser_->setRange(0, 1000, 1, true); + maxjobsperuser_->setSpecialValueText(i18n("Unlimited")); + maxjobsperuser_->setSteps(1, 10); + + QLabel *l1 = new QLabel(i18n("Max jobs:"), this); + QLabel *l2 = new QLabel(i18n("Max jobs per printer:"), this); + QLabel *l3 = new QLabel(i18n("Max jobs per user:"), this); + + QGridLayout *m1 = new QGridLayout(this, 7, 2, 10, 7); + m1->setRowStretch(6, 1); + m1->setColStretch(1, 1); + m1->addWidget(keepjobhistory_, 0, 1); + m1->addWidget(keepjobfiles_, 1, 1); + m1->addWidget(autopurgejobs_, 2, 1); + m1->addWidget(l1, 3, 0, Qt::AlignRight); + m1->addWidget(l2, 4, 0, Qt::AlignRight); + m1->addWidget(l3, 5, 0, Qt::AlignRight); + m1->addWidget(maxjobs_, 3, 1); + m1->addWidget(maxjobsperprinter_, 4, 1); + m1->addWidget(maxjobsperuser_, 5, 1); + + connect(keepjobhistory_, SIGNAL(toggled(bool)), SLOT(historyChanged(bool))); + keepjobhistory_->setChecked(true); +} + +bool CupsdJobsPage::loadConfig(CupsdConf *conf, QString&) +{ + conf_ = conf; + keepjobhistory_->setChecked(conf_->keepjobhistory_); + if (conf_->keepjobhistory_) + { + keepjobfiles_->setChecked(conf_->keepjobfiles_); + autopurgejobs_->setChecked(conf_->autopurgejobs_); + } + maxjobs_->setValue(conf_->maxjobs_); + maxjobsperprinter_->setValue(conf_->maxjobsperprinter_); + maxjobsperuser_->setValue(conf_->maxjobsperuser_); + + return true; +} + +bool CupsdJobsPage::saveConfig(CupsdConf *conf, QString&) +{ + conf->keepjobhistory_ = keepjobhistory_->isChecked(); + if (conf->keepjobhistory_) + { + conf->keepjobfiles_ = keepjobfiles_->isChecked(); + conf->autopurgejobs_ = autopurgejobs_->isChecked(); + } + conf->maxjobs_ = maxjobs_->value(); + conf->maxjobsperprinter_ = maxjobsperprinter_->value(); + conf->maxjobsperuser_ = maxjobsperuser_->value(); + + return true; +} + +void CupsdJobsPage::setInfos(CupsdConf *conf) +{ + QWhatsThis::add(keepjobhistory_, conf->comments_.toolTip("preservejobhistory")); + QWhatsThis::add(keepjobfiles_, conf->comments_.toolTip("preservejobfiles")); + QWhatsThis::add(autopurgejobs_, conf->comments_.toolTip("autopurgejobs")); + QWhatsThis::add(maxjobs_, conf->comments_.toolTip("maxjobs")); + QWhatsThis::add(maxjobsperprinter_, conf->comments_.toolTip("maxjobsperprinter")); + QWhatsThis::add(maxjobsperuser_, conf->comments_.toolTip("maxjobsperuser")); +} + +void CupsdJobsPage::historyChanged(bool on) +{ + keepjobfiles_->setEnabled(on); + autopurgejobs_->setEnabled(on); +} + +#include "cupsdjobspage.moc" diff --git a/kdeprint/cups/cupsdconf2/cupsdjobspage.h b/kdeprint/cups/cupsdconf2/cupsdjobspage.h new file mode 100644 index 000000000..19e76a2aa --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdjobspage.h @@ -0,0 +1,47 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef CUPSDJOBSPAGE_H +#define CUPSDJOBSPAGE_H + +#include "cupsdpage.h" + +class KIntNumInput; +class QCheckBox; + +class CupsdJobsPage : public CupsdPage +{ + Q_OBJECT + +public: + CupsdJobsPage(QWidget *parent = 0, const char *name = 0); + + bool loadConfig(CupsdConf*, QString&); + bool saveConfig(CupsdConf*, QString&); + void setInfos(CupsdConf*); + +protected slots: + void historyChanged(bool); + +private: + KIntNumInput *maxjobs_, *maxjobsperprinter_, *maxjobsperuser_; + QCheckBox *keepjobhistory_, *keepjobfiles_, *autopurgejobs_; +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/cupsdlogpage.cpp b/kdeprint/cups/cupsdconf2/cupsdlogpage.cpp new file mode 100644 index 000000000..49840050e --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdlogpage.cpp @@ -0,0 +1,111 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "cupsdlogpage.h" +#include "cupsdconf.h" +#include "qdirlineedit.h" +#include "sizewidget.h" + +#include <qlabel.h> +#include <qcombobox.h> +#include <qlayout.h> +#include <qwhatsthis.h> + +#include <klocale.h> +#include <kfiledialog.h> + +CupsdLogPage::CupsdLogPage(QWidget *parent, const char *name) + : CupsdPage(parent, name) +{ + setPageLabel(i18n("Log")); + setHeader(i18n("Log Settings")); + setPixmap("contents"); + + accesslog_ = new QDirLineEdit(true, this); + errorlog_ = new QDirLineEdit(true, this); + pagelog_ = new QDirLineEdit(true, this); + maxlogsize_ = new SizeWidget(this); + loglevel_ = new QComboBox(this); + + loglevel_->insertItem(i18n("Detailed Debugging")); + loglevel_->insertItem(i18n("Debug Information")); + loglevel_->insertItem(i18n("General Information")); + loglevel_->insertItem(i18n("Warnings")); + loglevel_->insertItem(i18n("Errors")); + loglevel_->insertItem(i18n("No Logging")); + + /*maxlogsize_->setRange(0, 100, 1, true); + maxlogsize_->setSteps(1, 5); + maxlogsize_->setSpecialValueText(i18n("Unlimited")); + maxlogsize_->setSuffix(i18n("MB"));*/ + + QLabel *l1 = new QLabel(i18n("Access log:"), this); + QLabel *l2 = new QLabel(i18n("Error log:"), this); + QLabel *l3 = new QLabel(i18n("Page log:"), this); + QLabel *l4 = new QLabel(i18n("Max log size:"), this); + QLabel *l5 = new QLabel(i18n("Log level:"), this); + + loglevel_->setCurrentItem(2); + + QGridLayout *m1 = new QGridLayout(this, 6, 2, 10, 7); + m1->setRowStretch(5, 1); + m1->setColStretch(1, 1); + m1->addWidget(l1, 0, 0, Qt::AlignRight); + m1->addWidget(l2, 1, 0, Qt::AlignRight); + m1->addWidget(l3, 2, 0, Qt::AlignRight); + m1->addWidget(l4, 3, 0, Qt::AlignRight); + m1->addWidget(l5, 4, 0, Qt::AlignRight); + m1->addWidget(accesslog_, 0, 1); + m1->addWidget(errorlog_, 1, 1); + m1->addWidget(pagelog_, 2, 1); + m1->addWidget(maxlogsize_, 3, 1); + m1->addWidget(loglevel_, 4, 1); +} + +bool CupsdLogPage::loadConfig(CupsdConf *conf, QString&) +{ + conf_ = conf; + accesslog_->setURL(conf_->accesslog_); + errorlog_->setURL(conf_->errorlog_); + pagelog_->setURL(conf_->pagelog_); + maxlogsize_->setSizeString(conf_->maxlogsize_); + loglevel_->setCurrentItem(conf_->loglevel_); + + return true; +} + +bool CupsdLogPage::saveConfig(CupsdConf *conf, QString&) +{ + conf->accesslog_ = accesslog_->url(); + conf->errorlog_ = errorlog_->url(); + conf->pagelog_ = pagelog_->url(); + conf->maxlogsize_ = maxlogsize_->sizeString(); + conf->loglevel_ = loglevel_->currentItem(); + + return true; +} + +void CupsdLogPage::setInfos(CupsdConf *conf) +{ + QWhatsThis::add(accesslog_, conf->comments_.toolTip("accesslog")); + QWhatsThis::add(errorlog_, conf->comments_.toolTip("errorlog")); + QWhatsThis::add(pagelog_, conf->comments_.toolTip("pagelog")); + QWhatsThis::add(maxlogsize_, conf->comments_.toolTip("maxlogsize")); + QWhatsThis::add(loglevel_, conf->comments_.toolTip("loglevel")); +} diff --git a/kdeprint/cups/cupsdconf2/cupsdlogpage.h b/kdeprint/cups/cupsdconf2/cupsdlogpage.h new file mode 100644 index 000000000..68e15ff45 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdlogpage.h @@ -0,0 +1,44 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef CUPSDLOGPAGE_H +#define CUPSDLOGPAGE_H + +#include "cupsdpage.h" + +class QDirLineEdit; +class SizeWidget; +class QComboBox; + +class CupsdLogPage : public CupsdPage +{ +public: + CupsdLogPage(QWidget *parent = 0, const char *name = 0); + + bool loadConfig(CupsdConf*, QString&); + bool saveConfig(CupsdConf*, QString&); + void setInfos(CupsdConf*); + +private: + QDirLineEdit *accesslog_, *errorlog_, *pagelog_; + QComboBox *loglevel_; + SizeWidget *maxlogsize_; +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/cupsdnetworkpage.cpp b/kdeprint/cups/cupsdconf2/cupsdnetworkpage.cpp new file mode 100644 index 000000000..6b0f196b5 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdnetworkpage.cpp @@ -0,0 +1,159 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "cupsdnetworkpage.h" +#include "cupsdconf.h" +#include "editlist.h" +#include "portdialog.h" +#include "sizewidget.h" + +#include <qlabel.h> +#include <qcheckbox.h> +#include <qcombobox.h> +#include <qlayout.h> +#include <qwhatsthis.h> + +#include <klocale.h> +#include <knuminput.h> + +CupsdNetworkPage::CupsdNetworkPage(QWidget *parent, const char *name) + : CupsdPage(parent, name) +{ + setPageLabel(i18n("Network")); + setHeader(i18n("Network Settings")); + setPixmap("network"); + + keepalive_ = new QCheckBox(i18n("Keep alive"), this); + keepalivetimeout_ = new KIntNumInput(this); + maxclients_ = new KIntNumInput(this); + maxrequestsize_ = new SizeWidget(this); + clienttimeout_ = new KIntNumInput(this); + hostnamelookup_ = new QComboBox(this); + listen_ = new EditList(this); + + keepalivetimeout_->setRange(0, 10000, 1, true); + keepalivetimeout_->setSteps(1, 10); + keepalivetimeout_->setSpecialValueText(i18n("Unlimited")); + keepalivetimeout_->setSuffix(i18n(" sec")); + + maxclients_->setRange(1, 1000, 1, true); + maxclients_->setSteps(1, 10); + + clienttimeout_->setRange(0, 10000, 1, true); + clienttimeout_->setSteps(1, 10); + clienttimeout_->setSpecialValueText(i18n("Unlimited")); + clienttimeout_->setSuffix(i18n(" sec")); + + hostnamelookup_->insertItem(i18n("Off")); + hostnamelookup_->insertItem(i18n("On")); + hostnamelookup_->insertItem(i18n("Double")); + + QLabel *l1 = new QLabel(i18n("Hostname lookups:"), this); + QLabel *l2 = new QLabel(i18n("Keep-alive timeout:"), this); + QLabel *l3 = new QLabel(i18n("Max clients:"), this); + QLabel *l4 = new QLabel(i18n("Max request size:"), this); + QLabel *l5 = new QLabel(i18n("Client timeout:"), this); + QLabel *l6 = new QLabel(i18n("Listen to:"), this); + + QGridLayout *m1 = new QGridLayout(this, 8, 2, 10, 7); + m1->setRowStretch(7, 1); + m1->setColStretch(1, 1); + m1->addWidget(l1, 0, 0, Qt::AlignRight); + m1->addWidget(l2, 2, 0, Qt::AlignRight); + m1->addWidget(l3, 3, 0, Qt::AlignRight); + m1->addWidget(l4, 4, 0, Qt::AlignRight); + m1->addWidget(l5, 5, 0, Qt::AlignRight); + m1->addWidget(l6, 6, 0, Qt::AlignTop|Qt::AlignRight); + m1->addWidget(keepalive_, 1, 1); + m1->addWidget(hostnamelookup_, 0, 1); + m1->addWidget(keepalivetimeout_, 2, 1); + m1->addWidget(maxclients_, 3, 1); + m1->addWidget(maxrequestsize_, 4, 1); + m1->addWidget(clienttimeout_, 5, 1); + m1->addWidget(listen_, 6, 1); + + connect(listen_, SIGNAL(add()), SLOT(slotAdd())); + connect(listen_, SIGNAL(edit(int)), SLOT(slotEdit(int))); + connect(listen_, SIGNAL(defaultList()), SLOT(slotDefaultList())); + connect(keepalive_, SIGNAL(toggled(bool)), keepalivetimeout_, SLOT(setEnabled(bool))); + keepalive_->setChecked(true); +} + +bool CupsdNetworkPage::loadConfig(CupsdConf *conf, QString&) +{ + conf_ = conf; + hostnamelookup_->setCurrentItem(conf_->hostnamelookup_); + keepalive_->setChecked(conf_->keepalive_); + keepalivetimeout_->setValue(conf_->keepalivetimeout_); + maxclients_->setValue(conf_->maxclients_); + maxrequestsize_->setSizeString(conf_->maxrequestsize_); + clienttimeout_->setValue(conf_->clienttimeout_); + listen_->insertItems(conf_->listenaddresses_); + + return true; +} + +bool CupsdNetworkPage::saveConfig(CupsdConf *conf, QString&) +{ + conf->hostnamelookup_ = hostnamelookup_->currentItem(); + conf->keepalive_ = keepalive_->isChecked(); + conf->keepalivetimeout_ = keepalivetimeout_->value(); + conf->maxclients_ = maxclients_->value(); + conf->maxrequestsize_ = maxrequestsize_->sizeString(); + conf->clienttimeout_ = clienttimeout_->value(); + conf->listenaddresses_ = listen_->items(); + + return true; +} + +void CupsdNetworkPage::setInfos(CupsdConf *conf) +{ + QWhatsThis::add(hostnamelookup_, conf->comments_.toolTip("hostnamelookups")); + QWhatsThis::add(keepalive_, conf->comments_.toolTip("keepalive")); + QWhatsThis::add(keepalivetimeout_, conf->comments_.toolTip("keepalivetimeout")); + QWhatsThis::add(maxclients_, conf->comments_.toolTip("maxclients")); + QWhatsThis::add(maxrequestsize_, conf->comments_.toolTip("maxrequestsize")); + QWhatsThis::add(clienttimeout_, conf->comments_.toolTip("timeout")); + QWhatsThis::add(listen_, conf->comments_.toolTip("listen")); +} + +void CupsdNetworkPage::slotAdd() +{ + QString s = PortDialog::newListen(this, conf_); + if (!s.isEmpty()) + listen_->insertItem(s); +} + +void CupsdNetworkPage::slotEdit(int index) +{ + QString s = listen_->text(index); + s = PortDialog::editListen(s, this, conf_); + if (!s.isEmpty()) + listen_->setText(index, s); +} + +void CupsdNetworkPage::slotDefaultList() +{ + listen_->clear(); + QStringList l; + l << "Listen *:631"; + listen_->insertItems(l); +} + +#include "cupsdnetworkpage.moc" diff --git a/kdeprint/cups/cupsdconf2/cupsdnetworkpage.h b/kdeprint/cups/cupsdconf2/cupsdnetworkpage.h new file mode 100644 index 000000000..c4c8bd450 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdnetworkpage.h @@ -0,0 +1,55 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef CUPSDNETWORKPAGE_H +#define CUPSDNETWORKPAGE_H + +#include "cupsdpage.h" + +class KIntNumInput; +class QCheckBox; +class QComboBox; +class EditList; +class SizeWidget; + +class CupsdNetworkPage : public CupsdPage +{ + Q_OBJECT + +public: + CupsdNetworkPage(QWidget *parent = 0, const char *name = 0); + + bool loadConfig(CupsdConf*, QString&); + bool saveConfig(CupsdConf*, QString&); + void setInfos(CupsdConf*); + +protected slots: + void slotAdd(); + void slotEdit(int); + void slotDefaultList(); + +private: + KIntNumInput *keepalivetimeout_, *maxclients_, *clienttimeout_; + QComboBox *hostnamelookup_; + QCheckBox *keepalive_; + EditList *listen_; + SizeWidget *maxrequestsize_; +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/cupsdpage.cpp b/kdeprint/cups/cupsdconf2/cupsdpage.cpp new file mode 100644 index 000000000..00798552c --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdpage.cpp @@ -0,0 +1,32 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "cupsdpage.h" + +CupsdPage::CupsdPage(QWidget *parent, const char *name) + : QWidget(parent, name) +{ + conf_ = 0; +} + +CupsdPage::~CupsdPage() +{ +} + +#include "cupsdpage.moc" diff --git a/kdeprint/cups/cupsdconf2/cupsdpage.h b/kdeprint/cups/cupsdconf2/cupsdpage.h new file mode 100644 index 000000000..dedd53ade --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdpage.h @@ -0,0 +1,54 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef CUPSDPAGE_H +#define CUPSDPAGE_H + +#include <qwidget.h> + +struct CupsdConf; + +class CupsdPage : public QWidget +{ + Q_OBJECT +public: + CupsdPage(QWidget *parent = 0, const char *name = 0); + virtual ~CupsdPage(); + + virtual bool loadConfig(CupsdConf *conf, QString& msg) = 0; + virtual bool saveConfig(CupsdConf *conf, QString& msg) = 0; + virtual void setInfos(CupsdConf*) {} + + QString pageLabel() const { return label_; } + QString header() const { return header_; } + QString pixmap() const { return pixmap_; } + +protected: + void setPageLabel(const QString& s) { label_ = s; } + void setHeader(const QString& s) { header_ = s; } + void setPixmap(const QString& s) { pixmap_ = s; } + +protected: + CupsdConf *conf_; + QString label_; + QString header_; + QString pixmap_; +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/cupsdsecuritypage.cpp b/kdeprint/cups/cupsdconf2/cupsdsecuritypage.cpp new file mode 100644 index 000000000..a77f21708 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdsecuritypage.cpp @@ -0,0 +1,168 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "cupsdsecuritypage.h" +#include "cupsdconf.h" +#include "qdirlineedit.h" +#include "editlist.h" +#include "locationdialog.h" + +#include <qlabel.h> +#include <qlineedit.h> +#include <qlayout.h> +#include <qwhatsthis.h> + +#include <klocale.h> +#include <kiconloader.h> +#include <kmessagebox.h> + +CupsdSecurityPage::CupsdSecurityPage(QWidget *parent, const char *name) + : CupsdPage(parent, name) +{ + setPageLabel(i18n("Security")); + setHeader(i18n("Security Settings")); + setPixmap("password"); + locs_.setAutoDelete(true); + + remoteroot_ = new QLineEdit(this); + systemgroup_ = new QLineEdit(this); + encryptcert_ = new QDirLineEdit(true, this); + encryptkey_ = new QDirLineEdit(true, this); + locations_ = new EditList(this); + + QLabel *l1 = new QLabel(i18n("Remote root user:"), this); + QLabel *l2 = new QLabel(i18n("System group:"), this); + QLabel *l3 = new QLabel(i18n("Encryption certificate:"), this); + QLabel *l4 = new QLabel(i18n("Encryption key:"), this); + QLabel *l5 = new QLabel(i18n("Locations:"), this); + + QGridLayout *m1 = new QGridLayout(this, 6, 2, 10, 7); + m1->setRowStretch(5, 1); + m1->setColStretch(1, 1); + m1->addWidget(l1, 0, 0, Qt::AlignRight); + m1->addWidget(l2, 1, 0, Qt::AlignRight); + m1->addWidget(l3, 2, 0, Qt::AlignRight); + m1->addWidget(l4, 3, 0, Qt::AlignRight); + m1->addWidget(l5, 4, 0, Qt::AlignRight|Qt::AlignTop); + m1->addWidget(remoteroot_, 0, 1); + m1->addWidget(systemgroup_, 1, 1); + m1->addWidget(encryptcert_, 2, 1); + m1->addWidget(encryptkey_, 3, 1); + m1->addWidget(locations_, 4, 1); + + connect(locations_, SIGNAL(add()), SLOT(slotAdd())); + connect(locations_, SIGNAL(edit(int)), SLOT(slotEdit(int))); + connect(locations_, SIGNAL(defaultList()), SLOT(slotDefaultList())); + connect(locations_, SIGNAL(deleted(int)), SLOT(slotDeleted(int))); +} + +bool CupsdSecurityPage::loadConfig(CupsdConf *conf, QString&) +{ + conf_ = conf; + remoteroot_->setText(conf_->remoteroot_); + systemgroup_->setText(conf_->systemgroup_); + encryptcert_->setURL(conf_->encryptcert_); + encryptkey_->setURL(conf_->encryptkey_); + locs_.clear(); + QPtrListIterator<CupsLocation> it(conf_->locations_); + for (;it.current();++it) + { + locs_.append(new CupsLocation(*(it.current()))); + if (it.current()->resource_) + locations_->insertItem(SmallIcon(CupsResource::typeToIconName(it.current()->resource_->type_)), it.current()->resource_->text_); + else + locations_->insertItem(it.current()->resourcename_); + } + + return true; +} + +bool CupsdSecurityPage::saveConfig(CupsdConf *conf, QString&) +{ + conf->remoteroot_ = remoteroot_->text(); + conf->systemgroup_ = systemgroup_->text(); + conf->encryptcert_ = encryptcert_->url(); + conf->encryptkey_ = encryptkey_->url(); + conf->locations_.clear(); + QPtrListIterator<CupsLocation> it(locs_); + for (;it.current();++it) + conf->locations_.append(new CupsLocation(*(it.current()))); + + return true; +} + +void CupsdSecurityPage::setInfos(CupsdConf *conf) +{ + QWhatsThis::add(remoteroot_, conf->comments_.toolTip("remoteroot")); + QWhatsThis::add(systemgroup_, conf->comments_.toolTip("systemgroup")); + QWhatsThis::add(encryptcert_, conf->comments_.toolTip("servercertificate")); + QWhatsThis::add(encryptkey_, conf->comments_.toolTip("serverkey")); + QWhatsThis::add(locations_, conf->comments_.toolTip("locationsshort")); +} + +void CupsdSecurityPage::slotAdd() +{ + CupsLocation *loc = new CupsLocation; + if (LocationDialog::newLocation(loc, this, conf_)) + { + int index(-1); + for (locs_.first(); locs_.current(); locs_.next()) + if (locs_.current()->resource_ == loc->resource_) + { + if (KMessageBox::warningContinueCancel(this, i18n("This location is already defined. Do you want to replace the existing one?"),QString::null,i18n("Replace")) == KMessageBox::Continue) + { + index = locs_.at(); + locs_.remove(); + break; + } + else + { + delete loc; + return; + } + } + + if (index == -1) + index = locs_.count(); + locs_.insert(index, loc); + locations_->insertItem(SmallIcon(loc->resource_->typeToIconName(loc->resource_->type_)), loc->resource_->text_); + } + else + delete loc; +} + +void CupsdSecurityPage::slotEdit(int index) +{ + CupsLocation *loc = locs_.at(index); + LocationDialog::editLocation(loc, this, conf_); +} + +void CupsdSecurityPage::slotDefaultList() +{ + locs_.clear(); + locations_->clear(); +} + +void CupsdSecurityPage::slotDeleted(int index) +{ + if (index >= 0 && index < (int)(locs_.count())) + locs_.remove(index); +} + +#include "cupsdsecuritypage.moc" diff --git a/kdeprint/cups/cupsdconf2/cupsdsecuritypage.h b/kdeprint/cups/cupsdconf2/cupsdsecuritypage.h new file mode 100644 index 000000000..56a9e2e45 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdsecuritypage.h @@ -0,0 +1,56 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef CUPSDSECURITYPAGE_H +#define CUPSDSECURITYPAGE_H + +#include "cupsdpage.h" +#include <qptrlist.h> + +class QLineEdit; +class EditList; +class QDirLineEdit; +struct CupsLocation; + +class CupsdSecurityPage : public CupsdPage +{ + Q_OBJECT + +public: + CupsdSecurityPage(QWidget *parent = 0, const char *name = 0); + + bool loadConfig(CupsdConf*, QString&); + bool saveConfig(CupsdConf*, QString&); + void setInfos(CupsdConf*); + +protected slots: + void slotAdd(); + void slotEdit(int); + void slotDefaultList(); + void slotDeleted(int); + +private: + QLineEdit *remoteroot_, *systemgroup_; + QDirLineEdit *encryptcert_, *encryptkey_; + EditList *locations_; + + QPtrList<CupsLocation> locs_; +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/cupsdserverpage.cpp b/kdeprint/cups/cupsdconf2/cupsdserverpage.cpp new file mode 100644 index 000000000..861dad9de --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdserverpage.cpp @@ -0,0 +1,181 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "cupsdserverpage.h" +#include "cupsdconf.h" + +#include <qlineedit.h> +#include <qlabel.h> +#include <qcheckbox.h> +#include <qcombobox.h> +#include <qlayout.h> +#include <qwhatsthis.h> + +#include <klocale.h> + +int findComboItem(QComboBox *cb, const QString& str) +{ + for (int i=0; i<cb->count(); i++) + if (cb->text(i) == str) + return i; + return (-1); +} + +CupsdServerPage::CupsdServerPage(QWidget *parent, const char *name) + : CupsdPage(parent, name) +{ + setPageLabel(i18n("Server")); + setHeader(i18n("Server Settings")); + setPixmap("gear"); + + servername_ = new QLineEdit(this); + serveradmin_ = new QLineEdit(this); + otherclassname_ = new QLineEdit(this); + language_ = new QLineEdit(this); + printcap_ = new QLineEdit(this); + classification_ = new QComboBox(this); + charset_ = new QComboBox(this); + printcapformat_ = new QComboBox(this); + classoverride_ = new QCheckBox(i18n("Allow overrides"), this); + + classification_->insertItem(i18n("None")); + classification_->insertItem(i18n("Classified")); + classification_->insertItem(i18n("Confidential")); + classification_->insertItem(i18n("Secret")); + classification_->insertItem(i18n("Top Secret")); + classification_->insertItem(i18n("Unclassified")); + classification_->insertItem(i18n("Other")); + + charset_->insertItem("UTF-8"); + charset_->insertItem("ISO-8859-1"); + charset_->insertItem("ISO-8859-2"); + charset_->insertItem("ISO-8859-3"); + charset_->insertItem("ISO-8859-4"); + charset_->insertItem("ISO-8859-5"); + charset_->insertItem("ISO-8859-6"); + charset_->insertItem("ISO-8859-7"); + charset_->insertItem("ISO-8859-8"); + charset_->insertItem("ISO-8859-9"); + charset_->insertItem("ISO-8859-10"); + charset_->insertItem("ISO-8859-13"); + charset_->insertItem("ISO-8859-14"); + charset_->insertItem("ISO-8859-15"); + + printcapformat_->insertItem("BSD"); + printcapformat_->insertItem("SOLARIS"); + + QLabel *l1 = new QLabel(i18n("Server name:"), this); + QLabel *l2 = new QLabel(i18n("Server administrator:"), this); + QLabel *l3 = new QLabel(i18n("Classification:"), this); + QLabel *l4 = new QLabel(i18n("Default character set:"), this); + QLabel *l5 = new QLabel(i18n("Default language:"), this); + QLabel *l6 = new QLabel(i18n("Printcap file:"), this); + QLabel *l7 = new QLabel(i18n("Printcap format:"), this); + + connect(classification_, SIGNAL(activated(int)), SLOT(classChanged(int))); + classification_->setCurrentItem(0); + charset_->setCurrentItem(0); + printcapformat_->setCurrentItem(0); + classChanged(0); + + QGridLayout *m1 = new QGridLayout(this, 9, 2, 10, 7); + m1->setRowStretch(8, 1); + m1->setColStretch(1, 1); + m1->addWidget(l1, 0, 0, Qt::AlignRight); + m1->addWidget(l2, 1, 0, Qt::AlignRight); + m1->addWidget(l3, 2, 0, Qt::AlignRight); + m1->addWidget(l4, 4, 0, Qt::AlignRight); + m1->addWidget(l5, 5, 0, Qt::AlignRight); + m1->addWidget(l6, 6, 0, Qt::AlignRight); + m1->addWidget(l7, 7, 0, Qt::AlignRight); + m1->addWidget(servername_, 0, 1); + m1->addWidget(serveradmin_, 1, 1); + m1->addWidget(charset_, 4, 1); + m1->addWidget(language_, 5, 1); + m1->addWidget(printcap_, 6, 1); + m1->addWidget(printcapformat_, 7, 1); + QHBoxLayout *m2 = new QHBoxLayout(0, 0, 5); + m1->addLayout(m2, 2, 1); + m2->addWidget(classification_); + m2->addWidget(otherclassname_); + QWidget *w = new QWidget(this); + w->setFixedWidth(20); + QHBoxLayout *m3 = new QHBoxLayout(0, 0, 0); + m1->addLayout(m3, 3, 1); + m3->addWidget(w); + m3->addWidget(classoverride_); +} + +bool CupsdServerPage::loadConfig(CupsdConf *conf, QString&) +{ + conf_ = conf; + servername_->setText(conf_->servername_); + serveradmin_->setText(conf_->serveradmin_); + classification_->setCurrentItem(conf_->classification_); + classChanged(conf_->classification_); + if (conf->classification_ != CLASS_NONE) + classoverride_->setChecked(conf_->classoverride_); + if (conf->classification_ == CLASS_OTHER) + otherclassname_->setText(conf_->otherclassname_); + int index = findComboItem(charset_, conf_->charset_.upper()); + if (index != -1) + charset_->setCurrentItem(index); + language_->setText(conf_->language_); + printcap_->setText(conf_->printcap_); + printcapformat_->setCurrentItem(conf_->printcapformat_); + + return true; +} + +bool CupsdServerPage::saveConfig(CupsdConf *conf, QString&) +{ + conf->servername_ = servername_->text(); + conf->serveradmin_ = serveradmin_->text(); + conf->classification_ = classification_->currentItem(); + if (conf->classification_ != CLASS_NONE) + conf->classoverride_ = classoverride_->isChecked(); + if (conf->classification_ == CLASS_OTHER) + conf->otherclassname_ = otherclassname_->text(); + conf->charset_ = charset_->currentText(); + conf->language_ = language_->text(); + conf->printcap_ = printcap_->text(); + conf->printcapformat_ = printcapformat_->currentItem(); + + return true; +} + +void CupsdServerPage::setInfos(CupsdConf *conf) +{ + QWhatsThis::add(servername_, conf->comments_.toolTip("servername")); + QWhatsThis::add(serveradmin_, conf->comments_.toolTip("serveradmin")); + QWhatsThis::add(classification_, conf->comments_.toolTip("classification")); + QWhatsThis::add(classoverride_, conf->comments_.toolTip("classifyoverride")); + QWhatsThis::add(charset_, conf->comments_.toolTip("defaultcharset")); + QWhatsThis::add(language_, conf->comments_.toolTip("defaultlanguage")); + QWhatsThis::add(printcap_, conf->comments_.toolTip("printcap")); + QWhatsThis::add(printcapformat_, conf->comments_.toolTip("printcapformat")); +} + +void CupsdServerPage::classChanged(int index) +{ + classoverride_->setEnabled(index != 0); + otherclassname_->setEnabled(index == CLASS_OTHER); +} + +#include "cupsdserverpage.moc" diff --git a/kdeprint/cups/cupsdconf2/cupsdserverpage.h b/kdeprint/cups/cupsdconf2/cupsdserverpage.h new file mode 100644 index 000000000..d82367c30 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdserverpage.h @@ -0,0 +1,49 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef CUPSDSERVERPAGE_H +#define CUPSDSERVERPAGE_H + +#include "cupsdpage.h" + +class QLineEdit; +class QCheckBox; +class QComboBox; + +class CupsdServerPage : public CupsdPage +{ + Q_OBJECT + +public: + CupsdServerPage(QWidget *parent = 0, const char *name = 0); + + bool loadConfig(CupsdConf*, QString&); + bool saveConfig(CupsdConf*, QString&); + void setInfos(CupsdConf*); + +protected slots: + void classChanged(int); + +private: + QLineEdit *servername_, *serveradmin_, *language_, *printcap_, *otherclassname_; + QComboBox *classification_, *charset_, *printcapformat_; + QCheckBox *classoverride_; +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/cupsdsplash.cpp b/kdeprint/cups/cupsdconf2/cupsdsplash.cpp new file mode 100644 index 000000000..7a623e972 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdsplash.cpp @@ -0,0 +1,73 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "cupsdsplash.h" + +#include <qlabel.h> +#include <qpixmap.h> +#include <qlayout.h> +#include <klocale.h> +#include <kstandarddirs.h> + +CupsdSplash::CupsdSplash(QWidget *parent, const char *name) + : CupsdPage(parent, name) +{ + setHeader(i18n("Welcome to the CUPS Server Configuration Tool")); + setPageLabel(i18n("Welcome")); + setPixmap("go"); + + QVBoxLayout *main_ = new QVBoxLayout(this, 10, 10); + QHBoxLayout *sub_ = new QHBoxLayout(0, 0, 10); + main_->addLayout(sub_); + + QLabel *cupslogo_ = new QLabel(this); + QString logopath = locate("data", QString("kdeprint/cups_logo.png")); + cupslogo_->setPixmap(logopath.isEmpty() ? QPixmap() : QPixmap(logopath)); + cupslogo_->setAlignment(Qt::AlignCenter); + QLabel *kupslogo_ = new QLabel(this); + logopath = locate("data", QString("kdeprint/kde_logo.png")); + kupslogo_->setPixmap(logopath.isEmpty() ? QPixmap() : QPixmap(logopath)); + kupslogo_->setAlignment(Qt::AlignCenter); + + QLabel *helptxt_ = new QLabel(this); + helptxt_->setText(i18n( "<p>This tool will help you to configure graphically the server of the CUPS printing system. " + "The available options are grouped into sets of related topics and can be accessed " + "quickly through the icon view located on the left. Each option has a default value that is " + "shown if it has not been previously set. This default value should be OK in most cases.</p><br>" + "<p>You can access a short help message for each option using either the '?' button in the " + "the title bar, or the button at the bottom of this dialog.</p>")); + + sub_->addWidget(cupslogo_); + sub_->addWidget(kupslogo_); + main_->addWidget(helptxt_, 1); +} + +CupsdSplash::~CupsdSplash() +{ +} + +bool CupsdSplash::loadConfig(CupsdConf*, QString&) +{ + return true; +} + +bool CupsdSplash::saveConfig(CupsdConf*, QString&) +{ + return true; +} diff --git a/kdeprint/cups/cupsdconf2/cupsdsplash.h b/kdeprint/cups/cupsdconf2/cupsdsplash.h new file mode 100644 index 000000000..ed548948d --- /dev/null +++ b/kdeprint/cups/cupsdconf2/cupsdsplash.h @@ -0,0 +1,35 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef CUPSDSPLASH_H +#define CUPSDSPLASH_H + +#include "cupsdpage.h" + +class CupsdSplash : public CupsdPage +{ +public: + CupsdSplash(QWidget *parent = 0, const char *name = 0); + ~CupsdSplash(); + + bool loadConfig(CupsdConf *conf, QString& msg); + bool saveConfig(CupsdConf *conf, QString& msg); +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/editlist.cpp b/kdeprint/cups/cupsdconf2/editlist.cpp new file mode 100644 index 000000000..4c924dbb4 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/editlist.cpp @@ -0,0 +1,124 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "editlist.h" + +#include <klistbox.h> +#include <kpushbutton.h> +#include <qlayout.h> +#include <klocale.h> +#include <kiconloader.h> +#include <kguiitem.h> + +EditList::EditList(QWidget *parent, const char *name) + : QWidget(parent, name) +{ + list_ = new KListBox(this); + addbtn_ = new KPushButton(KGuiItem(i18n("Add..."), "filenew"), this); + editbtn_ = new KPushButton(KGuiItem(i18n("Edit..."), "edit"), this); + delbtn_ = new KPushButton(KGuiItem(i18n("Delete"), "editdelete"), this); + defbtn_ = new KPushButton(KGuiItem(i18n("Default List"), "history"), this); + + QGridLayout *m1 = new QGridLayout(this, 4, 2, 0, 0); + m1->setColStretch(0, 1); + m1->addMultiCellWidget(list_, 0, 3, 0, 1); + m1->addWidget(addbtn_, 0, 1); + m1->addWidget(editbtn_, 1, 1); + m1->addWidget(delbtn_, 2, 1); + m1->addWidget(defbtn_, 3, 1); + + connect(addbtn_, SIGNAL(clicked()), SIGNAL(add())); + connect(editbtn_, SIGNAL(clicked()), SLOT(slotEdit())); + connect(delbtn_, SIGNAL(clicked()), SLOT(slotDelete())); + connect(defbtn_, SIGNAL(clicked()), SIGNAL(defaultList())); + connect(list_, SIGNAL(highlighted(int)), SLOT(slotSelected(int))); + slotSelected(-1); +} + +void EditList::slotEdit() +{ + int index = list_->currentItem(); + if (index >= 0) + emit edit(index); +} + +void EditList::slotDelete() +{ + int index = list_->currentItem(); + list_->removeItem(index); + slotSelected((list_->count() > 0 ? list_->currentItem() : -1)); + emit deleted(index); +} + +void EditList::slotSelected(int index) +{ + editbtn_->setEnabled(index >= 0); + delbtn_->setEnabled(index >= 0); +} + +QString EditList::text(int index) +{ + return list_->text(index); +} + +void EditList::setText(int index, const QString& s) +{ + if (list_->text(index) != s) + { + QListBoxItem *it = list_->findItem(s, Qt::ExactMatch); + if (!it) + list_->changeItem(s, index); + else + list_->removeItem(index); + } +} + +void EditList::clear() +{ + list_->clear(); + slotSelected(-1); +} + +void EditList::insertItem(const QString& s) +{ + if (!list_->findItem(s, Qt::ExactMatch)) + list_->insertItem(s); +} + +void EditList::insertItem(const QPixmap& icon, const QString& s) +{ + if (!list_->findItem(s, Qt::ExactMatch)) + list_->insertItem(icon, s); +} + +void EditList::insertItems(const QStringList& l) +{ + for (QStringList::ConstIterator it=l.begin(); it!=l.end(); ++it) + insertItem(*it); +} + +QStringList EditList::items() +{ + QStringList l; + for (uint i=0; i<list_->count(); i++) + l << list_->text(i); + return l; +} + +#include "editlist.moc" diff --git a/kdeprint/cups/cupsdconf2/editlist.h b/kdeprint/cups/cupsdconf2/editlist.h new file mode 100644 index 000000000..773667304 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/editlist.h @@ -0,0 +1,60 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef EDITLIST_H +#define EDITLIST_H + +#include <qwidget.h> +#include <qpixmap.h> + +class KListBox; +class QPushButton; + +class EditList : public QWidget +{ + Q_OBJECT + +public: + EditList(QWidget *parent = 0, const char *name = 0); + + QString text(int); + void setText(int, const QString&); + void insertItem(const QString&); + void insertItem(const QPixmap&, const QString&); + void insertItems(const QStringList&); + QStringList items(); + void clear(); + +signals: + void add(); + void edit(int); + void defaultList(); + void deleted(int); + +protected slots: + void slotDelete(); + void slotEdit(); + void slotSelected(int); + +private: + KListBox *list_; + QPushButton *addbtn_, *editbtn_, *delbtn_, *defbtn_; +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/kde_logo.png b/kdeprint/cups/cupsdconf2/kde_logo.png Binary files differnew file mode 100644 index 000000000..6ba204607 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/kde_logo.png diff --git a/kdeprint/cups/cupsdconf2/locationdialog.cpp b/kdeprint/cups/cupsdconf2/locationdialog.cpp new file mode 100644 index 000000000..fc5c55076 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/locationdialog.cpp @@ -0,0 +1,222 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "locationdialog.h" +#include "cupsdconf.h" +#include "editlist.h" +#include "addressdialog.h" + +#include <qlineedit.h> +#include <qcombobox.h> +#include <qlayout.h> +#include <qlabel.h> +#include <qpushbutton.h> +#include <qwhatsthis.h> + +#include <klocale.h> +#include <kiconloader.h> + +LocationDialog::LocationDialog(QWidget *parent, const char *name) + : KDialogBase(parent, name, true, QString::null, Ok|Cancel, Ok, true) +{ + QWidget *dummy = new QWidget(this); + setMainWidget(dummy); + resource_ = new QComboBox(dummy); + authtype_ = new QComboBox(dummy); + authclass_ = new QComboBox(dummy); + authname_ = new QLineEdit(dummy); + encryption_ = new QComboBox(dummy); + satisfy_ = new QComboBox(dummy); + order_ = new QComboBox(dummy); + addresses_ = new EditList(dummy); + + authtype_->insertItem(i18n("None")); + authtype_->insertItem(i18n("Basic")); + authtype_->insertItem(i18n("Digest")); + + authclass_->insertItem(i18n("None")); + authclass_->insertItem(i18n("User")); + authclass_->insertItem(i18n("System")); + authclass_->insertItem(i18n("Group")); + + encryption_->insertItem(i18n("Always")); + encryption_->insertItem(i18n("Never")); + encryption_->insertItem(i18n("Required")); + encryption_->insertItem(i18n("If Requested")); + + satisfy_->insertItem(i18n("All")); + satisfy_->insertItem(i18n("Any")); + + order_->insertItem(i18n("Allow, Deny")); + order_->insertItem(i18n("Deny, Allow")); + + connect(authclass_, SIGNAL(activated(int)), SLOT(slotClassChanged(int))); + connect(authtype_, SIGNAL(activated(int)), SLOT(slotTypeChanged(int))); + + QLabel *l1 = new QLabel(i18n("Resource:"), dummy); + QLabel *l2 = new QLabel(i18n("Authentication:"), dummy); + QLabel *l3 = new QLabel(i18n("Class:"), dummy); + QLabel *l4 = new QLabel(i18n("Names:"), dummy); + QLabel *l5 = new QLabel(i18n("Encryption:"), dummy); + QLabel *l6 = new QLabel(i18n("Satisfy:"), dummy); + QLabel *l7 = new QLabel(i18n("ACL order:"), dummy); + QLabel *l8 = new QLabel(i18n("ACL addresses:"),dummy); + + QGridLayout *m1 = new QGridLayout(dummy, 8, 2, 0, 5); + m1->setColStretch(1, 1); + m1->addWidget(l1, 0, 0, Qt::AlignRight); + m1->addWidget(l2, 1, 0, Qt::AlignRight); + m1->addWidget(l3, 2, 0, Qt::AlignRight); + m1->addWidget(l4, 3, 0, Qt::AlignRight); + m1->addWidget(l5, 4, 0, Qt::AlignRight); + m1->addWidget(l6, 5, 0, Qt::AlignRight); + m1->addWidget(l7, 6, 0, Qt::AlignRight); + m1->addWidget(l8, 7, 0, Qt::AlignRight|Qt::AlignTop); + m1->addWidget(resource_, 0, 1); + m1->addWidget(authtype_, 1, 1); + m1->addWidget(authclass_, 2, 1); + m1->addWidget(authname_, 3, 1); + m1->addWidget(encryption_, 4, 1); + m1->addWidget(satisfy_, 5, 1); + m1->addWidget(order_, 6, 1); + m1->addWidget(addresses_, 7, 1); + + setCaption(i18n("Location")); + resize(400, 100); + + slotTypeChanged(AUTHTYPE_NONE); + slotClassChanged(AUTHCLASS_ANONYMOUS); + encryption_->setCurrentItem(ENCRYPT_IFREQUESTED); + + connect(addresses_, SIGNAL(add()), SLOT(slotAdd())); + connect(addresses_, SIGNAL(edit(int)), SLOT(slotEdit(int))); + connect(addresses_, SIGNAL(defaultList()), SLOT(slotDefaultList())); +} + +void LocationDialog::setInfos(CupsdConf *conf) +{ + conf_ = conf; + + QPtrListIterator<CupsResource> it(conf->resources_); + for (; it.current(); ++it) + resource_->insertItem(SmallIcon(it.current()->typeToIconName(it.current()->type_)), it.current()->text_); + + QWhatsThis::add(encryption_, conf_->comments_.toolTip("encryption")); + QWhatsThis::add(order_, conf_->comments_.toolTip("order")); + QWhatsThis::add(authclass_, conf_->comments_.toolTip("authclass")); + QWhatsThis::add(authtype_, conf_->comments_.toolTip("authtype")); + QWhatsThis::add(authname_, conf_->comments_.toolTip("authname")); + QWhatsThis::add(satisfy_, conf_->comments_.toolTip("satisfy")); + QWhatsThis::add(addresses_, conf_->comments_.toolTip("allowdeny")); +} + +void LocationDialog::fillLocation(CupsLocation *loc) +{ + loc->resource_ = conf_->resources_.at(resource_->currentItem()); + loc->resourcename_ = loc->resource_->path_; + loc->authtype_ = authtype_->currentItem(); + loc->authclass_ = (loc->authtype_ == AUTHTYPE_NONE ? AUTHCLASS_ANONYMOUS : authclass_->currentItem()); + loc->authname_ = (loc->authclass_ == AUTHCLASS_USER || loc->authclass_ == AUTHCLASS_GROUP ? authname_->text() : QString::null); + loc->encryption_ = encryption_->currentItem(); + loc->satisfy_ = satisfy_->currentItem(); + loc->order_ = order_->currentItem(); + loc->addresses_ = addresses_->items(); +} + +void LocationDialog::setLocation(CupsLocation *loc) +{ + int index = conf_->resources_.findRef(loc->resource_); + resource_->setCurrentItem(index); + authtype_->setCurrentItem(loc->authtype_); + authclass_->setCurrentItem(loc->authclass_); + authname_->setText(loc->authname_); + encryption_->setCurrentItem(loc->encryption_); + satisfy_->setCurrentItem(loc->satisfy_); + order_->setCurrentItem(loc->order_); + addresses_->insertItems(loc->addresses_); + + slotTypeChanged(loc->authtype_); + slotClassChanged(loc->authclass_); +} + +void LocationDialog::slotTypeChanged(int index) +{ + authclass_->setEnabled(index != AUTHTYPE_NONE); + if (index != AUTHTYPE_NONE) + slotClassChanged(authclass_->currentItem()); + else + authname_->setEnabled(false); +} + +void LocationDialog::slotClassChanged(int index) +{ + authname_->setEnabled((index == AUTHCLASS_USER || index == AUTHCLASS_GROUP)); +} + +bool LocationDialog::newLocation(CupsLocation *loc, QWidget *parent, CupsdConf *conf) +{ + LocationDialog dlg(parent); + if (conf) + dlg.setInfos(conf); + if (dlg.exec()) + { + dlg.fillLocation(loc); + return true; + } + else + return false; +} + +bool LocationDialog::editLocation(CupsLocation *loc, QWidget *parent, CupsdConf *conf) +{ + LocationDialog dlg(parent); + if (conf) + dlg.setInfos(conf); + dlg.setLocation(loc); + dlg.resource_->setEnabled(false); + if (dlg.exec()) + { + dlg.fillLocation(loc); + return true; + } + else + return false; +} + +void LocationDialog::slotAdd() +{ + QString addr = AddressDialog::newAddress(this); + if (!addr.isEmpty()) + addresses_->insertItem(addr); +} + +void LocationDialog::slotEdit(int index) +{ + QString addr = addresses_->text(index); + addr = AddressDialog::editAddress(addr, this); + if (!addr.isEmpty()) + addresses_->insertItem(addr); +} + +void LocationDialog::slotDefaultList() +{ + addresses_->clear(); +} + +#include "locationdialog.moc" diff --git a/kdeprint/cups/cupsdconf2/locationdialog.h b/kdeprint/cups/cupsdconf2/locationdialog.h new file mode 100644 index 000000000..5ca8c4d53 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/locationdialog.h @@ -0,0 +1,58 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef LOCATIONDIALOG_H +#define LOCATIONDIALOG_H + +#include <kdialogbase.h> + +class QComboBox; +class QLineEdit; +class EditList; +struct CupsdConf; +struct CupsLocation; + +class LocationDialog : public KDialogBase +{ + Q_OBJECT +public: + LocationDialog(QWidget *parent = 0, const char *name = 0); + + void setInfos(CupsdConf*); + void fillLocation(CupsLocation*); + void setLocation(CupsLocation*); + + static bool newLocation(CupsLocation*, QWidget *parent = 0, CupsdConf *conf = 0); + static bool editLocation(CupsLocation*, QWidget *parent = 0, CupsdConf *conf = 0); + +protected slots: + void slotTypeChanged(int); + void slotClassChanged(int); + void slotAdd(); + void slotEdit(int); + void slotDefaultList(); + +private: + QComboBox *resource_, *authtype_, *authclass_, *encryption_, *satisfy_, *order_; + QLineEdit *authname_; + EditList *addresses_; + CupsdConf *conf_; +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/main.cpp b/kdeprint/cups/cupsdconf2/main.cpp new file mode 100644 index 000000000..e8fd3df6a --- /dev/null +++ b/kdeprint/cups/cupsdconf2/main.cpp @@ -0,0 +1,48 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "cupsddialog.h" + +#include <qfile.h> +#include <klocale.h> +#include <kcmdlineargs.h> +#include <kapplication.h> + +static KCmdLineOptions options[] = +{ + { "+[file]", I18N_NOOP("Configuration file to load"), 0}, + KCmdLineLastOption +}; + +extern "C" KDE_EXPORT int kdemain(int argc, char *argv[]) +{ + KCmdLineArgs::init(argc,argv,"cupsdconf", + I18N_NOOP("A CUPS configuration tool"), + I18N_NOOP("A CUPS configuration tool"),"0.0.1"); + KCmdLineArgs::addCmdLineOptions(options); + KApplication app; + KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); + + KURL configfile; + if (args->count() > 0) + CupsdDialog::configure(args->url(0).path()); + else + CupsdDialog::configure(); + return (0); +} diff --git a/kdeprint/cups/cupsdconf2/portdialog.cpp b/kdeprint/cups/cupsdconf2/portdialog.cpp new file mode 100644 index 000000000..f866450b8 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/portdialog.cpp @@ -0,0 +1,118 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "portdialog.h" +#include "cupsdconf.h" + +#include <qlineedit.h> +#include <qspinbox.h> +#include <qcheckbox.h> +#include <qpushbutton.h> +#include <qlabel.h> +#include <qlayout.h> +#include <qwhatsthis.h> + +#include <klocale.h> + +PortDialog::PortDialog(QWidget *parent, const char *name) + : KDialogBase(parent, name, true, QString::null, Ok|Cancel, Ok, true) +{ + QWidget *dummy = new QWidget(this); + setMainWidget(dummy); + address_ = new QLineEdit(dummy); + port_ = new QSpinBox(0, 9999, 1, dummy); + port_->setValue(631); + usessl_ = new QCheckBox(i18n("Use SSL encryption"), dummy); + + QLabel *l1 = new QLabel(i18n("Address:"), dummy); + QLabel *l2 = new QLabel(i18n("Port:"), dummy); + + QVBoxLayout *m1 = new QVBoxLayout(dummy, 0, 10); + QGridLayout *m2 = new QGridLayout(0, 3, 2, 0, 5); + m1->addLayout(m2); + m2->addWidget(l1, 0, 0, Qt::AlignRight); + m2->addWidget(l2, 1, 0, Qt::AlignRight); + m2->addMultiCellWidget(usessl_, 2, 2, 0, 1); + m2->addWidget(address_, 0, 1); + m2->addWidget(port_, 1, 1); + + setCaption(i18n("Listen To")); + resize(250, 100); +} + +QString PortDialog::listenString() +{ + QString s; + if (usessl_->isChecked()) + s.append("SSLListen "); + else + s.append("Listen "); + if (!address_->text().isEmpty()) + s.append(address_->text()); + else + s.append("*"); + s.append(":").append(port_->text()); + return s; +} + +void PortDialog::setInfos(CupsdConf *conf) +{ + QWhatsThis::add(address_, conf->comments_.toolTip("address")); + QWhatsThis::add(port_, conf->comments_.toolTip("port")); + QWhatsThis::add(usessl_, conf->comments_.toolTip("usessl")); +} + +QString PortDialog::newListen(QWidget *parent, CupsdConf *conf) +{ + PortDialog dlg(parent); + dlg.setInfos(conf); + if (dlg.exec()) + { + return dlg.listenString(); + } + return QString::null; +} + +QString PortDialog::editListen(const QString& s, QWidget *parent, CupsdConf *conf) +{ + PortDialog dlg(parent); + dlg.setInfos(conf); + int p = s.find(' '); + if (p != -1) + { + dlg.usessl_->setChecked(s.left(p).startsWith("SSL")); + QString addr = s.mid(p+1).stripWhiteSpace(); + int p1 = addr.find(':'); + if (p1 == -1) + { + dlg.address_->setText(addr); + dlg.port_->setValue(631); + } + else + { + dlg.address_->setText(addr.left(p1)); + dlg.port_->setValue(addr.mid(p1+1).toInt()); + } + } + if (dlg.exec()) + { + return dlg.listenString(); + } + return QString::null; +} diff --git a/kdeprint/cups/cupsdconf2/portdialog.h b/kdeprint/cups/cupsdconf2/portdialog.h new file mode 100644 index 000000000..8f0b9f3e9 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/portdialog.h @@ -0,0 +1,46 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef PORTDIALOG_H +#define PORTDIALOG_H + +#include <kdialogbase.h> + +class QLineEdit; +class QSpinBox; +class QCheckBox; +struct CupsdConf; + +class PortDialog : public KDialogBase +{ +public: + PortDialog(QWidget *parent = 0, const char *name = 0); + + QString listenString(); + void setInfos(CupsdConf*); + static QString newListen(QWidget *parent = 0, CupsdConf *conf = 0); + static QString editListen(const QString& s, QWidget *parent = 0, CupsdConf *conf = 0); + +private: + QLineEdit *address_; + QSpinBox *port_; + QCheckBox *usessl_; +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/qdirlineedit.cpp b/kdeprint/cups/cupsdconf2/qdirlineedit.cpp new file mode 100644 index 000000000..931d6ac4a --- /dev/null +++ b/kdeprint/cups/cupsdconf2/qdirlineedit.cpp @@ -0,0 +1,73 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "qdirlineedit.h" + +#include <qlineedit.h> +#include <qlayout.h> +#include <kpushbutton.h> +#include <kfiledialog.h> +#include <kiconloader.h> + +QDirLineEdit::QDirLineEdit(bool file, QWidget *parent, const char *name) + : QWidget(parent, name) +{ + edit_ = new QLineEdit(this); + button_ = new KPushButton(this); + button_->setPixmap(SmallIcon("fileopen")); + connect(button_,SIGNAL(clicked()),SLOT(buttonClicked())); + + QHBoxLayout *main_ = new QHBoxLayout(this, 0, 3); + main_->addWidget(edit_); + main_->addWidget(button_); + + fileedit_ = file; +} + +QDirLineEdit::~QDirLineEdit() +{ +} + +void QDirLineEdit::setURL(const QString& txt) +{ + edit_->setText(txt); +} + +QString QDirLineEdit::url() +{ + return edit_->text(); +} + +void QDirLineEdit::buttonClicked() +{ + QString dirname; + if (!fileedit_) + dirname = KFileDialog::getExistingDirectory(edit_->text(), this); + else + dirname = KFileDialog::getOpenFileName(edit_->text(), QString::null, this); + if (!dirname.isEmpty()) + edit_->setText(dirname); +} + +void QDirLineEdit::setFileEdit(bool on) +{ + fileedit_ = on; +} + +#include "qdirlineedit.moc" diff --git a/kdeprint/cups/cupsdconf2/qdirlineedit.h b/kdeprint/cups/cupsdconf2/qdirlineedit.h new file mode 100644 index 000000000..b4b977b75 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/qdirlineedit.h @@ -0,0 +1,49 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef QDIRLINEEDIT_H +#define QDIRLINEEDIT_H + +#include <qwidget.h> +#include <qstring.h> + +class QLineEdit; +class QPushButton; + +class QDirLineEdit : public QWidget +{ + Q_OBJECT +public: + QDirLineEdit(bool file, QWidget *parent = 0, const char *name = 0); + ~QDirLineEdit(); + + void setURL(const QString& txt); + QString url(); + void setFileEdit(bool on = true); + +private slots: + void buttonClicked(); + +private: + QLineEdit *edit_; + QPushButton *button_; + bool fileedit_; +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/qdirmultilineedit.cpp b/kdeprint/cups/cupsdconf2/qdirmultilineedit.cpp new file mode 100644 index 000000000..31a544e91 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/qdirmultilineedit.cpp @@ -0,0 +1,109 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001-2002 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "qdirmultilineedit.h" + +#include <qlayout.h> +#include <qheader.h> +#include <qpushbutton.h> +#include <klistview.h> +#include <klocale.h> +#include <kfiledialog.h> +#include <kiconloader.h> + +QDirMultiLineEdit::QDirMultiLineEdit(QWidget *parent, const char *name) +: QWidget(parent, name) +{ + m_view = new KListView(this); + m_view->header()->hide(); + m_view->addColumn(""); + m_view->setFullWidth(true); + connect(m_view, SIGNAL(selectionChanged(QListViewItem*)), SLOT(slotSelected(QListViewItem*))); + + m_add = new QPushButton(this); + m_add->setPixmap(SmallIcon("folder_new")); + connect(m_add, SIGNAL(clicked()), SLOT(slotAddClicked())); + m_remove = new QPushButton(this); + m_remove->setPixmap(SmallIcon("editdelete")); + connect(m_remove, SIGNAL(clicked()), SLOT(slotRemoveClicked())); + m_remove->setEnabled(false); + + m_view->setFixedHeight(QMAX(m_view->fontMetrics().lineSpacing()*3+m_view->lineWidth()*2, m_add->sizeHint().height()*2)); + + QHBoxLayout *l0 = new QHBoxLayout(this, 0, 3); + QVBoxLayout *l1 = new QVBoxLayout(0, 0, 0); + l0->addWidget(m_view); + l0->addLayout(l1); + l1->addWidget(m_add); + l1->addWidget(m_remove); + l1->addStretch(1); +} + +QDirMultiLineEdit::~QDirMultiLineEdit() +{ +} + +void QDirMultiLineEdit::setURLs(const QStringList& urls) +{ + m_view->clear(); + for (QStringList::ConstIterator it=urls.begin(); it!=urls.end(); ++it) + addURL(*it); +} + +QStringList QDirMultiLineEdit::urls() +{ + QListViewItem *item = m_view->firstChild(); + QStringList l; + while (item) + { + l << item->text(0); + item = item->nextSibling(); + } + return l; +} + +void QDirMultiLineEdit::addURL(const QString& url) +{ + QListViewItem *item = new QListViewItem(m_view, url); + item->setRenameEnabled(0, true); +} + +void QDirMultiLineEdit::slotAddClicked() +{ + QString dirname = KFileDialog::getExistingDirectory(QString::null, this); + if (!dirname.isEmpty()) + addURL(dirname); +} + +void QDirMultiLineEdit::slotRemoveClicked() +{ + QListViewItem *item = m_view->currentItem(); + if (item) + { + delete item; + slotSelected(m_view->currentItem()); + } +} + +void QDirMultiLineEdit::slotSelected(QListViewItem *item) +{ + m_remove->setEnabled((item != NULL)); +} + +#include "qdirmultilineedit.moc" diff --git a/kdeprint/cups/cupsdconf2/qdirmultilineedit.h b/kdeprint/cups/cupsdconf2/qdirmultilineedit.h new file mode 100644 index 000000000..963292985 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/qdirmultilineedit.h @@ -0,0 +1,53 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001-2002 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef QDIRMULTILINEEDIT_H +#define QDIRMULTILINEEDIT_H + +#include <qwidget.h> + +class KListView; +class QListViewItem; +class QPushButton; + +class QDirMultiLineEdit : public QWidget +{ + Q_OBJECT + +public: + QDirMultiLineEdit(QWidget *parent = 0, const char *name = 0); + ~QDirMultiLineEdit(); + + void setURLs(const QStringList&); + QStringList urls(); + +protected: + void addURL(const QString&); + +private slots: + void slotAddClicked(); + void slotRemoveClicked(); + void slotSelected(QListViewItem*); + +private: + KListView *m_view; + QPushButton *m_add, *m_remove; +}; + +#endif diff --git a/kdeprint/cups/cupsdconf2/sizewidget.cpp b/kdeprint/cups/cupsdconf2/sizewidget.cpp new file mode 100644 index 000000000..c61996282 --- /dev/null +++ b/kdeprint/cups/cupsdconf2/sizewidget.cpp @@ -0,0 +1,83 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2002 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "sizewidget.h" + +#include <qcombobox.h> +#include <qspinbox.h> +#include <qlayout.h> +#include <qregexp.h> +#include <klocale.h> + +SizeWidget::SizeWidget( QWidget *parent, const char *name ) + : QWidget( parent, name ) +{ + m_size = new QSpinBox( 0, 9999, 1, this ); + m_unit = new QComboBox( this ); + + m_unit->insertItem( i18n( "KB" ) ); + m_unit->insertItem( i18n( "MB" ) ); + m_unit->insertItem( i18n( "GB" ) ); + m_unit->insertItem( i18n( "Tiles" ) ); + m_unit->setCurrentItem( 1 ); + m_size->setSpecialValueText( i18n( "Unlimited" ) ); + + QHBoxLayout *l0 = new QHBoxLayout( this, 0, 5 ); + l0->addWidget( m_size, 1 ); + l0->addWidget( m_unit, 0 ); +} + +void SizeWidget::setSizeString( const QString& sz ) +{ + int p = sz.find( QRegExp( "\\D" ) ); + m_size->setValue( sz.left( p ).toInt() ); + switch( sz[ p ].latin1() ) + { + case 'k': p = 0; break; + default: + case 'm': p = 1; break; + case 'g': p = 2; break; + case 't': p = 3; break; + } + m_unit->setCurrentItem( p ); +} + +QString SizeWidget::sizeString() const +{ + QString result = QString::number( m_size->value() ); + switch ( m_unit->currentItem() ) + { + case 0: result.append( "k" ); break; + case 1: result.append( "m" ); break; + case 2: result.append( "g" ); break; + case 3: result.append( "t" ); break; + } + return result; +} + +void SizeWidget::setValue( int value ) +{ + m_size->setValue( value ); + m_unit->setCurrentItem( 1 ); +} + +int SizeWidget::value() const +{ + return m_size->value(); +} diff --git a/kdeprint/cups/cupsdconf2/sizewidget.h b/kdeprint/cups/cupsdconf2/sizewidget.h new file mode 100644 index 000000000..c7f6557df --- /dev/null +++ b/kdeprint/cups/cupsdconf2/sizewidget.h @@ -0,0 +1,43 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2002 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef SIZEWIDGET_H +#define SIZEWIDGET_H + +#include <qwidget.h> + +class QSpinBox; +class QComboBox; + +class SizeWidget : public QWidget +{ +public: + SizeWidget( QWidget *parent = 0, const char *name = 0 ); + + void setSizeString( const QString& sizeString ); + QString sizeString() const; + void setValue( int sz ); + int value() const; + +private: + QSpinBox *m_size; + QComboBox *m_unit; +}; + +#endif diff --git a/kdeprint/cups/cupsdoprint.c b/kdeprint/cups/cupsdoprint.c new file mode 100644 index 000000000..743042b2a --- /dev/null +++ b/kdeprint/cups/cupsdoprint.c @@ -0,0 +1,257 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include <config.h> + +#include <unistd.h> +#include <string.h> +#include <stdio.h> +#include <stdlib.h> +#include <ctype.h> + +#include <cups/cups.h> +#include <cups/ipp.h> + +#define BUFSIZE 1024 +#define BUFSIZE2 32 + +#define USE_LOG 0 + +/* global variables */ +char passwd[BUFSIZE2] = {0}; +int pwd_asked = 0; +#if USE_LOG +FILE *debugF = NULL; +#endif + +/* utility functions */ +static void error(const char* msg) +{ + fprintf(stderr, "%s\n", msg); +#if USE_LOG + if (debugF != NULL) fclose(debugF); +#endif + exit(-1); +} + +static void usage() +{ + error("usage: cupsdoprint [-H host[:port]][-P dest][-J name][-o opt=value[,...]][-U login[:password]] files..."); +} + +static char * shell_quote(const char *s) +{ + char *result; + char *p; + p = result = malloc(strlen(s)*4+3); + *p++ = '\''; + while(*s) + { + if (*s == '\'') + { + *p++ = '\''; + *p++ = '\\'; + *p++ = '\''; + *p++ = '\''; + s++; + } + else + { + *p++ = *s++; + } + } + *p++ = '\''; + *p = '\0'; + return result; +} + +static const char* getPasswordCB(const char* prompt) +{ + char buf[ 256 ] = {0}, *c; + char *_user = shell_quote( cupsUser() ), *_passwd = NULL; + FILE *output; + + snprintf( buf, sizeof( buf )-1, "dcop kded kdeprintd requestPassword %s %s %d %d", + _user, + cupsServer(), + ippPort(), + pwd_asked ); + free( _user ); + _user = NULL; + output = popen( buf, "r" ); + if ( output != NULL ) + { + while ( fgets( buf, sizeof( buf )-1, output ) ) + { + _user = _passwd = NULL; + if ( strcmp( buf, "::" ) != 0 ) + { + c = strchr( buf, ':' ); + if ( c != NULL ) + { + *c = '\0'; + _user = buf; + _passwd = ++c; + c = strchr( c, ':' ); + if ( c != NULL ) + { + *c = '\0'; + /* retrieve password sequence number */ + pwd_asked = atoi( ++c ); + /* update CUPS with current username */ + cupsSetUser( _user ); + /* copy password to a non temporary location */ + strlcpy( passwd, _passwd, BUFSIZE2 ); + _passwd = passwd; + } + else + _passwd = NULL; + } + } + } + pclose( output ); + } + else + return NULL; + + /* erase buffer containing unencrypted password, for security */ + memset( buf, 0, 256 ); + + /* if OK, _passwd should point to global passwd variable, otherwise it should be NULL */ + return _passwd; +} + +/* main function */ +int main(int argc, char* argv[]) +{ + int c, port = -1; + char printer[BUFSIZE] = {0}, jobname[BUFSIZE] = {0}, host[BUFSIZE] = {0}; + char login[BUFSIZE2] = {0}; + char *a; + cups_option_t *options = NULL; + int num_options = 0; + char* files[100] = {0}; + int num_files = 0; + int jobID = 0; + +#if USE_LOG + debugF = fopen("/tmp/cupsdoprint.debug","w"); + if (debugF == NULL) + error("unable to open log file"); +#endif + + while ((c=getopt(argc, argv, "P:J:H:o:U:?")) != -1) + { +#if USE_LOG + fprintf(debugF,"%c: %s\n",c,optarg); +#endif + switch (c) + { + case 'P': + strlcpy(printer, optarg, BUFSIZE); + if ((a=strchr(printer, '/')) != NULL) + error("This utility doesn't support printer instances"); + break; + case 'J': + strlcpy(jobname, optarg, BUFSIZE); + break; + case 'H': + strlcpy(host, optarg, BUFSIZE); + if ((a=strchr(host, ':')) != NULL) + { + *a = 0; + port = atoi(++a); + if (port == 0) + error("Wrong port value"); + } + break; + case 'U': + strlcpy(login, optarg, BUFSIZE2); + if ((a=strchr(login, ':')) != NULL) + { + *a = 0; + strlcpy(passwd, ++a, BUFSIZE2); + } + break; + case 'o': +#if USE_LOG + fprintf(debugF,"Parsing options (n=%d)\n",num_options); +#endif + num_options = cupsParseOptions(optarg, num_options, &options); +#if USE_LOG + fprintf(debugF,"Options parsed (n=%d)\n",num_options); +#endif + break; + case '?': + default: + usage(); + break; + } + } + + /* check the printer */ + if (!*printer) + { + printer[BUFSIZE-1] = '\0'; + if (getenv("PRINTER") != NULL) + strlcpy(printer, getenv("PRINTER"), BUFSIZE-1); + else + error("No printer specified (and PRINTER variable is empty)"); + } + + /* CUPS settings */ + if (host[0] != 0) cupsSetServer(host); + if (port > 0) ippSetPort(port); + if (login[0] != 0) cupsSetUser(login); + if (jobname[0] == 0) strcpy(jobname,"KDE Print System"); + cupsSetPasswordCB(getPasswordCB); + + /* check for files */ + if (optind < 1 || optind >= argc) + error("This utility doesn't support printing from STDIN"); + else + for (c=optind; c<argc; c++) + { + if (access(argv[c], R_OK) != 0) + { + fprintf(stderr, "%s: ", argv[c]); + error("file not found or not readable"); + } + else + files[num_files++] = strdup(argv[c]); + } + +#if USE_LOG + fprintf(debugF,"Processed options:\n"); + for (c=0; c<num_options; c++) + fprintf(debugF,"%s = %s\n",options[c].name,options[c].value); +#endif + /* print files */ + jobID = cupsPrintFiles(printer, num_files, files, jobname, num_options, options); + /* erase unemcrypted password for security */ + memset( passwd, 0, BUFSIZE2 ); + /* check job creation status */ + if (jobID <= 0) + error(ippErrorString(cupsLastError())); + +#if USE_LOG + fclose(debugF); +#endif + return 0; +} diff --git a/kdeprint/cups/cupsinfos.cpp b/kdeprint/cups/cupsinfos.cpp new file mode 100644 index 000000000..f96451d76 --- /dev/null +++ b/kdeprint/cups/cupsinfos.cpp @@ -0,0 +1,166 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "cupsinfos.h" +#include "kmfactory.h" +#include "kmtimer.h" +#include "messagewindow.h" + +#include <kio/passdlg.h> +#include <kio/authinfo.h> +#include <klocale.h> +#include <kconfig.h> +#include <kapplication.h> +#include <dcopclient.h> +#include <kdebug.h> +#include <kstringhandler.h> + +#include <cups/cups.h> +#include <cups/ipp.h> + +const char* cupsGetPasswordCB(const char*) +{ + return CupsInfos::self()->getPasswordCB(); +} + +CupsInfos* CupsInfos::unique_ = 0; + +CupsInfos* CupsInfos::self() +{ + if (!unique_) + { + unique_ = new CupsInfos(); + } + return unique_; +} + +CupsInfos::CupsInfos() +: KPReloadObject(true) +{ + count_ = 0; + + load(); +/* host_ = cupsServer(); + login_ = cupsUser(); + if (login_.isEmpty()) login_ = QString::null; + port_ = ippPort(); + password_ = QString::null;*/ + + cupsSetPasswordCB(cupsGetPasswordCB); +} + +CupsInfos::~CupsInfos() +{ +} + +QString CupsInfos::hostaddr() const +{ + if (host_[0] != '/') + return host_ + ":" + QString::number(port_); + return "localhost"; +} + +void CupsInfos::setHost(const QString& s) +{ + host_ = s; + cupsSetServer(s.latin1()); +} + +void CupsInfos::setPort(int p) +{ + port_ = p; + ippSetPort(p); +} + +void CupsInfos::setLogin(const QString& s) +{ + login_ = s; + cupsSetUser(s.latin1()); +} + +void CupsInfos::setPassword(const QString& s) +{ + password_ = s; +} + +void CupsInfos::setSavePassword( bool on ) +{ + savepwd_ = on; +} + +const char* CupsInfos::getPasswordCB() +{ + QPair<QString,QString> pwd = KMFactory::self()->requestPassword( count_, login_, host_, port_ ); + + if ( pwd.first.isEmpty() && pwd.second.isEmpty() ) + return NULL; + setLogin( pwd.first ); + setPassword( pwd.second ); + return pwd.second.latin1(); +} + +void CupsInfos::load() +{ + KConfig *conf_ = KMFactory::self()->printConfig(); + conf_->setGroup("CUPS"); + host_ = conf_->readEntry("Host",QString::fromLatin1(cupsServer())); + port_ = conf_->readNumEntry("Port",ippPort()); + login_ = conf_->readEntry("Login",QString::fromLatin1(cupsUser())); + savepwd_ = conf_->readBoolEntry( "SavePassword", false ); + if ( savepwd_ ) + { + password_ = KStringHandler::obscure( conf_->readEntry( "Password" ) ); + KMFactory::self()->initPassword( login_, password_, host_, port_ ); + } + else + password_ = QString::null; + if (login_.isEmpty()) login_ = QString::null; + reallogin_ = cupsUser(); + + // synchronize with CUPS + cupsSetServer(host_.latin1()); + cupsSetUser(login_.latin1()); + ippSetPort(port_); +} + +void CupsInfos::save() +{ + KConfig *conf_ = KMFactory::self()->printConfig(); + conf_->setGroup("CUPS"); + conf_->writeEntry("Host",host_); + conf_->writeEntry("Port",port_); + conf_->writeEntry("Login",login_); + conf_->writeEntry( "SavePassword", savepwd_ ); + if ( savepwd_ ) + conf_->writeEntry( "Password", KStringHandler::obscure( password_ ) ); + else + conf_->deleteEntry( "Password" ); + conf_->sync(); +} + +void CupsInfos::reload() +{ + // do nothing, but needs to be implemented +} + +void CupsInfos::configChanged() +{ + // we need to reload settings + load(); +} diff --git a/kdeprint/cups/cupsinfos.h b/kdeprint/cups/cupsinfos.h new file mode 100644 index 000000000..429970b9d --- /dev/null +++ b/kdeprint/cups/cupsinfos.h @@ -0,0 +1,88 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef CUPSINFOS_H +#define CUPSINFOS_H + +#include <qstring.h> +#include "kpreloadobject.h" + +class CupsInfos : public KPReloadObject +{ +public: + static CupsInfos* self(); + + CupsInfos(); + ~CupsInfos(); + + const QString& host() const; + QString hostaddr() const; + int port() const; + const QString& login() const; + const QString& password() const; + const QString& realLogin() const; + bool savePassword() const; + + void setHost(const QString& s); + void setPort(int p); + void setLogin(const QString& s); + void setPassword(const QString& s); + void setSavePassword( bool on ); + + const char* getPasswordCB(); + + void load(); + void save(); + +protected: + void reload(); + void configChanged(); + +private: + static CupsInfos *unique_; + + QString host_; + int port_; + QString login_; + QString password_; + QString reallogin_; + bool savepwd_; + + int count_; +}; + +inline const QString& CupsInfos::host() const +{ return host_; } + +inline int CupsInfos::port() const +{ return port_; } + +inline const QString& CupsInfos::login() const +{ return login_; } + +inline const QString& CupsInfos::password() const +{ return password_; } + +inline const QString& CupsInfos::realLogin() const +{ return reallogin_; } + +inline bool CupsInfos::savePassword() const +{ return savepwd_; } + +#endif diff --git a/kdeprint/cups/image.cpp b/kdeprint/cups/image.cpp new file mode 100644 index 000000000..7ec0ed7a6 --- /dev/null +++ b/kdeprint/cups/image.cpp @@ -0,0 +1,295 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include <qimage.h> +#include <math.h> + +void +mult(float a[3][3], /* I - First matrix */ + float b[3][3], /* I - Second matrix */ + float c[3][3]) /* I - Destination matrix */ +{ + int x, y; /* Looping vars */ + float temp[3][3]; /* Temporary matrix */ + + + /* + * Multiply a and b, putting the result in temp... + */ + + for (y = 0; y < 3; y ++) + for (x = 0; x < 3; x ++) + temp[y][x] = b[y][0] * a[0][x] + + b[y][1] * a[1][x] + + b[y][2] * a[2][x]; + + /* + * Copy temp to c (that way c can be a pointer to a or b). + */ + + memcpy(c, temp, sizeof(temp)); +} + +void +saturate(float mat[3][3], /* I - Matrix to append to */ + float sat) /* I - Desired color saturation */ +{ + float smat[3][3]; /* Saturation matrix */ + + + smat[0][0] = (1.0 - sat) * 0.3086 + sat; + smat[0][1] = (1.0 - sat) * 0.3086; + smat[0][2] = (1.0 - sat) * 0.3086; + smat[1][0] = (1.0 - sat) * 0.6094; + smat[1][1] = (1.0 - sat) * 0.6094 + sat; + smat[1][2] = (1.0 - sat) * 0.6094; + smat[2][0] = (1.0 - sat) * 0.0820; + smat[2][1] = (1.0 - sat) * 0.0820; + smat[2][2] = (1.0 - sat) * 0.0820 + sat; + + mult(smat, mat, mat); +} + +void +xform(float mat[3][3], /* I - Matrix */ + float x, /* I - Input X coordinate */ + float y, /* I - Input Y coordinate */ + float z, /* I - Input Z coordinate */ + float *tx, /* O - Output X coordinate */ + float *ty, /* O - Output Y coordinate */ + float *tz) /* O - Output Z coordinate */ +{ + *tx = x * mat[0][0] + y * mat[1][0] + z * mat[2][0]; + *ty = x * mat[0][1] + y * mat[1][1] + z * mat[2][1]; + *tz = x * mat[0][2] + y * mat[1][2] + z * mat[2][2]; +} + +void +xrotate(float mat[3][3], /* I - Matrix */ + float rs, /* I - Rotation angle sine */ + float rc) /* I - Rotation angle cosine */ +{ + float rmat[3][3]; /* I - Rotation matrix */ + + + rmat[0][0] = 1.0; + rmat[0][1] = 0.0; + rmat[0][2] = 0.0; + + rmat[1][0] = 0.0; + rmat[1][1] = rc; + rmat[1][2] = rs; + + rmat[2][0] = 0.0; + rmat[2][1] = -rs; + rmat[2][2] = rc; + + mult(rmat, mat, mat); +} + +void +yrotate(float mat[3][3], /* I - Matrix */ + float rs, /* I - Rotation angle sine */ + float rc) /* I - Rotation angle cosine */ +{ + float rmat[3][3]; /* I - Rotation matrix */ + + + rmat[0][0] = rc; + rmat[0][1] = 0.0; + rmat[0][2] = -rs; + + rmat[1][0] = 0.0; + rmat[1][1] = 1.0; + rmat[1][2] = 0.0; + + rmat[2][0] = rs; + rmat[2][1] = 0.0; + rmat[2][2] = rc; + + mult(rmat,mat,mat); +} + +void +zrotate(float mat[3][3], /* I - Matrix */ + float rs, /* I - Rotation angle sine */ + float rc) /* I - Rotation angle cosine */ +{ + float rmat[3][3]; /* I - Rotation matrix */ + + + rmat[0][0] = rc; + rmat[0][1] = rs; + rmat[0][2] = 0.0; + + rmat[1][0] = -rs; + rmat[1][1] = rc; + rmat[1][2] = 0.0; + + rmat[2][0] = 0.0; + rmat[2][1] = 0.0; + rmat[2][2] = 1.0; + + mult(rmat,mat,mat); +} + +void +zshear(float mat[3][3], /* I - Matrix */ + float dx, /* I - X shear */ + float dy) /* I - Y shear */ +{ + float smat[3][3]; /* Shear matrix */ + + + smat[0][0] = 1.0; + smat[0][1] = 0.0; + smat[0][2] = dx; + + smat[1][0] = 0.0; + smat[1][1] = 1.0; + smat[1][2] = dy; + + smat[2][0] = 0.0; + smat[2][1] = 0.0; + smat[2][2] = 1.0; + + mult(smat, mat, mat); +} + +void +huerotate(float mat[3][3], /* I - Matrix to append to */ + float rot) /* I - Hue rotation in degrees */ +{ + float hmat[3][3] = {{1.0,0.0,0.0},{0.0,1.0,0.0},{0.0,0.0,1.0}}; /* Hue matrix */ + float lx, ly, lz; /* Luminance vector */ + float xrs, xrc; /* X rotation sine/cosine */ + float yrs, yrc; /* Y rotation sine/cosine */ + float zrs, zrc; /* Z rotation sine/cosine */ + float zsx, zsy; /* Z shear x/y */ + + + /* + * Rotate the gray vector into positive Z... + */ + + xrs = M_SQRT1_2; + xrc = M_SQRT1_2; + xrotate(hmat,xrs,xrc); + + yrs = -1.0 / sqrt(3.0); + yrc = -M_SQRT2 * yrs; + yrotate(hmat,yrs,yrc); + + /* + * Shear the space to make the luminance plane horizontal... + */ + + xform(hmat, 0.3086, 0.6094, 0.0820, &lx, &ly, &lz); + zsx = lx / lz; + zsy = ly / lz; + zshear(hmat, zsx, zsy); + + /* + * Rotate the hue... + */ + + zrs = sin(rot * M_PI / 180.0); + zrc = cos(rot * M_PI / 180.0); + + zrotate(hmat, zrs, zrc); + + /* + * Unshear the space to put the luminance plane back... + */ + + zshear(hmat, -zsx, -zsy); + + /* + * Rotate the gray vector back into place... + */ + + yrotate(hmat, -yrs, yrc); + xrotate(hmat, -xrs, xrc); + + /* + * Append it to the current matrix... + */ + + mult(hmat, mat, mat); +} + +void +bright(float mat[3][3], + float scale) +{ + for (int i=0;i<3;i++) + for (int j=0;j<3;j++) + mat[i][j] *= scale; +} + +//---------------------------------------------------------------------------------------------------- + +QImage convertImage(const QImage& image, int hue, int saturation, int brightness, int gamma) +{ + float mat[3][3] = {{1.0,0.0,0.0},{0.0,1.0,0.0},{0.0,0.0,1.0}}; + int lut[3][3][256]; + QRgb c; + int r,g,b,v,r2,g2,b2; + float gam = 1.0/(float(gamma)/1000.0); + QImage img(image); + + saturate(mat,saturation*0.01); + huerotate(mat,(float)hue); + bright(mat,brightness*0.01); + for (int i = 0; i < 3; i ++) + for (int j = 0; j < 3; j ++) + for (int k = 0; k < 256; k ++) + lut[i][j][k] = (int)(mat[i][j] * k + 0.5); + + img.detach(); + for (int i=0;i<image.width();i++) + for (int j=0;j<image.height();j++) + { + c = image.pixel(i,j); + r = qRed(c); + g = qGreen(c); + b = qBlue(c); + + v = lut[0][0][r] + lut[1][0][g] + lut[2][0][b]; + if (gamma != 1000) v = (int)rint(pow(v,gam)); + if (v < 0) r2 = 0; + else if (v > 255) r2 = 255; + else r2 = v; + + v = lut[0][1][r] + lut[1][1][g] + lut[2][1][b]; + if (gamma != 1000) v = (int)rint(pow(v,gam)); + if (v < 0) g2 = 0; + else if (v > 255) g2 = 255; + else g2 = v; + + v = lut[0][2][r] + lut[1][2][g] + lut[2][2][b]; + if (gamma != 1000) v = (int)rint(pow(v,gam)); + if (v < 0) b2 = 0; + else if (v > 255) b2 = 255; + else b2 = v; + + img.setPixel(i,j,qRgb(r2,g2,b2)); + } + return img; +} diff --git a/kdeprint/cups/imageposition.cpp b/kdeprint/cups/imageposition.cpp new file mode 100644 index 000000000..0489b5079 --- /dev/null +++ b/kdeprint/cups/imageposition.cpp @@ -0,0 +1,153 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "imageposition.h" + +#include <qpainter.h> +#include <kstandarddirs.h> + +static void draw3DPage(QPainter *p, QRect r) +{ + // draw white page + p->fillRect(r,Qt::white); + // draw 3D border + p->setPen(Qt::black); + p->moveTo(r.left(),r.bottom()); + p->lineTo(r.right(),r.bottom()); + p->lineTo(r.right(),r.top()); + p->setPen(Qt::darkGray); + p->lineTo(r.left(),r.top()); + p->lineTo(r.left(),r.bottom()); + p->setPen(Qt::gray); + p->moveTo(r.left()+1,r.bottom()-1); + p->lineTo(r.right()-1,r.bottom()-1); + p->lineTo(r.right()-1,r.top()+1); +} + +ImagePosition::ImagePosition(QWidget *parent, const char *name) + : QWidget(parent,name) +{ + position_ = Center; + setMinimumSize(sizeHint()); + setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); + pix_.load(locate("data", "kdeprint/preview-mini.png")); +} + +ImagePosition::~ImagePosition() +{ +} + +void ImagePosition::setPosition(const char *type) +{ + int pos(Center); + if (strcmp(type,"top-left") == 0) pos = TopLeft; + else if (strcmp(type,"top") == 0) pos = Top; + else if (strcmp(type,"top-right") == 0) pos = TopRight; + else if (strcmp(type,"left") == 0) pos = Left; + else if (strcmp(type,"center") == 0) pos = Center; + else if (strcmp(type,"right") == 0) pos = Right; + else if (strcmp(type,"bottom-left") == 0) pos = BottomLeft; + else if (strcmp(type,"bottom") == 0) pos = Bottom; + else if (strcmp(type,"bottom-right") == 0) pos = BottomRight; + setPosition((PositionType)pos); +} + +void ImagePosition::setPosition(PositionType type) +{ + if (position_ != type) { + position_ = type; + update(); + } +} + +void ImagePosition::setPosition(int horiz, int vert) +{ + int type = vert*3+horiz; + setPosition((PositionType)type); +} + +QString ImagePosition::positionString() const +{ + switch (position_) { + case TopLeft: return "top-left"; + case Top: return "top"; + case TopRight: return "top-right"; + case Left: return "left"; + case Center: return "center"; + case Right: return "right"; + case BottomLeft: return "bottom-left"; + case Bottom: return "bottom"; + case BottomRight: return "bottom-right"; + } + return "center"; +} + +void ImagePosition::paintEvent(QPaintEvent*) +{ + int horiz, vert, x, y; + int margin = 5; + int pw(width()), ph(height()), px(0), py(0); + + if (pw > ((ph * 3) / 4)) + { + pw = (ph * 3) / 4; + px = (width() - pw) / 2; + } + else + { + ph = (pw * 4) / 3; + py = (height() - ph) / 2; + } + QRect page(px, py, pw, ph), img(0, 0, pix_.width(), pix_.height()); + + // compute img position + horiz = position_%3; + vert = position_/3; + switch (horiz) { + case 0: x = page.left()+margin; break; + default: + case 1: x = (page.left()+page.right()-img.width())/2; break; + case 2: x = page.right()-margin-img.width(); break; + } + switch (vert) { + case 0: y = page.top()+margin; break; + default: + case 1: y = (page.top()+page.bottom()-img.height())/2; break; + case 2: y = page.bottom()-margin-img.height(); break; + } + img.moveTopLeft(QPoint(x,y)); + + // draw page + QPainter p(this); + draw3DPage(&p,page); + + // draw img + /*p.setPen(darkRed); + p.drawRect(img); + p.drawLine(img.topLeft(),img.bottomRight()); + p.drawLine(img.topRight(),img.bottomLeft());*/ + p.drawPixmap(x, y, pix_); + + p.end(); +} + +QSize ImagePosition::sizeHint() const +{ + return QSize(60, 80); +} diff --git a/kdeprint/cups/imageposition.h b/kdeprint/cups/imageposition.h new file mode 100644 index 000000000..64a105db7 --- /dev/null +++ b/kdeprint/cups/imageposition.h @@ -0,0 +1,58 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef IMAGEPOSITION_H +#define IMAGEPOSITION_H + +#include <qwidget.h> +#include <qstring.h> +#include <qpixmap.h> + +class ImagePosition : public QWidget +{ +public: + enum PositionType {TopLeft, + Top, + TopRight, + Left, + Center, + Right, + BottomLeft, + Bottom, + BottomRight}; + + ImagePosition(QWidget *parent = 0, const char *name = 0); + ~ImagePosition(); + + void setPosition(const char *type = "center"); + void setPosition(PositionType type = Center); + void setPosition(int horiz = 1, int vert = 1); + PositionType position() const { return (PositionType)position_; } + QString positionString() const; + QSize sizeHint() const; + +protected: + void paintEvent(QPaintEvent *); + +private: + int position_; + QPixmap pix_; +}; + +#endif diff --git a/kdeprint/cups/imagepreview.cpp b/kdeprint/cups/imagepreview.cpp new file mode 100644 index 000000000..a7badd09b --- /dev/null +++ b/kdeprint/cups/imagepreview.cpp @@ -0,0 +1,78 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "imagepreview.h" + +#include <qpainter.h> +#include <qpixmap.h> +#include <qpaintdevice.h> + +// forward definition +QImage convertImage(const QImage& image, int hue, int saturation, int brightness, int gamma); + +ImagePreview::ImagePreview(QWidget *parent, const char *name ) : QWidget(parent,name) { + brightness_ = 100; + hue_ = 0; + saturation_ = 100; + gamma_ = 1000; + bw_ = false; + + setBackgroundMode(NoBackground); +} + +ImagePreview::~ImagePreview(){ +} + +void ImagePreview::setImage(const QImage& image){ + image_ = image.convertDepth(32); + image_.detach(); + resize(image_.size()); + update(); +} + +void ImagePreview::setParameters(int brightness, int hue, int saturation, int gamma){ + brightness_ = brightness; + hue_ = hue; + saturation_ = saturation; + gamma_ = gamma; + repaint(); +} + +void ImagePreview::paintEvent(QPaintEvent*){ + QImage tmpImage = convertImage(image_,hue_,(bw_ ? 0 : saturation_),brightness_,gamma_); + int x = (width()-tmpImage.width())/2, y = (height()-tmpImage.height())/2; + + QPixmap buffer(width(), height()); + buffer.fill(parentWidget(), 0, 0); + QPainter p(&buffer); + p.drawImage(x,y,tmpImage); + p.end(); + + bitBlt(this, QPoint(0, 0), &buffer, buffer.rect(), Qt::CopyROP); +} + +void ImagePreview::setBlackAndWhite(bool on){ + bw_ = on; + update(); +} + +QSize ImagePreview::minimumSizeHint() const +{ + return image_.size(); +} diff --git a/kdeprint/cups/imagepreview.h b/kdeprint/cups/imagepreview.h new file mode 100644 index 000000000..e709490fb --- /dev/null +++ b/kdeprint/cups/imagepreview.h @@ -0,0 +1,49 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef IMAGEPREVIEW_H +#define IMAGEPREVIEW_H + +#include <qwidget.h> +#include <qimage.h> + +class ImagePreview : public QWidget +{ +public: + ImagePreview(QWidget *parent=0, const char *name=0); + ~ImagePreview(); + + void setParameters(int brightness, int hue, int saturation, int gamma); + void setImage(const QImage& image); + void setBlackAndWhite(bool on); + QSize minimumSizeHint() const; + +private: // Private attributes + int brightness_; + int hue_; + int saturation_; + int gamma_; + bool bw_; + QImage image_; + +protected: // Protected methods + void paintEvent(QPaintEvent*); +}; + +#endif diff --git a/kdeprint/cups/ippreportdlg.cpp b/kdeprint/cups/ippreportdlg.cpp new file mode 100644 index 000000000..71256ce39 --- /dev/null +++ b/kdeprint/cups/ippreportdlg.cpp @@ -0,0 +1,96 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "ippreportdlg.h" +#include "ipprequest.h" +#include "kprinter.h" + +#include <klocale.h> +#include <kguiitem.h> +#include <kmessagebox.h> +#include <kdebug.h> +#include <ktextedit.h> +#include <qsimplerichtext.h> +#include <qpainter.h> +#include <qpaintdevicemetrics.h> + +IppReportDlg::IppReportDlg(QWidget *parent, const char *name) +: KDialogBase(parent, name, true, i18n("IPP Report"), Close|User1, Close, false, KGuiItem(i18n("&Print"), "fileprint")) +{ + m_edit = new KTextEdit(this); + m_edit->setReadOnly(true); + setMainWidget(m_edit); + resize(540, 500); + setFocusProxy(m_edit); + setButtonGuiItem(User1, KGuiItem(i18n("&Print"),"fileprint")); +} + +void IppReportDlg::slotUser1() +{ + KPrinter printer; + printer.setFullPage(true); + printer.setDocName(caption()); + if (printer.setup(this)) + { + QPainter painter(&printer); + QPaintDeviceMetrics metrics(&printer); + + // report is printed using QSimpleRichText + QSimpleRichText rich(m_edit->text(), font()); + rich.setWidth(&painter, metrics.width()); + int margin = (int)(1.5 / 2.54 * metrics.logicalDpiY()); // 1.5 cm + QRect r(margin, margin, metrics.width()-2*margin, metrics.height()-2*margin); + int hh = rich.height(), page(1); + while (1) + { + rich.draw(&painter, margin, margin, r, colorGroup()); + QString s = caption() + ": " + QString::number(page); + QRect br = painter.fontMetrics().boundingRect(s); + painter.drawText(r.right()-br.width()-5, r.top()-br.height()-4, br.width()+5, br.height()+4, Qt::AlignRight|Qt::AlignTop, s); + r.moveBy(0, r.height()-10); + painter.translate(0, -(r.height()-10)); + if (r.top() < hh) + { + printer.newPage(); + page++; + } + else + break; + } + } +} + +void IppReportDlg::report(IppRequest *req, int group, const QString& caption) +{ + QString str_report; + QTextStream t(&str_report, IO_WriteOnly); + + if (req->htmlReport(group, t)) + { + IppReportDlg dlg; + if (!caption.isEmpty()) + dlg.setCaption(caption); + dlg.m_edit->setText(str_report); + dlg.exec(); + } + else + KMessageBox::error(0, i18n("Internal error: unable to generate HTML report.")); +} + +#include "ippreportdlg.moc" diff --git a/kdeprint/cups/ippreportdlg.h b/kdeprint/cups/ippreportdlg.h new file mode 100644 index 000000000..fe3f36621 --- /dev/null +++ b/kdeprint/cups/ippreportdlg.h @@ -0,0 +1,42 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef IPPREPORTDLG_H +#define IPPREPORTDLG_H + +#include <kdialogbase.h> + +class IppRequest; +class KTextEdit; + +class IppReportDlg : public KDialogBase +{ + Q_OBJECT +public: + IppReportDlg(QWidget *parent = 0, const char *name = 0); + static void report(IppRequest *req, int group, const QString& caption = QString::null); + +protected slots: + void slotUser1(); + +private: + KTextEdit *m_edit; +}; + +#endif diff --git a/kdeprint/cups/ipprequest.cpp b/kdeprint/cups/ipprequest.cpp new file mode 100644 index 000000000..b4812a171 --- /dev/null +++ b/kdeprint/cups/ipprequest.cpp @@ -0,0 +1,544 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "ipprequest.h" +#include "cupsinfos.h" + +#include <stdlib.h> +#include <cups/language.h> +#include <kdebug.h> +#include <kglobal.h> +#include <klocale.h> +#include <qdatetime.h> +#include <qregexp.h> +#include <cups/cups.h> + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#ifdef HAVE_CUPS_NO_PWD_CACHE +#include <qcstring.h> +static QCString cups_authstring = ""; +#endif + +void dumpRequest(ipp_t *req, bool answer = false, const QString& s = QString::null) +{ + kdDebug(500) << "==========" << endl; + if (s.isEmpty()) + kdDebug(500) << (answer ? "Answer" : "Request") << endl; + else + kdDebug(500) << s << endl; + kdDebug(500) << "==========" << endl; + if (!req) + { + kdDebug(500) << "Null request" << endl; + return; + } + kdDebug(500) << "State = 0x" << QString::number(req->state, 16) << endl; + kdDebug(500) << "ID = 0x" << QString::number(req->request.status.request_id, 16) << endl; + if (answer) + { + kdDebug(500) << "Status = 0x" << QString::number(req->request.status.status_code, 16) << endl; + kdDebug(500) << "Status message = " << ippErrorString(req->request.status.status_code) << endl; + } + else + kdDebug(500) << "Operation = 0x" << QString::number(req->request.op.operation_id, 16) << endl; + kdDebug(500) << "Version = " << (int)(req->request.status.version[0]) << "." << (int)(req->request.status.version[1]) << endl; + kdDebug(500) << endl; + + ipp_attribute_t *attr = req->attrs; + while (attr) + { + QString s = QString::fromLatin1("%1 (0x%2) = ").arg(attr->name).arg(attr->value_tag, 0, 16); + for (int i=0;i<attr->num_values;i++) + { + switch (attr->value_tag) + { + case IPP_TAG_INTEGER: + case IPP_TAG_ENUM: + s += ("0x"+QString::number(attr->values[i].integer, 16)); + break; + case IPP_TAG_BOOLEAN: + s += (attr->values[i].boolean ? "true" : "false"); + break; + case IPP_TAG_STRING: + case IPP_TAG_TEXT: + case IPP_TAG_NAME: + case IPP_TAG_KEYWORD: + case IPP_TAG_URI: + case IPP_TAG_MIMETYPE: + case IPP_TAG_NAMELANG: + case IPP_TAG_TEXTLANG: + case IPP_TAG_CHARSET: + case IPP_TAG_LANGUAGE: + s += attr->values[i].string.text; + break; + default: + break; + } + if (i != (attr->num_values-1)) + s += ", "; + } + kdDebug(500) << s << endl; + attr = attr->next; + } +} + +QString errorString(int status) +{ + QString str; + switch (status) + { + case IPP_FORBIDDEN: + str = i18n("You don't have access to the requested resource."); + break; + case IPP_NOT_AUTHORIZED: + str = i18n("You are not authorized to access the requested resource."); + break; + case IPP_NOT_POSSIBLE: + str = i18n("The requested operation cannot be completed."); + break; + case IPP_SERVICE_UNAVAILABLE: + str = i18n("The requested service is currently unavailable."); + break; + case IPP_NOT_ACCEPTING: + str = i18n("The target printer is not accepting print jobs."); + break; + default: + str = QString::fromLocal8Bit(ippErrorString((ipp_status_t)status)); + break; + } + return str; +} + +//************************************************************************************* + +IppRequest::IppRequest() +{ + request_ = 0; + port_ = -1; + host_ = QString::null; + dump_ = 0; + init(); +} + +IppRequest::~IppRequest() +{ + ippDelete(request_); +} + +void IppRequest::init() +{ + connect_ = true; + + if (request_) + { + ippDelete(request_); + request_ = 0; + } + request_ = ippNew(); + //kdDebug(500) << "kdeprint: IPP request, lang=" << KGlobal::locale()->language() << endl; + QCString langstr = KGlobal::locale()->language().latin1(); + cups_lang_t* lang = cupsLangGet(langstr.data()); + // default charset to UTF-8 (ugly hack) + lang->encoding = CUPS_UTF8; + ippAddString(request_, IPP_TAG_OPERATION, IPP_TAG_CHARSET, "attributes-charset", NULL, cupsLangEncoding(lang)); + ippAddString(request_, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE, "attributes-natural-language", NULL, lang->language); + cupsLangFree(lang); +} + +void IppRequest::addString_p(int group, int type, const QString& name, const QString& value) +{ + if (!name.isEmpty()) + ippAddString(request_,(ipp_tag_t)group,(ipp_tag_t)type,name.latin1(),NULL,(value.isEmpty() ? "" : value.local8Bit().data())); +} + +void IppRequest::addStringList_p(int group, int type, const QString& name, const QStringList& values) +{ + if (!name.isEmpty()) + { + ipp_attribute_t *attr = ippAddStrings(request_,(ipp_tag_t)group,(ipp_tag_t)type,name.latin1(),(int)(values.count()),NULL,NULL); + int i(0); + for (QStringList::ConstIterator it=values.begin(); it != values.end(); ++it, i++) + attr->values[i].string.text = strdup((*it).local8Bit()); + } +} + +void IppRequest::addInteger_p(int group, int type, const QString& name, int value) +{ + if (!name.isEmpty()) ippAddInteger(request_,(ipp_tag_t)group,(ipp_tag_t)type,name.latin1(),value); +} + +void IppRequest::addIntegerList_p(int group, int type, const QString& name, const QValueList<int>& values) +{ + if (!name.isEmpty()) + { + ipp_attribute_t *attr = ippAddIntegers(request_,(ipp_tag_t)group,(ipp_tag_t)type,name.latin1(),(int)(values.count()),NULL); + int i(0); + for (QValueList<int>::ConstIterator it=values.begin(); it != values.end(); ++it, i++) + attr->values[i].integer = *it; + } +} + +void IppRequest::addBoolean(int group, const QString& name, bool value) +{ + if (!name.isEmpty()) ippAddBoolean(request_,(ipp_tag_t)group,name.latin1(),(char)value); +} + +void IppRequest::addBoolean(int group, const QString& name, const QValueList<bool>& values) +{ + if (!name.isEmpty()) + { + ipp_attribute_t *attr = ippAddBooleans(request_,(ipp_tag_t)group,name.latin1(),(int)(values.count()),NULL); + int i(0); + for (QValueList<bool>::ConstIterator it=values.begin(); it != values.end(); ++it, i++) + attr->values[i].boolean = (char)(*it); + } +} + +void IppRequest::setOperation(int op) +{ + request_->request.op.operation_id = (ipp_op_t)op; + request_->request.op.request_id = 1; // 0 is not RFC-compliant, should be at least 1 +} + +int IppRequest::status() +{ + return (request_ ? request_->request.status.status_code : (connect_ ? cupsLastError() : -2)); +} + +QString IppRequest::statusMessage() +{ + QString msg; + switch (status()) + { + case -2: + msg = i18n("Connection to CUPS server failed. Check that the CUPS server is correctly installed and running."); + break; + case -1: + msg = i18n("The IPP request failed for an unknown reason."); + break; + default: + msg = errorString(status()); + break; + } + return msg; +} + +bool IppRequest::integerValue_p(const QString& name, int& value, int type) +{ + if (!request_ || name.isEmpty()) return false; + ipp_attribute_t *attr = ippFindAttribute(request_, name.latin1(), (ipp_tag_t)type); + if (attr) + { + value = attr->values[0].integer; + return true; + } + else return false; +} + +bool IppRequest::stringValue_p(const QString& name, QString& value, int type) +{ + if (!request_ || name.isEmpty()) return false; + ipp_attribute_t *attr = ippFindAttribute(request_, name.latin1(), (ipp_tag_t)type); + if (attr) + { + value = QString::fromLocal8Bit(attr->values[0].string.text); + return true; + } + else return false; +} + +bool IppRequest::stringListValue_p(const QString& name, QStringList& values, int type) +{ + if (!request_ || name.isEmpty()) return false; + ipp_attribute_t *attr = ippFindAttribute(request_, name.latin1(), (ipp_tag_t)type); + values.clear(); + if (attr) + { + for (int i=0;i<attr->num_values;i++) + values.append(QString::fromLocal8Bit(attr->values[i].string.text)); + return true; + } + else return false; +} + +bool IppRequest::boolean(const QString& name, bool& value) +{ + if (!request_ || name.isEmpty()) return false; + ipp_attribute_t *attr = ippFindAttribute(request_, name.latin1(), IPP_TAG_BOOLEAN); + if (attr) + { + value = (bool)attr->values[0].boolean; + return true; + } + else return false; +} + +bool IppRequest::doFileRequest(const QString& res, const QString& filename) +{ + QString myHost = host_; + int myPort = port_; + if (myHost.isEmpty()) myHost = CupsInfos::self()->host(); + if (myPort <= 0) myPort = CupsInfos::self()->port(); + http_t *HTTP = httpConnect(myHost.latin1(),myPort); + + connect_ = (HTTP != NULL); + + if (HTTP == NULL) + { + ippDelete(request_); + request_ = 0; + return false; + } + +#ifdef HAVE_CUPS_NO_PWD_CACHE +#if CUPS_VERSION_MAJOR == 1 && CUPS_VERSION_MINOR <= 2 + strncpy( HTTP->authstring, cups_authstring.data(), HTTP_MAX_VALUE ); +#else + httpSetAuthString( HTTP, NULL, cups_authstring.data() ); +#endif +#endif + + if (dump_ > 0) + { + dumpRequest(request_, false, "Request to "+myHost+":"+QString::number(myPort)); + } + + request_ = cupsDoFileRequest(HTTP, request_, (res.isEmpty() ? "/" : res.latin1()), (filename.isEmpty() ? NULL : filename.latin1())); +#ifdef HAVE_CUPS_NO_PWD_CACHE +#if CUPS_VERSION_MAJOR == 1 && CUPS_VERSION_MINOR <= 2 + cups_authstring = HTTP->authstring; +#else + cups_authstring = httpGetAuthString( HTTP ); +#endif +#endif + httpClose(HTTP); + + if (dump_ > 1) + { + dumpRequest(request_, true); + } + + /* No printers found */ + if ( request_ && request_->request.status.status_code == 0x406 ) + return true; + + if (!request_ || request_->state == IPP_ERROR || (request_->request.status.status_code & 0x0F00)) + return false; + + + return true; +} + +bool IppRequest::htmlReport(int group, QTextStream& output) +{ + if (!request_) return false; + // start table + output << "<table border=\"1\" cellspacing=\"0\" cellpadding=\"0\">" << endl; + output << "<tr><th bgcolor=\"dark blue\"><font color=\"white\">" << i18n("Attribute") << "</font></th>" << endl; + output << "<th bgcolor=\"dark blue\"><font color=\"white\">" << i18n("Values") << "</font></th></tr>" << endl; + // go to the first attribute of the specified group + ipp_attribute_t *attr = request_->attrs; + while (attr && attr->group_tag != group) + attr = attr->next; + // print each attribute + ipp_uchar_t *d; + QCString dateStr; + QDateTime dt; + bool bg(false); + while (attr && attr->group_tag == group) + { + output << " <tr bgcolor=\"" << (bg ? "#ffffd9" : "#ffffff") << "\">\n <td><b>" << attr->name << "</b></td>\n <td>" << endl; + bg = !bg; + for (int i=0; i<attr->num_values; i++) + { + switch (attr->value_tag) + { + case IPP_TAG_INTEGER: + if (attr->name && strstr(attr->name, "time")) + { + dt.setTime_t((unsigned int)(attr->values[i].integer)); + output << dt.toString(); + } + else + output << attr->values[i].integer; + break; + case IPP_TAG_ENUM: + output << "0x" << hex << attr->values[i].integer << dec; + break; + case IPP_TAG_BOOLEAN: + output << (attr->values[i].boolean ? i18n("True") : i18n("False")); + break; + case IPP_TAG_STRING: + case IPP_TAG_TEXTLANG: + case IPP_TAG_NAMELANG: + case IPP_TAG_TEXT: + case IPP_TAG_NAME: + case IPP_TAG_KEYWORD: + case IPP_TAG_URI: + case IPP_TAG_CHARSET: + case IPP_TAG_LANGUAGE: + case IPP_TAG_MIMETYPE: + output << attr->values[i].string.text; + break; + case IPP_TAG_RESOLUTION: + output << "( " << attr->values[i].resolution.xres + << ", " << attr->values[i].resolution.yres << " )"; + break; + case IPP_TAG_RANGE: + output << "[ " << (attr->values[i].range.lower > 0 ? attr->values[i].range.lower : 1) + << ", " << (attr->values[i].range.upper > 0 ? attr->values[i].range.upper : 65535) << " ]"; + break; + case IPP_TAG_DATE: + d = attr->values[i].date; + dateStr.sprintf("%.4d-%.2d-%.2d, %.2d:%.2d:%.2d %c%.2d%.2d", + d[0]*256+d[1], d[2], d[3], + d[4], d[5], d[6], + d[8], d[9], d[10]); + output << dateStr; + break; + default: + continue; + } + if (i < attr->num_values-1) + output << "<br>"; + } + output << "</td>\n </tr>" << endl; + attr = attr->next; + } + // end table + output << "</table>" << endl; + + return true; +} + +QMap<QString,QString> IppRequest::toMap(int group) +{ + QMap<QString,QString> opts; + if (request_) + { + ipp_attribute_t *attr = first(); + while (attr) + { + if (group != -1 && attr->group_tag != group) + { + attr = attr->next; + continue; + } + QString value; + for (int i=0; i<attr->num_values; i++) + { + switch (attr->value_tag) + { + case IPP_TAG_INTEGER: + case IPP_TAG_ENUM: + value.append(QString::number(attr->values[i].integer)).append(","); + break; + case IPP_TAG_BOOLEAN: + value.append((attr->values[i].boolean ? "true" : "false")).append(","); + break; + case IPP_TAG_RANGE: + if (attr->values[i].range.lower > 0) + value.append(QString::number(attr->values[i].range.lower)); + if (attr->values[i].range.lower != attr->values[i].range.upper) + { + value.append("-"); + if (attr->values[i].range.upper > 0) + value.append(QString::number(attr->values[i].range.upper)); + } + value.append(","); + break; + case IPP_TAG_STRING: + case IPP_TAG_TEXT: + case IPP_TAG_NAME: + case IPP_TAG_KEYWORD: + case IPP_TAG_URI: + case IPP_TAG_MIMETYPE: + case IPP_TAG_NAMELANG: + case IPP_TAG_TEXTLANG: + case IPP_TAG_CHARSET: + case IPP_TAG_LANGUAGE: + value.append(QString::fromLocal8Bit(attr->values[i].string.text)).append(","); + break; + default: + break; + } + } + if (!value.isEmpty()) + value.truncate(value.length()-1); + opts[QString::fromLocal8Bit(attr->name)] = value; + attr = attr->next; + } + } + return opts; +} + +void IppRequest::setMap(const QMap<QString,QString>& opts) +{ + if (!request_) + return; + + QRegExp re("^\"|\"$"); + cups_option_t *options = NULL; + int n = 0; + for (QMap<QString,QString>::ConstIterator it=opts.begin(); it!=opts.end(); ++it) + { + if (it.key().startsWith("kde-") || it.key().startsWith("app-")) + continue; + QString value = it.data().stripWhiteSpace(), lovalue; + value.replace(re, ""); + lovalue = value.lower(); + + // handles specific cases: boolean, empty strings, or option that has that boolean + // keyword as value (to prevent them from conversion to real boolean) + if (value == "true" || value == "false") + addBoolean(IPP_TAG_JOB, it.key(), (value == "true")); + else if (value.isEmpty() || lovalue == "off" || lovalue == "on" + || lovalue == "yes" || lovalue == "no" + || lovalue == "true" || lovalue == "false") + addName(IPP_TAG_JOB, it.key(), value); + else + n = cupsAddOption(it.key().local8Bit(), value.local8Bit(), n, &options); + } + if (n > 0) + cupsEncodeOptions(request_, n, options); + cupsFreeOptions(n, options); + + // find an remove that annoying "document-format" attribute +#if CUPS_VERSION_MAJOR == 1 && CUPS_VERSION_MINOR >= 2 + ipp_attribute_t *attr = ippFindAttribute(request_, "document-format", IPP_TAG_NAME); + ippDeleteAttribute(request_, attr); +#else + // (can't use IppDeleteAttribute as older cups doesn't have that) + ipp_attribute_t *attr = request_->attrs; + while (attr) + { + if (attr->next && strcmp(attr->next->name, "document-format") == 0) + { + ipp_attribute_t *attr2 = attr->next; + attr->next = attr2->next; + _ipp_free_attr(attr2); + break; + } + attr = attr->next; + } +#endif +} diff --git a/kdeprint/cups/ipprequest.h b/kdeprint/cups/ipprequest.h new file mode 100644 index 000000000..68fe3ec0b --- /dev/null +++ b/kdeprint/cups/ipprequest.h @@ -0,0 +1,196 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef IPPREQUEST_H +#define IPPREQUEST_H + +#include <qstring.h> +#include <qstringlist.h> +#include <qtextstream.h> +#include <qmap.h> + +#include <cups/ipp.h> + +class IppRequest +{ +public: + IppRequest(); + ~IppRequest(); + + void init(); // re-initializes the request + + // request building functions + void addMime(int group, const QString& name, const QString& mime); + void addKeyword(int group, const QString& name, const QString& key); + void addKeyword(int group, const QString& name, const QStringList& keys); + void addURI(int group, const QString& name, const QString& uri); + void addURI(int group, const QString& name, const QStringList& uris); + void addText(int group, const QString& name, const QString& txt); + void addText(int group, const QString& name, const QStringList& txts); + void addName(int group, const QString& name, const QString& nm); + void addName(int group, const QString& name, const QStringList& nms); + void addInteger(int group, const QString& name, int value); + void addInteger(int group, const QString& name, const QValueList<int>& values); + void addEnum(int group, const QString& name, int value); + void addEnum(int group, const QString& name, const QValueList<int>& values); + void addBoolean(int group, const QString& name, bool value); + void addBoolean(int group, const QString& name, const QValueList<bool>& values); + + void setOperation(int op); + void setHost(const QString& host); + void setPort(int p); + + // request answer functions + int status(); + QString statusMessage(); + bool integer(const QString& name, int& value); + bool boolean(const QString& name, bool& value); + bool enumvalue(const QString& name, int& value); + bool name(const QString& name, QString& value); + bool name(const QString& name, QStringList& value); + bool text(const QString& name, QString& value); + bool text(const QString& name, QStringList& value); + bool uri(const QString& name, QString& value); + bool uri(const QString& name, QStringList& value); + bool keyword(const QString& name, QString& value); + bool keyword(const QString& name, QStringList& value); + bool mime(const QString& name, QString& value); + ipp_attribute_t* first(); + ipp_attribute_t* last(); + QMap<QString,QString> toMap(int group = -1); + void setMap(const QMap<QString,QString>& opts); + + // processing functions + bool doRequest(const QString& res); + bool doFileRequest(const QString& res, const QString& filename = QString::null); + + // report functions + bool htmlReport(int group, QTextStream& output); + + // debug function + void dump(int state); + +protected: + void addString_p(int group, int type, const QString& name, const QString& value); + void addStringList_p(int group, int type, const QString& name, const QStringList& values); + void addInteger_p(int group, int type, const QString& name, int value); + void addIntegerList_p(int group, int type, const QString& name, const QValueList<int>& values); + bool stringValue_p(const QString& name, QString& value, int type); + bool stringListValue_p(const QString& name, QStringList& values, int type); + bool integerValue_p(const QString& name, int& value, int type); + +private: + ipp_t *request_; + QString host_; + int port_; + bool connect_; + int dump_; +}; + +inline void IppRequest::addMime(int group, const QString& name, const QString& mime) +{ addString_p(group, IPP_TAG_MIMETYPE, name, mime); } + +inline void IppRequest::addKeyword(int group, const QString& name, const QString& key) +{ addString_p(group, IPP_TAG_KEYWORD, name, key); } + +inline void IppRequest::addKeyword(int group, const QString& name, const QStringList& keys) +{ addStringList_p(group, IPP_TAG_KEYWORD, name, keys); } + +inline void IppRequest::addURI(int group, const QString& name, const QString& uri) +{ addString_p(group, IPP_TAG_URI, name, uri); } + +inline void IppRequest::addURI(int group, const QString& name, const QStringList& uris) +{ addStringList_p(group, IPP_TAG_URI, name, uris); } + +inline void IppRequest::addText(int group, const QString& name, const QString& txt) +{ addString_p(group, IPP_TAG_TEXT, name, txt); } + +inline void IppRequest::addText(int group, const QString& name, const QStringList& txts) +{ addStringList_p(group, IPP_TAG_TEXT, name, txts); } + +inline void IppRequest::addName(int group, const QString& name, const QString& nm) +{ addString_p(group, IPP_TAG_NAME, name, nm); } + +inline void IppRequest::addName(int group, const QString& name, const QStringList& nms) +{ addStringList_p(group, IPP_TAG_NAME, name, nms); } + +inline void IppRequest::addInteger(int group, const QString& name, int value) +{ addInteger_p(group, IPP_TAG_INTEGER, name, value); } + +inline void IppRequest::addInteger(int group, const QString& name, const QValueList<int>& values) +{ addIntegerList_p(group, IPP_TAG_INTEGER, name, values); } + +inline void IppRequest::addEnum(int group, const QString& name, int value) +{ addInteger_p(group, IPP_TAG_ENUM, name, value); } + +inline void IppRequest::addEnum(int group, const QString& name, const QValueList<int>& values) +{ addIntegerList_p(group, IPP_TAG_ENUM, name, values); } + +inline bool IppRequest::integer(const QString& name, int& value) +{ return integerValue_p(name, value, IPP_TAG_INTEGER); } + +inline bool IppRequest::enumvalue(const QString& name, int& value) +{ return integerValue_p(name, value, IPP_TAG_ENUM); } + +inline bool IppRequest::name(const QString& name, QString& value) +{ return stringValue_p(name, value, IPP_TAG_NAME); } + +inline bool IppRequest::name(const QString& name, QStringList& values) +{ return stringListValue_p(name, values, IPP_TAG_NAME); } + +inline bool IppRequest::text(const QString& name, QString& value) +{ return stringValue_p(name, value, IPP_TAG_TEXT); } + +inline bool IppRequest::text(const QString& name, QStringList& values) +{ return stringListValue_p(name, values, IPP_TAG_TEXT); } + +inline bool IppRequest::uri(const QString& name, QString& value) +{ return stringValue_p(name, value, IPP_TAG_URI); } + +inline bool IppRequest::uri(const QString& name, QStringList& values) +{ return stringListValue_p(name, values, IPP_TAG_URI); } + +inline bool IppRequest::keyword(const QString& name, QString& value) +{ return stringValue_p(name, value, IPP_TAG_KEYWORD); } + +inline bool IppRequest::keyword(const QString& name, QStringList& values) +{ return stringListValue_p(name, values, IPP_TAG_KEYWORD); } + +inline bool IppRequest::mime(const QString& name, QString& value) +{ return stringValue_p(name, value, IPP_TAG_MIMETYPE); } + +inline bool IppRequest::doRequest(const QString& res) +{ return doFileRequest(res); } + +inline ipp_attribute_t* IppRequest::first() +{ return (request_ ? request_->attrs : NULL); } + +inline ipp_attribute_t* IppRequest::last() +{ return (request_ ? request_->last : NULL); } + +inline void IppRequest::setHost(const QString& host) +{ host_ = host; } + +inline void IppRequest::setPort(int p) +{ port_ = p; } + +inline void IppRequest::dump(int state) +{ dump_ = state; } + +#endif diff --git a/kdeprint/cups/kcupsprinterimpl.cpp b/kdeprint/cups/kcupsprinterimpl.cpp new file mode 100644 index 000000000..665183063 --- /dev/null +++ b/kdeprint/cups/kcupsprinterimpl.cpp @@ -0,0 +1,159 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kcupsprinterimpl.h" +#include "kprinter.h" +#include "driver.h" +#include "kmfactory.h" +#include "kmmanager.h" +#include "cupsinfos.h" + +#include <qfile.h> +#include <cups/cups.h> +#include <stdlib.h> +#include <kprocess.h> + +static void mapToCupsOptions(const QMap<QString,QString>& opts, QString& cmd); + +QSize rangeToSize(const QString& s) +{ + QString range = s; + int p(-1); + int from, to; + + if ((p=range.find(',')) != -1) + range.truncate(p); + if ((p=range.find('-')) != -1) + { + from = range.left(p).toInt(); + to = range.right(range.length()-p-1).toInt(); + } + else if (!range.isEmpty()) + from = to = range.toInt(); + else + from = to = 0; + + return QSize(from,to); +} +//****************************************************************************************************** + +KCupsPrinterImpl::KCupsPrinterImpl(QObject *parent, const char *name, const QStringList & /*args*/) +: KPrinterImpl(parent,name) +{ +} + +KCupsPrinterImpl::~KCupsPrinterImpl() +{ +} + +bool KCupsPrinterImpl::setupCommand(QString& cmd, KPrinter *printer) +{ + // check printer object + if (!printer) return false; + + QString hoststr = QString::fromLatin1("%1:%2").arg(CupsInfos::self()->host()).arg(CupsInfos::self()->port()); + cmd = QString::fromLatin1("cupsdoprint -P %1 -J %3 -H %2").arg(quote(printer->printerName())).arg(quote(hoststr)).arg(quote(printer->docName())); + if (!CupsInfos::self()->login().isEmpty()) + { + QString userstr(CupsInfos::self()->login()); + //if (!CupsInfos::self()->password().isEmpty()) + // userstr += (":" + CupsInfos::self()->password()); + cmd.append(" -U ").append(quote(userstr)); + } + mapToCupsOptions(printer->options(),cmd); + return true; +} + +void KCupsPrinterImpl::preparePrinting(KPrinter *printer) +{ + // process orientation + QString o = printer->option("orientation-requested"); + printer->setOption("kde-orientation",(o == "4" || o == "5" ? "Landscape" : "Portrait")); + // if it's a Qt application, then convert orientation as it will be handled by Qt directly + if (printer->applicationType() == KPrinter::Dialog) + printer->setOption("orientation-requested",(o == "5" || o == "6" ? "6" : "3")); + + // translate copies number + if (!printer->option("kde-copies").isEmpty()) printer->setOption("copies",printer->option("kde-copies")); + + // page ranges are handled by CUPS, so application should print all pages + if (printer->pageSelection() == KPrinter::SystemSide) + { // Qt => CUPS + // translations + if (!printer->option("kde-range").isEmpty()) + printer->setOption("page-ranges",printer->option("kde-range")); + if (printer->option("kde-pageorder") == "Reverse") + printer->setOption("OutputOrder",printer->option("kde-pageorder")); + o = printer->option("kde-pageset"); + if (!o.isEmpty() && o != "0") + printer->setOption("page-set",(o == "1" ? "odd" : "even")); + printer->setOption("multiple-document-handling",(printer->option("kde-collate") == "Collate" ? "separate-documents-collated-copies" : "separate-documents-uncollated-copies")); + } + else + { // No translation needed (but range => (from,to)) + QString range = printer->option("kde-range"); + if (!range.isEmpty()) + { + QSize s = rangeToSize(range); + printer->setOption("kde-from",QString::number(s.width())); + printer->setOption("kde-to",QString::number(s.height())); + } + } + + // needed for page size and margins + KPrinterImpl::preparePrinting(printer); +} + +void KCupsPrinterImpl::broadcastOption(const QString& key, const QString& value) +{ + KPrinterImpl::broadcastOption(key,value); + if (key == "kde-orientation") + KPrinterImpl::broadcastOption("orientation-requested",(value == "Landscape" ? "4" : "3")); + else if (key == "kde-pagesize") + { + QString pagename = QString::fromLatin1(pageSizeToPageName((KPrinter::PageSize)value.toInt())); + KPrinterImpl::broadcastOption("PageSize",pagename); + // simple hack for classes + KPrinterImpl::broadcastOption("media",pagename); + } +} + +//****************************************************************************************************** + +static void mapToCupsOptions(const QMap<QString,QString>& opts, QString& cmd) +{ + QString optstr; + for (QMap<QString,QString>::ConstIterator it=opts.begin(); it!=opts.end(); ++it) + { + // only encode those options that doesn't start with "kde-" or "app-". + if (!it.key().startsWith("kde-") && !it.key().startsWith("app-") && !it.key().startsWith("_kde")) + { + QString key = it.key(); + if (key.startsWith("KDEPrint-")) + /* Those are keys added by the "Additional Tags" page. * + * Strip the prefix to build valid a CUPS option. */ + key = key.mid(9); + optstr.append(" ").append(key); + if (!it.data().isEmpty()) + optstr.append("=").append(it.data()); + } + } + if (!optstr.isEmpty()) + cmd.append(" -o ").append( KProcess::quote( optstr ) ); +} diff --git a/kdeprint/cups/kcupsprinterimpl.h b/kdeprint/cups/kcupsprinterimpl.h new file mode 100644 index 000000000..81b0a364a --- /dev/null +++ b/kdeprint/cups/kcupsprinterimpl.h @@ -0,0 +1,36 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KCUPSPRINTERIMPL_H +#define KCUPSPRINTERIMPL_H + +#include "kprinterimpl.h" + +class KCupsPrinterImpl : public KPrinterImpl +{ +public: + KCupsPrinterImpl(QObject *parent, const char *name, const QStringList & /*args*/ = QStringList()); + ~KCupsPrinterImpl(); + + bool setupCommand(QString&, KPrinter*); + void preparePrinting(KPrinter*); + void broadcastOption(const QString& key, const QString& value); +}; + +#endif diff --git a/kdeprint/cups/kmconfigcups.cpp b/kdeprint/cups/kmconfigcups.cpp new file mode 100644 index 000000000..3d5ece0ab --- /dev/null +++ b/kdeprint/cups/kmconfigcups.cpp @@ -0,0 +1,51 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kmconfigcups.h" +#include "kmcupsconfigwidget.h" + +#include <klocale.h> +#include <kconfig.h> +#include <kdialog.h> + +#include <qlayout.h> + +KMConfigCups::KMConfigCups(QWidget *parent) +: KMConfigPage(parent,"ConfigCups") +{ + setPageName(i18n("CUPS Server")); + setPageHeader(i18n("CUPS Server Settings")); + setPagePixmap("gear"); + + m_widget = new KMCupsConfigWidget(this); + + QVBoxLayout *lay0 = new QVBoxLayout(this, 0, KDialog::spacingHint()); + lay0->addWidget(m_widget); + lay0->addStretch(1); +} + +void KMConfigCups::loadConfig(KConfig *) +{ + m_widget->load(); +} + +void KMConfigCups::saveConfig(KConfig *conf) +{ + m_widget->saveConfig(conf); +} diff --git a/kdeprint/cups/kmconfigcups.h b/kdeprint/cups/kmconfigcups.h new file mode 100644 index 000000000..3f0afa2bb --- /dev/null +++ b/kdeprint/cups/kmconfigcups.h @@ -0,0 +1,39 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KMCONFIGCUPS_H +#define KMCONFIGCUPS_H + +#include "kmconfigpage.h" + +class KMCupsConfigWidget; + +class KMConfigCups : public KMConfigPage +{ +public: + KMConfigCups(QWidget *parent = 0); + + void loadConfig(KConfig*); + void saveConfig(KConfig*); + +private: + KMCupsConfigWidget *m_widget; +}; + +#endif diff --git a/kdeprint/cups/kmconfigcupsdir.cpp b/kdeprint/cups/kmconfigcupsdir.cpp new file mode 100644 index 000000000..31005752d --- /dev/null +++ b/kdeprint/cups/kmconfigcupsdir.cpp @@ -0,0 +1,67 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kmconfigcupsdir.h" + +#include <qcheckbox.h> +#include <kurlrequester.h> +#include <klocale.h> +#include <kdialog.h> +#include <kconfig.h> +#include <qgroupbox.h> +#include <qlayout.h> +#include <kcursor.h> + +KMConfigCupsDir::KMConfigCupsDir(QWidget *parent) +: KMConfigPage(parent,"ConfigCupsDir") +{ + setPageName(i18n("Folder")); + setPageHeader(i18n("CUPS Folder Settings")); + setPagePixmap("folder"); + + QGroupBox *m_dirbox = new QGroupBox(0, Qt::Vertical, i18n("Installation Folder"), this); + m_installdir = new KURLRequester(m_dirbox); + m_installdir->setMode((KFile::Mode)(KFile::Directory|KFile::ExistingOnly|KFile::LocalOnly)); + m_stddir = new QCheckBox(i18n("Standard installation (/)"), m_dirbox); + m_stddir->setCursor(KCursor::handCursor()); + + QVBoxLayout *lay0 = new QVBoxLayout(this, 0, KDialog::spacingHint()); + lay0->addWidget(m_dirbox); + lay0->addStretch(1); + QVBoxLayout *lay1 = new QVBoxLayout(m_dirbox->layout(), 10); + lay1->addWidget(m_stddir); + lay1->addWidget(m_installdir); + + connect(m_stddir,SIGNAL(toggled(bool)),m_installdir,SLOT(setDisabled(bool))); + m_stddir->setChecked(true); +} + +void KMConfigCupsDir::loadConfig(KConfig *conf) +{ + conf->setGroup("CUPS"); + QString dir = conf->readPathEntry("InstallDir"); + m_stddir->setChecked(dir.isEmpty()); + m_installdir->setURL(dir); +} + +void KMConfigCupsDir::saveConfig(KConfig *conf) +{ + conf->setGroup("CUPS"); + conf->writePathEntry("InstallDir",(m_stddir->isChecked() ? QString::null : m_installdir->url())); +} diff --git a/kdeprint/cups/kmconfigcupsdir.h b/kdeprint/cups/kmconfigcupsdir.h new file mode 100644 index 000000000..253b2bd2d --- /dev/null +++ b/kdeprint/cups/kmconfigcupsdir.h @@ -0,0 +1,41 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KMCONFIGCUPSDIR_H +#define KMCONFIGCUPSDIR_H + +#include "kmconfigpage.h" + +class KURLRequester; +class QCheckBox; + +class KMConfigCupsDir : public KMConfigPage +{ +public: + KMConfigCupsDir(QWidget *parent = 0); + + void loadConfig(KConfig*); + void saveConfig(KConfig*); + +private: + KURLRequester *m_installdir; + QCheckBox *m_stddir; +}; + +#endif diff --git a/kdeprint/cups/kmcupsconfigwidget.cpp b/kdeprint/cups/kmcupsconfigwidget.cpp new file mode 100644 index 000000000..9c3fa7516 --- /dev/null +++ b/kdeprint/cups/kmcupsconfigwidget.cpp @@ -0,0 +1,159 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kmcupsconfigwidget.h" +#include "cupsinfos.h" + +#include <qlabel.h> +#include <qgroupbox.h> +#include <qlineedit.h> +#include <qcheckbox.h> +#include <qlayout.h> +#include <qpushbutton.h> +#include <qvalidator.h> + +#include <klocale.h> +#include <kcursor.h> +#include <kconfig.h> +#include <kstringhandler.h> + +class PortValidator : public QIntValidator +{ +public: + PortValidator(QWidget *parent, const char *name = 0); + virtual QValidator::State validate(QString&, int&) const; +}; + +PortValidator::PortValidator(QWidget *parent, const char *name) +: QIntValidator(1, 65535, parent, name) +{ +} + +QValidator::State PortValidator::validate(QString& txt, int&) const +{ + bool ok(false); + int p = txt.toInt(&ok); + if (txt.isEmpty()) + return QValidator::Intermediate; + else if (ok && p >= bottom() && p <= top()) + return QValidator::Acceptable; + return QValidator::Invalid; +} + +//****************************************************************************************** + +KMCupsConfigWidget::KMCupsConfigWidget(QWidget *parent, const char *name) +: QWidget(parent,name) +{ + // widget creation + QGroupBox *m_hostbox = new QGroupBox(0, Qt::Vertical, i18n("Server Information"), this); + QGroupBox *m_loginbox = new QGroupBox(0, Qt::Vertical, i18n("Account Information"), this); + QLabel *m_hostlabel = new QLabel(i18n("&Host:"), m_hostbox); + QLabel *m_portlabel = new QLabel(i18n("&Port:"), m_hostbox); + m_host = new QLineEdit(m_hostbox); + m_port = new QLineEdit(m_hostbox); + m_hostlabel->setBuddy(m_host); + m_portlabel->setBuddy(m_port); + m_port->setValidator(new PortValidator(m_port)); + m_login = new QLineEdit(m_loginbox); + QLabel *m_loginlabel = new QLabel(i18n("&User:"), m_loginbox); + QLabel *m_passwordlabel = new QLabel(i18n("Pass&word:"), m_loginbox); + m_password = new QLineEdit(m_loginbox); + m_password->setEchoMode(QLineEdit::Password); + m_savepwd = new QCheckBox( i18n( "&Store password in configuration file" ), m_loginbox ); + m_savepwd->setCursor( KCursor::handCursor() ); + m_anonymous = new QCheckBox(i18n("Use &anonymous access"), m_loginbox); + m_anonymous->setCursor(KCursor::handCursor()); + m_loginlabel->setBuddy(m_login); + m_passwordlabel->setBuddy(m_password); + + // layout creation + QVBoxLayout *lay0 = new QVBoxLayout(this, 0, 10); + lay0->addWidget(m_hostbox,1); + lay0->addWidget(m_loginbox,1); + QGridLayout *lay2 = new QGridLayout(m_hostbox->layout(), 2, 2, 10); + lay2->setColStretch(1,1); + lay2->addWidget(m_hostlabel,0,0); + lay2->addWidget(m_portlabel,1,0); + lay2->addWidget(m_host,0,1); + lay2->addWidget(m_port,1,1); + QGridLayout *lay3 = new QGridLayout(m_loginbox->layout(), 4, 2, 10); + lay3->setColStretch(1,1); + lay3->addWidget(m_loginlabel,0,0); + lay3->addWidget(m_passwordlabel,1,0); + lay3->addWidget(m_login,0,1); + lay3->addWidget(m_password,1,1); + lay3->addMultiCellWidget(m_savepwd,2,2,0,1); + lay3->addMultiCellWidget(m_anonymous,3,3,0,1); + + // connections + connect(m_anonymous,SIGNAL(toggled(bool)),m_login,SLOT(setDisabled(bool))); + connect(m_anonymous,SIGNAL(toggled(bool)),m_password,SLOT(setDisabled(bool))); + connect(m_anonymous,SIGNAL(toggled(bool)),m_savepwd,SLOT(setDisabled(bool))); +} + +void KMCupsConfigWidget::load() +{ + CupsInfos *inf = CupsInfos::self(); + m_host->setText(inf->host()); + m_port->setText(QString::number(inf->port())); + if (inf->login().isEmpty()) + m_anonymous->setChecked(true); + else + { + m_login->setText(inf->login()); + m_password->setText(inf->password()); + m_savepwd->setChecked( inf->savePassword() ); + } +} + +void KMCupsConfigWidget::save(bool sync) +{ + CupsInfos *inf = CupsInfos::self(); + inf->setHost(m_host->text()); + inf->setPort(m_port->text().toInt()); + if (m_anonymous->isChecked()) + { + inf->setLogin(QString::null); + inf->setPassword(QString::null); + inf->setSavePassword( false ); + } + else + { + inf->setLogin(m_login->text()); + inf->setPassword(m_password->text()); + inf->setSavePassword( m_savepwd->isChecked() ); + } + if (sync) inf->save(); +} + +void KMCupsConfigWidget::saveConfig(KConfig *conf) +{ + conf->setGroup("CUPS"); + conf->writeEntry("Host",m_host->text()); + conf->writeEntry("Port",m_port->text().toInt()); + conf->writeEntry("Login",(m_anonymous->isChecked() ? QString::null : m_login->text())); + conf->writeEntry( "SavePassword", ( m_anonymous->isChecked() ? false : m_savepwd->isChecked() ) ); + if ( m_savepwd->isChecked() && !m_anonymous->isChecked() ) + conf->writeEntry( "Password", ( m_anonymous->isChecked() ? QString::null : KStringHandler::obscure( m_password->text() ) ) ); + else + conf->deleteEntry( "Password" ); + // synchronize CupsInfos object + save(false); +} diff --git a/kdeprint/cups/kmcupsconfigwidget.h b/kdeprint/cups/kmcupsconfigwidget.h new file mode 100644 index 000000000..34c488290 --- /dev/null +++ b/kdeprint/cups/kmcupsconfigwidget.h @@ -0,0 +1,43 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KMCUPSCONFIGWIDGET_H +#define KMCUPSCONFIGWIDGET_H + +#include <qwidget.h> + +class QLineEdit; +class QCheckBox; +class KConfig; + +class KMCupsConfigWidget : public QWidget +{ +public: + KMCupsConfigWidget(QWidget *parent = 0, const char *name = 0); + + void load(); + void save(bool sync = true); + void saveConfig(KConfig*); + +protected: + QLineEdit *m_host, *m_port, *m_login, *m_password; + QCheckBox *m_anonymous, *m_savepwd; +}; + +#endif diff --git a/kdeprint/cups/kmcupsfactory.cpp b/kdeprint/cups/kmcupsfactory.cpp new file mode 100644 index 000000000..93e179f4c --- /dev/null +++ b/kdeprint/cups/kmcupsfactory.cpp @@ -0,0 +1,30 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kmcupsmanager.h" +#include "kmcupsjobmanager.h" +#include "kmcupsuimanager.h" +#include "kcupsprinterimpl.h" + +#include <kglobal.h> +#include <kgenericfactory.h> + +typedef K_TYPELIST_4( KMCupsManager, KMCupsJobManager, KMCupsUiManager, KCupsPrinterImpl ) Products; +K_EXPORT_COMPONENT_FACTORY( kdeprint_cups, KGenericFactory< Products >( "ppdtranslations" ) ) + diff --git a/kdeprint/cups/kmcupsjobmanager.cpp b/kdeprint/cups/kmcupsjobmanager.cpp new file mode 100644 index 000000000..73f6005d9 --- /dev/null +++ b/kdeprint/cups/kmcupsjobmanager.cpp @@ -0,0 +1,452 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kmcupsjobmanager.h" +#include "kmcupsmanager.h" +#include "kmjob.h" +#include "cupsinfos.h" +#include "ipprequest.h" +#include "pluginaction.h" +#include "kprinter.h" +#include "kprinterpropertydialog.h" +#include "kmuimanager.h" +#include "kmfactory.h" +#include "kpdriverpage.h" +#include "kpschedulepage.h" +#include "kpcopiespage.h" +#include "kptagspage.h" + +#include <klocale.h> +#include <kdebug.h> +#include <kurl.h> + +KMCupsJobManager::KMCupsJobManager(QObject *parent, const char *name, const QStringList & /*args*/) +: KMJobManager(parent,name) +{ +} + +KMCupsJobManager::~KMCupsJobManager() +{ +} + +int KMCupsJobManager::actions() +{ + return KMJob::All; +} + +bool KMCupsJobManager::sendCommandSystemJob(const QPtrList<KMJob>& jobs, int action, const QString& argstr) +{ + IppRequest req; + QString uri; + bool value(true); + + QPtrListIterator<KMJob> it(jobs); + for (;it.current() && value;++it) + { + // hypothesis: job operation are always done on local jobs. The only operation + // allowed on remote jobs is listing (done elsewhere). + + req.addURI(IPP_TAG_OPERATION,"job-uri",it.current()->uri()); + req.addName(IPP_TAG_OPERATION,"requesting-user-name",CupsInfos::self()->login()); + /* + QString jobHost; + if (!it.current()->uri().isEmpty()) + { + KURL url(it.current()->uri()); + req.setHost(url.host()); + req.setPort(url.port()); + jobHost = url.host(); + } + */ + + switch (action) + { + case KMJob::Remove: + req.setOperation(IPP_CANCEL_JOB); + break; + case KMJob::Hold: + req.setOperation(IPP_HOLD_JOB); + break; + case KMJob::Resume: + req.setOperation(IPP_RELEASE_JOB); + break; + case KMJob::Restart: + req.setOperation(IPP_RESTART_JOB); + break; + case KMJob::Move: + if (argstr.isEmpty()) return false; + req.setOperation(CUPS_MOVE_JOB); + uri = + QString::fromLatin1("ipp://%1/printers/%2").arg(CupsInfos::self()->hostaddr(), + argstr); + req.addURI(IPP_TAG_OPERATION, "job-printer-uri", uri); + break; + default: + return false; + } + + if (!(value = req.doRequest("/jobs/"))) + KMManager::self()->setErrorMsg(req.statusMessage()); + } + + return value; +} + +bool KMCupsJobManager::listJobs(const QString& prname, KMJobManager::JobType type, int limit) +{ + IppRequest req; + QStringList keys; + CupsInfos *infos = CupsInfos::self(); + + // wanted attributes + keys.append("job-id"); + keys.append("job-uri"); + keys.append("job-name"); + keys.append("job-state"); + keys.append("job-printer-uri"); + keys.append("job-k-octets"); + keys.append("job-originating-user-name"); + keys.append("job-k-octets-completed"); + keys.append("job-media-sheets"); + keys.append("job-media-sheets-completed"); + keys.append("job-priority"); + keys.append("job-billing"); + + req.setOperation(IPP_GET_JOBS); + + // add printer-uri + KMPrinter *mp = KMManager::self()->findPrinter(prname); + if (!mp) + return false; + + if (!mp->uri().isEmpty()) + { + req.addURI(IPP_TAG_OPERATION, "printer-uri", mp->uri().prettyURL()); + /* + req.setHost(mp->uri().host()); + req.setPort(mp->uri().port()); + */ + } + else + req.addURI(IPP_TAG_OPERATION, "printer-uri", QString("ipp://%1/%2/%3").arg(infos->hostaddr(), + (mp&&mp->isClass())?"classes":"printers", prname)); + + // other attributes + req.addKeyword(IPP_TAG_OPERATION, "requested-attributes", keys); + if (type == KMJobManager::CompletedJobs) + req.addKeyword(IPP_TAG_OPERATION,"which-jobs",QString::fromLatin1("completed")); + if (limit > 0) + req.addInteger(IPP_TAG_OPERATION,"limit",limit); + + // send request + if (req.doRequest("/")) + parseListAnswer(req, mp); + else + return false; + + return true; +} + +void KMCupsJobManager::parseListAnswer(IppRequest& req, KMPrinter *pr) +{ + ipp_attribute_t *attr = req.first(); + KMJob *job = new KMJob(); + QString uri; + while (attr) + { + QString name(attr->name); + if (name == "job-id") job->setId(attr->values[0].integer); + else if (name == "job-uri") job->setUri(QString::fromLocal8Bit(attr->values[0].string.text)); + else if (name == "job-name") job->setName(QString::fromLocal8Bit(attr->values[0].string.text)); + else if (name == "job-state") + { + switch (attr->values[0].integer) + { + case IPP_JOB_PENDING: + job->setState(KMJob::Queued); + break; + case IPP_JOB_HELD: + job->setState(KMJob::Held); + break; + case IPP_JOB_PROCESSING: + job->setState(KMJob::Printing); + break; + case IPP_JOB_STOPPED: + job->setState(KMJob::Error); + break; + case IPP_JOB_CANCELLED: + job->setState(KMJob::Cancelled); + break; + case IPP_JOB_ABORTED: + job->setState(KMJob::Aborted); + break; + case IPP_JOB_COMPLETED: + job->setState(KMJob::Completed); + break; + default: + job->setState(KMJob::Unknown); + break; + } + } + else if (name == "job-k-octets") job->setSize(attr->values[0].integer); + else if (name == "job-originating-user-name") job->setOwner(QString::fromLocal8Bit(attr->values[0].string.text)); + else if (name == "job-k-octets-completed") job->setProcessedSize(attr->values[0].integer); + else if (name == "job-media-sheets") job->setPages(attr->values[0].integer); + else if (name == "job-media-sheets-completed") job->setProcessedPages(attr->values[0].integer); + else if (name == "job-printer-uri" && !pr->isRemote()) + { + QString str(attr->values[0].string.text); + int p = str.findRev('/'); + if (p != -1) + job->setPrinter(str.mid(p+1)); + } + else if (name == "job-priority") + { + job->setAttribute(0, QString::fromLatin1("%1").arg(attr->values[0].integer, 3)); + } + else if (name == "job-billing") + { + job->setAttributeCount(2); + job->setAttribute(1, QString::fromLocal8Bit(attr->values[0].string.text)); + } + + if (name.isEmpty() || attr == req.last()) + { + if (job->printer().isEmpty()) + job->setPrinter(pr->printerName()); + job->setRemote(pr->isRemote()); + addJob(job); // don't use job after this call !!! + job = new KMJob(); + } + + attr = attr->next; + } + delete job; +} + +bool KMCupsJobManager::doPluginAction(int ID, const QPtrList<KMJob>& jobs) +{ + switch (ID) + { + case 0: + if (jobs.count() == 1) + return jobIppReport(jobs.getFirst()); + break; + case 1: + return changePriority(jobs, true); + case 2: + return changePriority(jobs, false); + case 3: + return editJobAttributes(jobs.getFirst()); + } + return false; +} + +bool KMCupsJobManager::jobIppReport(KMJob *j) +{ + IppRequest req; + + req.setOperation(IPP_GET_JOB_ATTRIBUTES); + req.addURI(IPP_TAG_OPERATION, "job-uri", j->uri()); + bool result(true); + /* + if (!j->uri().isEmpty()) + { + KURL url(j->uri()); + req.setHost(url.host()); + req.setPort(url.port()); + } + */ + if ((result=req.doRequest("/"))) + static_cast<KMCupsManager*>(KMManager::self())->ippReport(req, IPP_TAG_JOB, i18n("Job Report")); + else + KMManager::self()->setErrorMsg(i18n("Unable to retrieve job information: ")+req.statusMessage()); + return result; +} + +QValueList<KAction*> KMCupsJobManager::createPluginActions(KActionCollection *coll) +{ + QValueList<KAction*> list; + KAction *act(0); + + list << (act = new PluginAction(0, i18n("&Job IPP Report"), "kdeprint_report", 0, coll, "plugin_ipp")); + act->setGroup("plugin"); + list << (act = new PluginAction(1, i18n("&Increase Priority"), "up", 0, coll, "plugin_prioup")); + act->setGroup("plugin"); + list << (act = new PluginAction(2, i18n("&Decrease Priority"), "down", 0, coll, "plugin_priodown")); + act->setGroup("plugin"); + list << (act = new PluginAction(3, i18n("&Edit Attributes..."), "edit", 0, coll, "plugin_editjob")); + act->setGroup("plugin"); + + return list; +} + +void KMCupsJobManager::validatePluginActions(KActionCollection *coll, const QPtrList<KMJob>& joblist) +{ + QPtrListIterator<KMJob> it(joblist); + bool flag(true); + for (; it.current(); ++it) + { + flag = (flag && it.current()->type() == KMJob::System + && (it.current()->state() == KMJob::Queued || it.current()->state() == KMJob::Held) + /*&& !it.current()->isRemote()*/); + } + flag = (flag && joblist.count() > 0); + KAction *a; + if ( ( a = coll->action( "plugin_ipp" ) ) ) + a->setEnabled( joblist.count() == 1 ); + if ( ( a = coll->action( "plugin_prioup" ) ) ) + a->setEnabled( flag ); + if ( ( a = coll->action( "plugin_priodown" ) ) ) + a->setEnabled( flag ); + if ( ( a = coll->action( "plugin_editjob" ) ) ) + a->setEnabled( flag && ( joblist.count() == 1 ) ); +} + +bool KMCupsJobManager::changePriority(const QPtrList<KMJob>& jobs, bool up) +{ + QPtrListIterator<KMJob> it(jobs); + bool result(true); + for (; it.current() && result; ++it) + { + int value = it.current()->attribute(0).toInt(); + if (up) value = QMIN(value+10, 100); + else value = QMAX(value-10, 1); + + IppRequest req; + /* + if (!it.current()->uri().isEmpty()) + { + KURL url(it.current()->uri()); + req.setHost(url.host()); + req.setPort(url.port()); + } + */ + req.setOperation(IPP_SET_JOB_ATTRIBUTES); + req.addURI(IPP_TAG_OPERATION, "job-uri", it.current()->uri()); + req.addName(IPP_TAG_OPERATION, "requesting-user-name", CupsInfos::self()->login()); + req.addInteger(IPP_TAG_JOB, "job-priority", value); + + if (!(result = req.doRequest("/jobs/"))) + KMManager::self()->setErrorMsg(i18n("Unable to change job priority: ")+req.statusMessage()); + } + return result; +} + +static QString processRange(const QString& range) +{ + QStringList l = QStringList::split(',', range, false); + QString s; + for (QStringList::ConstIterator it=l.begin(); it!=l.end(); ++it) + { + s.append(*it); + if ((*it).find('-') == -1) + s.append("-").append(*it); + s.append(","); + } + if (!s.isEmpty()) + s.truncate(s.length()-1); + return s; +} + +bool KMCupsJobManager::editJobAttributes(KMJob *j) +{ + IppRequest req; + + req.setOperation(IPP_GET_JOB_ATTRIBUTES); + req.addURI(IPP_TAG_OPERATION, "job-uri", j->uri()); + /* + if (!j->uri().isEmpty()) + { + KURL url(j->uri()); + req.setHost(url.host()); + req.setPort(url.port()); + } + */ + if (!req.doRequest("/")) + { + KMManager::self()->setErrorMsg(i18n("Unable to retrieve job information: ")+req.statusMessage()); + return false; + } + + QMap<QString,QString> opts = req.toMap(IPP_TAG_JOB); + // translate the "Copies" option to non-CUPS syntax + if (opts.contains("copies")) + opts["kde-copies"] = opts["copies"]; + if (opts.contains("page-set")) + opts["kde-pageset"] = (opts["page-set"] == "even" ? "2" : (opts["page-set"] == "odd" ? "1" : "0")); + if (opts.contains("OutputOrder")) + opts["kde-pageorder"] = opts["OutputOrder"]; + if (opts.contains("multiple-document-handling")) + opts["kde-collate"] = (opts["multiple-document-handling"] == "separate-documents-collated-copies" ? "Collate" : "Uncollate"); + if (opts.contains("page-ranges")) + opts["kde-range"] = opts["page-ranges"]; + + // find printer and construct dialog + KMPrinter *prt = KMManager::self()->findPrinter(j->printer()); + if (!prt) + { + KMManager::self()->setErrorMsg(i18n("Unable to find printer %1.").arg(j->printer())); + return false; + } + KMManager::self()->completePrinterShort(prt); + KPrinter::ApplicationType oldAppType = KPrinter::applicationType(); + KPrinter::setApplicationType(KPrinter::StandAlone); + KPrinterPropertyDialog dlg(prt); + dlg.setDriver(KMManager::self()->loadPrinterDriver(prt)); + KMFactory::self()->uiManager()->setupPrinterPropertyDialog(&dlg); + KPrinter::setApplicationType( oldAppType ); + if (dlg.driver()) + dlg.addPage(new KPDriverPage(prt, dlg.driver(), &dlg)); + dlg.addPage(new KPCopiesPage(0, &dlg)); + dlg.addPage(new KPSchedulePage(&dlg)); + dlg.addPage(new KPTagsPage(true, &dlg)); + dlg.setOptions(opts); + dlg.enableSaveButton(false); + dlg.setCaption(i18n("Attributes of Job %1@%2 (%3)").arg(j->id()).arg(j->printer()).arg(j->name())); + if (dlg.exec()) + { + opts.clear(); + // include default values to override non-default values + dlg.getOptions(opts, true); + // translate the "Copies" options from non-CUPS syntax + opts["copies"] = opts["kde-copies"]; + opts["OutputOrder"] = opts["kde-pageorder"]; + opts["multiple-document-handling"] = (opts["kde-collate"] == "Collate" ? "separate-documents-collated-copies" : "separate-documents-uncollated-copies"); + opts["page-set"] = (opts["kde-pageset"] == "1" ? "odd" : (opts["kde-pageset"] == "2" ? "even" : "all")); + // it seems CUPS is buggy. Disable page-ranges modification, otherwise nothing gets printed + opts["page-ranges"] = processRange(opts["kde-range"]); + + req.init(); + req.setOperation(IPP_SET_JOB_ATTRIBUTES); + req.addURI(IPP_TAG_OPERATION, "job-uri", j->uri()); + req.addName(IPP_TAG_OPERATION, "requesting-user-name", CupsInfos::self()->login()); + req.setMap(opts); + //req.dump(1); + if (!req.doRequest("/jobs/")) + { + KMManager::self()->setErrorMsg(i18n("Unable to set job attributes: ")+req.statusMessage()); + return false; + } + } + + return true; +} + +#include "kmcupsjobmanager.moc" diff --git a/kdeprint/cups/kmcupsjobmanager.h b/kdeprint/cups/kmcupsjobmanager.h new file mode 100644 index 000000000..27f3073aa --- /dev/null +++ b/kdeprint/cups/kmcupsjobmanager.h @@ -0,0 +1,53 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KMCUPSJOBMANAGER_H +#define KMCUPSJOBMANAGER_H + +#include "kmjobmanager.h" +#include "ipprequest.h" +#include <qstringlist.h> + +class KMPrinter; + +class KMCupsJobManager : public KMJobManager +{ + Q_OBJECT + +public: + KMCupsJobManager(QObject *parent, const char *name, const QStringList &/*args*/); + virtual ~KMCupsJobManager(); + + int actions(); + QValueList<KAction*> createPluginActions(KActionCollection*); + void validatePluginActions(KActionCollection*, const QPtrList<KMJob>&); + bool doPluginAction(int, const QPtrList<KMJob>&); + +protected: + bool jobIppReport(KMJob*); + bool changePriority(const QPtrList<KMJob>&, bool); + bool editJobAttributes(KMJob*); + +protected: + bool listJobs(const QString&, JobType, int = 0); + bool sendCommandSystemJob(const QPtrList<KMJob>& jobs, int action, const QString& arg = QString::null); + void parseListAnswer(IppRequest& req, KMPrinter *pr); +}; + +#endif diff --git a/kdeprint/cups/kmcupsmanager.cpp b/kdeprint/cups/kmcupsmanager.cpp new file mode 100644 index 000000000..bc17bb93d --- /dev/null +++ b/kdeprint/cups/kmcupsmanager.cpp @@ -0,0 +1,1077 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include <config.h> + +#include "kmcupsmanager.h" +#include "kmprinter.h" +#include "ipprequest.h" +#include "cupsinfos.h" +#include "driver.h" +#include "kmfactory.h" +#include "kmdbentry.h" +#include "cupsaddsmb2.h" +#include "ippreportdlg.h" +#include "kpipeprocess.h" +#include "util.h" +#include "foomatic2loader.h" +#include "ppdloader.h" + +#include <qfile.h> +#include <qtextstream.h> +#include <qregexp.h> +#include <qtimer.h> +#include <qsocket.h> +#include <qdatetime.h> + +#include <kdebug.h> +#include <kapplication.h> +#include <klocale.h> +#include <kconfig.h> +#include <kstandarddirs.h> +#include <ksocketbase.h> +#include <klibloader.h> +#include <kmessagebox.h> +#include <kaction.h> +#include <kdialogbase.h> +#include <kextendedsocket.h> +#include <kprocess.h> +#include <kbufferedsocket.h> +#include <kfilterdev.h> +#include <cups/cups.h> +#include <cups/ppd.h> +#include <math.h> + +#define ppdi18n(s) i18n(QString::fromLocal8Bit(s).utf8()) + +static void extractMaticData(QString& buf, const QString& filename); +static QString printerURI(KMPrinter *p, bool useExistingURI); +static QString downloadDriver(KMPrinter *p); + +static int trials = 5; + +//***************************************************************************************************** + + KMCupsManager::KMCupsManager(QObject *parent, const char *name, const QStringList & /*args*/) +: KMManager(parent,name) +{ + // be sure to create the CupsInfos object -> password + // management is handled correctly. + CupsInfos::self(); + m_cupsdconf = 0; + m_currentprinter = 0; + m_socket = 0; + + setHasManagement(true); + setPrinterOperationMask(KMManager::PrinterAll); + setServerOperationMask(KMManager::ServerAll); + + // change LANG variable so that CUPS is always using + // english language: translation may only come from the PPD + // itself, or from KDE. + setenv("LANG", "en", 1); +} + +KMCupsManager::~KMCupsManager() +{ + delete m_socket; +} + +QString KMCupsManager::driverDbCreationProgram() +{ + return QString::fromLatin1("make_driver_db_cups"); +} + +QString KMCupsManager::driverDirectory() +{ + QString d = cupsInstallDir(); + if (d.isEmpty()) + d = "/usr"; + d.append("/share/cups/model"); + // raw foomatic support + d.append(":/usr/share/foomatic/db/source"); + return d; +} + +QString KMCupsManager::cupsInstallDir() +{ + KConfig *conf= KMFactory::self()->printConfig(); + conf->setGroup("CUPS"); + QString dir = conf->readPathEntry("InstallDir"); + return dir; +} + +void KMCupsManager::reportIppError(IppRequest *req) +{ + setErrorMsg(req->statusMessage()); +} + +bool KMCupsManager::createPrinter(KMPrinter *p) +{ + bool isclass = p->isClass(false), result(false); + IppRequest req; + QString uri; + + uri = printerURI(p,false); + req.addURI(IPP_TAG_OPERATION,"printer-uri",uri); + // needed to avoid problems when changing printer name + p->setUri(KURL(uri)); + + if (isclass) + { + req.setOperation(CUPS_ADD_CLASS); + QStringList members = p->members(), uris; + QString s; + s = QString::fromLocal8Bit("ipp://%1/printers/").arg(CupsInfos::self()->hostaddr()); + for (QStringList::ConstIterator it=members.begin(); it!=members.end(); ++it) + uris.append(s+(*it)); + req.addURI(IPP_TAG_PRINTER,"member-uris",uris); + } + else + { + req.setOperation(CUPS_ADD_PRINTER); + // only set the device-uri if needed, otherwise you may loose authentification + // data (login/password in URI's like smb or ipp). + KMPrinter *otherP = findPrinter(p->printerName()); + if (!otherP || otherP->device() != p->device()) + { + /** + * As now the device is a QString instead of KURL, special encoding + * required for SMB is not needed anymore. Use a unique mechanism + * for all backends. + */ + req.addURI(IPP_TAG_PRINTER,"device-uri",p->device()); + } + if (!p->option("kde-banners").isEmpty()) + { + QStringList bans = QStringList::split(',',p->option("kde-banners"),false); + while (bans.count() < 2) + bans.append("none"); + req.addName(IPP_TAG_PRINTER,"job-sheets-default",bans); + } + req.addInteger(IPP_TAG_PRINTER,"job-quota-period",p->option("job-quota-period").toInt()); + req.addInteger(IPP_TAG_PRINTER,"job-k-limit",p->option("job-k-limit").toInt()); + req.addInteger(IPP_TAG_PRINTER,"job-page-limit",p->option("job-page-limit").toInt()); + if (!p->option("requesting-user-name-denied").isEmpty()) + req.addName(IPP_TAG_PRINTER,"requesting-user-name-denied",QStringList::split(",",p->option("requesting-user-name-denied"),false)); + else if (!p->option("requesting-user-name-allowed").isEmpty()) + req.addName(IPP_TAG_PRINTER,"requesting-user-name-allowed",QStringList::split(",",p->option("requesting-user-name-allowed"),false)); + else + req.addName(IPP_TAG_PRINTER,"requesting-user-name-allowed",QString::fromLatin1("all")); + } + req.addText(IPP_TAG_PRINTER,"printer-info",p->description()); + req.addText(IPP_TAG_PRINTER,"printer-location",p->location()); + + if (req.doRequest("/admin/")) + { + result = true; + if (p->driver()) + result = savePrinterDriver(p,p->driver()); + if (result) + upPrinter(p, true); + } + else reportIppError(&req); + + return result; +} + +bool KMCupsManager::removePrinter(KMPrinter *p) +{ + bool result = setPrinterState(p,CUPS_DELETE_PRINTER); + return result; +} + +bool KMCupsManager::enablePrinter(KMPrinter *p, bool state) +{ + return setPrinterState(p, (state ? CUPS_ACCEPT_JOBS : CUPS_REJECT_JOBS)); +} + +bool KMCupsManager::startPrinter(KMPrinter *p, bool state) +{ + return setPrinterState(p, (state ? IPP_RESUME_PRINTER : IPP_PAUSE_PRINTER)); +} + +bool KMCupsManager::setDefaultPrinter(KMPrinter *p) +{ + return setPrinterState(p,CUPS_SET_DEFAULT); +} + +bool KMCupsManager::setPrinterState(KMPrinter *p, int state) +{ + IppRequest req; + QString uri; + + req.setOperation(state); + uri = printerURI(p, true); + req.addURI(IPP_TAG_OPERATION,"printer-uri",uri); + if (req.doRequest("/admin/")) + return true; + reportIppError(&req); + return false; +} + +bool KMCupsManager::completePrinter(KMPrinter *p) +{ + if (completePrinterShort(p)) + { + // driver informations + QString ppdname = downloadDriver(p); + ppd_file_t *ppd = (ppdname.isEmpty() ? NULL : ppdOpenFile(ppdname.local8Bit())); + if (ppd) + { + KMDBEntry entry; + // use the validation mechanism of KMDBEntry to + // fill possible missing entries like manufacturer + // or model. + entry.manufacturer = ppd->manufacturer; + entry.model = ppd->shortnickname; + entry.modelname = ppd->modelname; + // do not check the driver regarding the manager + entry.validate(false); + // update the KMPrinter object + p->setManufacturer(entry.manufacturer); + p->setModel(entry.model); + p->setDriverInfo(QString::fromLocal8Bit(ppd->nickname)); + ppdClose(ppd); + } + if (!ppdname.isEmpty()) + QFile::remove(ppdname); + + return true; + } + return false; +} + +bool KMCupsManager::completePrinterShort(KMPrinter *p) +{ + IppRequest req; + QStringList keys; + QString uri; + + req.setOperation(IPP_GET_PRINTER_ATTRIBUTES); + uri = printerURI(p, true); + req.addURI(IPP_TAG_OPERATION,"printer-uri",uri); + + /* + // change host and port for remote stuffs + if (!p->uri().isEmpty()) + { + // THIS IS AN UGLY HACK!! FIXME + // This attempts a "pre-connection" to see if the host is + // actually reachable. It times out after 2 seconds at most, + // preventing application freezes. + m_hostSuccess = false; + m_lookupDone = false; + // Give 2 seconds to connect to the printer, or abort + KExtendedSocket *kes = new KExtendedSocket(p->uri().host(), + p->uri().port()); + connect(kes, SIGNAL(connectionSuccess()), this, SLOT(hostPingSlot())); + connect(kes, SIGNAL(connectionFailed(int)), this, SLOT(hostPingFailedSlot())); + if (kes->startAsyncConnect() != 0) { + delete kes; + m_hostSuccess = false; + } else { + QDateTime tm = QDateTime::currentDateTime().addSecs(2); + while (!m_lookupDone && (QDateTime::currentDateTime() < tm)) + qApp->processEvents(); + + kes->cancelAsyncConnect(); + + delete kes; + + if (!m_lookupDone) + m_hostSuccess = false; + } + + if (m_hostSuccess == true) { + req.setHost(p->uri().host()); + req.setPort(p->uri().port()); + } + } + */ + + // disable location as it has been transferred to listing (for filtering) + //keys.append("printer-location"); + keys.append("printer-info"); + keys.append("printer-make-and-model"); + keys.append("job-sheets-default"); + keys.append("job-sheets-supported"); + keys.append("job-quota-period"); + keys.append("job-k-limit"); + keys.append("job-page-limit"); + keys.append("requesting-user-name-allowed"); + keys.append("requesting-user-name-denied"); + if (p->isClass(true)) + { + keys.append("member-uris"); + keys.append("member-names"); + } + else + keys.append("device-uri"); + req.addKeyword(IPP_TAG_OPERATION,"requested-attributes",keys); + + if (req.doRequest("/printers/")) + { + QString value; + if (req.text("printer-info",value)) p->setDescription(value); + // disabled location + //if (req.text("printer-location",value)) p->setLocation(value); + if (req.text("printer-make-and-model",value)) p->setDriverInfo(value); + if (req.uri("device-uri",value)) + { + /** + * No specific treatment required as the device is + * a normal QString instead of a KURL + */ + p->setDevice( value ); + } + QStringList values; + /* if (req.uri("member-uris",values)) + { + QStringList members; + for (QStringList::ConstIterator it=values.begin(); it!=values.end(); ++it) + { + int p = (*it).findRev('/'); + if (p != -1) + members.append((*it).right((*it).length()-p-1)); + } + p->setMembers(members); + }*/ + if (req.name("member-names",values)) + p->setMembers(values); + // banners + req.name("job-sheets-default",values); + while (values.count() < 2) values.append("none"); + p->setOption("kde-banners",values.join(QString::fromLatin1(","))); + if (req.name("job-sheets-supported",values)) p->setOption("kde-banners-supported",values.join(QString::fromLatin1(","))); + + // quotas + int ival; + if (req.integer("job-quota-period",ival)) p->setOption("job-quota-period",QString::number(ival)); + if (req.integer("job-k-limit",ival)) p->setOption("job-k-limit",QString::number(ival)); + if (req.integer("job-page-limit",ival)) p->setOption("job-page-limit",QString::number(ival)); + + // access permissions (allow and deny are mutually exclusives) + if (req.name("requesting-user-name-allowed",values) && values.count() > 0) + { + p->removeOption("requesting-user-name-denied"); + p->setOption("requesting-user-name-allowed",values.join(",")); + } + if (req.name("requesting-user-name-denied",values) && values.count() > 0) + { + p->removeOption("requesting-user-name-allowed"); + p->setOption("requesting-user-name-denied",values.join(",")); + } + + return true; + } + + reportIppError(&req); + return false; +} + +bool KMCupsManager::testPrinter(KMPrinter *p) +{ + return KMManager::testPrinter(p); + /* + QString testpage = testPage(); + if (testpage.isEmpty()) + { + setErrorMsg(i18n("Unable to locate test page.")); + return false; + } + + IppRequest req; + QString uri; + + req.setOperation(IPP_PRINT_JOB); + uri = printerURI(p); + req.addURI(IPP_TAG_OPERATION,"printer-uri",uri); + req.addMime(IPP_TAG_OPERATION,"document-format","application/postscript"); + if (!CupsInfos::self()->login().isEmpty()) req.addName(IPP_TAG_OPERATION,"requesting-user-name",CupsInfos::self()->login()); + req.addName(IPP_TAG_OPERATION,"job-name",QString::fromLatin1("KDE Print Test")); + if (req.doFileRequest("/printers/",testpage)) + return true; + reportIppError(&req); + return false; + */ +} + +void KMCupsManager::listPrinters() +{ + loadServerPrinters(); +} + +void KMCupsManager::loadServerPrinters() +{ + IppRequest req; + QStringList keys; + + // get printers + req.setOperation(CUPS_GET_PRINTERS); + keys.append("printer-name"); + keys.append("printer-type"); + keys.append("printer-state"); + // location needed for filtering + keys.append("printer-location"); + keys.append("printer-uri-supported"); + keys.append("printer-is-accepting-jobs"); + req.addKeyword(IPP_TAG_OPERATION,"requested-attributes",keys); + + // filtering by username (hides printers user doesn't have allowance to use) + req.addName(IPP_TAG_OPERATION, "requesting-user-name", QString(cupsUser())); + + if (req.doRequest("/printers/")) + { + processRequest(&req); + + // get classes + req.init(); + req.setOperation(CUPS_GET_CLASSES); + req.addKeyword(IPP_TAG_OPERATION,"requested-attributes",keys); + + if (req.doRequest("/classes/")) + { + processRequest(&req); + + // load default + req.init(); + req.setOperation(CUPS_GET_DEFAULT); + req.addKeyword(IPP_TAG_OPERATION,"requested-attributes",QString::fromLatin1("printer-name")); + if (req.doRequest("/printers/")) + { + QString s = QString::null; + req.name("printer-name",s); + setHardDefault(findPrinter(s)); + } + // This request may fails for example if no printer is defined. Just + // discard the error message. Indeed as we successfully got printers + // and classes, the most probable reason why this request may fail is + // because of no printer defined. The best would be to actually check + // there's no printer (TODO). + return; + } + } + + // something went wrong if we get there, report the error + reportIppError(&req); +} + +void KMCupsManager::processRequest(IppRequest* req) +{ + ipp_attribute_t *attr = req->first(); + KMPrinter *printer = new KMPrinter(); + while (attr) + { + QString attrname(attr->name); + if (attrname == "printer-name") + { + QString value = QString::fromLocal8Bit(attr->values[0].string.text); + printer->setName(value); + printer->setPrinterName(value); + } + else if (attrname == "printer-type") + { + int value = attr->values[0].integer; + printer->setType(0); + printer->addType(((value & CUPS_PRINTER_CLASS) || (value & CUPS_PRINTER_IMPLICIT) ? KMPrinter::Class : KMPrinter::Printer)); + if ((value & CUPS_PRINTER_REMOTE)) printer->addType(KMPrinter::Remote); + if ((value & CUPS_PRINTER_IMPLICIT)) printer->addType(KMPrinter::Implicit); + + // convert printer-type attribute + printer->setPrinterCap( ( value & CUPS_PRINTER_OPTIONS ) >> 2 ); + } + else if (attrname == "printer-state") + { + switch (attr->values[0].integer) + { + case IPP_PRINTER_IDLE: printer->setState(KMPrinter::Idle); break; + case IPP_PRINTER_PROCESSING: printer->setState(KMPrinter::Processing); break; + case IPP_PRINTER_STOPPED: printer->setState(KMPrinter::Stopped); break; + } + } + else if (attrname == "printer-uri-supported") + { + printer->setUri(KURL(attr->values[0].string.text)); + } + else if (attrname == "printer-location") + { + printer->setLocation(QString::fromLocal8Bit(attr->values[0].string.text)); + } + else if (attrname == "printer-is-accepting-jobs") + { + printer->setAcceptJobs(attr->values[0].boolean); + } + if (attrname.isEmpty() || attr == req->last()) + { + addPrinter(printer); + printer = new KMPrinter(); + } + attr = attr->next; + } + delete printer; +} + +DrMain* KMCupsManager::loadPrinterDriver(KMPrinter *p, bool) +{ + if (!p) + return NULL; + + if (p->isClass(true)) + { + KMPrinter *first_class_member = NULL; + /* find the first printer in the class */ + first_class_member = findPrinter(p->members().first()); + + if (first_class_member == NULL) + { + /* we didn't find a printer in the class */ + return NULL; + } + else + { + p = first_class_member; + } + } + + QString fname = downloadDriver(p); + DrMain *driver(0); + if (!fname.isEmpty()) + { + driver = loadDriverFile(fname); + if (driver) + driver->set("temporary",fname); + } + + return driver; +} + +DrMain* KMCupsManager::loadFileDriver(const QString& filename) +{ + if (filename.startsWith("ppd:")) + return loadDriverFile(filename.mid(4)); + else if (filename.startsWith("foomatic/")) + return loadMaticDriver(filename); + else + return loadDriverFile(filename); +} + +DrMain* KMCupsManager::loadMaticDriver(const QString& drname) +{ + QStringList comps = QStringList::split('/', drname, false); + QString tmpFile = locateLocal("tmp", "foomatic_" + kapp->randomString(8)); + QString PATH = getenv("PATH") + QString::fromLatin1(":/usr/sbin:/usr/local/sbin:/opt/sbin:/opt/local/sbin"); + QString exe = KStandardDirs::findExe("foomatic-datafile", PATH); + if (exe.isEmpty()) + { + setErrorMsg(i18n("Unable to find the executable foomatic-datafile " + "in your PATH. Check that Foomatic is correctly installed.")); + return NULL; + } + + KPipeProcess in; + QFile out(tmpFile); + QString cmd = KProcess::quote(exe); + cmd += " -t cups -d "; + cmd += KProcess::quote(comps[2]); + cmd += " -p "; + cmd += KProcess::quote(comps[1]); + if (in.open(cmd) && out.open(IO_WriteOnly)) + { + QTextStream tin(&in), tout(&out); + QString line; + while (!tin.atEnd()) + { + line = tin.readLine(); + tout << line << endl; + } + in.close(); + out.close(); + + DrMain *driver = loadDriverFile(tmpFile); + if (driver) + { + driver->set("template", tmpFile); + driver->set("temporary", tmpFile); + return driver; + } + } + setErrorMsg(i18n("Unable to create the Foomatic driver [%1,%2]. " + "Either that driver does not exist, or you don't have " + "the required permissions to perform that operation.").arg(comps[1]).arg(comps[2])); + QFile::remove(tmpFile); + return NULL; +} + +DrMain* KMCupsManager::loadDriverFile(const QString& fname) +{ + if (QFile::exists(fname)) + { + QString msg; /* possible error message */ + DrMain *driver = PPDLoader::loadDriver( fname, &msg ); + if ( driver ) + { + driver->set( "template", fname ); + // FIXME: should fix option in group "install" + } + else + setErrorMsg( msg ); + return driver; + } + return NULL; +} + +void KMCupsManager::saveDriverFile(DrMain *driver, const QString& filename) +{ + kdDebug( 500 ) << "Saving PPD file with template=" << driver->get( "template" ) << endl; + QIODevice *in = KFilterDev::deviceForFile( driver->get( "template" ) ); + QFile out(filename); + if (in && in->open(IO_ReadOnly) && out.open(IO_WriteOnly)) + { + QTextStream tin(in), tout(&out); + QString line, keyword; + bool isnumeric(false); + DrBase *opt(0); + + while (!tin.eof()) + { + line = tin.readLine(); + if (line.startsWith("*% COMDATA #")) + { + int p(-1), q(-1); + if ((p=line.find("'name'")) != -1) + { + p = line.find('\'',p+6)+1; + q = line.find('\'',p); + keyword = line.mid(p,q-p); + opt = driver->findOption(keyword); + if (opt && (opt->type() == DrBase::Integer || opt->type() == DrBase::Float)) + isnumeric = true; + else + isnumeric = false; + } + /*else if ((p=line.find("'type'")) != -1) + { + p = line.find('\'',p+6)+1; + if (line.find("float",p) != -1 || line.find("int",p) != -1) + isnumeric = true; + else + isnumeric = false; + }*/ + else if ((p=line.find("'default'")) != -1 && !keyword.isEmpty() && opt && isnumeric) + { + QString prefix = line.left(p+9); + tout << prefix << " => '" << opt->valueText() << '\''; + if (line.find(',',p) != -1) + tout << ','; + tout << endl; + continue; + } + tout << line << endl; + } + else if (line.startsWith("*Default")) + { + int p = line.find(':',8); + keyword = line.mid(8,p-8); + DrBase *bopt = 0; + if ( keyword == "PageRegion" || keyword == "ImageableArea" || keyword == "PaperDimension" ) + bopt = driver->findOption( QString::fromLatin1( "PageSize" ) ); + else + bopt = driver->findOption( keyword ); + if (bopt) + switch (bopt->type()) + { + case DrBase::List: + case DrBase::Boolean: + { + DrListOption *opt = static_cast<DrListOption*>(bopt); + if (opt && opt->currentChoice()) + tout << "*Default" << keyword << ": " << opt->currentChoice()->name() << endl; + else + tout << line << endl; + } + break; + case DrBase::Integer: + { + DrIntegerOption *opt = static_cast<DrIntegerOption*>(bopt); + tout << "*Default" << keyword << ": " << opt->fixedVal() << endl; + } + break; + case DrBase::Float: + { + DrFloatOption *opt = static_cast<DrFloatOption*>(bopt); + tout << "*Default" << keyword << ": " << opt->fixedVal() << endl; + } + break; + default: + tout << line << endl; + break; + } + else + tout << line << endl; + } + else + tout << line << endl; + } + } + delete in; +} + +bool KMCupsManager::savePrinterDriver(KMPrinter *p, DrMain *d) +{ + QString tmpfilename = locateLocal("tmp","print_") + kapp->randomString(8); + + // first save the driver in a temporary file + saveDriverFile(d,tmpfilename); + + // then send a request + IppRequest req; + QString uri; + bool result(false); + + req.setOperation(CUPS_ADD_PRINTER); + uri = printerURI(p, true); + req.addURI(IPP_TAG_OPERATION,"printer-uri",uri); + result = req.doFileRequest("/admin/",tmpfilename); + + // remove temporary file + QFile::remove(tmpfilename); + + if (!result) + reportIppError(&req); + return result; +} + +void* KMCupsManager::loadCupsdConfFunction(const char *name) +{ + if (!m_cupsdconf) + { + m_cupsdconf = KLibLoader::self()->library("cupsdconf"); + if (!m_cupsdconf) + { + setErrorMsg(i18n("Library cupsdconf not found. Check your installation.")); + return NULL; + } + } + void* func = m_cupsdconf->symbol(name); + if (!func) + setErrorMsg(i18n("Symbol %1 not found in cupsdconf library.").arg(name)); + return func; +} + +void KMCupsManager::unloadCupsdConf() +{ + if (m_cupsdconf) + { + KLibLoader::self()->unloadLibrary("libcupsdconf"); + m_cupsdconf = 0; + } +} + +bool KMCupsManager::restartServer() +{ + QString msg; + bool (*f1)(QString&) = (bool(*)(QString&))loadCupsdConfFunction("restartServer"); + bool result(false); + if (f1) + { + result = f1(msg); + if (!result) setErrorMsg(msg); + } + unloadCupsdConf(); + return result; +} + +bool KMCupsManager::configureServer(QWidget *parent) +{ + QString msg; + bool (*f2)(QWidget*, QString&) = (bool(*)(QWidget*, QString&))loadCupsdConfFunction("configureServer"); + bool result(false); + if (f2) + { + result = f2(parent, msg); + if ( !result ) + setErrorMsg( msg ); + } + unloadCupsdConf(); + return result; +} + +QStringList KMCupsManager::detectLocalPrinters() +{ + QStringList list; + IppRequest req; + req.setOperation(CUPS_GET_DEVICES); + if (req.doRequest("/")) + { + QString desc, uri, printer, cl; + ipp_attribute_t *attr = req.first(); + while (attr) + { + QString attrname(attr->name); + if (attrname == "device-info") desc = attr->values[0].string.text; + else if (attrname == "device-make-and-model") printer = attr->values[0].string.text; + else if (attrname == "device-uri") uri = attr->values[0].string.text; + else if ( attrname == "device-class" ) cl = attr->values[ 0 ].string.text; + if (attrname.isEmpty() || attr == req.last()) + { + if (!uri.isEmpty()) + { + if (printer == "Unknown") printer = QString::null; + list << cl << uri << desc << printer; + } + uri = desc = printer = cl = QString::null; + } + attr = attr->next; + } + } + return list; +} + +void KMCupsManager::createPluginActions(KActionCollection *coll) +{ + KAction *act = new KAction(i18n("&Export Driver..."), "kdeprint_uploadsmb", 0, this, SLOT(exportDriver()), coll, "plugin_export_driver"); + act->setGroup("plugin"); + act = new KAction(i18n("&Printer IPP Report"), "kdeprint_report", 0, this, SLOT(printerIppReport()), coll, "plugin_printer_ipp_report"); + act->setGroup("plugin"); +} + +void KMCupsManager::validatePluginActions(KActionCollection *coll, KMPrinter *pr) +{ + // save selected printer for future use in slots + m_currentprinter = pr; + coll->action("plugin_export_driver")->setEnabled(pr && pr->isLocal() && !pr->isClass(true) && !pr->isSpecial()); + coll->action("plugin_printer_ipp_report")->setEnabled(pr && !pr->isSpecial()); +} + +void KMCupsManager::exportDriver() +{ + if (m_currentprinter && m_currentprinter->isLocal() && + !m_currentprinter->isClass(true) && !m_currentprinter->isSpecial()) + { + QString path = cupsInstallDir(); + if (path.isEmpty()) + path = "/usr/share/cups"; + else + path += "/share/cups"; + CupsAddSmb::exportDest(m_currentprinter->printerName(), path); + } +} + +void KMCupsManager::printerIppReport() +{ + if (m_currentprinter && !m_currentprinter->isSpecial()) + { + IppRequest req; + QString uri; + + req.setOperation(IPP_GET_PRINTER_ATTRIBUTES); + uri = printerURI(m_currentprinter, true); + req.addURI(IPP_TAG_OPERATION,"printer-uri",uri); + /* + if (!m_currentprinter->uri().isEmpty()) + { + req.setHost(m_currentprinter->uri().host()); + req.setPort(m_currentprinter->uri().port()); + } + */ + req.dump(2); + if (req.doRequest("/printers/")) + { + ippReport(req, IPP_TAG_PRINTER, i18n("IPP Report for %1").arg(m_currentprinter->printerName())); + } + else + { + KMessageBox::error(0, "<p>"+i18n("Unable to retrieve printer information. Error received:")+"</p>"+req.statusMessage()); + } + } +} + +void KMCupsManager::ippReport(IppRequest& req, int group, const QString& caption) +{ + IppReportDlg::report(&req, group, caption); +} + +QString KMCupsManager::stateInformation() +{ + return QString("%1: %2") + .arg(i18n("Server")) + .arg(CupsInfos::self()->host()[0] != '/' ? + QString("%1:%2").arg(CupsInfos::self()->host()).arg(CupsInfos::self()->port()) + : CupsInfos::self()->host()); +} + +void KMCupsManager::checkUpdatePossibleInternal() +{ + kdDebug(500) << "Checking for update possible" << endl; + delete m_socket; + m_socket = new KNetwork::KBufferedSocket; + m_socket->setTimeout( 1500 ); + connect( m_socket, SIGNAL( connected(const KResolverEntry&) ), + SLOT( slotConnectionSuccess() ) ); + connect( m_socket, SIGNAL( gotError( int ) ), SLOT( slotConnectionFailed( int ) ) ); + + trials = 5; + QTimer::singleShot( 1, this, SLOT( slotAsyncConnect() ) ); +} + +void KMCupsManager::slotConnectionSuccess() +{ + kdDebug(500) << "Connection success, trying to send a request..." << endl; + m_socket->close(); + + IppRequest req; + req.setOperation( CUPS_GET_PRINTERS ); + req.addKeyword( IPP_TAG_OPERATION, "requested-attributes", QString::fromLatin1( "printer-name" ) ); + if ( req.doRequest( "/printers/" ) ) + setUpdatePossible( true ); + else + { + kdDebug(500) << "Unable to get printer list" << endl; + if ( trials > 0 ) + { + trials--; + QTimer::singleShot( 1000, this, SLOT( slotAsyncConnect() ) ); + } + else + { + setErrorMsg( i18n( "Connection to CUPS server failed. Check that the CUPS server is correctly installed and running. " + "Error: %1." ).arg( i18n( "the IPP request failed for an unknown reason" ) ) ); + setUpdatePossible( false ); + } + } +} + +void KMCupsManager::slotAsyncConnect() +{ + kdDebug(500) << "Starting async connect to " << CupsInfos::self()->hostaddr() << endl; + //m_socket->startAsyncConnect(); + if (CupsInfos::self()->host().startsWith("/")) + m_socket->connect( QString(), CupsInfos::self()->host()); + else + m_socket->connectToHost( CupsInfos::self()->host(), CupsInfos::self()->port() ); +} + +void KMCupsManager::slotConnectionFailed( int errcode ) +{ + kdDebug(500) << "Connection failed trials=" << trials << endl; + if ( trials > 0 ) + { + //m_socket->setTimeout( ++to ); + //m_socket->cancelAsyncConnect(); + trials--; + m_socket->close(); + QTimer::singleShot( 1000, this, SLOT( slotAsyncConnect() ) ); + return; + } + + QString einfo; + + switch (errcode) { + case KNetwork::KSocketBase::ConnectionRefused: + case KNetwork::KSocketBase::ConnectionTimedOut: + einfo = i18n("connection refused") + QString(" (%1)").arg(errcode); + break; + case KNetwork::KSocketBase::LookupFailure: + einfo = i18n("host not found") + QString(" (%1)").arg(errcode); + break; + case KNetwork::KSocketBase::WouldBlock: + default: + einfo = i18n("read failed (%1)").arg(errcode); + break; + } + + setErrorMsg( i18n( "Connection to CUPS server failed. Check that the CUPS server is correctly installed and running. " + "Error: %2: %1." ).arg( einfo, CupsInfos::self()->host())); + setUpdatePossible( false ); +} + +void KMCupsManager::hostPingSlot() { + m_hostSuccess = true; + m_lookupDone = true; +} + +void KMCupsManager::hostPingFailedSlot() { + m_hostSuccess = false; + m_lookupDone = true; +} + +//***************************************************************************************************** + +static void extractMaticData(QString& buf, const QString& filename) +{ + QFile f(filename); + if (f.exists() && f.open(IO_ReadOnly)) + { + QTextStream t(&f); + QString line; + while (!t.eof()) + { + line = t.readLine(); + if (line.startsWith("*% COMDATA #")) + buf.append(line.right(line.length()-12)).append('\n'); + } + } +} + +static QString printerURI(KMPrinter *p, bool use) +{ + QString uri; + if (use && !p->uri().isEmpty()) + uri = p->uri().prettyURL(); + else + uri = QString("ipp://%1/%3/%2").arg(CupsInfos::self()->hostaddr()).arg(p->printerName()).arg((p->isClass(false) ? "classes" : "printers")); + return uri; +} + +static QString downloadDriver(KMPrinter *p) +{ + QString driverfile, prname = p->printerName(); + bool changed(false); + + /* + if (!p->uri().isEmpty()) + { + // try to load the driver from the host:port + // specified in its URI. Doing so may also change + // the printer name to use. Note that for remote + // printer, this operation is read-only, no counterpart + // for saving operation. + cupsSetServer(p->uri().host().local8Bit()); + ippSetPort(p->uri().port()); + // strip any "@..." from the printer name + prname = prname.replace(QRegExp("@.*"), ""); + changed = true; + } + */ + + // download driver + driverfile = cupsGetPPD(prname.local8Bit()); + + // restore host:port (if they have changed) + if (changed) + { + cupsSetServer(CupsInfos::self()->host().local8Bit()); + ippSetPort(CupsInfos::self()->port()); + } + + return driverfile; +} + +#include "kmcupsmanager.moc" diff --git a/kdeprint/cups/kmcupsmanager.h b/kdeprint/cups/kmcupsmanager.h new file mode 100644 index 000000000..54307fc86 --- /dev/null +++ b/kdeprint/cups/kmcupsmanager.h @@ -0,0 +1,106 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KMCUPSMANAGER_H +#define KMCUPSMANAGER_H + +#include "kmmanager.h" + +class IppRequest; +class KLibrary; +class KExtendedSocket; + +namespace KNetwork { + class KStreamSocket; +} + +class KMCupsManager : public KMManager +{ + friend class KMWIppPrinter; + friend class KMCupsJobManager; + + Q_OBJECT +public: + KMCupsManager(QObject *parent, const char *name, const QStringList & /*args*/); + virtual ~KMCupsManager(); + + // printer management functions + bool createPrinter(KMPrinter *p); + bool removePrinter(KMPrinter *p); + bool enablePrinter(KMPrinter *p, bool state); + bool startPrinter(KMPrinter *p, bool state); + bool completePrinter(KMPrinter *p); + bool completePrinterShort(KMPrinter *p); + bool setDefaultPrinter(KMPrinter *p); + bool testPrinter(KMPrinter *p); + + // printer listing functions + // driver DB functions + QString driverDbCreationProgram(); + QString driverDirectory(); + + DrMain* loadPrinterDriver(KMPrinter *p, bool config = false); + DrMain* loadFileDriver(const QString& filename); + bool savePrinterDriver(KMPrinter *p, DrMain *d); + + bool restartServer(); + bool configureServer(QWidget *parent = 0); + QStringList detectLocalPrinters(); + + void createPluginActions(KActionCollection*); + void validatePluginActions(KActionCollection*, KMPrinter*); + QString stateInformation(); + +public slots: + void exportDriver(); + void printerIppReport(); + +protected slots: + void slotConnectionFailed( int ); + void slotConnectionSuccess(); + void slotAsyncConnect(); + + void hostPingSlot(); + void hostPingFailedSlot(); + +protected: + // the real printer listing job is done here + void listPrinters(); + void loadServerPrinters(); + void processRequest(IppRequest*); + bool setPrinterState(KMPrinter *p, int st); + DrMain* loadDriverFile(const QString& filename); + DrMain* loadMaticDriver(const QString& drname); + void saveDriverFile(DrMain *driver, const QString& filename); + void reportIppError(IppRequest*); + void* loadCupsdConfFunction(const char*); + void unloadCupsdConf(); + QString cupsInstallDir(); + void ippReport(IppRequest&, int, const QString&); + void checkUpdatePossibleInternal(); + +private: + KLibrary *m_cupsdconf; + KMPrinter *m_currentprinter; + KNetwork::KStreamSocket *m_socket; + bool m_hostSuccess; + bool m_lookupDone; +}; + +#endif diff --git a/kdeprint/cups/kmcupsuimanager.cpp b/kdeprint/cups/kmcupsuimanager.cpp new file mode 100644 index 000000000..897199f88 --- /dev/null +++ b/kdeprint/cups/kmcupsuimanager.cpp @@ -0,0 +1,219 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kmcupsuimanager.h" +#include "kmpropertypage.h" +#include "kmwizard.h" +#include "kmconfigdialog.h" +#include "kmwbackend.h" +#include "kmfactory.h" +#include "kprinter.h" + +#include "kmpropbanners.h" +#include "kmpropmembers.h" +#include "kmpropbackend.h" +#include "kmpropdriver.h" +#include "kmwbanners.h" +#include "kmwipp.h" +#include "kmwippselect.h" +#include "kmwippprinter.h" +#include "kmconfigcups.h" +#include "kmconfigcupsdir.h" +#include "kmwfax.h" +#include "kmwother.h" +#include "kmwquota.h" +#include "kmpropquota.h" +#include "kmwusers.h" +#include "kmpropusers.h" +#include "kpschedulepage.h" +#include "kptagspage.h" + +#include "kprinterpropertydialog.h" +#include "kpgeneralpage.h" +#include "kpimagepage.h" +#include "kptextpage.h" +#include "kphpgl2page.h" + +#include "ipprequest.h" +#include "cupsinfos.h" + +#include <qlistview.h> +#include <qwhatsthis.h> +#include <klocale.h> +#include <kdebug.h> +#include <kaction.h> +#include <kmessagebox.h> + +KMCupsUiManager::KMCupsUiManager(QObject *parent, const char *name, const QStringList & /*args*/) +: KMUiManager(parent,name) +{ +} + +KMCupsUiManager::~KMCupsUiManager() +{ +} + +void KMCupsUiManager::setupPropertyPages(KMPropertyPage *p) +{ + p->addPropPage(new KMPropMembers(p, "Members")); + p->addPropPage(new KMPropBackend(p, "Backend")); + p->addPropPage(new KMPropDriver(p, "Driver")); + p->addPropPage(new KMPropBanners(p, "Banners")); + p->addPropPage(new KMPropQuota(p, "Quotas")); + p->addPropPage(new KMPropUsers(p, "Users")); +} + +void KMCupsUiManager::setupWizard(KMWizard *wizard) +{ + QString whatsThisRemoteCUPSIPPBackend = + i18n( "<qt><p>Print queue on remote CUPS server</p>" + "<p>Use this for a print queue installed on a remote " + "machine running a CUPS server. This allows to use " + "remote printers when CUPS browsing is turned off.</p></qt>" + ); + + QString whatsThisRemotePrinterIPPBackend = + i18n( "<qt><p>Network IPP printer</p>" + "<p>Use this for a network-enabled printer using the " + "IPP protocol. Modern high-end printers can use this mode. " + "Use this mode instead of TCP if your printer can do both.</p></qt>" + ); + + QString whatsThisSerialFaxModemBackend = + i18n( "<qt><p>Fax/Modem printer</p>" + "<p>Use this for a fax/modem printer. This requires the installation " + "of the <a href=\"http://vigna.dsi.unimi.it/fax4CUPS/\">fax4CUPS</a> backend. Documents sent on this printer will be faxed " + "to the given target fax number.</p></qt>" + ); + + QString whatsThisOtherPrintertypeBackend = + i18n( "<qt><p>Other printer</p>" + "<p>Use this for any printer type. To use this option, you must know " + "the URI of the printer you want to install. Refer to the CUPS documentation " + "for more information about the printer URI. This option is mainly useful for " + "printer types using 3rd party backends not covered by the other possibilities.</p></qt>" + ); + + QString whatsThisClassOfPrinters = + i18n( "<qt><p>Class of printers</p>" + "<p>Use this to create a class of printers. When sending a document to a class, " + "the document is actually sent to the first available (idle) printer in the class. " + "Refer to the CUPS documentation for more information about class of printers.</p></qt>" + ); + + KMWBackend *backend = wizard->backendPage(); + if (!backend) + return; + backend->addBackend(KMWizard::Local,false); + backend->addBackend(KMWizard::LPD,false); + backend->addBackend(KMWizard::SMB,false,KMWizard::Password); + backend->addBackend(KMWizard::TCP,false); + backend->addBackend(KMWizard::IPP,i18n("Re&mote CUPS server (IPP/HTTP)"),false,whatsThisRemoteCUPSIPPBackend,KMWizard::Password); + backend->addBackend(KMWizard::Custom+1,i18n("Network printer w/&IPP (IPP/HTTP)"),false,whatsThisRemotePrinterIPPBackend); + backend->addBackend(KMWizard::Custom+2,i18n("S&erial Fax/Modem printer"),false,whatsThisSerialFaxModemBackend); + backend->addBackend(KMWizard::Custom+5,i18n("Other &printer type"),false,whatsThisOtherPrintertypeBackend); + backend->addBackend(); + backend->addBackend(KMWizard::Class,i18n("Cl&ass of printers"),false,whatsThisClassOfPrinters); + + IppRequest req; + QString uri; + + req.setOperation(CUPS_GET_DEVICES); + uri = QString::fromLocal8Bit("ipp://%1/printers/").arg(CupsInfos::self()->hostaddr()); + req.addURI(IPP_TAG_OPERATION,"printer-uri",uri); + + if (req.doRequest("/")) + { + ipp_attribute_t *attr = req.first(); + while (attr) + { + if (attr->name && strcmp(attr->name,"device-uri") == 0) + { + if (strncmp(attr->values[0].string.text,"socket",6) == 0) backend->enableBackend(KMWizard::TCP,true); + else if (strncmp(attr->values[0].string.text,"parallel",8) == 0) backend->enableBackend(KMWizard::Local,true); + else if (strncmp(attr->values[0].string.text,"serial",6) == 0) backend->enableBackend(KMWizard::Local,true); + else if (strncmp(attr->values[0].string.text,"smb",3) == 0) backend->enableBackend(KMWizard::SMB,true); + else if (strncmp(attr->values[0].string.text,"lpd",3) == 0) backend->enableBackend(KMWizard::LPD,true); + else if (strncmp(attr->values[0].string.text,"usb",3) == 0) backend->enableBackend(KMWizard::Local,true); + else if (strncmp(attr->values[0].string.text,"http",4) == 0 || strncmp(attr->values[0].string.text,"ipp",3) == 0) + { + backend->enableBackend(KMWizard::IPP,true); + backend->enableBackend(KMWizard::Custom+1,true); + } + else if (strncmp(attr->values[0].string.text,"fax",3) == 0) backend->enableBackend(KMWizard::Custom+2,true); + } + attr = attr->next; + } + backend->enableBackend(KMWizard::Class, true); + backend->enableBackend(KMWizard::Custom+5, true); + } + else + KMessageBox::error(wizard, + "<qt><nobr>" + + i18n("An error occurred while retrieving the list of available backends:") + + "</nobr><br><br>" + req.statusMessage() + "</qt>"); + + // banners page + wizard->addPage(new KMWBanners(wizard)); + wizard->setNextPage(KMWizard::DriverTest,KMWizard::Banners); + wizard->addPage(new KMWIpp(wizard)); + wizard->addPage(new KMWIppSelect(wizard)); + wizard->addPage(new KMWIppPrinter(wizard)); + wizard->addPage(new KMWFax(wizard)); + wizard->addPage(new KMWQuota(wizard)); + wizard->addPage(new KMWUsers(wizard)); + wizard->addPage(new KMWOther(wizard)); +} + +void KMCupsUiManager::setupPrinterPropertyDialog(KPrinterPropertyDialog *dlg) +{ + // add general page + dlg->addPage(new KPGeneralPage(dlg->printer(),dlg->driver(),dlg,"GeneralPage")); + if (KMFactory::self()->settings()->application != KPrinter::Dialog) + { + dlg->addPage(new KPImagePage(dlg->driver(), dlg, "ImagePage")); + dlg->addPage(new KPTextPage(dlg->driver(), dlg, "TextPage")); + dlg->addPage(new KPHpgl2Page(dlg, "Hpgl2Page")); + } +} + +void KMCupsUiManager::setupConfigDialog(KMConfigDialog *dlg) +{ + dlg->addConfigPage(new KMConfigCups(dlg)); + dlg->addConfigPage(new KMConfigCupsDir(dlg)); +} + +int KMCupsUiManager::pluginPageCap() +{ + return (KMUiManager::CopyAll & ~KMUiManager::Current); +} + +void KMCupsUiManager::setupPrintDialogPages(QPtrList<KPrintDialogPage>* pages) +{ + pages->append(new KPSchedulePage()); + pages->append(new KPTagsPage()); +} + +void KMCupsUiManager::setupJobViewer(QListView *lv) +{ + lv->addColumn(i18n("Priority")); + lv->setColumnAlignment(lv->columns()-1, Qt::AlignRight|Qt::AlignVCenter); + lv->addColumn(i18n("Billing Information")); + lv->setColumnAlignment(lv->columns()-1, Qt::AlignRight|Qt::AlignVCenter); +} diff --git a/kdeprint/cups/kmcupsuimanager.h b/kdeprint/cups/kmcupsuimanager.h new file mode 100644 index 000000000..15ab8684d --- /dev/null +++ b/kdeprint/cups/kmcupsuimanager.h @@ -0,0 +1,40 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KMCUPSUIMANAGER_H +#define KMCUPSUIMANAGER_H + +#include "kmuimanager.h" + +class KMCupsUiManager : public KMUiManager +{ +public: + KMCupsUiManager(QObject *parent, const char *name, const QStringList & /*args*/); + ~KMCupsUiManager(); + + void setupPropertyPages(KMPropertyPage*); + void setupWizard(KMWizard*); + void setupPrinterPropertyDialog(KPrinterPropertyDialog*); + void setupConfigDialog(KMConfigDialog*); + int pluginPageCap(); + void setupPrintDialogPages(QPtrList<KPrintDialogPage>*); + void setupJobViewer(QListView*); +}; + +#endif diff --git a/kdeprint/cups/kmpropbanners.cpp b/kdeprint/cups/kmpropbanners.cpp new file mode 100644 index 000000000..3826de708 --- /dev/null +++ b/kdeprint/cups/kmpropbanners.cpp @@ -0,0 +1,81 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kmpropbanners.h" +#include "kmprinter.h" +#include "kmwizard.h" +#include "kmwbanners.h" + +#include <qlabel.h> +#include <qlayout.h> +#include <klocale.h> + +KMPropBanners::KMPropBanners(QWidget *parent, const char *name) +: KMPropWidget(parent,name) +{ + m_startbanner = new QLabel(this); + m_stopbanner = new QLabel(this); + + QLabel *l1 = new QLabel(i18n("&Starting banner:"), this); + QLabel *l2 = new QLabel(i18n("&Ending banner:"), this); + + l1->setBuddy(m_startbanner); + l2->setBuddy(m_stopbanner); + + QGridLayout *main_ = new QGridLayout(this, 3, 2, 10, 10); + main_->setColStretch(1,1); + main_->setRowStretch(2,1); + main_->addWidget(l1,0,0); + main_->addWidget(l2,1,0); + main_->addWidget(m_startbanner,0,1); + main_->addWidget(m_stopbanner,1,1); + + m_title = i18n("Banners"); + m_header = i18n("Banner Settings"); + m_pixmap = "editcopy"; +} + +KMPropBanners::~KMPropBanners() +{ +} + +void KMPropBanners::setPrinter(KMPrinter *p) +{ + if (p && p->isPrinter()) + { + QStringList l = QStringList::split(',',p->option("kde-banners"),false); + while ( l.count() < 2 ) + l.append( "none" ); + m_startbanner->setText(i18n(mapBanner(l[0]).utf8())); + m_stopbanner->setText(i18n(mapBanner(l[1]).utf8())); + emit enable(true); + emit enableChange(p->isLocal()); + } + else + { + emit enable(false); + m_startbanner->setText(""); + m_stopbanner->setText(""); + } +} + +void KMPropBanners::configureWizard(KMWizard *w) +{ + w->configure(KMWizard::Banners,KMWizard::Banners,true); +} diff --git a/kdeprint/cups/kmpropbanners.h b/kdeprint/cups/kmpropbanners.h new file mode 100644 index 000000000..eb8d85204 --- /dev/null +++ b/kdeprint/cups/kmpropbanners.h @@ -0,0 +1,43 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KMPROPBANNERS_H +#define KMPROPBANNERS_H + +#include "kmpropwidget.h" + +class QLabel; + +class KMPropBanners : public KMPropWidget +{ +public: + KMPropBanners(QWidget *parent = 0, const char *name = 0); + ~KMPropBanners(); + + void setPrinter(KMPrinter*); + +protected: + void configureWizard(KMWizard*); + +private: + QLabel *m_startbanner; + QLabel *m_stopbanner; +}; + +#endif diff --git a/kdeprint/cups/kmpropquota.cpp b/kdeprint/cups/kmpropquota.cpp new file mode 100644 index 000000000..ffce459e0 --- /dev/null +++ b/kdeprint/cups/kmpropquota.cpp @@ -0,0 +1,96 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kmpropquota.h" +#include "kmprinter.h" +#include "kmwizard.h" + +#include <qlabel.h> +#include <qlayout.h> +#include <klocale.h> + +// some forward declarations (see kmwquota.cpp) +const char* unitKeyword(int); +int findUnit(int&); + +KMPropQuota::KMPropQuota(QWidget *parent, const char *name) +: KMPropWidget(parent,name) +{ + m_period = new QLabel(this); + m_sizelimit = new QLabel(this); + m_pagelimit = new QLabel(this); + + QLabel *l1 = new QLabel(i18n("&Period:"), this); + QLabel *l2 = new QLabel(i18n("&Size limit (KB):"), this); + QLabel *l3 = new QLabel(i18n("&Page limit:"), this); + + l1->setBuddy(m_period); + l2->setBuddy(m_sizelimit); + l3->setBuddy(m_pagelimit); + + QGridLayout *main_ = new QGridLayout(this, 4, 2, 10, 10); + main_->setColStretch(1,1); + main_->setRowStretch(3,1); + main_->addWidget(l1,0,0); + main_->addWidget(l2,1,0); + main_->addWidget(l3,2,0); + main_->addWidget(m_period,0,1); + main_->addWidget(m_sizelimit,1,1); + main_->addWidget(m_pagelimit,2,1); + + m_title = i18n("Quotas"); + m_header = i18n("Quota Settings"); + m_pixmap = "lock"; +} + +KMPropQuota::~KMPropQuota() +{ +} + +void KMPropQuota::setPrinter(KMPrinter *p) +{ + if (p && p->isPrinter()) + { + int qu(0), si(0), pa(0), un(0); + qu = p->option("job-quota-period").toInt(); + si = p->option("job-k-limit").toInt(); + pa = p->option("job-page-limit").toInt(); + if (si == 0 && pa == 0) + qu = -1; + if (qu > 0) + un = findUnit(qu); + m_period->setText(qu == -1 ? i18n("No quota") : QString::number(qu).append(" ").append(i18n(unitKeyword(un)))); + m_sizelimit->setText(si ? QString::number(si) : i18n("None")); + m_pagelimit->setText(pa ? QString::number(pa) : i18n("None")); + emit enable(true); + emit enableChange(p->isLocal()); + } + else + { + emit enable(false); + m_period->setText(""); + m_sizelimit->setText(""); + m_pagelimit->setText(""); + } +} + +void KMPropQuota::configureWizard(KMWizard *w) +{ + w->configure(KMWizard::Custom+3,KMWizard::Custom+3,true); +} diff --git a/kdeprint/cups/kmpropquota.h b/kdeprint/cups/kmpropquota.h new file mode 100644 index 000000000..53ed8c59c --- /dev/null +++ b/kdeprint/cups/kmpropquota.h @@ -0,0 +1,44 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KMPROPQUOTA_H +#define KMPROPQUOTA_H + +#include "kmpropwidget.h" + +class QLabel; + +class KMPropQuota : public KMPropWidget +{ +public: + KMPropQuota(QWidget *parent = 0, const char *name = 0); + ~KMPropQuota(); + + void setPrinter(KMPrinter*); + +protected: + void configureWizard(KMWizard*); + +private: + QLabel *m_period; + QLabel *m_sizelimit; + QLabel *m_pagelimit; +}; + +#endif diff --git a/kdeprint/cups/kmpropusers.cpp b/kdeprint/cups/kmpropusers.cpp new file mode 100644 index 000000000..58b3301de --- /dev/null +++ b/kdeprint/cups/kmpropusers.cpp @@ -0,0 +1,90 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kmpropusers.h" +#include "kmprinter.h" +#include "kmwizard.h" + +#include <qtextview.h> +#include <qlayout.h> +#include <klocale.h> + +KMPropUsers::KMPropUsers(QWidget *parent, const char *name) +: KMPropWidget(parent,name) +{ + m_text = new QTextView(this); + m_text->setPaper(colorGroup().background()); + m_text->setFrameStyle(QFrame::NoFrame); + + QVBoxLayout *l0 = new QVBoxLayout(this, 10, 0); + l0->addWidget(m_text, 1); + + m_title = i18n("Users"); + m_header = i18n("Users Access Settings"); + m_pixmap = "kdeprint_printer_users"; +} + +KMPropUsers::~KMPropUsers() +{ +} + +void KMPropUsers::setPrinter(KMPrinter *p) +{ + if (p && p->isPrinter()) + { + QString txt("<p>%1:<ul>%1</ul></p>"); + QStringList users; + if (!p->option("requesting-user-name-denied").isEmpty()) + { + txt = txt.arg(i18n("Denied users")); + users = QStringList::split(",", p->option("requesting-user-name-denied"), false); + if (users.count() == 1 && users[0] == "none") + users.clear(); + } + else if (!p->option("requesting-user-name-allowed").isEmpty()) + { + txt = txt.arg(i18n("Allowed users")); + users = QStringList::split(",", p->option("requesting-user-name-allowed"), false); + if (users.count() == 1 && users[0] == "all") + users.clear(); + } + if (users.count() > 0) + { + QString s; + for (QStringList::ConstIterator it=users.begin(); it!=users.end(); ++it) + s.append("<li>").append(*it).append("</li>"); + txt = txt.arg(s); + m_text->setText(txt); + } + else + m_text->setText(i18n("All users allowed")); + emit enable(true); + emit enableChange(p->isLocal()); + } + else + { + emit enable(false); + m_text->setText(""); + } +} + +void KMPropUsers::configureWizard(KMWizard *w) +{ + w->configure(KMWizard::Custom+4,KMWizard::Custom+4,true); +} diff --git a/kdeprint/cups/kmpropusers.h b/kdeprint/cups/kmpropusers.h new file mode 100644 index 000000000..2d007baf8 --- /dev/null +++ b/kdeprint/cups/kmpropusers.h @@ -0,0 +1,42 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KMPROPUSERS_H +#define KMPROPUSERS_H + +#include "kmpropwidget.h" + +class QTextView; + +class KMPropUsers : public KMPropWidget +{ +public: + KMPropUsers(QWidget *parent = 0, const char *name = 0); + ~KMPropUsers(); + + void setPrinter(KMPrinter*); + +protected: + void configureWizard(KMWizard*); + +private: + QTextView *m_text; +}; + +#endif diff --git a/kdeprint/cups/kmwbanners.cpp b/kdeprint/cups/kmwbanners.cpp new file mode 100644 index 000000000..0572d0e34 --- /dev/null +++ b/kdeprint/cups/kmwbanners.cpp @@ -0,0 +1,145 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kmwbanners.h" +#include "kmwizard.h" +#include "kmprinter.h" +#include "kmfactory.h" +#include "kmmanager.h" + +#include <qcombobox.h> +#include <qlabel.h> +#include <qlayout.h> +#include <qmap.h> +#include <klocale.h> + +QStringList defaultBanners() +{ + QStringList bans; + QPtrList<KMPrinter> *list = KMFactory::self()->manager()->printerList(false); + if (list && list->count() > 0) + { + QPtrListIterator<KMPrinter> it(*list); + for (;it.current() && !it.current()->isPrinter(); ++it) ; + if (it.current() && KMFactory::self()->manager()->completePrinter(it.current())) + { + QString s = list->getFirst()->option("kde-banners-supported"); + bans = QStringList::split(',',s,false); + } + } + if (bans.count() == 0) + bans.append("none"); + return bans; +} + +static struct +{ + const char *banner; + const char *name; +} bannermap[] = +{ + { "none", I18N_NOOP( "No Banner" ) }, + { "classified", I18N_NOOP( "Classified" ) }, + { "confidential", I18N_NOOP( "Confidential" ) }, + { "secret", I18N_NOOP( "Secret" ) }, + { "standard", I18N_NOOP( "Standard" ) }, + { "topsecret", I18N_NOOP( "Top Secret" ) }, + { "unclassified", I18N_NOOP( "Unclassified" ) }, + { 0, 0 } +}; + +QString mapBanner( const QString& ban ) +{ + static QMap<QString,QString> map; + if ( map.size() == 0 ) + for ( int i=0; bannermap[ i ].banner; i++ ) + map[ bannermap[ i ].banner ] = bannermap[ i ].name; + QMap<QString,QString>::ConstIterator it = map.find( ban ); + if ( it == map.end() ) + return ban; + else + return it.data(); +} + +//************************************************************************************************************** + +KMWBanners::KMWBanners(QWidget *parent, const char *name) +: KMWizardPage(parent,name) +{ + m_ID = KMWizard::Banners; + m_title = i18n("Banner Selection"); + m_nextpage = KMWizard::Custom+3; + + m_start = new QComboBox(this); + m_end = new QComboBox(this); + + QLabel *l1 = new QLabel(i18n("&Starting banner:"),this); + QLabel *l2 = new QLabel(i18n("&Ending banner:"),this); + + l1->setBuddy(m_start); + l2->setBuddy(m_end); + + QLabel *l0 = new QLabel(this); + l0->setText(i18n("<p>Select the default banners associated with this printer. These " + "banners will be inserted before and/or after each print job sent " + "to the printer. If you don't want to use banners, select <b>No Banner</b>.</p>")); + + QGridLayout *lay = new QGridLayout(this, 5, 2, 0, 10); + lay->setColStretch(1,1); + lay->addRowSpacing(1,20); + lay->setRowStretch(4,1); + lay->addMultiCellWidget(l0,0,0,0,1); + lay->addWidget(l1,2,0); + lay->addWidget(l2,3,0); + lay->addWidget(m_start,2,1); + lay->addWidget(m_end,3,1); +} + +void KMWBanners::initPrinter(KMPrinter *p) +{ + if (p) + { + if (m_start->count() == 0) + { + m_bans = QStringList::split(',',p->option("kde-banners-supported"),false); + if (m_bans.count() == 0) + m_bans = defaultBanners(); + if (m_bans.find("none") == m_bans.end()) + m_bans.prepend("none"); + for ( QStringList::Iterator it=m_bans.begin(); it!=m_bans.end(); ++it ) + { + m_start->insertItem( i18n( mapBanner(*it).utf8() ) ); + m_end->insertItem( i18n( mapBanner(*it).utf8() ) ); + } + } + QStringList l = QStringList::split(',',p->option("kde-banners"),false); + while (l.count() < 2) + l.append("none"); + m_start->setCurrentItem(m_bans.findIndex(l[0])); + m_end->setCurrentItem(m_bans.findIndex(l[1])); + } +} + +void KMWBanners::updatePrinter(KMPrinter *p) +{ + if (m_start->count() > 0) + { + p->setOption("kde-banners",m_bans[m_start->currentItem()]+","+m_bans[m_end->currentItem()]); + } +} diff --git a/kdeprint/cups/kmwbanners.h b/kdeprint/cups/kmwbanners.h new file mode 100644 index 000000000..2fa820767 --- /dev/null +++ b/kdeprint/cups/kmwbanners.h @@ -0,0 +1,43 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KMWBANNERS_H +#define KMWBANNERS_H + +#include "kmwizardpage.h" +#include <qstringlist.h> + +class QComboBox; + +class KMWBanners : public KMWizardPage +{ +public: + KMWBanners(QWidget *parent = 0, const char *name = 0); + + void initPrinter(KMPrinter*); + void updatePrinter(KMPrinter*); + +private: + QComboBox *m_start, *m_end; + QStringList m_bans; +}; + +QString mapBanner( const QString& ); + +#endif diff --git a/kdeprint/cups/kmwfax.cpp b/kdeprint/cups/kmwfax.cpp new file mode 100644 index 000000000..da42b8400 --- /dev/null +++ b/kdeprint/cups/kmwfax.cpp @@ -0,0 +1,81 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kmwfax.h" +#include "kmwizard.h" +#include "kmprinter.h" +#include "ipprequest.h" +#include "cupsinfos.h" + +#include <qlabel.h> +#include <qlayout.h> +#include <klistbox.h> +#include <klocale.h> +#include <kiconloader.h> +#include <kurl.h> + +KMWFax::KMWFax(QWidget *parent, const char *name) +: KMWizardPage(parent,name) +{ + m_ID = KMWizard::Custom+2; + m_title = i18n("Fax Serial Device"); + m_nextpage = KMWizard::Driver; + + QLabel *lab = new QLabel(this); + lab->setText(i18n("<p>Select the device which your serial Fax/Modem is connected to.</p>")); + m_list = new KListBox(this); + + QVBoxLayout *l1 = new QVBoxLayout(this,0,10); + l1->addWidget(lab,0); + l1->addWidget(m_list,1); + + // initialize + IppRequest req; + req.setOperation(CUPS_GET_DEVICES); + QString uri = QString::fromLatin1("ipp://%1/printers/").arg(CupsInfos::self()->hostaddr()); + req.addURI(IPP_TAG_OPERATION,"printer-uri",uri); + if (req.doRequest("/")) + { + ipp_attribute_t *attr = req.first(); + while (attr) + { + if (attr->name && strcmp(attr->name,"device-uri") == 0 && strncmp(attr->values[0].string.text,"fax",3) == 0) + { + m_list->insertItem(SmallIcon("blockdevice"),QString::fromLatin1(attr->values[0].string.text)); + } + attr = attr->next; + } + } +} + +bool KMWFax::isValid(QString& msg) +{ + if (m_list->currentItem() == -1) + { + msg = i18n("You must select a device."); + return false; + } + return true; +} + +void KMWFax::updatePrinter(KMPrinter *printer) +{ + QString uri = m_list->currentText(); + printer->setDevice(uri); +} diff --git a/kdeprint/cups/kmwfax.h b/kdeprint/cups/kmwfax.h new file mode 100644 index 000000000..4a46bc29b --- /dev/null +++ b/kdeprint/cups/kmwfax.h @@ -0,0 +1,39 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KMWFAX_H +#define KMWFAX_H + +#include "kmwizardpage.h" + +class KListBox; + +class KMWFax : public KMWizardPage +{ +public: + KMWFax(QWidget *parent = 0, const char *name = 0); + + bool isValid(QString&); + void updatePrinter(KMPrinter*); + +private: + KListBox *m_list; +}; + +#endif diff --git a/kdeprint/cups/kmwipp.cpp b/kdeprint/cups/kmwipp.cpp new file mode 100644 index 000000000..fbef937cf --- /dev/null +++ b/kdeprint/cups/kmwipp.cpp @@ -0,0 +1,86 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kmwipp.h" +#include "kmwizard.h" +#include "kmprinter.h" + +#include <qlabel.h> +#include <qlineedit.h> +#include <klocale.h> +#include <qvalidator.h> + +#include <cups/http.h> + +KMWIpp::KMWIpp(QWidget *parent, const char *name) +: KMWInfoBase(2,parent,name) +{ + m_ID = KMWizard::IPP; + m_title = i18n("Remote IPP server"); + m_nextpage = KMWizard::IPPSelect; + lineEdit( 1 )->setValidator( new QIntValidator( this ) ); + + setInfo(i18n("<p>Enter the information concerning the remote IPP server " + "owning the targeted printer. This wizard will poll the server " + "before continuing.</p>")); + setLabel(0,i18n("Host:")); + setLabel(1,i18n("Port:")); + setText( 1, QString::fromLatin1( "631" ) ); +} + +bool KMWIpp::isValid(QString& msg) +{ + // check informations + if (text(0).isEmpty()) + { + msg = i18n("Empty server name."); + return false; + } + bool ok(false); + int p = text(1).toInt(&ok); + if (!ok) + { + msg = i18n("Incorrect port number."); + return false; + } + + // check server + http_t *HTTP = httpConnect(text(0).latin1(),p); + if (HTTP) + { + httpClose(HTTP); + return true; + } + else + { + msg = i18n("<nobr>Unable to connect to <b>%1</b> on port <b>%2</b> .</nobr>").arg(text(0)).arg(p); + return false; + } +} + +void KMWIpp::updatePrinter(KMPrinter *p) +{ + KURL url; + url.setProtocol("ipp"); + url.setHost(text(0)); + url.setPort(text(1).toInt()); + if (!p->option("kde-login").isEmpty()) url.setUser(p->option("kde-login")); + if (!p->option("kde-password").isEmpty()) url.setPass(p->option("kde-password")); + p->setDevice(url.url()); +} diff --git a/kdeprint/cups/kmwipp.h b/kdeprint/cups/kmwipp.h new file mode 100644 index 000000000..81856c8cd --- /dev/null +++ b/kdeprint/cups/kmwipp.h @@ -0,0 +1,34 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KMWIPP_H +#define KMWIPP_H + +#include "kmwinfobase.h" + +class KMWIpp : public KMWInfoBase +{ +public: + KMWIpp(QWidget *parent = 0, const char *name = 0); + + bool isValid(QString&); + void updatePrinter(KMPrinter*); +}; + +#endif diff --git a/kdeprint/cups/kmwippprinter.cpp b/kdeprint/cups/kmwippprinter.cpp new file mode 100644 index 000000000..de636ea8c --- /dev/null +++ b/kdeprint/cups/kmwippprinter.cpp @@ -0,0 +1,227 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kmwippprinter.h" +#include "kmwizard.h" +#include "kmprinter.h" +#include "ipprequest.h" +#include "kmcupsmanager.h" +#include "networkscanner.h" + +#include <klistview.h> +#include <qheader.h> +#include <kpushbutton.h> +#include <qlineedit.h> +#include <qlabel.h> +#include <kmessagebox.h> +#include <qtextview.h> +#include <qlayout.h> +#include <qregexp.h> +#include <kseparator.h> +#include <klocale.h> +#include <kiconloader.h> +#include <kguiitem.h> +#include <kurl.h> + +KMWIppPrinter::KMWIppPrinter(QWidget *parent, const char *name) +: KMWizardPage(parent,name) +{ + m_title = i18n("IPP Printer Information"); + m_ID = KMWizard::Custom+1; + m_nextpage = KMWizard::Driver; + + m_list = new KListView(this); + m_list->addColumn(""); + m_list->header()->hide(); + m_list->setFrameStyle(QFrame::WinPanel|QFrame::Sunken); + m_list->setLineWidth(1); + + QLabel *l1 = new QLabel(i18n("&Printer URI:"),this); + + m_uri = new QLineEdit(this); + + l1->setBuddy(m_uri); + + m_info = new QTextView(this); + m_info->setPaper(colorGroup().background()); + m_info->setMinimumHeight(100); + m_info->setText(i18n("<p>Either enter the printer URI directly, or use the network scanning facility.</p>")); + m_ippreport = new KPushButton(KGuiItem(i18n("&IPP Report"), "kdeprint_report"), this); + m_ippreport->setEnabled(false); + + m_scanner = new NetworkScanner( 631, this ); + + KSeparator* sep = new KSeparator( KSeparator::HLine, this); + sep->setFixedHeight(20); + + connect(m_list,SIGNAL(selectionChanged(QListViewItem*)),SLOT(slotPrinterSelected(QListViewItem*))); + connect( m_scanner, SIGNAL( scanStarted() ), SLOT( slotScanStarted() ) ); + connect( m_scanner, SIGNAL( scanFinished() ), SLOT( slotScanFinished() ) ); + connect( m_scanner, SIGNAL( scanStarted() ), parent, SLOT( disableWizard() ) ); + connect( m_scanner, SIGNAL( scanFinished() ), parent, SLOT( enableWizard() ) ); + connect(m_ippreport, SIGNAL(clicked()), SLOT(slotIppReport())); + + // layout + QHBoxLayout *lay3 = new QHBoxLayout(this, 0, 10); + QVBoxLayout *lay2 = new QVBoxLayout(0, 0, 0); + QHBoxLayout *lay4 = new QHBoxLayout(0, 0, 0); + + lay3->addWidget(m_list,1); + lay3->addLayout(lay2,1); + lay2->addWidget(l1); + lay2->addWidget(m_uri); + lay2->addSpacing(10); + lay2->addWidget(m_info, 1); + lay2->addSpacing(5); + lay2->addLayout(lay4); + lay4->addStretch(1); + lay4->addWidget(m_ippreport); + lay2->addWidget(sep); + lay2->addWidget( m_scanner ); +} + +KMWIppPrinter::~KMWIppPrinter() +{ +} + +void KMWIppPrinter::updatePrinter(KMPrinter *p) +{ + p->setDevice(m_uri->text()); +} + +bool KMWIppPrinter::isValid(QString& msg) +{ + if (m_uri->text().isEmpty()) + { + msg = i18n("You must enter a printer URI."); + return false; + } + + KURL uri( m_uri->text() ); + if (!m_scanner->checkPrinter(uri.host(),(uri.port()==0?631:uri.port()))) + { + msg = i18n("No printer found at this address/port."); + return false; + } + return true; +} + +void KMWIppPrinter::slotScanStarted() +{ + m_list->clear(); +} + +void KMWIppPrinter::slotScanFinished() +{ + m_ippreport->setEnabled(false); + const QPtrList<NetworkScanner::SocketInfo> *list = m_scanner->printerList(); + QPtrListIterator<NetworkScanner::SocketInfo> it(*list); + for (;it.current();++it) + { + QString name; + if (it.current()->Name.isEmpty()) + name = i18n("Unknown host - 1 is the IP", "<Unknown> (%1)").arg(it.current()->IP); + else + name = it.current()->Name; + QListViewItem *item = new QListViewItem(m_list,name,it.current()->IP,QString::number(it.current()->Port)); + item->setPixmap(0,SmallIcon("kdeprint_printer")); + } +} + +void KMWIppPrinter::slotPrinterSelected(QListViewItem *item) +{ + m_ippreport->setEnabled(item != 0); + if (!item) return; + + // trying to get printer attributes + IppRequest req; + QString uri; + QStringList keys; + + req.setOperation(IPP_GET_PRINTER_ATTRIBUTES); + req.setHost(item->text(1)); + req.setPort(item->text(2).toInt()); + uri = QString::fromLatin1("ipp://%1:%2/ipp").arg(item->text(1)).arg(item->text(2)); + req.addURI(IPP_TAG_OPERATION,"printer-uri",uri); + keys.append("printer-name"); + keys.append("printer-state"); + keys.append("printer-info"); + keys.append("printer-uri-supported"); + keys.append("printer-make-and-model"); + keys.append("printer-location"); + req.addKeyword(IPP_TAG_OPERATION,"requested-attributes",keys); + if (req.doRequest("/ipp/") && (req.status() == IPP_OK || req.status() == IPP_OK_SUBST || req.status() == IPP_OK_CONFLICT)) + { + QString value, txt; + int state; + if (req.name("printer-name",value)) txt.append(i18n("<b>Name</b>: %1<br>").arg(value)); + if (req.text("printer-location",value) && !value.isEmpty()) txt.append(i18n("<b>Location</b>: %1<br>").arg(value)); + if (req.text("printer-info",value) && !value.isEmpty()) txt.append(i18n("<b>Description</b>: %1<br>").arg(value.replace(QRegExp(";"),"<br>"))); + if (req.uri("printer-uri-supported",value)) + { + if (value[0] == '/') + value.prepend(QString::fromLatin1("ipp://%1:%2").arg(item->text(1)).arg(item->text(2))); + m_uri->setText(value); + } + if (req.text("printer-make-and-model",value) && !value.isEmpty()) txt.append(i18n("<b>Model</b>: %1<br>").arg(value)); + if (req.enumvalue("printer-state",state)) + { + switch (state) + { + case IPP_PRINTER_IDLE: value = i18n("Idle"); break; + case IPP_PRINTER_STOPPED: value = i18n("Stopped"); break; + case IPP_PRINTER_PROCESSING: value = i18n("Processing..."); break; + default: value = i18n("Unknown State", "Unknown"); break; + } + txt.append(i18n("<b>State</b>: %1<br>").arg(value)); + } + m_info->setText(txt); + } + else + { + m_uri->setText(uri); + m_info->setText(i18n("Unable to retrieve printer info. Printer answered:<br><br>%1").arg(ippErrorString((ipp_status_t)req.status()))); + } +} + +void KMWIppPrinter::slotIppReport() +{ + IppRequest req; + QString uri("ipp://%1:%2/ipp"); + QListViewItem *item = m_list->currentItem(); + + if (item) + { + req.setOperation(IPP_GET_PRINTER_ATTRIBUTES); + req.setHost(item->text(1)); + req.setPort(item->text(2).toInt()); + uri = uri.arg(item->text(1)).arg(item->text(2)); + req.addURI(IPP_TAG_OPERATION, "printer-uri", uri); + if (req.doRequest("/ipp/")) + { + QString caption = i18n("IPP Report for %1").arg(item->text(0)); + static_cast<KMCupsManager*>(KMManager::self())->ippReport(req, IPP_TAG_PRINTER, caption); + } + else + KMessageBox::error(this, i18n("Unable to generate report. IPP request failed with message: " + "%1 (0x%2).").arg(ippErrorString((ipp_status_t)req.status())).arg(req.status(),0,16)); + } +} + +#include "kmwippprinter.moc" diff --git a/kdeprint/cups/kmwippprinter.h b/kdeprint/cups/kmwippprinter.h new file mode 100644 index 000000000..f928c3e68 --- /dev/null +++ b/kdeprint/cups/kmwippprinter.h @@ -0,0 +1,56 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KMWIPPPRINTER_H +#define KMWIPPPRINTER_H + +#include "kmwizardpage.h" + +class KListView; +class QListViewItem; +class QLineEdit; +class QTextView; +class QPushButton; +class NetworkScanner; + +class KMWIppPrinter : public KMWizardPage +{ + Q_OBJECT +public: + KMWIppPrinter(QWidget *parent = 0, const char *name = 0); + ~KMWIppPrinter(); + + bool isValid(QString&); + void updatePrinter(KMPrinter*); + +protected slots: + void slotScanStarted(); + void slotScanFinished(); + void slotPrinterSelected(QListViewItem*); + void slotIppReport(); + +private: + KListView *m_list; + NetworkScanner *m_scanner; + QLineEdit *m_uri; + QTextView *m_info; + QPushButton *m_ippreport; +}; + +#endif diff --git a/kdeprint/cups/kmwippselect.cpp b/kdeprint/cups/kmwippselect.cpp new file mode 100644 index 000000000..d70c8603d --- /dev/null +++ b/kdeprint/cups/kmwippselect.cpp @@ -0,0 +1,108 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kmwippselect.h" +#include "kmwizard.h" +#include "kmprinter.h" +#include "cupsinfos.h" +#include "ipprequest.h" + +#include <klistbox.h> +#include <qlayout.h> +#include <klocale.h> +#include <kdebug.h> +#include <kiconloader.h> + +KMWIppSelect::KMWIppSelect(QWidget *parent, const char *name) +: KMWizardPage(parent,name) +{ + m_ID = KMWizard::IPPSelect; + m_title = i18n("Remote IPP Printer Selection"); + m_nextpage = KMWizard::Driver; + + m_list = new KListBox(this); + + QVBoxLayout *lay = new QVBoxLayout(this, 0, 0); + lay->addWidget(m_list); +} + +bool KMWIppSelect::isValid(QString& msg) +{ + if (m_list->currentItem() == -1) + { + msg = i18n("You must select a printer."); + return false; + } + return true; +} + +void KMWIppSelect::initPrinter(KMPrinter *p) +{ + // storage variables + QString host, login, password; + int port; + + // save config + host = CupsInfos::self()->host(); + login = CupsInfos::self()->login(); + password = CupsInfos::self()->password(); + port = CupsInfos::self()->port(); + + m_list->clear(); + + // retrieve printer list + KURL url = p->device(); + CupsInfos::self()->setHost(url.host()); + CupsInfos::self()->setLogin(url.user()); + CupsInfos::self()->setPassword(url.pass()); + CupsInfos::self()->setPort(url.port()); + IppRequest req; + QString uri; + req.setOperation(CUPS_GET_PRINTERS); + uri = QString::fromLatin1("ipp://%1/printers/").arg(CupsInfos::self()->hostaddr()); + req.addURI(IPP_TAG_OPERATION,"printer-uri",uri); + req.addKeyword(IPP_TAG_OPERATION,"requested-attributes",QString::fromLatin1("printer-name")); + if (req.doRequest("/printers/")) + { + ipp_attribute_t *attr = req.first(); + while (attr) + { + if (attr->name && strcmp(attr->name,"printer-name") == 0) + m_list->insertItem(SmallIcon("kdeprint_printer"),QString::fromLatin1(attr->values[0].string.text)); + attr = attr->next; + } + m_list->sort(); + } + + // restore config + CupsInfos::self()->setHost(host); + CupsInfos::self()->setLogin(login); + CupsInfos::self()->setPassword(password); + CupsInfos::self()->setPort(port); +} + +void KMWIppSelect::updatePrinter(KMPrinter *p) +{ + KURL url = p->device(); + QString path = m_list->currentText(); + path.prepend("/printers/"); + url.setPath(path); + p->setDevice(url.url()); +kdDebug(500) << url.url() << endl; +} diff --git a/kdeprint/cups/kmwippselect.h b/kdeprint/cups/kmwippselect.h new file mode 100644 index 000000000..5bf12e0c8 --- /dev/null +++ b/kdeprint/cups/kmwippselect.h @@ -0,0 +1,40 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KMWIPPSELECT_H +#define KMWIPPSELECT_H + +#include "kmwizardpage.h" + +class KListBox; + +class KMWIppSelect : public KMWizardPage +{ +public: + KMWIppSelect(QWidget *parent = 0, const char *name = 0); + + bool isValid(QString&); + void initPrinter(KMPrinter*); + void updatePrinter(KMPrinter*); + +private: + KListBox *m_list; +}; + +#endif diff --git a/kdeprint/cups/kmwother.cpp b/kdeprint/cups/kmwother.cpp new file mode 100644 index 000000000..034c88bb2 --- /dev/null +++ b/kdeprint/cups/kmwother.cpp @@ -0,0 +1,125 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kmwother.h" +#include "kmwizard.h" +#include "kmprinter.h" +#include "kmmanager.h" +#include "cupsinfos.h" + +#include <qlabel.h> +#include <qlayout.h> +#include <qlineedit.h> +#include <qheader.h> +#include <qdict.h> + +#include <klocale.h> +#include <klistview.h> +#include <kiconloader.h> +#include <kdebug.h> + +KMWOther::KMWOther(QWidget *parent, const char *name) +: KMWizardPage(parent,name) +{ + m_ID = KMWizard::Custom+5; + m_title = i18n("URI Selection"); + m_nextpage = KMWizard::Driver; + + m_uri = new QLineEdit(this); + QLabel *l1 = new QLabel(this); + l1->setText(i18n("<p>Enter the URI corresponding to the printer to be installed. " + "Examples:</p><ul>" + "<li>smb://[login[:passwd]@]server/printer</li>" + "<li>lpd://server/queue</li>" + "<li>parallel:/dev/lp0</li></ul>")); + QLabel *l2 = new QLabel(i18n("URI:"), this); + m_uriview = new KListView( this ); + m_uriview->addColumn( "" ); + m_uriview->header()->hide(); + m_uriview->setSorting( -1 ); + connect( m_uriview, SIGNAL( pressed( QListViewItem* ) ), SLOT( slotPressed( QListViewItem* ) ) ); + + QVBoxLayout *lay1 = new QVBoxLayout(this, 0, 15); + QVBoxLayout *lay2 = new QVBoxLayout(0, 0, 5); + lay1->addWidget(l1); + lay1->addLayout(lay2); + lay1->addWidget( m_uriview ); + lay2->addWidget(l2); + lay2->addWidget(m_uri); +} + +void KMWOther::initPrinter(KMPrinter *p) +{ + m_uri->setText(p->device()); + + if ( m_uriview->childCount() == 0 ) + { + QStringList l = KMManager::self()->detectLocalPrinters(); + if ( l.isEmpty() || l.count() % 4 != 0 ) + return; + + QListViewItem *item = 0, *lastparent = 0, *root; + root = new QListViewItem( m_uriview, i18n( "CUPS Server %1:%2" ).arg( CupsInfos::self()->host() ).arg( CupsInfos::self()->port() ) ); + root->setPixmap( 0, SmallIcon( "gear" ) ); + root->setOpen( true ); + QDict<QListViewItem> parents, last; + parents.setAutoDelete( false ); + last.setAutoDelete( false ); + for ( QStringList::Iterator it=l.begin(); it!=l.end(); ++it ) + { + QString cl = *it; + QString uri = *( ++it ); + QString desc = *( ++it ); + QString prt = *( ++it ); + if ( !prt.isEmpty() ) + desc.append( " [" + prt + "]" ); + QListViewItem *parent = parents.find( cl ); + if ( !parent ) + { + parent = new QListViewItem( root, lastparent, cl ); + parent->setOpen( true ); + if ( cl == "network" ) + parent->setPixmap( 0, SmallIcon( "network" ) ); + else if ( cl == "direct" ) + parent->setPixmap( 0, SmallIcon( "kdeprint_computer" ) ); + else if ( cl == "serial" ) + parent->setPixmap( 0, SmallIcon( "usb" ) ); + else + parent->setPixmap( 0, SmallIcon( "package" ) ); + lastparent = parent; + parents.insert( cl, parent ); + } + item = new QListViewItem( parent, last.find( cl ), desc, uri); + last.insert( cl, item ); + } + } +} + +void KMWOther::updatePrinter(KMPrinter *p) +{ + p->setDevice( m_uri->text() ); +} + +void KMWOther::slotPressed( QListViewItem *item ) +{ + if ( item && !item->text( 1 ).isEmpty() ) + m_uri->setText( item->text( 1 ) ); +} + +#include "kmwother.moc" diff --git a/kdeprint/cups/kmwother.h b/kdeprint/cups/kmwother.h new file mode 100644 index 000000000..211a670e9 --- /dev/null +++ b/kdeprint/cups/kmwother.h @@ -0,0 +1,46 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KMWOTHER_H +#define KMWOTHER_H + +#include "kmwizardpage.h" + +class QLineEdit; +class KListView; +class QListViewItem; + +class KMWOther : public KMWizardPage +{ + Q_OBJECT +public: + KMWOther(QWidget *parent = 0, const char *name = 0); + + void initPrinter(KMPrinter*); + void updatePrinter(KMPrinter*); + +protected slots: + void slotPressed( QListViewItem* ); + +private: + QLineEdit *m_uri; + KListView *m_uriview; +}; + +#endif diff --git a/kdeprint/cups/kmwquota.cpp b/kdeprint/cups/kmwquota.cpp new file mode 100644 index 000000000..e0b5d5f27 --- /dev/null +++ b/kdeprint/cups/kmwquota.cpp @@ -0,0 +1,171 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include <config.h> + +#include "kmwquota.h" +#include "kmwizard.h" +#include "kmprinter.h" + +#include <qspinbox.h> +#include <qlabel.h> +#include <qcombobox.h> +#include <qlayout.h> +#include <klocale.h> + +#ifdef HAVE_LIMITS_H +#include <limits.h> +#endif + +#define N_TIME_LIMITS 6 +static int time_periods[] = { + 1, // second + 60, // minute + 3600, // hour + 86400, // day + 604800, // week + 2592000 // month (30 days) +}; +static const char* time_keywords[] = { + I18N_NOOP("second(s)"), + I18N_NOOP("minute(s)"), + I18N_NOOP("hour(s)"), + I18N_NOOP("day(s)"), + I18N_NOOP("week(s)"), + I18N_NOOP("month(s)") +}; + +int findUnit(int& period) +{ + int unit(0); + for (int i=N_TIME_LIMITS-1;i>=0;i--) + { + if (period < time_periods[i]) + continue; + int d = period / time_periods[i]; + if ((d*time_periods[i]) == period) + { + unit = i; + break; + } + } + period /= time_periods[unit]; + return unit; +} + +const char* unitKeyword(int i) +{ return time_keywords[i]; } + +KMWQuota::KMWQuota(QWidget *parent, const char *name) +: KMWizardPage(parent, name) +{ + m_ID = KMWizard::Custom+3; + m_title = i18n("Printer Quota Settings"); + m_nextpage = KMWizard::Custom+4; + + m_period = new QSpinBox(this); + m_period->setRange(-1, INT_MAX); + m_period->setSpecialValueText(i18n("No quota")); + m_sizelimit = new QSpinBox(this); + m_sizelimit->setRange(0, INT_MAX); + m_sizelimit->setSpecialValueText(i18n("None")); + m_pagelimit = new QSpinBox(this); + m_pagelimit->setRange(0, INT_MAX); + m_pagelimit->setSpecialValueText(i18n("None")); + m_timeunit = new QComboBox(this); + for (int i=0;i<N_TIME_LIMITS;i++) + m_timeunit->insertItem(i18n(time_keywords[i])); + m_timeunit->setCurrentItem(3); + + QLabel *lab1 = new QLabel(i18n("&Period:"), this); + QLabel *lab2 = new QLabel(i18n("&Size limit (KB):"), this); + QLabel *lab3 = new QLabel(i18n("&Page limit:"), this); + + lab1->setBuddy(m_period); + lab2->setBuddy(m_sizelimit); + lab3->setBuddy(m_pagelimit); + + QLabel *lab4 = new QLabel(i18n("<p>Set here the quota for this printer. Using limits of <b>0</b> means " + "that no quota will be used. This is equivalent to set quota period to " + "<b><nobr>No quota</nobr></b> (-1). Quota limits are defined on a per-user base and " + "applied to all users.</p>"), this); + + QGridLayout *l0 = new QGridLayout(this, 5, 3, 0, 10); + l0->setRowStretch(4, 1); + l0->setColStretch(1, 1); + l0->addMultiCellWidget(lab4, 0, 0, 0, 2); + l0->addWidget(lab1, 1, 0); + l0->addWidget(lab2, 2, 0); + l0->addWidget(lab3, 3, 0); + l0->addWidget(m_period, 1, 1); + l0->addWidget(m_timeunit, 1, 2); + l0->addMultiCellWidget(m_sizelimit, 2, 2, 1, 2); + l0->addMultiCellWidget(m_pagelimit, 3, 3, 1, 2); +} + +KMWQuota::~KMWQuota() +{ +} + +bool KMWQuota::isValid(QString& msg) +{ + if (m_period->value() >= 0 && m_sizelimit->value() == 0 && m_pagelimit->value() == 0) + { + msg = i18n("You must specify at least one quota limit."); + return false; + } + return true; +} + +void KMWQuota::initPrinter(KMPrinter *p) +{ + int qu(-1), si(0), pa(0), un(3); + qu = p->option("job-quota-period").toInt(); + si = p->option("job-k-limit").toInt(); + pa = p->option("job-page-limit").toInt(); + if (si == 0 && pa == 0) + // no quota + qu = -1; + m_sizelimit->setValue(si); + m_pagelimit->setValue(pa); + if (qu > 0) + { + un = findUnit(qu); + } + m_timeunit->setCurrentItem(un); + m_period->setValue(qu); +} + +void KMWQuota::updatePrinter(KMPrinter *p) +{ + int qu(m_period->value()), si(m_sizelimit->value()), pa(m_pagelimit->value()); + if (qu == -1) + { + // no quota, set limits to 0 + si = 0; + pa = 0; + qu = 0; + } + qu *= time_periods[m_timeunit->currentItem()]; + + p->setOption("job-quota-period", QString::number(qu)); + p->setOption("job-k-limit", QString::number(si)); + p->setOption("job-page-limit", QString::number(pa)); +} +#include "kmwquota.moc" diff --git a/kdeprint/cups/kmwquota.h b/kdeprint/cups/kmwquota.h new file mode 100644 index 000000000..88b6359c9 --- /dev/null +++ b/kdeprint/cups/kmwquota.h @@ -0,0 +1,46 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KMWQUOTA_H +#define KMWQUOTA_H + +#include <kmwizardpage.h> + +class QSpinBox; +class QComboBox; + +class KMWQuota : public KMWizardPage +{ + Q_OBJECT +public: + KMWQuota(QWidget *parent = 0, const char *name = 0); + virtual ~KMWQuota(); + + bool isValid(QString&); + void initPrinter(KMPrinter*); + void updatePrinter(KMPrinter*); + +private: + QSpinBox *m_period; + QSpinBox *m_sizelimit; + QSpinBox *m_pagelimit; + QComboBox *m_timeunit; +}; + +#endif diff --git a/kdeprint/cups/kmwusers.cpp b/kdeprint/cups/kmwusers.cpp new file mode 100644 index 000000000..3dedddd47 --- /dev/null +++ b/kdeprint/cups/kmwusers.cpp @@ -0,0 +1,96 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include <config.h> + +#include "kmwusers.h" +#include "kmwizard.h" +#include "kmprinter.h" + +#include <qlabel.h> +#include <qlayout.h> +#include <qcombobox.h> +#include <klocale.h> +#include <keditlistbox.h> + +KMWUsers::KMWUsers(QWidget *parent, const char *name) +: KMWizardPage(parent, name) +{ + m_ID = KMWizard::Custom+4; + m_title = i18n("Users Access Settings"); + m_nextpage = KMWizard::Name; + + m_users = new KEditListBox(i18n("Users"), this, 0, false, KEditListBox::Add|KEditListBox::Remove); + m_type = new QComboBox(this); + m_type->insertItem(i18n("Allowed Users")); + m_type->insertItem(i18n("Denied Users")); + + QLabel *lab1 = new QLabel(i18n("Define here a group of allowed/denied users for this printer."), this); + QLabel *lab2 = new QLabel(i18n("&Type:"), this); + + lab2->setBuddy(m_type); + + QVBoxLayout *l0 = new QVBoxLayout(this, 0, 10); + QHBoxLayout *l1 = new QHBoxLayout(0, 0, 10); + l0->addWidget(lab1, 0); + l0->addLayout(l1, 0); + l1->addWidget(lab2, 0); + l1->addWidget(m_type, 1); + l0->addWidget(m_users, 1); +} + +KMWUsers::~KMWUsers() +{ +} + +void KMWUsers::initPrinter(KMPrinter *p) +{ + QStringList l; + int i(1); + if (!p->option("requesting-user-name-denied").isEmpty()) + { + l = QStringList::split(",", p->option("requesting-user-name-denied"), false); + if (l.count() == 1 && l[0] == "none") + l.clear(); + } + else if (!p->option("requesting-user-name-allowed").isEmpty()) + { + i = 0; + l = QStringList::split(",", p->option("requesting-user-name-allowed"), false); + if (l.count() && l[0] == "all") + l.clear(); + } + m_users->insertStringList(l); + m_type->setCurrentItem(i); +} + +void KMWUsers::updatePrinter(KMPrinter *p) +{ + p->removeOption("requesting-user-name-denied"); + p->removeOption("requesting-user-name-allowed"); + + QString str; + if (m_users->count() > 0) + str = m_users->items().join(","); + else + str = (m_type->currentItem() == 0 ? "all" : "none"); + QString optname = (m_type->currentItem() == 0 ? "requesting-user-name-allowed" : "requesting-user-name-denied"); + p->setOption(optname, str); +} +#include "kmwusers.moc" diff --git a/kdeprint/cups/kmwusers.h b/kdeprint/cups/kmwusers.h new file mode 100644 index 000000000..9c970bb54 --- /dev/null +++ b/kdeprint/cups/kmwusers.h @@ -0,0 +1,43 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KMWUSERS_H +#define KMWUSERS_H + +#include <kmwizardpage.h> + +class KEditListBox; +class QComboBox; + +class KMWUsers : public KMWizardPage +{ + Q_OBJECT +public: + KMWUsers(QWidget *parent = 0, const char *name = 0); + virtual ~KMWUsers(); + + void initPrinter(KMPrinter*); + void updatePrinter(KMPrinter*); + +private: + KEditListBox *m_users; + QComboBox *m_type; +}; + +#endif diff --git a/kdeprint/cups/kphpgl2page.cpp b/kdeprint/cups/kphpgl2page.cpp new file mode 100644 index 000000000..c6672aeaf --- /dev/null +++ b/kdeprint/cups/kphpgl2page.cpp @@ -0,0 +1,169 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kphpgl2page.h" + +#include <qcheckbox.h> +#include <qgroupbox.h> +#include <qlayout.h> +#include <qwhatsthis.h> +#include <klocale.h> +#include <knuminput.h> + +KPHpgl2Page::KPHpgl2Page(QWidget *parent, const char *name) +: KPrintDialogPage(parent, name) +{ + //WhatsThis strings.... (added by pfeifle@kde.org) + QString whatsThisBlackplotHpgl2Page = i18n( " <qt> " + " <b>Print in Black Only (Blackplot)</b> " + " <p>The \'blackplot\' option specifies that all pens should plot in black-only:" + " The default is to use the colors defined in the plot file, or the standard " + " pen colors defined in the HP-GL/2 reference manual from Hewlett Packard. </p> " + " <br> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches " + " with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o blackplot=true " + " </pre> " + " </p> " + " </qt>" ); + + QString whatsThisFitplotHpgl2Page = i18n( " <qt> " + " <b>Scale Print Image to Page Size</b> " + " <p>The 'fitplot' option specifies that the HP-GL image should be scaled to fill " + " exactly the page with the (elsewhere selected) media size. </p> " + " <p>The default is 'fitplot is disabled'. The default will therefore use the absolute " + " distances specified in the plot file. (You should be aware that HP-GL files are very " + " often CAD drawings intended for large format plotters. On standard office printers " + " they will therefore lead to the drawing printout being spread across multiple pages.) </p> " + " <p><b>Note:</b>This feature depends upon an accurate plot size (PS) command in the " + " HP-GL/2 file. If no plot size is given in the file the filter converting the HP-GL " + " to PostScript assumes the plot is ANSI E size. </p> " + " <br> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches with the CUPS commandline job option parameter:</em> " + " <pre> " + " -o fitplot=true " + " </pre>" + " </p> " + " </qt>" ); + + QString whatsThisPenwidthHpgl2Page = i18n( " <qt> " + " <b>Set Pen Width for HP-GL (if not defined in file)</b>. " + " <p>The pen width value can be set here in case the original HP-GL file does not have it " + " set. The pen width specifies the value in micrometers. The default value of 1000 produces " + " lines that are 1000 micrometers == 1 millimeter in width. Specifying a pen width of 0 " + " produces lines that are exactly 1 pixel wide. </p> " + " <p><b>Note:</b> The penwidth option set here is ignored if the pen widths are set inside " + " the plot file itself..</p> " + " <br> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o penwidth=... # example: \"2000\" or \"500\" " + " </pre>" + " </p> " + " </qt>" ); + + QString whatsThisAllOptionsHpgl2Page = i18n( " <qt> " + " <b>HP-GL Print Options</b> " + " <p>All options on this page are only applicable if you use KDEPrint to send HP-GL and " + " HP-GL/2 files to one of your printers. </p> " + " <p>HP-GL and HP-GL/2 are page description languages developed by Hewlett-Packard to drive " + " Pen Plotting devices. </p> " + " <p>KDEPrint can (with the help of CUPS) convert the HP-GL file format and print it " + " on any installed printer. </p> " + " <p><b>Note 1:</b> To print HP-GL files, start 'kprinter' and simply load the file into " + " the running kprinter.</p>" + " <p><b>Note 2:</b> The 'fitplot' parameter provided on this dialog does also work for " + " printing PDF files (if your CUPS version is more recent than 1.1.22).</p> " + " <br> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> These KDEPrint GUI elements match with CUPS commandline job option parameters:</em> " + " <pre>" + " -o blackplot=... # examples: \"true\" or \"false\" " + " <br> " + " -o fitplot=... # examples: \"true\" or \"false\" " + " <br> " + " -o penwidth=... # examples: \"true\" or \"false\" " + " </pre>" + " </p> " + " </qt>" ); + + + setTitle("HP-GL/2"); + + QGroupBox *box = new QGroupBox(0, Qt::Vertical, i18n("HP-GL/2 Options"), this); + + m_blackplot = new QCheckBox(i18n("&Use only black pen"), box); + QWhatsThis::add(m_blackplot, whatsThisBlackplotHpgl2Page); + + m_fitplot = new QCheckBox(i18n("&Fit plot to page"), box); + QWhatsThis::add(m_fitplot, whatsThisFitplotHpgl2Page); + + m_penwidth = new KIntNumInput(1000, box); + m_penwidth->setLabel(i18n("&Pen width:"), Qt::AlignLeft|Qt::AlignVCenter); + m_penwidth->setSuffix(" [um]"); + m_penwidth->setRange(0, 10000, 100, true); + QWhatsThis::add(m_penwidth, whatsThisPenwidthHpgl2Page); + + QVBoxLayout *l0 = new QVBoxLayout(this, 0, 10); + l0->addWidget(box); + l0->addStretch(1); + + QVBoxLayout *l1 = new QVBoxLayout(box->layout(), 10); + l1->addWidget(m_blackplot); + l1->addWidget(m_fitplot); + l1->addWidget(m_penwidth); + QWhatsThis::add(this, whatsThisAllOptionsHpgl2Page); +} + +KPHpgl2Page::~KPHpgl2Page() +{ +} + +void KPHpgl2Page::setOptions(const QMap<QString,QString>& opts) +{ + QString value; + if (opts.contains("blackplot") && ((value=opts["blackplot"]).isEmpty() || value == "true")) + m_blackplot->setChecked(true); + if (opts.contains("fitplot") && ((value=opts["fitplot"]).isEmpty() || value == "true")) + m_fitplot->setChecked(true); + if (!(value=opts["penwidth"]).isEmpty()) + m_penwidth->setValue(value.toInt()); +} + +void KPHpgl2Page::getOptions(QMap<QString,QString>& opts, bool incldef) +{ + if (incldef || m_penwidth->value() != 1000) + opts["penwidth"] = QString::number(m_penwidth->value()); + if (m_blackplot->isChecked()) + opts["blackplot"] = "true"; + else if (incldef) + opts["blackplot"] = "false"; + else + opts.remove("blackplot"); + if (m_fitplot->isChecked()) + opts["fitplot"] = "true"; + else if (incldef) + opts["fitplot"] = "false"; + else + opts.remove("fitplot"); +} diff --git a/kdeprint/cups/kphpgl2page.h b/kdeprint/cups/kphpgl2page.h new file mode 100644 index 000000000..206c409d8 --- /dev/null +++ b/kdeprint/cups/kphpgl2page.h @@ -0,0 +1,42 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KPHPGL2PAGE_H +#define KPHPGL2PAGE_H + +#include "kprintdialogpage.h" + +class KIntNumInput; +class QCheckBox; + +class KPHpgl2Page : public KPrintDialogPage +{ +public: + KPHpgl2Page(QWidget *parent = 0, const char *name = 0); + ~KPHpgl2Page(); + + void setOptions(const QMap<QString,QString>& opts); + void getOptions(QMap<QString,QString>& opts, bool incldef = false); + +private: + KIntNumInput *m_penwidth; + QCheckBox *m_blackplot, *m_fitplot; +}; + +#endif diff --git a/kdeprint/cups/kpimagepage.cpp b/kdeprint/cups/kpimagepage.cpp new file mode 100644 index 000000000..9ebdc9548 --- /dev/null +++ b/kdeprint/cups/kpimagepage.cpp @@ -0,0 +1,503 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kpimagepage.h" +#include "imageposition.h" +#include "imagepreview.h" +#include "driver.h" + +#include <qcombobox.h> +#include <qbuttongroup.h> +#include <qradiobutton.h> +#include <qgroupbox.h> +#include <qpushbutton.h> +#include <qapplication.h> +#include <qimage.h> +#include <qlabel.h> +#include <qlayout.h> +#include <qwhatsthis.h> +#include <klocale.h> +#include <knuminput.h> +#include <kseparator.h> +#include <kstandarddirs.h> + +KPImagePage::KPImagePage(DrMain *driver, QWidget *parent, const char *name) +: KPrintDialogPage(parent, name) +{ + //WhatsThis strings.... (added by pfeifle@kde.org) + QString whatsThisBrightnessImagePage = i18n( " <qt> " + " <p><b>Brightness:</b> Slider to control the brightness value of all colors used.</p>" + " <p> The brightness value can range from 0 to 200. Values greater than 100 will " + " lighten the print. Values less than 100 will darken the print. </p> " + " <br> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches " + " with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o brightness=... # use range from \"0\" to \"200\" " + " </pre> " + " </p> " + " </qt>" ); + + QString whatsThisHueImagePage = i18n( " <qt> " + " <p><b>Hue (Tint):</b> Slider to control the hue value for color rotation.</p>" + " <p> The hue value is a number from -360 to 360 and represents the color hue rotation. " + " The following table summarizes the change you will see for the base colors: " + " <center> " + " <table border=\"1\" width=\"70%\"> " + " <tr><th><b>Original</b></th> <th><b>hue=-45</b></th> <th><b>hue=45</b></th> </tr> " + " <tr><td>Red</td> <td>Purple</td> <td>Yellow-orange</td> </tr> " + " <tr><td>Green</td> <td>Yellow-green</td> <td>Blue-green</td> </tr> " + " <tr><td>Yellow</td> <td>Orange</td> <td>Green-yellow</td> </tr> " + " <tr><td>Blue</td> <td>Sky-blue</td> <td>Purple</td> </tr> " + " <tr><td>Magenta</td> <td>Indigo</td> <td>Crimson</td> </tr> " + " <tr><td>Cyan</td> <td>Blue-green</td> <td>Light-navy-blue</td> </tr> " + " </table> " + " </center> " + " <br> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches " + " with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o hue=... # use range from \"-360\" to \"360\" " + " </pre>" + " </p> " + " </qt>" ); + + QString whatsThisSaturationImagePage = i18n( " <qt> " + " <p><b>Saturation:</b> Slider to control the saturation value for all colors used.</p>" + " <p> The saturation value adjusts the saturation of the colors in an image, similar to " + " the color knob on your television. The color saturation value.can range from 0 to 200." + " On inkjet printers, a higher saturation value uses more ink. On laserjet printers, a " + " higher saturation uses more toner. " + " A color saturation of 0 produces a black-and-white print, while a value of 200 will " + " make the colors extremely intense. </p>" + " <br> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches " + " with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o saturation=... # use range from \"0\" to \"200\" " + " </pre>" + " </p> " + " </qt>" ); + + QString whatsThisGammaImagePage = i18n( " <qt> " + " <p><b>Gamma:</b> Slider to control the gamma value for color correction.</p>" + " <p> The gamma value can range from 1 to 3000. " + " A gamma values greater than 1000 lightens the print. A gamma value less than 1000 " + " darken the print. The default gamma is 1000. </p>" + " <p><b>Note:</b></p> the gamma value adjustment is not visible in the thumbnail " + " preview. </p> " + " <br> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches " + " with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o gamma=... # use range from \"1\" to \"3000\" " + " </pre>" + " </p> " + " </qt>" ); + + QString whatsThisImagePage = i18n( " <qt> " + " <p><b>Image Printing Options</b></p> " + " <p>All options controlled on this page only apply to printing images. " + " Most image file formats are supported. To name a few: JPEG, TIFF, PNG, GIF, " + " PNM (PBM/PGM/PNM/PPM), Sun Raster, SGI RGB, Windows BMP." + " Options to influence color output of image printouts are: " + " <ul> " + " <li> Brightness </li>" + " <li> Hue </li>" + " <li> Saturation </li>" + " <li> Gamma </li>" + " </ul> " + " <p>For a more detailed explanation about Brightness, Hue, Saturation and Gamma settings, please " + " look at the 'WhatsThis' items provided for these controls. " + " </p> " + " </p> " + " </qt>" ); + + QString whatsThisColorationPreviewImagePage = i18n( " <qt> " + " <p><b>Coloration Preview Thumbnail</b></p> " + " <p>The coloration preview thumbnail indicates change of image coloration by different settings. " + " Options to influence output are: " + " <ul> " + " <li> Brightness </li>" + " <li> Hue (Tint) </li>" + " <li> Saturation </li>" + " <li> Gamma </li>" + " </ul> " + " </p> " + " <p>For a more detailed explanation about Brightness, Hue, Saturation and Gamma settings, please " + " look at the 'WhatsThis' items provided for these controls. " + " </p> " + " </qt>" ); + + QString whatsThisSizeImagePage = i18n( " <qt> " + " <p><b>Image Size:</b> Dropdown menu to control the image size on the printed paper. Dropdown " + " works in conjunction with slider below. Dropdown options are:.</p>" + " <ul> " + " <li> <b>Natural Image Size:</b> Image prints in its natural image size. If it does not fit onto " + " one sheet, the printout will be spread across multiple sheets. Note, that the slider is disabled " + " when selecting 'natural image size' in the dropdown menu. </li>" + " <li> <b>Resolution (ppi):</b> The resolution value slider covers a number range from 1 to 1200. " + " It specifies the resolution of the image in Pixels Per Inch (PPI). An image that is 3000x2400 pixels " + " will print 10x8 inches at 300 pixels per inch, for example, but 5x4 inches at 600 pixels per inch." + " If the specified resolution makes the image larger than the page, multiple pages will be printed. " + " Resolution defaults to 72 ppi. " + " </li>" + " <li> <b>% of Page Size:</b> The percent value slider covers numbers from 1 to 800. It specifies the size " + " in relation to the page (not the image). A scaling of 100 percent will fill the page as completely " + " as the image aspect ratio allows (doing auto-rotation of the image as needed). " + " A scaling of more than 100 will print the image across multiple " + " sheets. A scaling of 200 percent will print on up to 4 pages. </li>" + " Scaling in % of page size defaults to 100 %. " + " <li> <b>% of Natural Image Size:</b> The percent value slider moves from 1 to 800. It specifies " + " the printout size in relation " + " to the natural image size. A scaling of 100 percent will print the image at its natural size, while a " + " scaling of 50 percent will print the image at half its natural size. If the specified scaling makes " + " the image larger than the page, multiple pages will be printed. " + " Scaling in % of natural image size defaults to 100 %. " + " </ul> " + " <br> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches " + " with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o natural-scaling=... # range in % is 1....800 " + " <br> " + " -o scaling=... # range in % is 1....800 " + " <br> " + " -o ppi=... # range in ppi is 1...1200 " + " </pre>" + " </p> " + " </qt>" ); + + QString whatsThisPreviewPositionImagePage = i18n( " <qt> " + " <p><b>Position Preview Thumbnail</b></p> " + " <p>This position preview thumbnail indicates the position of the image on the paper sheet. " + " <p>Click on horizontal and vertical radio buttons to move image alignment on paper around. Options are: " + " <ul> " + " <li> center </li>" + " <li> top </li>" + " <li> top-left </li>" + " <li> left </li>" + " <li> bottom-left </li>" + " <li> bottom </li>" + " <li> bottom-right</li>" + " <li> right </li>" + " <li> top-right </li>" + " </ul> " + " </p> " + " </qt>" ); + + QString whatsThisResetButtonImagePage = i18n( " <qt> " + " <p><b>Reset to Default Values</b> </p> " + " <p> Reset all coloration settings to default values. Default values are: " + " <ul> " + " <li> Brightness: 100 </li>" + " <li> Hue (Tint). 0 </li>" + " <li> Saturation: 100 </li>" + " <li> Gamma: 1000 </li>" + " </ul> " + " </p> " + " </qt>" ); + + QString whatsThisPositionImagePage = i18n( " <qt> " + " <p><b>Image Positioning:</b></p> " + " <p>Select a pair of radiobuttons to " + " move image to the position you want on the paper printout. Default " + " is 'center'. </p> " + " <br> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches " + " with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o position=... # examples: \"top-left\" or \"bottom\" " + " </pre>" + " </p> " + " </qt>" ); + + setTitle(i18n("Image")); + + QGroupBox *colorbox = new QGroupBox(0, Qt::Vertical, i18n("Color Settings"), this); + QWhatsThis::add(this, whatsThisImagePage); + QGroupBox *sizebox = new QGroupBox(0, Qt::Vertical, i18n("Image Size"), this); + QWhatsThis::add(sizebox, whatsThisSizeImagePage); + QGroupBox *positionbox = new QGroupBox(0, Qt::Vertical, i18n("Image Position"), this); + QWhatsThis::add(positionbox, whatsThisPositionImagePage); + + m_brightness = new KIntNumInput(100, colorbox); + m_brightness->setLabel(i18n("&Brightness:")); + m_brightness->setRange(0, 200, 20, true); + QWhatsThis::add(m_brightness, whatsThisBrightnessImagePage); + + m_hue = new KIntNumInput(m_brightness, 0, colorbox); + m_hue->setLabel(i18n("&Hue (Color rotation):")); + m_hue->setRange(-360, 360, 36, true); + QWhatsThis::add(m_hue, whatsThisHueImagePage); + + m_saturation = new KIntNumInput(m_brightness, 100, colorbox); + m_saturation->setLabel(i18n("&Saturation:")); + m_saturation->setRange(0, 200, 20, true); + QWhatsThis::add(m_saturation, whatsThisSaturationImagePage); + + m_gamma = new KIntNumInput(m_saturation, 1000, colorbox); + m_gamma->setLabel(i18n("&Gamma (Color correction):")); + m_gamma->setRange(1, 3000, 100, true); + QWhatsThis::add(m_gamma, whatsThisGammaImagePage); + + connect(m_brightness, SIGNAL(valueChanged(int)), SLOT(slotImageSettingsChanged())); + connect(m_hue, SIGNAL(valueChanged(int)), SLOT(slotImageSettingsChanged())); + connect(m_saturation, SIGNAL(valueChanged(int)), SLOT(slotImageSettingsChanged())); + //connect(m_gamma, SIGNAL(valueChanged(int)), SLOT(slotImageSettingsChanged())); + + m_preview = new ImagePreview(colorbox); + bool useColor = (driver ? driver->get("colordevice") == "1" : true); + m_preview->setBlackAndWhite(!useColor); + QWhatsThis::add(m_preview, whatsThisColorationPreviewImagePage); + + m_hue->setEnabled(useColor); + m_saturation->setEnabled(useColor); + QImage img(locate("data", "kdeprint/preview.png")); + m_preview->setImage(img); + + KSeparator *sep = new KSeparator(Qt::Horizontal, colorbox); + + QPushButton *defbtn = new QPushButton(i18n("&Default Settings"), colorbox); + QWhatsThis::add(defbtn, whatsThisResetButtonImagePage); + connect(defbtn, SIGNAL(clicked()), SLOT(slotDefaultClicked())); + slotDefaultClicked(); + + m_sizetype = new QComboBox(sizebox); + m_sizetype->insertItem(i18n("Natural Image Size")); + m_sizetype->insertItem(i18n("Resolution (ppi)")); + // xgettext:no-c-format + m_sizetype->insertItem(i18n("% of Page")); + // xgettext:no-c-format + m_sizetype->insertItem(i18n("% of Natural Image Size")); + + m_size = new KIntNumInput(sizebox); + m_size->setRange(1, 1200, 20, true); + m_size->setValue(72); + + connect(m_sizetype, SIGNAL(activated(int)), SLOT(slotSizeTypeChanged(int))); + m_sizetype->setCurrentItem(0); + slotSizeTypeChanged(0); + + QLabel *lab = new QLabel(i18n("&Image size type:"), sizebox); + lab->setBuddy(m_sizetype); + + m_position = new ImagePosition(positionbox); + QWhatsThis::add(m_position, whatsThisPreviewPositionImagePage); + + QRadioButton *bottom = new QRadioButton(positionbox); + QRadioButton *top = new QRadioButton(positionbox); + QRadioButton *vcenter = new QRadioButton(positionbox); + QRadioButton *left = new QRadioButton(positionbox); + QRadioButton *right = new QRadioButton(positionbox); + QRadioButton *hcenter = new QRadioButton(positionbox); + QSize sz = bottom->sizeHint(); + bottom->setFixedSize(sz); + vcenter->setFixedSize(sz); + top->setFixedSize(sz); + left->setFixedSize(sz); + hcenter->setFixedSize(sz); + right->setFixedSize(sz); + + m_vertgrp = new QButtonGroup(positionbox); + m_vertgrp->hide(); + + m_horizgrp = new QButtonGroup(positionbox); + m_horizgrp->hide(); + + m_vertgrp->insert(top, 0); + m_vertgrp->insert(vcenter, 1); + m_vertgrp->insert(bottom, 2); + if ( QApplication::reverseLayout() ) + { + m_horizgrp->insert(left, 2); + m_horizgrp->insert(hcenter, 1); + m_horizgrp->insert(right, 0); + } + else + { + m_horizgrp->insert(left, 0); + m_horizgrp->insert(hcenter, 1); + m_horizgrp->insert(right, 2); + } + connect(m_vertgrp, SIGNAL(clicked(int)), SLOT(slotPositionChanged())); + connect(m_horizgrp, SIGNAL(clicked(int)), SLOT(slotPositionChanged())); + m_vertgrp->setButton(1); + m_horizgrp->setButton(1); + slotPositionChanged(); + + QGridLayout *l0 = new QGridLayout(this, 2, 2, 0, 10); + l0->addMultiCellWidget(colorbox, 0, 0, 0, 1); + l0->addWidget(sizebox, 1, 0); + l0->addWidget(positionbox, 1, 1); + l0->setColStretch(0, 1); + QGridLayout *l1 = new QGridLayout(colorbox->layout(), 5, 2, 10); + l1->addWidget(m_brightness, 0, 0); + l1->addWidget(m_hue, 1, 0); + l1->addWidget(m_saturation, 2, 0); + l1->addWidget(sep, 3, 0); + l1->addWidget(m_gamma, 4, 0); + l1->addMultiCellWidget(m_preview, 0, 3, 1, 1); + l1->addWidget(defbtn, 4, 1); + QVBoxLayout *l2 = new QVBoxLayout(sizebox->layout(), 3); + l2->addStretch(1); + l2->addWidget(lab); + l2->addWidget(m_sizetype); + l2->addSpacing(10); + l2->addWidget(m_size); + l2->addStretch(1); + QGridLayout *l3 = new QGridLayout(positionbox->layout(), 2, 2, 10); + QHBoxLayout *l4 = new QHBoxLayout(0, 0, 10); + QVBoxLayout *l5 = new QVBoxLayout(0, 0, 10); + l3->addLayout(l4, 0, 1); + l3->addLayout(l5, 1, 0); + l3->addWidget(m_position, 1, 1); + l4->addWidget(left, Qt::AlignLeft); + l4->addWidget(hcenter, Qt::AlignCenter); + l4->addWidget(right, Qt::AlignRight); + l5->addWidget(top, Qt::AlignTop); + l5->addWidget(vcenter, Qt::AlignVCenter); + l5->addWidget(bottom, Qt::AlignBottom); +} + +KPImagePage::~KPImagePage() +{ +} + +void KPImagePage::setOptions(const QMap<QString,QString>& opts) +{ + QString value; + if (!(value=opts["brightness"]).isEmpty()) + m_brightness->setValue(value.toInt()); + if (!(value=opts["hue"]).isEmpty()) + m_hue->setValue(value.toInt()); + if (!(value=opts["saturation"]).isEmpty()) + m_saturation->setValue(value.toInt()); + if (!(value=opts["gamma"]).isEmpty()) + m_gamma->setValue(value.toInt()); + + int type = 0; + int ival(0); + if ((ival = opts["ppi"].toInt()) != 0) + type = 1; + else if ((ival = opts["scaling"].toInt()) != 0) + type = 2; + else if (!opts["natural-scaling"].isEmpty() && (ival = opts["natural-scaling"].toInt()) != 1) + type = 3; + m_sizetype->setCurrentItem(type); + slotSizeTypeChanged(type); + if (type != 0) + m_size->setValue(ival); + + if (!(value=opts["position"]).isEmpty()) + { + m_position->setPosition(value.latin1()); + int pos = m_position->position(); + m_vertgrp->setButton(pos/3); + m_horizgrp->setButton(pos%3); + } +} + +void KPImagePage::getOptions(QMap<QString,QString>& opts, bool incldef) +{ + if (incldef || m_brightness->value() != 100) + opts["brightness"] = QString::number(m_brightness->value()); + if (m_hue->isEnabled()) + { + if (incldef || m_hue->value() != 0) + opts["hue"] = QString::number(m_hue->value()); + if (incldef || m_saturation->value() != 100) + opts["saturation"] = QString::number(m_saturation->value()); + } + if (incldef || m_gamma->value() != 1000) + opts["gamma"] = QString::number(m_gamma->value()); + + QString name; + if (incldef) + { + opts["ppi"] = "0"; + opts["scaling"] = "0"; + opts["natural-scaling"] = "1"; + } + switch (m_sizetype->currentItem()) + { + case 0: break; + case 1: name = "ppi"; break; + case 2: name = "scaling"; break; + case 3: name = "natural-scaling"; break; + } + if (!name.isEmpty()) + opts[name] = QString::number(m_size->value()); + + if (incldef || m_position->position() != ImagePosition::Center) + opts["position"] = m_position->positionString(); +} + +void KPImagePage::slotSizeTypeChanged(int t) +{ + m_size->setEnabled(t > 0); + if (t > 0) + { + int minval, maxval, defval; + if (t == 1) + { + minval = 1; + maxval = 1200; + defval = 72; + } + else + { + minval = 1; + maxval = 800; + defval = 100; + } + m_size->setRange(minval, maxval); + m_size->setValue(defval); + } +} + +void KPImagePage::slotPositionChanged() +{ + int h = m_horizgrp->id(m_horizgrp->selected()), v = m_vertgrp->id(m_vertgrp->selected()); + m_position->setPosition(h, v); +} + +void KPImagePage::slotImageSettingsChanged() +{ + int b = m_brightness->value(), h = m_hue->value(), s = m_saturation->value(); + //int g = m_gamma->value(); + int g = 1000; + m_preview->setParameters(b, h, s, g); +} + +void KPImagePage::slotDefaultClicked() +{ + m_brightness->setValue(100); + m_hue->setValue(0); + m_saturation->setValue(100); + m_gamma->setValue(1000); +} + +#include "kpimagepage.moc" diff --git a/kdeprint/cups/kpimagepage.h b/kdeprint/cups/kpimagepage.h new file mode 100644 index 000000000..9ec623686 --- /dev/null +++ b/kdeprint/cups/kpimagepage.h @@ -0,0 +1,56 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KPIMAGEPAGE_H +#define KPIMAGEPAGE_H + +#include "kprintdialogpage.h" + +class KIntNumInput; +class QComboBox; +class QButtonGroup; +class ImagePreview; +class ImagePosition; + +class KPImagePage : public KPrintDialogPage +{ + Q_OBJECT +public: + KPImagePage(DrMain *driver = 0, QWidget *parent = 0, const char *name = 0); + ~KPImagePage(); + + void setOptions(const QMap<QString,QString>& opts); + void getOptions(QMap<QString,QString>& opts, bool incldef = false); + +protected slots: + void slotSizeTypeChanged(int); + void slotPositionChanged(); + void slotImageSettingsChanged(); + void slotDefaultClicked(); + +private: + KIntNumInput *m_brightness, *m_hue, *m_saturation, *m_gamma; + QComboBox *m_sizetype; + KIntNumInput *m_size; + QButtonGroup *m_vertgrp, *m_horizgrp; + ImagePreview *m_preview; + ImagePosition *m_position; +}; + +#endif diff --git a/kdeprint/cups/kpschedulepage.cpp b/kdeprint/cups/kpschedulepage.cpp new file mode 100644 index 000000000..a698b1d51 --- /dev/null +++ b/kdeprint/cups/kpschedulepage.cpp @@ -0,0 +1,282 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kpschedulepage.h" + +#include <qlabel.h> +#include <qlayout.h> +#include <qcombobox.h> +#include <qregexp.h> +#include <qdatetimeedit.h> +#include <qdatetime.h> +#include <qlineedit.h> +#include <qwhatsthis.h> +#include <klocale.h> +#include <kseparator.h> +#include <knuminput.h> + +#include <time.h> + +KPSchedulePage::KPSchedulePage(QWidget *parent, const char *name) +: KPrintDialogPage(parent, name) +{ + //WhatsThis strings.... (added by pfeifle@kde.org) + QString whatsThisBillingInfo = i18n( " <qt> <p><b>Print Job Billing and Accounting</b></p> " + " <p>Insert a meaningful string here to associate" + " the current print job with a certain account. This" + " string will appear in the CUPS \"page_log\" to help" + " with the print accounting in your organization. (Leave" + " it empty if you do not need it.)" + " <p> It is useful for people" + " who print on behalf of different \"customers\", like" + " print service bureaux, letter shops, press and prepress" + " companies, or secretaries who serve different bosses, etc.</p>" + " <br> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches " + " with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o job-billing=... # example: \"Marketing_Department\" or \"Joe_Doe\" " + " </pre>" + " </p> " + " </qt>" ); + + QString whatsThisScheduledPrinting = i18n(" <qt> <p><b>Scheduled Printing</b></p> " + " <p>Scheduled printing lets you control the time" + " of the actual printout, while you can still send away your" + " job <b>now</b> and have it out of your way." + " <p> Especially useful" + " is the \"Never (hold indefinitely)\" option. It allows you" + " to park your job until a time when you (or a printer administrator)" + " decides to manually release it." + " <p> This is often required in" + " enterprise environments, where you normally are not" + " allowed to directly and immediately access the huge production" + " printers in your <em>Central Repro Department</em>. However it" + " is okay to send jobs to the queue which is under the control of the" + " operators (who, after all, need to make sure that the 10,000" + " sheets of pink paper which is required by the Marketing" + " Department for a particular job are available and loaded" + " into the paper trays).</p>" + " <br> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches " + " with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o job-hold-until=... # example: \"indefinite\" or \"no-hold\" " + " </pre>" + " </p> " + " </qt>" ); + + QString whatsThisPageLabel = i18n( " <qt> <p><b>Page Labels</b></p> " + " <p>Page Labels are printed by CUPS at the top and bottom" + " of each page. They appear on the pages surrounded by a little" + " frame box." + " <p>They contain any string you type into the line edit field.</p>" + " <br> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches " + " with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o page-label=\"...\" # example: \"Company Confidential\" " + " </pre>" + " </p> " + " </qt>" ); + + QString whatsThisJobPriority = i18n( " <qt> <p><b>Job Priority</b></p> " + " <p>Usually CUPS prints all jobs per queue according to" + " the \"FIFO\" principle: <em>First In, First Out</em>." + " <p> The" + " job priority option allows you to re-order the queue according" + " to your needs." + " <p> It works in both directions: you can increase" + " as well as decrease priorities. (Usually you can only control" + " your <b>own</b> jobs)." + " <p> Since the default job priority is \"50\", any job sent" + " with, for example, \"49\" will be printed only after all those" + " others have finished. Conversely, a" + " \"51\" or higher priority job will go right to the top of" + " a populated queue (if no other, higher prioritized one is present).</p>" + " <br> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches " + " with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o job-priority=... # example: \"10\" or \"66\" or \"99\" " + " </pre>" + " </p> " + " </qt>" ); + + setTitle(i18n("Advanced Options")); + setOnlyRealPrinters(true); + + // compute difference in hours between GMT and local time + time_t ct = time(0); + struct tm *ts = gmtime(&ct); + m_gmtdiff = ts->tm_hour; + ts = localtime(&ct); + m_gmtdiff -= ts->tm_hour; + + m_time = new QComboBox(this); + m_time->insertItem(i18n("Immediately")); + m_time->insertItem(i18n("Never (hold indefinitely)")); + m_time->insertItem(i18n("Daytime (6 am - 6 pm)")); + m_time->insertItem(i18n("Evening (6 pm - 6 am)")); + m_time->insertItem(i18n("Night (6 pm - 6 am)")); + m_time->insertItem(i18n("Weekend")); + m_time->insertItem(i18n("Second Shift (4 pm - 12 am)")); + m_time->insertItem(i18n("Third Shift (12 am - 8 am)")); + m_time->insertItem(i18n("Specified Time")); + QWhatsThis::add(m_time, whatsThisScheduledPrinting); + m_tedit = new QTimeEdit(this); + m_tedit->setAutoAdvance(true); + m_tedit->setTime(QTime::currentTime()); + m_tedit->setEnabled(false); + QWhatsThis::add(m_tedit, whatsThisScheduledPrinting); + m_billing = new QLineEdit(this); + QWhatsThis::add(m_billing, whatsThisBillingInfo); + m_pagelabel = new QLineEdit(this); + QWhatsThis::add(m_pagelabel, whatsThisPageLabel); + m_priority = new KIntNumInput(50, this); + QWhatsThis::add(m_priority, whatsThisJobPriority); + m_priority->setRange(1, 100, 10, true); + + QLabel *lab = new QLabel(i18n("&Scheduled printing:"), this); + lab->setBuddy(m_time); + QWhatsThis::add(lab, whatsThisScheduledPrinting); + QLabel *lab1 = new QLabel(i18n("&Billing information:"), this); + QWhatsThis::add(lab1, whatsThisBillingInfo); + lab1->setBuddy(m_billing); + QLabel *lab2 = new QLabel(i18n("T&op/Bottom page label:"), this); + QWhatsThis::add(lab2, whatsThisPageLabel); + lab2->setBuddy(m_pagelabel); + m_priority->setLabel(i18n("&Job priority:"), Qt::AlignVCenter|Qt::AlignLeft); + QWhatsThis::add(m_priority, whatsThisJobPriority); + + KSeparator *sep0 = new KSeparator(this); + sep0->setFixedHeight(10); + + QGridLayout *l0 = new QGridLayout(this, 6, 2, 0, 7); + l0->addWidget(lab, 0, 0); + QHBoxLayout *l1 = new QHBoxLayout(0, 0, 5); + l0->addLayout(l1, 0, 1); + l1->addWidget(m_time); + l1->addWidget(m_tedit); + l0->addWidget(lab1, 1, 0); + l0->addWidget(lab2, 2, 0); + l0->addWidget(m_billing, 1, 1); + l0->addWidget(m_pagelabel, 2, 1); + l0->addMultiCellWidget(sep0, 3, 3, 0, 1); + l0->addMultiCellWidget(m_priority, 4, 4, 0, 1); + l0->setRowStretch(5, 1); + + connect(m_time, SIGNAL(activated(int)), SLOT(slotTimeChanged())); +} + +KPSchedulePage::~KPSchedulePage() +{ +} + +bool KPSchedulePage::isValid(QString& msg) +{ + if (m_time->currentItem() == 8 && !m_tedit->time().isValid()) + { + msg = i18n("The time specified is not valid."); + return false; + } + return true; +} + +void KPSchedulePage::setOptions(const QMap<QString,QString>& opts) +{ + QString t = opts["job-hold-until"]; + if (!t.isEmpty()) + { + int item(-1); + + if (t == "no-hold") item = 0; + else if (t == "indefinite") item = 1; + else if (t == "day-time") item = 2; + else if (t == "evening") item = 3; + else if (t == "night") item = 4; + else if (t == "weekend") item = 5; + else if (t == "second-shift") item = 6; + else if (t == "third-shift") item = 7; + else + { + QTime qt = QTime::fromString(t); + m_tedit->setTime(qt.addSecs(-3600 * m_gmtdiff)); + item = 8; + } + + if (item != -1) + { + m_time->setCurrentItem(item); + slotTimeChanged(); + } + } + QRegExp re("^\"|\"$"); + t = opts["job-billing"].stripWhiteSpace(); + t.replace(re, ""); + m_billing->setText(t); + t = opts["page-label"].stripWhiteSpace(); + t.replace(re, ""); + m_pagelabel->setText(t); + int val = opts["job-priority"].toInt(); + if (val != 0) + m_priority->setValue(val); +} + +void KPSchedulePage::getOptions(QMap<QString,QString>& opts, bool incldef) +{ + if (incldef || m_time->currentItem() != 0) + { + QString t; + switch (m_time->currentItem()) + { + case 0: t = "no-hold"; break; + case 1: t = "indefinite"; break; + case 2: t = "day-time"; break; + case 3: t = "evening"; break; + case 4: t = "night"; break; + case 5: t = "weekend"; break; + case 6: t = "second-shift"; break; + case 7: t = "third-shift"; break; + case 8: + t = m_tedit->time().addSecs(3600 * m_gmtdiff).toString(); + break; + } + opts["job-hold-until"] = t; + } + if (incldef || !m_billing->text().isEmpty()) + opts["job-billing"] = "\"" + m_billing->text() + "\""; + if (incldef || !m_pagelabel->text().isEmpty()) + opts["page-label"] = "\"" + m_pagelabel->text() + "\""; + if (incldef || m_priority->value() != 50) + opts["job-priority"] = QString::number(m_priority->value()); +} + +void KPSchedulePage::slotTimeChanged() +{ + m_tedit->setEnabled(m_time->currentItem() == 8); + if (m_time->currentItem() == 8) + m_tedit->setFocus(); +} + +#include "kpschedulepage.moc" diff --git a/kdeprint/cups/kpschedulepage.h b/kdeprint/cups/kpschedulepage.h new file mode 100644 index 000000000..b8a5946fe --- /dev/null +++ b/kdeprint/cups/kpschedulepage.h @@ -0,0 +1,52 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KPSCHEDULEPAGE_H +#define KPSCHEDULEPAGE_H + +#include <kprintdialogpage.h> + +class QComboBox; +class QTimeEdit; +class QLineEdit; +class KIntNumInput; + +class KPSchedulePage : public KPrintDialogPage +{ + Q_OBJECT +public: + KPSchedulePage(QWidget *parent = 0, const char *name = 0); + ~KPSchedulePage(); + + void getOptions(QMap<QString,QString>& opts, bool incldef = false); + void setOptions(const QMap<QString,QString>& opts); + bool isValid(QString& msg); + +protected slots: + void slotTimeChanged(); + +private: + QComboBox *m_time; + QTimeEdit *m_tedit; + QLineEdit *m_billing, *m_pagelabel; + KIntNumInput *m_priority; + int m_gmtdiff; +}; + +#endif diff --git a/kdeprint/cups/kptagspage.cpp b/kdeprint/cups/kptagspage.cpp new file mode 100644 index 000000000..ec7e451b7 --- /dev/null +++ b/kdeprint/cups/kptagspage.cpp @@ -0,0 +1,164 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kptagspage.h" + +#include <qtable.h> +#include <qheader.h> +#include <qlayout.h> +#include <qlabel.h> +#include <qregexp.h> +#include <qwhatsthis.h> + +#include <klocale.h> + +KPTagsPage::KPTagsPage(bool ro, QWidget *parent, const char *name) +: KPrintDialogPage(parent, name) +{ + + //WhatsThis strings.... (added by pfeifle@kde.org) + QString whatsThisAdditionalTagsTable = i18n(" <qt><p><b>Additional Tags</b></p>" + " You may send additional commands to the CUPS server via this editable list. " + " There are 3 purposes for this:" + " <ul>" + " <li>Use any current or future standard CUPS job option not supported by the " + " KDEPrint GUI. </li>" + " <li>Control any custom job option you may want to support in custom CUPS filters " + " and backends plugged into the CUPS filtering chain.</li> " + " <li>Send short messages to the operators of your production printers in your " + " <em>Central Repro Department</em>." + " </ul> " + " <p><b>Standard CUPS job options:</b> A complete list of standard CUPS job " + " options is in the <a href=\"http://localhost:631/sum.html\">CUPS User Manual</a>. " + " Mappings of the kprinter user interface widgets to respective CUPS job option " + " names are named in the various <em>WhatsThis</em> help items..</p>" + " <p><b>Custom CUPS job options:</b> CUPS print servers may be customized with additional " + " print filters and backends which understand custom job options. You can specify such " + " custom job options here. If in doubt, ask your system administrator..</p>" + " <p><b> </b></p>" + " <p><b>Operator Messages:</b> You may send additional messages to the operator(s) of your" + " production printers (e.g. in your <em>Central Repro Department</p>)" + " Messages can be read by the operator(s) (or yourself) by viewing" + " the <em>\"Job IPP Report\"</em> for the job.</p>" + " <b>Examples:</b><br>" + " <pre>" + " A standard CUPS job option:<br> " + " <em>(Name) number-up</em> -- <em>(Value) 9</em> <br>" + " <br>" + " A job option for custom CUPS filters or backends:<br> " + " <em>(Name) DANKA_watermark</em> -- <em>(Value) Company_Confidential</em> <br>" + " <br>" + " A message to the operator(s):<br> " + " <em>(Name) Deliver_after_completion</em> -- <em>(Value) to_Marketing_Departm.</em><br>" + " </pre>" + " <p><b>Note:</b> the fields must not include spaces, tabs or quotes. You may need to " + " double-click on a field to edit it." + " <p><b>Warning:</b> Do not use such standard CUPS option names which also can be used " + " through the KDEPrint GUI. Results may be unpredictable if they conflict, " + " or if they are sent multiple times. For all options supported by the GUI, please do use " + " the GUI. (Each GUI element's 'WhatsThis' names the related CUPS option name.) </p> " + " </qt>" ); + setTitle(i18n("Additional Tags")); + setOnlyRealPrinters(true); + + m_tags = new QTable(10, 2, this); + m_tags->horizontalHeader()->setStretchEnabled(true); + m_tags->horizontalHeader()->setLabel(0, i18n("Name")); + m_tags->horizontalHeader()->setLabel(1, i18n("Value")); + m_tags->setReadOnly(ro); + QWhatsThis::add(m_tags, whatsThisAdditionalTagsTable); + + QVBoxLayout *l0 = new QVBoxLayout(this, 0, 5); + l0->addWidget(m_tags); + + if (ro) + { + QLabel *lab = new QLabel(i18n("Read-Only"), this); + QFont f = lab->font(); + f.setBold(true); + lab->setFont(f); + lab->setAlignment(AlignVCenter|AlignRight); + l0->addWidget(lab); + } +} + +KPTagsPage::~KPTagsPage() +{ +} + +bool KPTagsPage::isValid(QString& msg) +{ + QRegExp re("\\s"); + for (int r=0; r<m_tags->numCols(); r++) + { + QString tag(m_tags->text(r, 0)); + if (tag.isEmpty()) + continue; + else if (tag.find(re) != -1) + { + msg = i18n("The tag name must not contain any spaces, tabs or quotes: <b>%1</b>.").arg(tag); + return false; + } + } + return true; +} + +void KPTagsPage::setOptions(const QMap<QString,QString>& opts) +{ + int r(0); + QRegExp re("^\"|\"$"); + for (QMap<QString,QString>::ConstIterator it=opts.begin(); it!=opts.end() && r<m_tags->numRows(); ++it) + { + if (it.key().startsWith("KDEPrint-")) + { + m_tags->setText(r, 0, it.key().mid(9)); + QString data = it.data(); + m_tags->setText(r, 1, data.replace(re, "")); + r++; + } + } + for (; r<m_tags->numRows(); r++) + { + m_tags->setText(r, 0, QString::null); + m_tags->setText(r, 1, QString::null); + } +} + +void KPTagsPage::getOptions(QMap<QString,QString>& opts, bool) +{ + for (int r=0; r<m_tags->numRows(); r++) + { + QString tag(m_tags->text(r, 0)), val(m_tags->text(r, 1)); + if (!tag.isEmpty()) + { + tag.prepend("KDEPrint-"); + opts[tag] = val.prepend("\"").append("\""); + } + } +} + +QSize KPTagsPage::sizeHint() const +{ + return QSize(-1, -1); +} + +QSize KPTagsPage::minimumSizeHint() const +{ + return QSize(-1, -1); +} diff --git a/kdeprint/cups/kptagspage.h b/kdeprint/cups/kptagspage.h new file mode 100644 index 000000000..2dd55c8d8 --- /dev/null +++ b/kdeprint/cups/kptagspage.h @@ -0,0 +1,44 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KPTAGSPAGE_H +#define KPTAGSPAGE_H + +#include <kprintdialogpage.h> + +class QTable; + +class KPTagsPage : public KPrintDialogPage +{ +public: + KPTagsPage(bool ro = false, QWidget *parent = 0, const char *name = 0); + ~KPTagsPage(); + + void getOptions(QMap<QString,QString>& opts, bool incldef = false); + void setOptions(const QMap<QString,QString>& opts); + bool isValid(QString& msg); + + QSize sizeHint() const; + QSize minimumSizeHint() const; + +private: + QTable *m_tags; +}; + +#endif diff --git a/kdeprint/cups/kptextpage.cpp b/kdeprint/cups/kptextpage.cpp new file mode 100644 index 000000000..b896606e0 --- /dev/null +++ b/kdeprint/cups/kptextpage.cpp @@ -0,0 +1,375 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#include "kptextpage.h" +#include "marginwidget.h" +#include "driver.h" +#include "kprinter.h" + +#include <qbuttongroup.h> +#include <qgroupbox.h> +#include <qlayout.h> +#include <qlabel.h> +#include <qradiobutton.h> +#include <qwhatsthis.h> +#include <knuminput.h> +#include <klocale.h> +#include <kiconloader.h> +#include <kseparator.h> +#include <kdebug.h> + +KPTextPage::KPTextPage(DrMain *driver, QWidget *parent, const char *name) +: KPrintDialogPage(0, driver, parent, name) +{ + //WhatsThis strings.... (added by pfeifle@kde.org) + QString whatsThisCPITextPage = i18n( " <qt> " + " <p><b>Characters Per Inch</b></p> " + " <p>This setting controls the horizontal size of characters when printing a text file. </p>" + " <p>The default value is 10, meaning that the font is scaled in a way that 10 characters " + " per inch will be printed. </p> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches " + " with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o cpi=... # example: \"8\" or \"12\" " + " </pre>" + " </p> " + " </qt>" ); + + QString whatsThisLPITextPage = i18n( " <qt> " + " <p><b>Lines Per Inch</b></p> " + " <p>This setting controls the vertical size of characters when printing a text file. </p>" + " <p>The default value is 6, meaning that the font is scaled in a way that 6 lines " + " per inch will be printed. </p> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches " + " with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o lpi=... # example \"5\" or \"7\" " + " </pre>" + " </p> " + " </qt>" ); + + QString whatsThisColumnsTextPage = i18n( " <qt> " + " <p><b>Columns</b></p> " + " <p>This setting controls how many columns of text will be printed on each page when." + " printing text files. </p> " + " <p>The default value is 1, meaning that only one column of text per page " + " will be printed. </p> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches " + " with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o columns=... # example: \"2\" or \"4\" " + " </pre>" + " </p> " + " </qt>" ); + + QString whatsThisPrettyprintPreviewIconTextPage = i18n( " <qt> " + " Preview icon changes when you turn on or off prettyprint. " + " </qt>" ); + QString whatsThisFormatTextPage = i18n( " <qt> " + " <p><b>Text Formats</b></p> " + " <p>These settings control the appearance of text on printouts. They are only valid for " + " printing text files or input directly through kprinter. </p> " + " <p><b>Note:</b> These settings have no effect whatsoever for other input formats than " + " text, or for printing from applications such as the KDE Advanced Text Editor. (Applications " + " in general send PostScript to the print system, and 'kate' in particular has its own " + " knobs to control the print output. </p>." + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches " + " with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o cpi=... # example: \"8\" or \"12\" " + " <br> " + " -o lpi=... # example: \"5\" or \"7\" " + " <br> " + " -o columns=... # example: \"2\" or \"4\" " + " </pre>" + " </p> " + " </qt>" ); + + QString whatsThisMarginsTextPage = i18n( " <qt> " + " <p><b>Margins</b></p> " + " <p>These settings control the margins of printouts on the paper. They are not valid for " + " jobs originating from applications which define their own page layout internally and " + " send PostScript to KDEPrint (such as KOffice or OpenOffice.org). </p> " + " <p>When printing from KDE applications, such as KMail and Konqueror, or printing an ASCII text " + " file through kprinter, you can choose your preferred margin settings here. </p> " + " <p>Margins may be set individually for each edge of the paper. The combo box at the bottom lets you change " + " the units of measurement between Pixels, Millimeters, Centimeters, and Inches. </p> " + " <p>You can even use the mouse to grab one margin and drag it to the intended position (see the " + " preview picture on the right side). </p> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches " + " with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o page-top=... # example: \"72\" " + " <br> " + " -o page-bottom=... # example: \"24\" " + " <br> " + " -o page-left=... # example: \"36\" " + " <br> " + " -o page-right=... # example: \"12\" " + " </pre>" + " </p> " + " </qt>" ); + + QString whatsThisPrettyprintButtonOnTextPage = i18n( " <qt> " + " <p><b>Turn Text Printing with Syntax Highlighting (Prettyprint) On!</b></p> " + " <p>ASCII text file printouts can be 'prettyfied' by enabling this option. If you do so, " + " a header is printed at the top of each page. The header contains " + " the page number, job title (usually the filename), and the date. In addition, C and " + " C++ keywords are highlighted, and comment lines are italicized.</p>" + " <p>This prettyprint option is handled by CUPS.</p> " + " <p>If you prefer another 'plaintext-to-prettyprint' converter, look for the <em>enscript</em> " + " pre-filter on the <em>Filters</em> tab. </p>" + " <br> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches " + " with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o prettyprint=true. " + " </pre>" + " </p> " + " </qt>" ); + + QString whatsThisPrettyprintButtonOffTextPage = i18n( " <qt> " + " <p><b>Turn Text Printing with Syntax Highlighting (Prettyprint) Off! </b></p> " + " <p>ASCII text file printing with this option turned off are appearing without a page " + " header and without syntax highlighting. (You can still set the page margins, though.) </p> " + " <br> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches " + " with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o prettyprint=false " + " </pre>" + " </p> " + " </qt>" ); + + QString whatsThisPrettyprintFrameTextPage = i18n( " <qt> " + " <p><b>Print Text with Syntax Highlighting (Prettyprint)</b></p> " + " <p>ASCII file printouts can be 'prettyfied' by enabling this option. If you do so, " + " a header is printed at the top of each page. The header contains " + " the page number, job title (usually the filename), and the date. In addition, C and " + " C++ keywords are highlighted, and comment lines are italicized.</p>" + " <p>This prettyprint option is handled by CUPS.</p> " + " <p>If you prefer another 'plaintext-to-prettyprint' converter, look for the <em>enscript</em> " + " pre-filter on the <em>Filters</em> tab. </p> " + " <br> " + " <hr> " + " <p><em><b>Additional hint for power users:</b> This KDEPrint GUI element matches " + " with the CUPS commandline job option parameter:</em> " + " <pre>" + " -o prettyprint=true. " + " <br> " + " -o prettyprint=false " + " </pre>" + " </p> " + " </qt>" ); + + setTitle(i18n("Text")); + m_block = false; + + QGroupBox *formatbox = new QGroupBox(0, Qt::Vertical, i18n("Text Format"), this); + QWhatsThis::add(formatbox, whatsThisFormatTextPage); + QGroupBox *prettybox = new QGroupBox(0, Qt::Vertical, i18n("Syntax Highlighting"), this); + QWhatsThis::add(prettybox, whatsThisPrettyprintFrameTextPage); + QGroupBox *marginbox = new QGroupBox(0, Qt::Vertical, i18n("Margins"), this); + QWhatsThis::add(marginbox, whatsThisMarginsTextPage); + + m_cpi = new KIntNumInput(10, formatbox); + QWhatsThis::add(m_cpi, whatsThisCPITextPage); + m_cpi->setLabel(i18n("&Chars per inch:"), Qt::AlignLeft|Qt::AlignVCenter); + m_cpi->setRange(1, 999, 1, false); + m_lpi = new KIntNumInput(m_cpi, 6, formatbox); + QWhatsThis::add(m_lpi, whatsThisLPITextPage); + m_lpi->setLabel(i18n("&Lines per inch:"), Qt::AlignLeft|Qt::AlignVCenter); + m_lpi->setRange(1, 999, 1, false); + m_columns = new KIntNumInput(m_lpi, 1, formatbox); + QWhatsThis::add(m_columns, whatsThisColumnsTextPage); + m_columns->setLabel(i18n("C&olumns:"), Qt::AlignLeft|Qt::AlignVCenter); + m_columns->setRange(1, 10, 1, false); + KSeparator *sep = new KSeparator(Qt::Horizontal, formatbox); + connect(m_columns, SIGNAL(valueChanged(int)), SLOT(slotColumnsChanged(int))); + + m_prettypix = new QLabel(prettybox); + QWhatsThis::add(m_prettypix, whatsThisPrettyprintPreviewIconTextPage); + m_prettypix->setAlignment(Qt::AlignCenter); + QRadioButton *off = new QRadioButton(i18n("&Disabled"), prettybox); + QWhatsThis::add(off, whatsThisPrettyprintButtonOffTextPage); + QRadioButton *on = new QRadioButton(i18n("&Enabled"), prettybox); + QWhatsThis::add(on, whatsThisPrettyprintButtonOnTextPage); + m_prettyprint = new QButtonGroup(prettybox); + m_prettyprint->hide(); + m_prettyprint->insert(off, 0); + m_prettyprint->insert(on, 1); + m_prettyprint->setButton(0); + connect(m_prettyprint, SIGNAL(clicked(int)), SLOT(slotPrettyChanged(int))); + slotPrettyChanged(0); + + m_margin = new MarginWidget(marginbox); + QWhatsThis::add(m_margin, whatsThisMarginsTextPage); + m_margin->setPageSize(595, 842); + + QGridLayout *l0 = new QGridLayout(this, 2, 2, 0, 10); + l0->addWidget(formatbox, 0, 0); + l0->addWidget(prettybox, 0, 1); + l0->addMultiCellWidget(marginbox, 1, 1, 0, 1); + QVBoxLayout *l1 = new QVBoxLayout(formatbox->layout(), 5); + l1->addWidget(m_cpi); + l1->addWidget(m_lpi); + l1->addWidget(sep); + l1->addWidget(m_columns); + QGridLayout *l2 = new QGridLayout(prettybox->layout(), 2, 2, 10); + l2->addWidget(off, 0, 0); + l2->addWidget(on, 1, 0); + l2->addMultiCellWidget(m_prettypix, 0, 1, 1, 1); + QVBoxLayout *l3 = new QVBoxLayout(marginbox->layout(), 10); + l3->addWidget(m_margin); +} + +KPTextPage::~KPTextPage() +{ +} + +void KPTextPage::setOptions(const QMap<QString,QString>& opts) +{ + QString value; + + if (!(value=opts["cpi"]).isEmpty()) + m_cpi->setValue(value.toInt()); + if (!(value=opts["lpi"]).isEmpty()) + m_lpi->setValue(value.toInt()); + if (!(value=opts["columns"]).isEmpty()) + m_columns->setValue(value.toInt()); + int ID(0); + if (opts.contains("prettyprint") && (opts["prettyprint"].isEmpty() || opts["prettyprint"] == "true")) + ID = 1; + m_prettyprint->setButton(ID); + slotPrettyChanged(ID); + + // get default margins + m_currentps = opts["PageSize"]; + QString orient = opts["orientation-requested"]; + bool landscape = (orient == "4" || orient == "5"); + initPageSize(landscape); + + bool marginset(false); + if (!(value=opts["page-top"]).isEmpty() && value.toFloat() != m_margin->top()) + { + marginset = true; + m_margin->setTop(value.toFloat()); + } + if (!(value=opts["page-bottom"]).isEmpty() && value.toFloat() != m_margin->bottom()) + { + marginset = true; + m_margin->setBottom(value.toFloat()); + } + if (!(value=opts["page-left"]).isEmpty() && value.toFloat() != m_margin->left()) + { + marginset = true; + m_margin->setLeft(value.toFloat()); + } + if (!(value=opts["page-right"]).isEmpty() && value.toFloat() != m_margin->right()) + { + marginset = true; + m_margin->setRight(value.toFloat()); + } + m_margin->setCustomEnabled(marginset); +} + +void KPTextPage::getOptions(QMap<QString,QString>& opts, bool incldef) +{ + if (incldef || m_cpi->value() != 10) + opts["cpi"] = QString::number(m_cpi->value()); + if (incldef || m_lpi->value() != 6) + opts["lpi"] = QString::number(m_lpi->value()); + if (incldef || m_columns->value() != 1) + opts["columns"] = QString::number(m_columns->value()); + + //if (m_margin->isCustomEnabled() || incldef) + if (m_margin->isCustomEnabled()) + { + opts["page-top"] = QString::number(( int )( m_margin->top()+0.5 )); + opts["page-bottom"] = QString::number(( int )( m_margin->bottom()+0.5 )); + opts["page-left"] = QString::number(( int )( m_margin->left()+0.5 )); + opts["page-right"] = QString::number(( int )( m_margin->right()+0.5 )); + } + else + { + opts.remove("page-top"); + opts.remove("page-bottom"); + opts.remove("page-left"); + opts.remove("page-right"); + } + + if (m_prettyprint->id(m_prettyprint->selected()) == 1) + opts["prettyprint"] = "true"; + else if (incldef) + opts["prettyprint"] = "false"; + else + opts.remove("prettyprint"); +} + +void KPTextPage::slotPrettyChanged(int ID) +{ + QString iconstr = (ID == 0 ? "kdeprint_nup1" : "kdeprint_prettyprint"); + m_prettypix->setPixmap(UserIcon(iconstr)); +} + +void KPTextPage::slotColumnsChanged(int) +{ + // TO BE IMPLEMENTED +} + +void KPTextPage::initPageSize(bool landscape) +{ + float w( -1 ), h( -1 ); + float mt( 36 ), mb( mt ), ml( 18 ), mr( ml ); + if (driver()) + { + if (m_currentps.isEmpty()) + { + DrListOption *o = (DrListOption*)driver()->findOption("PageSize"); + if (o) + m_currentps = o->get("default"); + } + if (!m_currentps.isEmpty()) + { + DrPageSize *ps = driver()->findPageSize(m_currentps); + if (ps) + { + w = ps->pageWidth(); + h = ps->pageHeight(); + mt = ps->topMargin(); + ml = ps->leftMargin(); + mr = ps->rightMargin(); + mb = ps->bottomMargin(); + } + } + } + m_margin->setPageSize(w, h); + m_margin->setOrientation(landscape ? KPrinter::Landscape : KPrinter::Portrait); + m_margin->setDefaultMargins( mt, mb, ml, mr ); + m_margin->setCustomEnabled(false); +} + +#include "kptextpage.moc" diff --git a/kdeprint/cups/kptextpage.h b/kdeprint/cups/kptextpage.h new file mode 100644 index 000000000..72029f4af --- /dev/null +++ b/kdeprint/cups/kptextpage.h @@ -0,0 +1,57 @@ +/* + * This file is part of the KDE libraries + * Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + **/ + +#ifndef KPTEXTPAGE_H +#define KPTEXTPAGE_H + +#include "kprintdialogpage.h" + +class DrMain; +class KIntNumInput; +class QButtonGroup; +class QLabel; +class MarginWidget; + +class KPTextPage : public KPrintDialogPage +{ + Q_OBJECT +public: + KPTextPage(DrMain *driver, QWidget *parent = 0, const char *name = 0); + ~KPTextPage(); + + void setOptions(const QMap<QString,QString>& opts); + void getOptions(QMap<QString,QString>& opts, bool incldef = false); + +protected slots: + void slotPrettyChanged(int); + void slotColumnsChanged(int); + +protected: + void initPageSize(bool landscape); + +private: + KIntNumInput *m_cpi, *m_lpi, *m_columns; + QButtonGroup *m_prettyprint; + MarginWidget *m_margin; + QLabel *m_prettypix; + QString m_currentps; + bool m_block; +}; + +#endif diff --git a/kdeprint/cups/make_driver_db_cups.c b/kdeprint/cups/make_driver_db_cups.c new file mode 100644 index 000000000..b39dda8de --- /dev/null +++ b/kdeprint/cups/make_driver_db_cups.c @@ -0,0 +1,149 @@ +#include <config.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <dirent.h> +#include <unistd.h> +#include <ctype.h> +#include <zlib.h> + +#include "driverparse.h" + +void initPpd(const char *dirname) +{ + DIR *dir = opendir(dirname); + struct dirent *entry; + char buffer[4096] = {0}; + char drFile[256]; + int len = strlen(dirname); + + if (dir == NULL) + { + fprintf(stderr, "Can't open drivers directory : %s\n", dirname); + return; + } + while ((entry=readdir(dir)) != NULL) + { + if (strcmp(entry->d_name,".") == 0 || strcmp(entry->d_name,"..") == 0) + { + continue; + } + if (len+strlen(entry->d_name)+1 < 4096) + { + struct stat st; + + strcpy(buffer,dirname); + strcat(buffer,"/"); + strcat(buffer,entry->d_name); + if (stat(buffer,&st) == 0) + { + if (S_ISDIR(st.st_mode)) + { + initPpd(buffer); + } + else if (S_ISREG(st.st_mode)) + { + char *c = strrchr(buffer,'.'); + snprintf(drFile, 255, "ppd:%s", buffer); + if (c && strncmp(c,".ppd",4) == 0) + { + addFile(drFile); + } + else if (c && strncmp(c, ".gz", 3) == 0) + { /* keep also compressed driver files */ + while (c != buffer) + { + if (*(--c) == '.') break; + } + if (*c == '.' && strncmp(c, ".ppd",4) == 0) + { + addFile(drFile); + } + } + } + } + } + } + closedir(dir); +} + +int parsePpdFile(const char *filename, FILE *output_file) +{ + gzFile ppd_file; + char line[4096], value[256], langver[64] = {0}, desc[256] = {0}; + char *c1, *c2; + int count = 0; + + ppd_file = gzopen(filename,"r"); + if (ppd_file == NULL) + { + fprintf(stderr, "Can't open driver file : %s\n", filename); + return 0; + } + fprintf(output_file,"FILE=ppd:%s\n",filename); + + while (gzgets(ppd_file,line,4095) != Z_NULL) + { + memset(value,0,256); + c1 = strchr(line,':'); + if (c1) + { + c2 = strchr(c1,'"'); + if (c2) + { + c2++; + c1 = strchr(c2,'"'); + if (c1) strlcpy(value,c2,c1-c2+1); + } + else + { + c1++; + while (*c1 && isspace(*c1)) + c1++; + if (!*c1) + continue; + c2 = line+strlen(line)-1; /* point to \n */ + while (*c2 && isspace(*c2)) + c2--; + strlcpy(value,c1,c2-c1+2); + } + } + count++; + if (strncmp(line,"*Manufacturer:",14) == 0) fprintf(output_file,"MANUFACTURER=%s\n",value); + else if (strncmp(line,"*ShortNickName:",15) == 0) fprintf(output_file,"MODEL=%s\n",value); + else if (strncmp(line,"*ModelName:",11) == 0) fprintf(output_file,"MODELNAME=%s\n",value); + else if (strncmp(line,"*NickName:",10) == 0) strncat(desc,value,255-strlen(desc)); + else if (strncmp(line,"*pnpManufacturer:",17) == 0) fprintf(output_file,"PNPMANUFACTURER=%s\n",value); + else if (strncmp(line,"*pnpModel:",10) == 0) fprintf(output_file,"PNPMODEL=%s\n",value); + else if (strncmp(line,"*LanguageVersion:",17) == 0) strncat(langver,value,63-strlen(langver)); + else count--; + /* Either we got everything we needed, or we encountered an "OpenUI" directive + * and it's reasonable to assume that there's no needed info further in the file, + * just stop here */ + if (count >= 7 || strncmp(line, "*OpenUI", 7) == 0) + { + if (strlen(langver) > 0) + { + strncat(desc, " [", 255-strlen(desc)); + strncat(desc, langver, 255-strlen(desc)); + strncat(desc, "]", 255-strlen(desc)); + } + if (strlen(desc) > 0) + fprintf(output_file, "DESCRIPTION=%s\n", desc); + break; + } + } + fprintf(output_file,"\n"); + + gzclose(ppd_file); + return 1; +} + +int main(int argc, char *argv[]) +{ + registerHandler("ppd:", initPpd, parsePpdFile); + initFoomatic(); + return execute(argc, argv); +} diff --git a/kdeprint/cups/postscript.ppd.gz b/kdeprint/cups/postscript.ppd.gz Binary files differnew file mode 100644 index 000000000..92fd6862c --- /dev/null +++ b/kdeprint/cups/postscript.ppd.gz diff --git a/kdeprint/cups/preview-mini.png b/kdeprint/cups/preview-mini.png Binary files differnew file mode 100644 index 000000000..7212eaf51 --- /dev/null +++ b/kdeprint/cups/preview-mini.png diff --git a/kdeprint/cups/preview.png b/kdeprint/cups/preview.png Binary files differnew file mode 100644 index 000000000..8e436dbd1 --- /dev/null +++ b/kdeprint/cups/preview.png |