int KAction::plug( QWidget *w, int index ) { //kdDebug(129) << "KAction::plug( " << w << ", " << index << " )" << endl; if (!w ) { kdWarning(129) << "KAction::plug called with 0 argument\n"; return -1; } // Ellis: print warning if there is a shortcut, but no KAccel available (often due to no widget available in the actioncollection) // David: Well, it doesn't matter much, things still work (e.g. Undo in koffice) via QAccel. // We should probably re-enable the warning for things that only KAccel can do, though - e.g. WIN key (mapped to Meta). #if 0 //ndef NDEBUG KAccel* kaccel = kaccelCurrent(); if( !d->m_cut.isNull() && !kaccel ) { kdDebug(129) << "KAction::plug(): has no KAccel object; this = " << this << " name = " << name() << " parentCollection = " << m_parentCollection << endl; // ellis } #endif // Check if action is permitted if (kapp && !kapp->authorizeKAction(name())) return -1; plugShortcut(); if ( ::qt_cast<QPopupMenu *>( w ) ) { QPopupMenu* menu = static_cast<QPopupMenu*>( w ); int id; // Don't insert shortcut into menu if it's already in a KAccel object. int keyQt = (d->m_kaccelList.count() || d->m_kaccel) ? 0 : d->m_cut.keyCodeQt(); if ( d->hasIcon() ) { KInstance *instance; if ( m_parentCollection ) instance = m_parentCollection->instance(); else instance = KGlobal::instance(); id = menu->insertItem( d->iconSet( KIcon::Small, 0, instance ), d->text(), this,//dsweet SLOT( slotPopupActivated() ), keyQt, -1, index ); } else id = menu->insertItem( d->text(), this, SLOT( slotPopupActivated() ), keyQt, -1, index ); // If the shortcut is already in a KAccel object, then // we need to set the menu item's shortcut text. if ( d->m_kaccelList.count() || d->m_kaccel ) updateShortcut( menu, id ); // call setItemEnabled only if the item really should be disabled, // because that method is slow and the item is per default enabled if ( !d->isEnabled() ) menu->setItemEnabled( id, false ); if ( !d->whatsThis().isEmpty() ) menu->setWhatsThis( id, whatsThisWithIcon() ); addContainer( menu, id ); connect( menu, SIGNAL( destroyed() ), this, SLOT( slotDestroyed() ) ); if ( m_parentCollection ) m_parentCollection->connectHighlight( menu, this ); return d->m_containers.count() - 1; } else if ( ::qt_cast<KToolBar *>( w ) ) { KToolBar *bar = static_cast<KToolBar *>( w ); int id_ = getToolButtonID(); KInstance *instance; if ( m_parentCollection ) instance = m_parentCollection->instance(); else instance = KGlobal::instance(); if ( icon().isEmpty() && !iconSet().pixmap().isNull() ) // old code using QIconSet directly { bar->insertButton( iconSet().pixmap(), id_, SIGNAL( buttonClicked(int, Qt::ButtonState) ), this, SLOT( slotButtonClicked(int, Qt::ButtonState) ), d->isEnabled(), d->plainText(), index ); } else {
bool ColorSchema::rereadSchemaFile() { QString fPath = fRelPath.isEmpty() ? "" : (fRelPath.startsWith("/") ? fRelPath : locate("data", "konsole/"+fRelPath)); if (fPath.isEmpty() || !QFile::exists(fPath)) return false; //KONSOLEDEBUG << "Rereading schema file " << fPath << endl; FILE *sysin = fopen(QFile::encodeName(fPath),"r"); if (!sysin) { int e = errno; kdWarning() << "Schema file " << fPath << " could not be opened (" << strerror(e) << ")" << endl; return false; } char line[100]; *lastRead = QDateTime::currentDateTime(); while (fscanf(sysin,"%80[^\n]\n",line) > 0) { if (strlen(line) > 5) { if (!strncmp(line,"title",5)) { m_title = i18n(line+6); } if (!strncmp(line,"image",5)) { char rend[100], path[100]; int attr = 1; if (sscanf(line,"image %s %s",rend,path) != 2) continue; if (!strcmp(rend,"tile" )) attr = 2; else if (!strcmp(rend,"center")) attr = 3; else if (!strcmp(rend,"full" )) attr = 4; else continue; QString qline(line); m_imagePath = locate("wallpaper", qline.mid( qline.find(" ",7)+1 ) ); m_alignment = attr; } if (!strncmp(line,"transparency",12)) { float rx; int rr, rg, rb; // Transparency needs 4 parameters: fade strength and the 3 // components of the fade color. if (sscanf(line,"transparency %g %d %d %d",&rx,&rr,&rg,&rb) != 4) continue; m_useTransparency=true; m_tr_x=rx; m_tr_r=rr; m_tr_g=rg; m_tr_b=rb; } if (!strncmp(line,"rcolor",6)) { int fi,ch,cs,cv,tr,bo; if(sscanf(line,"rcolor %d %d %d %d %d",&fi,&cs,&cv,&tr,&bo) != 5) continue; if (!(0 <= fi && fi <= TABLE_COLORS)) continue; if (random_hue == -1) random_hue = (KApplication::random()%32) * 11; ch = random_hue; if (!(0 <= cs && cs <= 255 )) continue; if (!(0 <= cv && cv <= 255 )) continue; if (!(0 <= tr && tr <= 1 )) continue; if (!(0 <= bo && bo <= 1 )) continue; m_table[fi].color = QColor(); m_table[fi].color.setHsv(ch,cs,cv); m_table[fi].transparent = tr; m_table[fi].bold = bo; } if (!strncmp(line,"color",5)) { int fi,cr,cg,cb,tr,bo; if(sscanf(line,"color %d %d %d %d %d %d",&fi,&cr,&cg,&cb,&tr,&bo) != 6) continue; if (!(0 <= fi && fi <= TABLE_COLORS)) continue; if (!(0 <= cr && cr <= 255 )) continue; if (!(0 <= cg && cg <= 255 )) continue; if (!(0 <= cb && cb <= 255 )) continue; if (!(0 <= tr && tr <= 1 )) continue; if (!(0 <= bo && bo <= 1 )) continue; m_table[fi].color = QColor(cr,cg,cb); m_table[fi].transparent = tr; m_table[fi].bold = bo; } if (!strncmp(line,"sysfg",5)) { int fi,tr,bo; if(sscanf(line,"sysfg %d %d %d",&fi,&tr,&bo) != 3) continue; if (!(0 <= fi && fi <= TABLE_COLORS)) continue; if (!(0 <= tr && tr <= 1 )) continue; if (!(0 <= bo && bo <= 1 )) continue; m_table[fi].color = kapp->palette().active().text(); m_table[fi].transparent = tr; m_table[fi].bold = bo; } if (!strncmp(line,"sysbg",5)) { int fi,tr,bo; if(sscanf(line,"sysbg %d %d %d",&fi,&tr,&bo) != 3) continue; if (!(0 <= fi && fi <= TABLE_COLORS)) continue; if (!(0 <= tr && tr <= 1 )) continue; if (!(0 <= bo && bo <= 1 )) continue; m_table[fi].color = kapp->palette().active().base(); m_table[fi].transparent = tr; m_table[fi].bold = bo; } } } fclose(sysin); m_fileRead=true; return true; }
extern "C" KDE_EXPORT int kdemain( int argc, char**argv ) { // Started via kdeinit. if (fcntl(LAUNCHER_FD, F_GETFD) == -1) { fprintf(stderr, "%s", i18n("klauncher: This program is not supposed to be started manually.\n" "klauncher: It is started automatically by kdeinit.\n").local8Bit().data()); return 1; } QCString cname = KApplication::launcher(); char *name = cname.data(); KCmdLineArgs::init(argc, argv, name, "KLauncher", "A service launcher.", "v1.0"); KLauncher::addCmdLineOptions(); KCmdLineArgs::addCmdLineOptions( options ); // WABA: Make sure not to enable session management. putenv(strdup("SESSION_MANAGER=")); // Allow the locale to initialize properly KLocale::setMainCatalogue("kdelibs"); KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); int maxTry = 3; while(true) { QCString dcopName = KApplication::dcopClient()->registerAs(name, false); if (dcopName.isEmpty()) { kdWarning() << "DCOP communication problem!" << endl; return 1; } if (dcopName == cname) break; // Good! if (--maxTry == 0) { kdWarning() << "Another instance of klauncher is already running!" << endl; return 1; } // Wait a bit... kdWarning() << "Waiting for already running klauncher to exit." << endl; sleep(1); // Try again... } KLauncher *launcher = new KLauncher(LAUNCHER_FD, args->isSet("new-startup")); launcher->dcopClient()->setDefaultObject( name ); launcher->dcopClient()->setDaemonMode( true ); KCrash::setEmergencySaveFunction(sig_handler); signal( SIGHUP, sig_handler); signal( SIGPIPE, SIG_IGN); signal( SIGTERM, sig_handler); launcher->exec(); return 0; }
void KKioDrop::slotConnectionWarning( const QString& msg ) { kdWarning() << msg << endl; }
void PakProtocol::get(const KURL &url) { kdDebug(PAK_DEBUG_ID) << "ArchiveProtocol::get " << url << endl; QString path; KIO::Error errorNum; if ( !checkNewFile( url, path, errorNum ) ) { if ( errorNum == KIO::ERR_CANNOT_OPEN_FOR_READING ) { // If we cannot open, it might be a problem with the archive header (e.g. unsupported format) // Therefore give a more specific error message error( KIO::ERR_SLAVE_DEFINED, i18n( "Could not open the file, probably due to an unsupported file format.\n%1") .arg( url.prettyURL() ) ); return; } else { // We have any other error error( errorNum, url.prettyURL() ); return; } } kdDebug(PAK_DEBUG_ID) << "Continue getting" << endl; path = QString::fromLocal8Bit(remoteEncoding()->encode(path)); kdDebug(PAK_DEBUG_ID) << "Path > " << path << endl; const KArchiveDirectory* root = _pakFile->directory(); const KArchiveEntry* archiveEntry = root->entry( path ); kdDebug(PAK_DEBUG_ID) << "Check if no archiveEntry > " << archiveEntry << endl; if ( !archiveEntry ) { error( KIO::ERR_DOES_NOT_EXIST, url.prettyURL() ); return; } kdDebug(PAK_DEBUG_ID) << "archiveEntry::name > " << archiveEntry->name() << endl; if ( archiveEntry->isDirectory() ) { error( KIO::ERR_IS_DIRECTORY, url.prettyURL() ); return; } const KArchiveFile* archiveFileEntry = static_cast<const KArchiveFile *>(archiveEntry); if ( !archiveEntry->symlink().isEmpty() ) { kdDebug(7109) << "Redirection to " << archiveEntry->symlink() << endl; KURL realURL; if (archiveEntry->symlink().startsWith("/")) { // absolute path realURL.setPath(archiveEntry->symlink() ); // goes out of tar:/, back into file: } else { realURL = KURL( url, archiveEntry->symlink() ); } kdDebug(7109) << "realURL= " << realURL << endl; redirection( realURL ); finished(); return; } //kdDebug(7109) << "Preparing to get the archive data" << endl; /* * The easy way would be to get the data by calling archiveFileEntry->data() * However this has drawbacks: * - the complete file must be read into the memory * - errors are skipped, resulting in an empty file */ QIODevice* io = 0; // Getting the device is hard, as archiveFileEntry->device() is not virtual! if ( url.protocol() == "pak" ) { io = archiveFileEntry->device(); } else { // Wrong protocol? Why was this not catched by checkNewFile? kdWarning(7109) << "Protocol " << url.protocol() << " not supported by this IOSlave; " << k_funcinfo << endl; error( KIO::ERR_UNSUPPORTED_PROTOCOL, url.protocol() ); return; } if (!io) { error( KIO::ERR_SLAVE_DEFINED, i18n( "The archive file could not be opened, perhaps because the format is unsupported.\n%1" ) .arg( url.prettyURL() ) ); return; } if ( !io->open( IO_ReadOnly ) ) { error( KIO::ERR_CANNOT_OPEN_FOR_READING, url.prettyURL() ); return; } totalSize( archiveFileEntry->size() ); // Size of a QIODevice read. It must be large enough so that the mime type check will not fail const int maxSize = 0x100000; // 1MB int bufferSize = kMin( maxSize, archiveFileEntry->size() ); QByteArray buffer ( bufferSize ); if ( buffer.isEmpty() && bufferSize > 0 ) { // Something went wrong error( KIO::ERR_OUT_OF_MEMORY, url.prettyURL() ); return; } bool firstRead = true; // How much file do we still have to process? int fileSize = archiveFileEntry->size(); KIO::filesize_t processed = 0; while ( !io->atEnd() && fileSize > 0 ) { if ( !firstRead ) { bufferSize = kMin( maxSize, fileSize ); buffer.resize( bufferSize, QGArray::SpeedOptim ); } const Q_LONG read = io->readBlock( buffer.data(), buffer.size() ); // Avoid to use bufferSize here, in case something went wrong. if ( read != bufferSize ) { kdWarning(7109) << "Read " << read << " bytes but expected " << bufferSize << endl; error( KIO::ERR_COULD_NOT_READ, url.prettyURL() ); return; } if ( firstRead ) { // We use the magic one the first data read // (As magic detection is about fixed positions, we can be sure that it is enough data.) KMimeMagicResult * result = KMimeMagic::self()->findBufferFileType( buffer, path ); kdDebug(7109) << "Emitting mimetype " << result->mimeType() << endl; mimeType( result->mimeType() ); firstRead = false; } data( buffer ); processed += read; processedSize( processed ); fileSize -= bufferSize; } io->close(); delete io; data( QByteArray() ); finished(); /*kdDebug(PAK_DEBUG_ID) << "Entering get()" << endl; mimetype("text/plain"); QCString str("Hello Pak World!!"); data(str); finished(); kdDebug(PAK_DEBUG_ID) << "Exiting get()" << endl;*/ }
void KMessageClient::processMessage (const QByteArray &msg) { if (d->isLocked) { // must NOT happen, since we check in processIncomingMessage as well as in processFirstMessage d->delayedMessages.append(msg); return; } QBuffer in_buffer (msg); in_buffer.open (IO_ReadOnly); QDataStream in_stream (&in_buffer); bool unknown = false; Q_UINT32 messageID; in_stream >> messageID; switch (messageID) { case KMessageServer::MSG_BROADCAST: { Q_UINT32 clientID; in_stream >> clientID; emit broadcastReceived (in_buffer.readAll(), clientID); } break; case KMessageServer::MSG_FORWARD: { Q_UINT32 clientID; QValueList <Q_UINT32> receivers; in_stream >> clientID >> receivers; emit forwardReceived (in_buffer.readAll(), clientID, receivers); } break; case KMessageServer::ANS_CLIENT_ID: { bool old_admin = isAdmin(); Q_UINT32 clientID; in_stream >> clientID; d->connection->setId (clientID); if (old_admin != isAdmin()) emit adminStatusChanged (isAdmin()); } break; case KMessageServer::ANS_ADMIN_ID: { bool old_admin = isAdmin(); in_stream >> d->adminID; if (old_admin != isAdmin()) emit adminStatusChanged (isAdmin()); } break; case KMessageServer::ANS_CLIENT_LIST: { in_stream >> d->clientList; } break; case KMessageServer::EVNT_CLIENT_CONNECTED: { Q_UINT32 id; in_stream >> id; if (d->clientList.contains (id)) kdWarning (11001) << k_funcinfo << ": Adding a client that already existed!" << endl; else d->clientList.append (id); emit eventClientConnected (id); } break; case KMessageServer::EVNT_CLIENT_DISCONNECTED: { Q_UINT32 id; Q_INT8 broken; in_stream >> id >> broken; if (!d->clientList.contains (id)) kdWarning (11001) << k_funcinfo << ": Removing a client that doesn't exist!" << endl; else d->clientList.remove (id); emit eventClientDisconnected (id, bool (broken)); } break; default: unknown = true; } if (!unknown && !in_buffer.atEnd()) kdWarning (11001) << k_funcinfo << ": Extra data received for message ID " << messageID << endl; emit serverMessageReceived (msg, unknown); if (unknown) kdWarning (11001) << k_funcinfo << ": received unknown message ID " << messageID << endl; }
void DistributionListDialog::slotUser1() { bool isEmpty = true; KABC::AddressBook *ab = KABC::StdAddressBook::self( true ); QListViewItem *i = mRecipientsList->firstChild(); while( i ) { DistributionListItem *item = static_cast<DistributionListItem *>( i ); if ( item->isOn() ) { isEmpty = false; break; } i = i->nextSibling(); } if ( isEmpty ) { KMessageBox::information( this, i18n("There are no recipients in your list. " "First select some recipients, " "then try again.") ); return; } #ifndef KDEPIM_NEW_DISTRLISTS KABC::DistributionListManager manager( ab ); manager.load(); #endif QString name = mTitleEdit->text(); if ( name.isEmpty() ) { bool ok = false; name = KInputDialog::getText( i18n("New Distribution List"), i18n("Please enter name:"), QString::null, &ok, this ); if ( !ok || name.isEmpty() ) return; } #ifdef KDEPIM_NEW_DISTRLISTS if ( !KPIM::DistributionList::findByName( ab, name ).isEmpty() ) { #else if ( manager.list( name ) ) { #endif KMessageBox::information( this, i18n( "<qt>Distribution list with the given name <b>%1</b> " "already exists. Please select a different name.</qt>" ).arg( name ) ); return; } #ifdef KDEPIM_NEW_DISTRLISTS KPIM::DistributionList dlist; dlist.setName( name ); i = mRecipientsList->firstChild(); while( i ) { DistributionListItem *item = static_cast<DistributionListItem *>( i ); if ( item->isOn() ) { kdDebug() << " " << item->addressee().fullEmail() << endl; if ( item->isTransient() ) { ab->insertAddressee( item->addressee() ); } if ( item->email() == item->addressee().preferredEmail() ) { dlist.insertEntry( item->addressee() ); } else { dlist.insertEntry( item->addressee(), item->email() ); } } i = i->nextSibling(); } ab->insertAddressee( dlist ); #else KABC::DistributionList *dlist = new KABC::DistributionList( &manager, name ); i = mRecipientsList->firstChild(); while( i ) { DistributionListItem *item = static_cast<DistributionListItem *>( i ); if ( item->isOn() ) { kdDebug() << " " << item->addressee().fullEmail() << endl; if ( item->isTransient() ) { ab->insertAddressee( item->addressee() ); } if ( item->email() == item->addressee().preferredEmail() ) { dlist->insertEntry( item->addressee() ); } else { dlist->insertEntry( item->addressee(), item->email() ); } } i = i->nextSibling(); } #endif // FIXME: Ask the user which resource to save to instead of the default bool saveError = true; KABC::Ticket *ticket = ab->requestSaveTicket( 0 /*default resource */ ); if ( ticket ) if ( ab->save( ticket ) ) saveError = false; else ab->releaseSaveTicket( ticket ); if ( saveError ) kdWarning(5006) << k_funcinfo << " Couldn't save new addresses in the distribution list just created to the address book" << endl; #ifndef KDEPIM_NEW_DISTRLISTS manager.save(); #endif close(); }
/* --| main |------------------------------------------------------ */ extern "C" int KDE_EXPORT kdemain(int argc, char* argv[]) { setgid(getgid()); setuid(getuid()); // drop privileges // deal with shell/command //////////////////////////// bool histon = true; bool menubaron = true; bool tabbaron = true; bool frameon = true; bool scrollbaron = true; bool showtip = true; KAboutData aboutData( "konsole", I18N_NOOP("Konsole"), KONSOLE_VERSION, description, KAboutData::License_GPL_V2, "Copyright (c) 1997-2006, Lars Doelle"); aboutData.addAuthor("Robert Knight",I18N_NOOP("Maintainer"), "*****@*****.**"); aboutData.addAuthor("Lars Doelle",I18N_NOOP("Author"), "*****@*****.**"); aboutData.addCredit("Kurt V. Hindenburg", I18N_NOOP("bug fixing and improvements"), "*****@*****.**"); aboutData.addCredit("Waldo Bastian", I18N_NOOP("bug fixing and improvements"), "*****@*****.**"); aboutData.addCredit("Stephan Binner", I18N_NOOP("bug fixing and improvements"), "*****@*****.**"); aboutData.addCredit("Chris Machemer", I18N_NOOP("bug fixing"), "*****@*****.**"); aboutData.addCredit("Stephan Kulow", I18N_NOOP("Solaris support and work on history"), "*****@*****.**"); aboutData.addCredit("Alexander Neundorf", I18N_NOOP("faster startup, bug fixing"), "*****@*****.**"); aboutData.addCredit("Peter Silva", I18N_NOOP("decent marking"), "*****@*****.**"); aboutData.addCredit("Lotzi Boloni", I18N_NOOP("partification\n" "Toolbar and session names"), "*****@*****.**"); aboutData.addCredit("David Faure", I18N_NOOP("partification\n" "overall improvements"), "*****@*****.**"); aboutData.addCredit("Antonio Larrosa", I18N_NOOP("transparency"), "*****@*****.**"); aboutData.addCredit("Matthias Ettrich", I18N_NOOP("most of main.C donated via kvt\n" "overall improvements"), "*****@*****.**"); aboutData.addCredit("Warwick Allison", I18N_NOOP("schema and selection improvements"), "*****@*****.**"); aboutData.addCredit("Dan Pilone", I18N_NOOP("SGI Port"), "*****@*****.**"); aboutData.addCredit("Kevin Street", I18N_NOOP("FreeBSD port"), "*****@*****.**"); aboutData.addCredit("Sven Fischer", I18N_NOOP("bug fixing"), "*****@*****.**"); aboutData.addCredit("Dale M. Flaven", I18N_NOOP("bug fixing"), "*****@*****.**"); aboutData.addCredit("Martin Jones", I18N_NOOP("bug fixing"), "*****@*****.**"); aboutData.addCredit("Lars Knoll", I18N_NOOP("bug fixing"), "*****@*****.**"); aboutData.addCredit("",I18N_NOOP("Thanks to many others.\n" "The above list only reflects the contributors\n" "I managed to keep track of.")); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. //1.53 sec KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); KCmdLineArgs *qtargs = KCmdLineArgs::parsedArgs("qt"); has_noxft = !args->isSet("xft"); TEWidget::setAntialias( !has_noxft ); TEWidget::setStandalone( true ); // The following Qt options have no effect; warn users. if( qtargs->isSet("background") ) kdWarning() << "The Qt option -bg, --background has no effect." << endl; if( qtargs->isSet("foreground") ) kdWarning() << "The Qt option -fg, --foreground has no effect." << endl; if( qtargs->isSet("button") ) kdWarning() << "The Qt option -btn, --button has no effect." << endl; if( qtargs->isSet("font") ) kdWarning() << "The Qt option -fn, --font has no effect." << endl; KApplication* a = NULL; #ifdef COMPOSITE if ( args->isSet("real-transparency")) { char *display = 0; if ( qtargs->isSet("display")) display = qtargs->getOption( "display" ).data(); Display *dpy = XOpenDisplay( display ); if ( !dpy ) { kdError() << "cannot connect to X server " << display << endl; exit( 1 ); } int screen = DefaultScreen( dpy ); Colormap colormap = 0; Visual *visual = 0; int event_base, error_base; if ( XRenderQueryExtension( dpy, &event_base, &error_base ) ) { int nvi; XVisualInfo templ; templ.screen = screen; templ.depth = 32; templ.c_class = TrueColor; XVisualInfo *xvi = XGetVisualInfo( dpy, VisualScreenMask | VisualDepthMask | VisualClassMask, &templ, &nvi ); for ( int i = 0; i < nvi; i++ ) { XRenderPictFormat *format = XRenderFindVisualFormat( dpy, xvi[i].visual ); if ( format->type == PictTypeDirect && format->direct.alphaMask ) { visual = xvi[i].visual; colormap = XCreateColormap( dpy, RootWindow( dpy, screen ), visual, AllocNone ); kdDebug() << "found visual with alpha support" << endl; argb_visual = true; break; } } } // The QApplication ctor used is normally intended for applications not using Qt // as the primary toolkit (e.g. Motif apps also using Qt), with some slightly // unpleasant side effects (e.g. #83974). This code checks if qt-copy patch #0078 // is applied, which allows turning this off. bool* qt_no_foreign_hack = static_cast< bool* >( dlsym( RTLD_DEFAULT, "qt_no_foreign_hack" )); if( qt_no_foreign_hack ) *qt_no_foreign_hack = true; // else argb_visual = false ... ? *shrug* if( argb_visual ) a = new KApplication( dpy, Qt::HANDLE( visual ), Qt::HANDLE( colormap ) ); else XCloseDisplay( dpy ); } if( a == NULL ) a = new KApplication; #else KApplication* a = new KApplication; #endif QString dataPathBase = KStandardDirs::kde_default("data").append("konsole/"); KGlobal::dirs()->addResourceType("wallpaper", dataPathBase + "wallpapers"); KImageIO::registerFormats(); // add io for additional image formats //2.1 secs QString title; if(args->isSet("T")) { title = QFile::decodeName(args->getOption("T")); } if(qtargs->isSet("title")) { title = QFile::decodeName(qtargs->getOption("title")); } QString term = ""; if(args->isSet("tn")) { term=QString::fromLatin1(args->getOption("tn")); } login_shell = args->isSet("ls"); QStrList eargs; const char* shell = 0; if (!args->getOption("e").isEmpty()) { if (args->isSet("ls")) KCmdLineArgs::usage(i18n("You can't use BOTH -ls and -e.\n")); shell = strdup(args->getOption("e")); eargs.append(shell); for(int i=0; i < args->count(); i++) eargs.append( args->arg(i) ); if (title.isEmpty() && (kapp->caption() == kapp->aboutData()->programName())) { title = QFile::decodeName(shell); // program executed in the title bar } showtip = false; } QCString sz = ""; sz = args->getOption("vt_sz"); histon = args->isSet("hist"); menubaron = args->isSet("menubar"); tabbaron = args->isSet("tabbar") && args->isSet("toolbar"); frameon = args->isSet("frame"); scrollbaron = args->isSet("scrollbar"); QCString wname = qtargs->getOption("name"); full_script = args->isSet("script"); auto_close = args->isSet("close"); fixed_size = !args->isSet("resize"); if (!full_script) a->dcopClient()->setQtBridgeEnabled(false); QCString type = ""; if(args->isSet("type")) { type = args->getOption("type"); } if(args->isSet("types")) { QStringList types = KGlobal::dirs()->findAllResources("appdata", "*.desktop", false, true); types.sort(); for(QStringList::ConstIterator it = types.begin(); it != types.end(); ++it) { QString file = *it; file = file.mid(file.findRev('/')+1); if (file.endsWith(".desktop")) file = file.left(file.length()-8); printf("%s\n", QFile::encodeName(file).data()); } return 0; } if(args->isSet("schemas") || args->isSet("schemata")) { ColorSchemaList colors; colors.checkSchemas(); for(int i = 0; i < (int) colors.count(); i++) { ColorSchema *schema = colors.find(i); QString relPath = schema->relPath(); if (!relPath.isEmpty()) printf("%s\n", QFile::encodeName(relPath).data()); } return 0; } if(args->isSet("keytabs")) { QStringList lst = KGlobal::dirs()->findAllResources("data", "konsole/*.keytab"); printf("default\n"); // 'buildin' keytab lst.sort(); for(QStringList::Iterator it = lst.begin(); it != lst.end(); ++it ) { QFileInfo fi(*it); QString file = fi.baseName(); printf("%s\n", QFile::encodeName(file).data()); } return 0; } QString workDir = QFile::decodeName( args->getOption("workdir") ); QString keytab = ""; if (args->isSet("keytab")) keytab = QFile::decodeName(args->getOption("keytab")); QString schema = ""; if (args->isSet("schema")) schema = args->getOption("schema"); KConfig * sessionconfig = 0; QString profile = ""; if (args->isSet("profile")) { profile = args->getOption("profile"); QString path = locate( "data", "konsole/profiles/" + profile ); if ( QFile::exists( path ) ) sessionconfig=new KConfig( path, true ); else profile = ""; } if (args->isSet("profiles")) { QStringList profiles = KGlobal::dirs()->findAllResources("data", "konsole/profiles/*", false, true); profiles.sort(); for(QStringList::ConstIterator it = profiles.begin(); it != profiles.end(); ++it) { QString file = *it; file = file.mid(file.findRev('/')+1); printf("%s\n", QFile::encodeName(file).data()); } return 0; } //FIXME: more: font args->clear(); int c = 0, l = 0; if ( !sz.isEmpty() ) { char *ls = (char*)strchr( sz.data(), 'x' ); if ( ls != NULL ) { *ls='\0'; ls++; c=atoi(sz.data()); l=atoi(ls); } else { KCmdLineArgs::usage(i18n("expected --vt_sz <#columns>x<#lines> e.g. 80x40\n")); } } if (!kapp->authorizeKAction("size")) fixed_size = true; // /////////////////////////////////////////////// // Ignore SIGHUP so that we don't get killed when // our parent-shell gets closed. signal(SIGHUP, SIG_IGN); putenv((char*)"COLORTERM="); // to trigger mc's color detection KonsoleSessionManaged ksm; if (a->isRestored() || !profile.isEmpty()) { if (!shell) shell = konsole_shell(eargs); if (profile.isEmpty()) sessionconfig = a->sessionConfig(); sessionconfig->setDesktopGroup(); int n = 1; QString key; QString sTitle; QString sPgm; QString sTerm; QString sIcon; QString sCwd; int n_tabbar; // TODO: Session management stores everything in same group, // should use one group / mainwindow while (KMainWindow::canBeRestored(n) || !profile.isEmpty()) { sessionconfig->setGroup(QString("%1").arg(n)); if (!sessionconfig->hasKey("Pgm0")) sessionconfig->setDesktopGroup(); // Backwards compatible int session_count = sessionconfig->readNumEntry("numSes"); int counter = 0; wname = sessionconfig->readEntry("class",wname).latin1(); sPgm = sessionconfig->readEntry("Pgm0", shell); sessionconfig->readListEntry("Args0", eargs); sTitle = sessionconfig->readEntry("Title0", title); sTerm = sessionconfig->readEntry("Term0"); sIcon = sessionconfig->readEntry("Icon0","konsole"); sCwd = sessionconfig->readPathEntry("Cwd0"); workDir = sessionconfig->readPathEntry("workdir"); n_tabbar = QMIN(sessionconfig->readUnsignedNumEntry("tabbar",Konsole::TabBottom),2); Konsole *m = new Konsole(wname,histon,menubaron,tabbaron,frameon,scrollbaron,0/*type*/,true,n_tabbar, workDir); m->newSession(sPgm, eargs, sTerm, sIcon, sTitle, sCwd); m->enableFullScripting(full_script); m->enableFixedSize(fixed_size); m->restore(n); sessionconfig->setGroup(QString("%1").arg(n)); if (!sessionconfig->hasKey("Pgm0")) sessionconfig->setDesktopGroup(); // Backwards compatible m->makeGUI(); m->setEncoding(sessionconfig->readNumEntry("Encoding0")); m->setSchema(sessionconfig->readEntry("Schema0")); // Use konsolerc default as tmpFont instead? QFont tmpFont = KGlobalSettings::fixedFont(); m->initSessionFont(sessionconfig->readFontEntry("SessionFont0", &tmpFont)); m->initSessionKeyTab(sessionconfig->readEntry("KeyTab0")); m->initMonitorActivity(sessionconfig->readBoolEntry("MonitorActivity0",false)); m->initMonitorSilence(sessionconfig->readBoolEntry("MonitorSilence0",false)); m->initMasterMode(sessionconfig->readBoolEntry("MasterMode0",false)); m->initTabColor(sessionconfig->readColorEntry("TabColor0")); // -1 will be changed to the default history in konsolerc m->initHistory(sessionconfig->readNumEntry("History0", -1), sessionconfig->readBoolEntry("HistoryEnabled0", true)); counter++; // show() before 2nd+ sessions are created allows --profile to // initialize the TE size correctly. m->show(); while (counter < session_count) { key = QString("Title%1").arg(counter); sTitle = sessionconfig->readEntry(key, title); key = QString("Args%1").arg(counter); sessionconfig->readListEntry(key, eargs); key = QString("Pgm%1").arg(counter); // if the -e option is passed on the command line, this overrides the program specified // in the profile file if ( args->isSet("e") ) sPgm = (shell ? QFile::decodeName(shell) : QString::null); else sPgm = sessionconfig->readEntry(key, shell); key = QString("Term%1").arg(counter); sTerm = sessionconfig->readEntry(key); key = QString("Icon%1").arg(counter); sIcon = sessionconfig->readEntry(key,"konsole"); key = QString("Cwd%1").arg(counter); sCwd = sessionconfig->readPathEntry(key); m->newSession(sPgm, eargs, sTerm, sIcon, sTitle, sCwd); m->setSessionTitle(sTitle); // Use title as is key = QString("Schema%1").arg(counter); m->setSchema(sessionconfig->readEntry(key)); key = QString("Encoding%1").arg(counter); m->setEncoding(sessionconfig->readNumEntry(key)); key = QString("SessionFont%1").arg(counter); QFont tmpFont = KGlobalSettings::fixedFont(); m->initSessionFont(sessionconfig->readFontEntry(key, &tmpFont)); key = QString("KeyTab%1").arg(counter); m->initSessionKeyTab(sessionconfig->readEntry(key)); key = QString("MonitorActivity%1").arg(counter); m->initMonitorActivity(sessionconfig->readBoolEntry(key,false)); key = QString("MonitorSilence%1").arg(counter); m->initMonitorSilence(sessionconfig->readBoolEntry(key,false)); key = QString("MasterMode%1").arg(counter); m->initMasterMode(sessionconfig->readBoolEntry(key,false)); key = QString("TabColor%1").arg(counter); m->initTabColor(sessionconfig->readColorEntry(key)); // -1 will be changed to the default history in konsolerc key = QString("History%1").arg(counter); QString key2 = QString("HistoryEnabled%1").arg(counter); m->initHistory(sessionconfig->readNumEntry(key, -1), sessionconfig->readBoolEntry(key2, true)); counter++; } m->setDefaultSession( sessionconfig->readEntry("DefaultSession","shell.desktop") ); m->initFullScreen(); if ( !profile.isEmpty() ) { m->callReadPropertiesInternal(sessionconfig,1); profile = ""; // Hack to work-around sessions initialized with minimum size for (int i=0;i<counter;i++) m->activateSession( i ); m->setColLin(c,l); // will use default height and width if called with (0,0) } // works only for the first one, but there won't be more. n++; m->activateSession( sessionconfig->readNumEntry("ActiveSession",0) ); m->setAutoClose(auto_close); } } else { Konsole* m = new Konsole(wname,histon,menubaron,tabbaron,frameon,scrollbaron,type, false, 0, workDir); m->newSession((shell ? QFile::decodeName(shell) : QString::null), eargs, term, QString::null, title, workDir); m->enableFullScripting(full_script); m->enableFixedSize(fixed_size); //3.8 :-( //exit(0); if (!keytab.isEmpty()) m->initSessionKeyTab(keytab); if (!schema.isEmpty()) { if (schema.right(7)!=".schema") schema+=".schema"; m->setSchema(schema); m->activateSession(0); // Fixes BR83162, transp. schema + notabbar } m->setColLin(c,l); // will use default height and width if called with (0,0) m->initFullScreen(); m->show(); if (showtip) m->showTipOnStart(); m->setAutoClose(auto_close); } int ret = a->exec(); //// Temporary code, waiting for Qt to do this properly // Delete all toplevel widgets that have WDestructiveClose QWidgetList *list = QApplication::topLevelWidgets(); // remove all toplevel widgets that have a parent (i.e. they // got WTopLevel explicitly), they'll be deleted by the parent list->first(); while( list->current()) { if( list->current()->parentWidget() != NULL || !list->current()->testWFlags( Qt::WDestructiveClose ) ) { list->remove(); continue; } list->next(); } QWidgetListIt it(*list); QWidget * w; while( (w=it.current()) != 0 ) { ++it; delete w; } delete list; delete a; return ret; }
int main(int argc, char *argv[]) { int i_file, i_v, i_curve; int i_plot; KAboutData aboutData( "kst", I18N_NOOP("Kst"), "0.95-devel", description, KAboutData::License_GPL, I18N_NOOP("(c) 2000-2003 Barth Netterfield"), 0, "http://extragear.kde.org/apps/kst.php"); aboutData.addAuthor("Barth Netterfield", I18N_NOOP("Original author and maintainer."), "*****@*****.**", "http://omega.astro.utoronto.ca/"); aboutData.addAuthor("Staikos Computing Services Inc.", I18N_NOOP("Developed for the University of Toronto."), "*****@*****.**", "http://www.staikos.net/"); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KApplication app; KImageIO::registerFormats(); if (app.isRestored()) { RESTORE(KstApp) } else { KstApp *kst = new KstApp; struct InType in; QColor color; QCStringList ycolList; QCStringList yEqList; QCStringList psdList; QCStringList hsList; QCStringList errorList; unsigned int i_ycol; QCStringList::Iterator psd; QCStringList::Iterator hs; QCStringList::Iterator eq_i; bool nOK; /* temp variables: these all get stuck into list objects */ KstDataSourcePtr file; KstRVector *xvector=NULL; KstRVector *yvector; KstRVector *evector; KstVCurve *curve; KstPSDCurve *psdcurve; KstEquationCurve *eqcurve; KstHistogram *hscurve; KstPlot *plot; int n_y, n_eq=0; /* Parse command line args */ KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); CheckForCMDErrors(args); // Initialise the plugin loader and collection. PluginCollection::self(); /* get Y axis collums */ ycolList = args->getOptionList("y"); yEqList = args->getOptionList("ye"); psdList = args->getOptionList("p"); hsList = args->getOptionList("h"); errorList = args->getOptionList("e"); // y axis or PSD specified, so the files are data files, not kst files. n_y = ycolList.count() + psdList.count() + hsList.count() + yEqList.count(); if (n_y > 0) { SetCMDOptions(args, in, n_y); CreatePlots(in); i_plot = 0; plot = KST::plotList.at(i_plot); /* make stand alone equations if there are no files */ if (args->count()<1) { if (!yEqList.isEmpty()) { QString eqS; double max, min; int n; bool xeq; SetEqXRanges(args->getOption("xe"), &min, &max, &n, &xeq); if (xeq) { for (eq_i = yEqList.begin(); eq_i != yEqList.end(); ++eq_i) { eqS = *eq_i; if (NoVectorEq(eqS)) { eqcurve = new KstEquationCurve(QString("E")+QString::number(n_eq+1)+ "-" + eqS, eqS, min,max,n, KstColorSequence::next()); KST::dataObjectList.lock().writeLock(); KST::dataObjectList.append(eqcurve); KST::dataObjectList.lock().writeUnlock(); plot->addCurve(eqcurve); if (in.sep_plots) { i_plot++; if (i_plot <in.n_plots) plot = KST::plotList.at(i_plot); } } } } } } /* Make the requested curves for each data file */ for (i_curve = i_v = 0, i_file = 0; i_file < args->count(); i_file++) { /* Make the file */ file = KstDataSource::loadSource(args->arg(i_file)); if (!file) { kdWarning() << I18N_NOOP("Error: No data in file: ") << args->arg(i_file) << endl; delete kst; exit(0); } if (!file->isValid() || file->frameCount() < 1) { kdWarning() << I18N_NOOP("Error: No data in file: ") << args->arg(i_file) << endl; // The file might get data later! } KST::dataObjectList.lock().writeLock(); KST::dataSourceList.append(file); KST::dataObjectList.lock().writeUnlock(); if (!ycolList.isEmpty()) { // if there are some xy plots /* make the x axis vector */ xvector = GetOrCreateVector(args->getOption("x"), file, in); /* make the y axis vectors */ for (i_ycol = 0; i_ycol < ycolList.count(); ++i_ycol ) { yvector = GetOrCreateVector(*(ycolList.at(i_ycol)), file, in); /* make the curves */ color = KstColorSequence::next(); curve = new KstVCurve(QString("C") + QString::number(1+i_curve++) + "-" + yvector->getField(), KstVectorPtr(xvector), KstVectorPtr(yvector), 0L, 0L, color); if (in.has_points) { curve->setHasPoints(true); curve->setHasLines(false); } if (i_ycol<errorList.count()) { evector = GetOrCreateVector(*(errorList.at(i_ycol)), file, in); curve->setYError(KstVectorPtr(evector)); } KST::dataObjectList.lock().writeLock(); KST::dataObjectList.append(curve); KST::dataObjectList.lock().writeUnlock(); plot->addCurve(curve); if (in.sep_plots) { i_plot++; if (i_plot < in.n_plots) plot = KST::plotList.at(i_plot); } // end (if they are separate plots) } // next y col } // end (if there are some xy plots) if (!yEqList.isEmpty()) { QString eqS; double max, min; int n; bool xeq, eq_ok; SetEqXRanges(args->getOption("xe"), &min, &max, &n, &xeq); for (eq_i = yEqList.begin(); eq_i != yEqList.end(); ++eq_i) { eqS = *eq_i; ProcessEq(eqS, file, in, &eq_ok); if (xeq) { eqcurve = new KstEquationCurve(QString("E")+QString::number(n_eq+1)+ "-" + eqS, eqS, min,max,n, KstColorSequence::next()); } else { if (xvector==NULL) xvector = GetOrCreateVector(args->getOption("x"), file, in); eqcurve = new KstEquationCurve(QString("E")+QString::number(n_eq+1)+eqS, eqS, KstVectorPtr(xvector), true, KstColorSequence::next()); } KST::dataObjectList.lock().writeLock(); KST::dataObjectList.append(eqcurve); KST::dataObjectList.lock().writeUnlock(); plot->addCurve(eqcurve); if (in.sep_plots) { i_plot++; if (i_plot <in.n_plots) plot = KST::plotList.at(i_plot); } } } if (psdList.count() > 0) { // if there are some psd plots KstRVectorList rvl = kstObjectSubList<KstVector,KstRVector>(KST::vectorList); for(psd = psdList.begin(); psd != psdList.end(); ++psd ) { yvector = GetOrCreateVector(*psd, file, in); color = KstColorSequence::next(); psdcurve = new KstPSDCurve(QString("P") + QString::number(1+i_curve++) + "-" + yvector->getField(), KstVectorPtr(yvector), in.rate, in.len, in.VUnits,in.RUnits, color); if (in.has_points) { psdcurve->setHasPoints(true); psdcurve->setHasLines(false); } KST::dataObjectList.lock().writeLock(); KST::dataObjectList.append(psdcurve); KST::dataObjectList.lock().writeUnlock(); plot->addCurve(psdcurve); if (in.sep_plots) { i_plot++; if (i_plot <in.n_plots) plot = KST::plotList.at(i_plot); } } // next psd } // end (if there are some psds) if (hsList.count()>0) { // if there are some histograms double max, min; int N; KstRVectorList rvl = kstObjectSubList<KstVector,KstRVector>(KST::vectorList); for (hs = hsList.begin(); hs != hsList.end(); ++hs ) { yvector = GetOrCreateVector(*hs, file, in); color = KstColorSequence::next(); KstHistogram::AutoBin(KstVectorPtr(yvector), &N, &max, &min); hscurve = new KstHistogram(QString("H") + QString::number(1+i_curve++) + "-" + yvector->getField(), KstVectorPtr(yvector), min, max, N, KST_HS_NUMBER, color); KST::dataObjectList.lock().writeLock(); KST::dataObjectList.append(KstDataObjectPtr(hscurve)); KST::dataObjectList.lock().writeUnlock(); plot->addCurve(hscurve); if (in.sep_plots) { i_plot++; if (i_plot < in.n_plots) plot = KST::plotList.at(i_plot); } } // next histogram } // end (if there are some histograms) } // next data file for (i_plot = 0; i_plot < in.n_plots; i_plot++) { KST::plotList.at(i_plot)->GenerateDefaultLabels(); } KST::plotList.setPlotCols(in.n_cols); } else if (args->count() > 0) { /* open a kst file */ /* some of the options can be overridden */ kst->openDocumentFile(args->arg(0), args->getOption("F"), // override FileName // override number of frames args->getOption("n").toInt(&nOK), // override starting frame args->getOption("f").toInt(&nOK), // override skip args->getOption("s").toInt(&nOK), // add averaging args->isSet("a")); } else { //kst->openDocumentFile(); } QString printfile; printfile = args->getOption("print"); QString pngfile; pngfile = args->getOption("png"); bool print_and_exit = false; if (printfile!="<none>") { args->clear(); kst->forceUpdate(); kst->immediatePrintToFile(printfile); print_and_exit = true; } if (pngfile!="<none>") { args->clear(); kst->forceUpdate(); kst->immediatePrintToPng(pngfile); print_and_exit = true; } if (print_and_exit) { delete kst; exit(0); } else { args->clear(); app.setMainWidget(kst); kst->show(); } // LEAVE THIS HERE - causes crashes otherwise! int rc = app.exec(); delete kst; return rc; } return app.exec(); }
KJS::Value Pixmap::call( KJS::ExecState *exec, KJS::Object &self, const KJS::List &args ) { if( !JSProxy::checkType( self, JSProxy::ValueProxy, "QPixmap") ) return KJS::Value(); JSValueProxy *op = JSProxy::toValueProxy( self.imp() ); pix = op->toVariant().toPixmap(); KJS::Value retValue = KJS::Value(); switch ( mid ) { case Methodwidth: retValue = KJS::Number(width()); break; case Methodheight: retValue = KJS::Number(height()); break; case Methoddepth: retValue = KJS::Number(depth()); break; case MethodisNull: retValue = KJS::Boolean(isNull()); break; case Methodsize: retValue = convertToValue(exec, size()); break; case Methodrect: retValue = convertToValue(exec, rect()); break; case Methodresize: { if( args.size() == 2) resize(extractInt(exec, args, 0), extractInt(exec, args, 1)); else if( args.size() == 1) resize(extractQSize(exec, args, 0) ); break; } case Methodfill: fill( extractQColor(exec, args, 0)); break; case Methodmask: { retValue = convertToValue(exec, mask() ); break; } case MethodsetMask: { setMask(extractQPixmap(exec, args, 0)); break; } case MethodcreateHeuristicMask: { retValue = convertToValue(exec, createHeuristicMask(extractBool(exec, args, 0))); break; } case MethodgrabWindow: { int winid = extractInt(exec, args,0); int x = extractInt(exec, args,1); int y = extractInt(exec, args,2); int w = extractInt(exec, args,3); int h = extractInt(exec, args,4); grabWindow(winid,x,y,w,h); break; } default: kdWarning() << "Image has no method " << mid << endl; break; } op->setValue(pix); return retValue; }
int main( int argc, char* argv[] ) { KStandardDirs stddir; if ( argc < 3 ) { std::cerr << "usage: r++ dbname directories..." << std::endl << std::endl; return -1; } bool rec = false; bool parseAllFiles = false; QString datadir = stddir.localkdedir() + "/" + KStandardDirs::kde_default( "data" ); if ( ! KStandardDirs::makeDir( datadir + "/kdevcppsupport/pcs/" ) ) { kdWarning() << "*error* " << "could not create " << datadir + "/kdevcppsupport/pcs/" << endl << endl; return -1; } if ( !QFile::exists( datadir + "/kdevcppsupport/pcs/" ) ) { kdWarning() << "*error* " << datadir + "/kdevcppsupport/pcs/" << " doesn't exists!!" << endl << endl; return -1; } QString dbFileName = datadir + "/kdevcppsupport/pcs/" + argv[ 1 ] + ".db"; // std::cout << "dbFileName = " << dbFileName << std::endl; if ( QFile::exists( dbFileName ) ) { kdWarning() << "*error* " << "database " << dbFileName << " already exists!" << endl << endl; return -1; } Catalog catalog; catalog.open( dbFileName ); catalog.addIndex( "kind" ); catalog.addIndex( "name" ); catalog.addIndex( "scope" ); catalog.addIndex( "fileName" ); RppDriver driver( &catalog ); driver.setResolveDependencesEnabled( true ); for ( int i = 2; i < argc; ++i ) { QString s( argv[ i ] ); if ( s == "-r" || s == "--recursive" ) { rec = true; continue; } else if ( s == "-a" || s == "--all" ) { parseAllFiles = true; continue; } else if ( s == "-f" || s == "--fast" ) { driver.setResolveDependencesEnabled( false ); continue; } else if ( s == "-c" || s == "--check-only" ) { driver.setGenerateTags( false ); continue; } else if ( s.startsWith( "-d" ) ) { driver.addDocDirectory( s.mid( 2 ) ); continue; } QDir dir( s ); if ( !dir.exists() ) { kdWarning() << "*error* " << "the directory " << dir.path() << " doesn't exists!" << endl << endl; continue; } parseDirectory( driver, dir, rec, parseAllFiles ); } return 0; }
int create(KCmdLineArgs *args) { KODE::Printer p; if(args->isSet("warning")) p.setCreationWarning(true); bool createKioslave = args->isSet("create-kioslave"); bool createMain = args->isSet("create-main"); QString filename = args->getOption("filename"); if(createMain) { if(filename.isEmpty()) { kdError() << "Error: No file name given." << endl; return 1; } if(filename.endsWith(".cpp")) { filename = filename.left(filename.length() - 4); } } else { if(!args->isSet("classname")) { kdError() << "Error: No class name given." << endl; return 1; } } QString className = args->getOption("classname"); QString protocol; if(createKioslave) { if(!args->isSet("protocol")) { protocol = className.lower(); kdWarning() << "Warning: No protocol for kioslave given. Assuming '" << protocol << "'" << endl; } else { protocol = args->getOption("protocol"); } } KODE::File file; file.setProject(args->getOption("project")); QString authorEmail = args->getOption("author-email"); QString authorName; KABC::Addressee a; if(authorEmail.isEmpty()) { a = KABC::StdAddressBook::self()->whoAmI(); authorEmail = a.preferredEmail(); } else { KABC::Addressee::List as = KABC::StdAddressBook::self()->findByEmail(authorEmail); if(as.isEmpty()) { kdDebug() << "Unable to find '" << authorEmail << "' in address book." << endl; } else { a = as.first(); } } if(!a.isEmpty()) { authorName = a.realName(); } if(!authorEmail.isEmpty()) { file.addCopyright(QDate::currentDate().year(), authorName, authorEmail); } KODE::License l; if(args->isSet("gpl")) l = KODE::License(KODE::License::GPL); if(args->isSet("lgpl")) l = KODE::License(KODE::License::LGPL); l.setQtException(args->isSet("qt-exception")); file.setLicense(l); file.setNameSpace(args->getOption("namespace")); if(createMain) { file.addInclude("kaboutdata.h"); file.addInclude("kapplication.h"); file.addInclude("kdebug"); file.addInclude("klocale"); file.addInclude("kcmdlineargs"); KODE::Code code; code += "static const KCmdLineOptions options[] ="; code += "{"; code += " { \"verbose\", \"Verbose output\", 0 },"; code += " KCmdLineLastOption"; code += "};"; file.addFileCode(code); KODE::Function main("main", "int"); main.addArgument("int argc"); main.addArgument("char **argv"); code.clear(); code += "KAboutData aboutData(\"test\",\"Test\",\"0.1\");"; code += "KCmdLineArgs::init(argc,argv,&aboutData);"; code += "KCmdLineArgs::addCmdLineOptions( options );"; code += ""; code += "KApplication app;"; code += ""; code += "KCmdLineArgs *args = KCmdLineArgs::parsedArgs();"; code += ""; code += "Q_UNUSED( args );"; main.setBody(code); file.addFileFunction(main); file.setFilename(filename); p.printImplementation(file, false); return 0; } KODE::Class c(className); if(args->isSet("create-dialog")) { c.addBaseClass(KODE::Class("KDialogBase")); c.addInclude("kdialogbase.h"); } else if(createKioslave) { c.setDocs("This class implements a kioslave for ..."); c.addBaseClass(KODE::Class("SlaveBase", "KIO")); c.addHeaderInclude("kio/slavebase.h"); KODE::Function get("get", "void"); get.addArgument("const KURL &url"); KODE::Code code; code += "kdDebug(7000) << \"" + className + "::get()\" << endl;"; code += "kdDebug(7000) << \" URL: \" << url.url() << endl;"; code += "#if 1"; code += "kdDebug(7000) << \" Path: \" << url.path() << endl;"; code += "kdDebug(7000) << \" Query: \" << url.query() << endl;"; code += "kdDebug(7000) << \" Protocol: \" << url.protocol() << endl;"; code += "kdDebug(7000) << \" Filename: \" << url.filename() << endl;"; code += "#endif"; code.newLine(); code += "mimeType( \"text/plain\" );"; code.newLine(); code += "QCString str( \"Hello!\" );"; code += "data( str );"; code.newLine(); code += "finished();"; code.newLine(); code += "kdDebug(7000) << \"" + className + "CgiProtocol::get() done\" << endl;"; get.setBody(code); c.addFunction(get); c.addInclude("kinstance.h"); c.addInclude("kdebug.h"); c.addInclude("sys/types.h"); c.addInclude("unistd.h"); c.addInclude("stdlib.h"); KODE::Function main("kdemain", "int"); main.addArgument("int argc"); main.addArgument("char **argv"); code.clear(); code += "KInstance instance( \"kio_" + protocol + "\" );"; code += ""; code += "kdDebug(7000) << \"Starting kio_" + protocol + "(pid: \" << getpid() << \")\" << endl;"; code += ""; code += "if (argc != 4) {"; code.indent(); code += "fprintf( stderr, \"Usage: kio_" + protocol + " protocol domain-socket1 domain-socket2\\n\");"; code += "exit( -1 );"; code.unindent(); code += "}"; code += ""; code += className + " slave( argv[2], argv[3] );"; code += "slave.dispatchLoop();"; code += ""; code += "return 0;"; main.setBody(code); file.addFileFunction(main); file.addExternCDeclaration(p.functionSignature(main)); } KODE::Function constructor(className); if(args->isSet("singleton")) { constructor.setAccess(KODE::Function::Private); KODE::Function self("self", className + " *"); self.setStatic(true); KODE::Code code; code += "if ( !mSelf ) {"; code += " selfDeleter.setObject( mSelf, new " + className + "() );"; code += "}"; code += "return mSelf;"; self.setBody(code); c.addFunction(self); KODE::MemberVariable selfVar("mSelf", className + " *", true); selfVar.setInitializer("0"); c.addMemberVariable(selfVar); KODE::Variable staticDeleter("selfDeleter", "KStaticDeleter<" + className + ">", true); file.addFileVariable(staticDeleter); file.addInclude("kstaticdeleter.h"); } if(createKioslave) { constructor.addArgument("const QCString &pool"); constructor.addArgument("const QCString &app"); constructor.addInitializer("SlaveBase( \"" + protocol + "\", pool, app )"); } c.addFunction(constructor); file.insertClass(c); p.printHeader(file); p.printImplementation(file); if(createKioslave) { // Write automake Makefile KODE::AutoMakefile am; am.addEntry("INCLUDES", "$(all_includes)"); am.newLine(); am.addEntry("noinst_HEADERS", className.lower() + ".h"); am.newLine(); am.addEntry("METASOURCES", "AUTO"); am.newLine(); am.addEntry("kdelnkdir", "$(kde_servicesdir)"); am.addEntry("kdelnk_DATA", protocol + ".protocol"); KODE::AutoMakefile::Target t("kde_module_LTLIBRARIES", "kio_" + protocol + ".la"); t.setSources(className.lower() + ".cpp"); t.setLibAdd("$(LIB_KIO)"); t.setLdFlags("$(all_libraries) -module $(KDE_PLUGIN)"); am.addTarget(t); p.printAutoMakefile(am); // Write protocol file QString protocolFilename = protocol + ".protocol"; QFileInfo fi(protocolFilename); protocolFilename = fi.absFilePath(); KSaveFile::backupFile(protocolFilename, QString::null, ".backup"); QFile::remove(protocolFilename); KSimpleConfig protocolFile(protocolFilename); protocolFile.setGroup("Protocol"); protocolFile.writeEntry("exec", "kio_" + protocol); protocolFile.writeEntry("protocol", protocol); protocolFile.writeEntry("input", "none"); protocolFile.writeEntry("output", "filesystem"); protocolFile.writeEntry("reading", "true"); protocolFile.writeEntry("DocPath", "kioslave/" + protocol + ".html"); protocolFile.sync(); } return 0; }
/* Check if file meets the find's requirements*/ void KQuery::processQuery( KFileItem* file) { QRegExp *filename_match; if ( file->name() == "." || file->name() == ".." ) return; bool matched=false; for ( filename_match = m_regexps.first(); !matched && filename_match; filename_match = m_regexps.next() ) { matched |= filename_match->isEmpty() || (filename_match->exactMatch( file->url().fileName( true ) ) ); } if (!matched) return; switch( m_sizemode ) { case 1: // "at least" if ( file->size() < m_sizeboundary1 ) return; break; case 2: // "at most" if ( file->size() > m_sizeboundary1 ) return; break; case 3: // "equal" if ( file->size() != m_sizeboundary1 ) return; break; case 4: // "between" if ( (file->size() < m_sizeboundary1) || (file->size() > m_sizeboundary2) ) return; break; case 0: // "none" -> fall to default default: break; } // make sure it's in the correct date range // what about 0 times? if ( m_timeFrom && m_timeFrom > file->time(KIO::UDS_MODIFICATION_TIME) ) return; if ( m_timeTo && m_timeTo < file->time(KIO::UDS_MODIFICATION_TIME) ) return; // username / group match if ( (!m_username.isEmpty()) && (m_username != file->user()) ) return; if ( (!m_groupname.isEmpty()) && (m_groupname != file->group()) ) return; // file type switch (m_filetype) { case 0: break; case 1: // plain file if ( !S_ISREG( file->mode() ) ) return; break; case 2: if ( !file->isDir() ) return; break; case 3: if ( !file->isLink() ) return; break; case 4: if ( !S_ISCHR ( file->mode() ) && !S_ISBLK ( file->mode() ) && !S_ISFIFO( file->mode() ) && !S_ISSOCK( file->mode() ) ) return; break; case 5: // binary if ( (file->permissions() & 0111) != 0111 || file->isDir() ) return; break; case 6: // suid if ( (file->permissions() & 04000) != 04000 ) // fixme return; break; default: if (!m_mimetype.isEmpty() && !m_mimetype.contains(file->mimetype())) return; } // match datas in metainfo... if ((!m_metainfo.isEmpty()) && (!m_metainfokey.isEmpty())) { bool foundmeta=false; QString filename = file->url().path(); if(filename.startsWith("/dev/")) return; KFileMetaInfo metadatas(filename); KFileMetaInfoItem metaitem; QStringList metakeys; QString strmetakeycontent; if(metadatas.isEmpty()) return; metakeys=metadatas.supportedKeys(); for ( QStringList::Iterator it = metakeys.begin(); it != metakeys.end(); ++it ) { if (!metaKeyRx->exactMatch(*it)) continue; metaitem=metadatas.item(*it); strmetakeycontent=metaitem.string(); if(strmetakeycontent.find(m_metainfo)!=-1) { foundmeta=true; break; } } if (!foundmeta) return; } // match contents... QString matchingLine; if (!m_context.isEmpty()) { if( !m_search_binary && ignore_mimetypes.findIndex(file->mimetype()) != -1 ) { kdDebug() << "ignoring, mime type is in exclusion list: " << file->url() << endl; return; } bool found = false; bool isZippedOfficeDocument=false; int matchingLineNumber=0; // FIXME: doesn't work with non local files QString filename; QTextStream* stream=0; QFile qf; QRegExp xmlTags; QByteArray zippedXmlFileContent; // KWord's and OpenOffice.org's files are zipped... if( ooo_mimetypes.findIndex(file->mimetype()) != -1 || koffice_mimetypes.findIndex(file->mimetype()) != -1 ) { KZip zipfile(file->url().path()); KZipFileEntry *zipfileEntry; if(zipfile.open(IO_ReadOnly)) { const KArchiveDirectory *zipfileContent = zipfile.directory(); if( koffice_mimetypes.findIndex(file->mimetype()) != -1 ) zipfileEntry = (KZipFileEntry*)zipfileContent->entry("maindoc.xml"); else zipfileEntry = (KZipFileEntry*)zipfileContent->entry("content.xml"); //for OpenOffice.org if(!zipfileEntry) { kdWarning() << "Expected XML file not found in ZIP archive " << file->url() << endl; return; } zippedXmlFileContent = zipfileEntry->data(); xmlTags.setPattern("<.*>"); xmlTags.setMinimal(true); stream = new QTextStream(zippedXmlFileContent, IO_ReadOnly); stream->setEncoding(QTextStream::UnicodeUTF8); isZippedOfficeDocument = true; } else { kdWarning() << "Cannot open supposed ZIP file " << file->url() << endl; } } else if( !m_search_binary && !file->mimetype().startsWith("text/") && file->url().isLocalFile() ) { KMimeType::Format f = KMimeType::findFormatByFileContent(file->url().path()); if ( !f.text ) { kdDebug() << "ignoring, not a text file: " << file->url() << endl; return; } } if(!isZippedOfficeDocument) //any other file or non-compressed KWord { filename = file->url().path(); if(filename.startsWith("/dev/")) return; qf.setName(filename); qf.open(IO_ReadOnly); stream=new QTextStream(&qf); stream->setEncoding(QTextStream::Locale); } while ( ! stream->atEnd() ) { QString str = stream->readLine(); matchingLineNumber++; if (str.isNull()) break; if(isZippedOfficeDocument) str.replace(xmlTags, ""); if (m_regexpForContent) { if (m_regexp.search(str)>=0) { matchingLine=QString::number(matchingLineNumber)+": "+str; found = true; break; } } else { if (str.find(m_context, 0, m_casesensitive) != -1) { matchingLine=QString::number(matchingLineNumber)+": "+str; found = true; break; } } kapp->processEvents(); } delete stream; if (!found) return; } emit addFile(file,matchingLine); }
KJS::Value QDirImp::call( KJS::ExecState *exec, KJS::Object &self, const KJS::List &args ) { JSOpaqueProxy *op = JSProxy::toOpaqueProxy( self.imp() ); if ( !op ) { kdWarning() << "QDirImp::call() failed, not a JSOpaqueProxy" << endl; return KJS::Value(); } if ( op->typeName() != "QDir" ) { kdWarning() << "QDirImp::call() failed, type is " << op->typeName() << endl; return KJS::Value(); } instance = op->toNative<QDir>(); switch( mid ) { case Method_setPath_7: return setPath_7( exec, self, args ); break; case Method_path_8: return path_8( exec, self, args ); break; case Method_absPath_9: return absPath_9( exec, self, args ); break; case Method_canonicalPath_10: return canonicalPath_10( exec, self, args ); break; case Method_dirName_11: return dirName_11( exec, self, args ); break; case Method_filePath_12: return filePath_12( exec, self, args ); break; case Method_absFilePath_13: return absFilePath_13( exec, self, args ); break; case Method_cd_14: return cd_14( exec, self, args ); break; case Method_cdUp_15: return cdUp_15( exec, self, args ); break; case Method_nameFilter_16: return nameFilter_16( exec, self, args ); break; case Method_setNameFilter_17: return setNameFilter_17( exec, self, args ); break; case Method_filter_18: return filter_18( exec, self, args ); break; case Method_setFilter_19: return setFilter_19( exec, self, args ); break; case Method_sorting_20: return sorting_20( exec, self, args ); break; case Method_setSorting_21: return setSorting_21( exec, self, args ); break; case Method_matchAllDirs_22: return matchAllDirs_22( exec, self, args ); break; case Method_setMatchAllDirs_23: return setMatchAllDirs_23( exec, self, args ); break; case Method_count_24: return count_24( exec, self, args ); break; case Method_encodedEntryList_26: return encodedEntryList_26( exec, self, args ); break; case Method_encodedEntryList_27: return encodedEntryList_27( exec, self, args ); break; case Method_entryList_28: return entryList_28( exec, self, args ); break; case Method_entryList_29: return entryList_29( exec, self, args ); break; case Method_entryInfoList_30: return entryInfoList_30( exec, self, args ); break; case Method_entryInfoList_31: return entryInfoList_31( exec, self, args ); break; case Method_mkdir_32: return mkdir_32( exec, self, args ); break; case Method_rmdir_33: return rmdir_33( exec, self, args ); break; case Method_isReadable_34: return isReadable_34( exec, self, args ); break; case Method_exists_35: return exists_35( exec, self, args ); break; case Method_isRoot_36: return isRoot_36( exec, self, args ); break; case Method_isRelative_37: return isRelative_37( exec, self, args ); break; case Method_convertToAbs_38: return convertToAbs_38( exec, self, args ); break; case Method_remove_41: return remove_41( exec, self, args ); break; case Method_rename_42: return rename_42( exec, self, args ); break; case Method_exists_43: return exists_43( exec, self, args ); break; case Method_refresh_44: return refresh_44( exec, self, args ); break; case Method_convertSeparators_45: return convertSeparators_45( exec, self, args ); break; case Method_drives_46: return drives_46( exec, self, args ); break; case Method_separator_47: return separator_47( exec, self, args ); break; case Method_setCurrent_48: return setCurrent_48( exec, self, args ); break; case Method_current_49: return current_49( exec, self, args ); break; case Method_home_50: return home_50( exec, self, args ); break; case Method_root_51: return root_51( exec, self, args ); break; case Method_currentDirPath_52: return currentDirPath_52( exec, self, args ); break; case Method_homeDirPath_53: return homeDirPath_53( exec, self, args ); break; case Method_rootDirPath_54: return rootDirPath_54( exec, self, args ); break; case Method_match_55: return match_55( exec, self, args ); break; case Method_match_56: return match_56( exec, self, args ); break; case Method_cleanDirPath_57: return cleanDirPath_57( exec, self, args ); break; case Method_isRelativePath_58: return isRelativePath_58( exec, self, args ); break; default: break; } QString msg = i18n( "QDirImp has no method with id '%1'." ).arg( mid ); return throwError(exec, msg,KJS::ReferenceError); }
QString KWDWriter::getText(QDomElement paragraph) { QDomNode temp=paragraph.elementsByTagName("TEXT").item(0).firstChild(); QDomText currentText=temp.toText(); if (temp.isNull()) { kdWarning(30503) << "no text" << endl; } return currentText.data(); }
void KJavaAppletContext::received( const QString& cmd, const QStringList& arg ) { kdDebug(6100) << "KJavaAppletContext::received, cmd = >>" << cmd << "<<" << endl; kdDebug(6100) << "arg count = " << arg.count() << endl; if ( cmd == QString::fromLatin1("showstatus") && !arg.empty() ) { QString tmp = arg.first(); tmp.replace(QRegExp("[\n\r]"), ""); kdDebug(6100) << "status message = " << tmp << endl; emit showStatus( tmp ); } else if ( cmd == QString::fromLatin1( "showurlinframe" ) && arg.count() > 1 ) { kdDebug(6100) << "url = " << arg[0] << ", frame = " << arg[1] << endl; emit showDocument( arg[0], arg[1] ); } else if ( cmd == QString::fromLatin1( "showdocument" ) && !arg.empty() ) { kdDebug(6100) << "url = " << arg.first() << endl; emit showDocument( arg.first(), "_top" ); } else if ( cmd == QString::fromLatin1( "resizeapplet" ) && arg.count() > 2 ) { //arg[1] should be appletID //arg[2] should be new width //arg[3] should be new height bool ok; const int appletID = arg[0].toInt( &ok ); const int width = arg[1].toInt( &ok ); const int height = arg[2].toInt( &ok ); if( !ok ) { kdError(DEBUGAREA) << "could not parse out parameters for resize" << endl; } else { KJavaApplet* const tmp = d->applets[appletID]; if (tmp) tmp->resizeAppletWidget( width, height ); } } else if (cmd.startsWith(QString::fromLatin1("audioclip_"))) { kdDebug(DEBUGAREA) << "process Audio command (not yet implemented): " << cmd << " " << arg[0] << endl; } else if ( cmd == QString::fromLatin1( "JS_Event" ) && arg.count() > 2 ) { bool ok; const int appletID = arg.first().toInt(&ok); KJavaApplet * applet; if (ok && (applet = d->applets[appletID])) { QStringList js_args(arg); js_args.pop_front(); applet->jsData(js_args); } else kdError(DEBUGAREA) << "parse JS event " << arg[0] << " " << arg[1] << endl; } else if ( cmd == QString::fromLatin1( "AppletStateNotification" ) ) { bool ok; const int appletID = arg.first().toInt(&ok); if (ok) { KJavaApplet* const applet = d->applets[appletID]; if ( applet ) { const int newState = arg[1].toInt(&ok); if (ok) { applet->stateChange(newState); if (newState == KJavaApplet::INITIALIZED) { kdDebug(DEBUGAREA) << "emit appletLoaded" << endl; emit appletLoaded(); } } else kdError(DEBUGAREA) << "AppletStateNotification: status is not numerical" << endl; } else kdWarning(DEBUGAREA) << "AppletStateNotification: No such Applet with ID=" << arg[0] << endl; } else kdError(DEBUGAREA) << "AppletStateNotification: Applet ID is not numerical" << endl; } else if ( cmd == QString::fromLatin1( "AppletFailed" ) ) { bool ok; const int appletID = arg.first().toInt(&ok); if (ok) { KJavaApplet* const applet = d->applets[appletID]; /* QString errorDetail(arg[1]); errorDetail.replace(QRegExp(":\\s*"), ":\n"); KMessageBox::detailedError(0L, i18n("Java error while loading applet."), errorDetail); */ if (applet) applet->setFailed(); emit appletLoaded(); } } }
QDomElement KWDWriter::startFormat(QDomElement paragraph) { if (paragraph.isNull()) { kdWarning(30503) << "startFormat on empty paragraph" << endl; } QDomElement format=_doc->createElement("FORMAT"); paragraph.elementsByTagName("FORMATS").item(0).appendChild(format); return format; }
KAction *XMLActionHandler::createAction( KActionCollection *parent ) { // kdDebug(80001) << "Creating Action, type is " << type << endl; // kdDebug(80001) << "text=" << text << ", icons=" << icons << endl; // kdDebug(80001) << "keys=" << keys << ", name=" << name << endl; if ( !parent ) { kdWarning() << "Create action called but no parent set" << endl; return 0; } KAction *act=0; if ( ad.type.isEmpty() || (ad.type == "KAction") ) { act = new KAction( ad.text, ad.icons, ad.keys, 0, 0, parent, ad.name.latin1() ); } else if ( ad.type == "KToggleAction" ) { act = new KToggleAction( ad.text, ad.icons, ad.keys, 0, 0, parent, ad.name.latin1() ); } else if ( ad.type == "KRadioAction" ) { KRadioAction *ra = new KRadioAction( ad.text, ad.icons, ad.keys, 0, 0, parent, ad.name.latin1() ); if ( ad.exclusive ) ra->setExclusiveGroup( ad.group ); act = ra; } else if ( ad.type == "KStdAction" ) { for ( int i = KStdAction::ActionNone ; i < KStdAction::ConfigureNotifications ; i++ ) { if ( KStdAction::stdName(static_cast<KStdAction::StdAction>(i)) == ad.name ) act = KStdAction::create( (KStdAction::StdAction)i, 0, 0, parent ); } } else if ( ad.type == "KListAction" ) { KListAction *la = new KListAction( ad.text, ad.icons, ad.keys, 0, 0, parent, ad.name.latin1() ); la->setItems( ad.items ); ad.items.clear(); act = la; } else if ( ad.type == "KActionMenu" ) { KActionMenu *am = new KActionMenu( ad.text, ad.icons, parent, ad.name.latin1() ); for ( QStringList::Iterator it = ad.items.begin() ; it != ad.items.end() ; ++it ) { KAction *a = parent->action( (*it).latin1() ); if ( a ) am->insert( a ); } ad.items.clear(); act = am; } else { kdWarning() << "Unknown ActionType " << ad.type << endl; return 0; } if ( !act ) { kdWarning() << "Unable to create action" << endl; return act; } if ( !ad.group.isEmpty() ) act->setGroup( ad.group ); act->setStatusText( ad.status ); act->setWhatsThis( ad.whatsthis ); QObject::connect( actclient, SIGNAL( destroyed() ), act, SLOT( deleteLater() ) ); return act; }
// virtual void kpTool::cancelShape () { kdWarning () << "Tool cannot cancel operation!" << endl; }
static kdbgstream warning() { return kdWarning( 5300 ) << "PluginLoaderBase: "; }
static int startApp() { KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); // Stop daemon and exit? if (args->isSet("s")) { KDEsuClient client; if (client.ping() == -1) { kdError(1206) << "Daemon not running -- nothing to stop\n"; exit(1); } if (client.stopServer() != -1) { kdDebug(1206) << "Daemon stopped\n"; exit(0); } kdError(1206) << "Could not stop daemon\n"; exit(1); } QString icon; if ( args->isSet("i")) icon = args->getOption("i"); bool prompt = true; if ( args->isSet("d")) prompt = false; // Get target uid QCString user = args->getOption("u"); QCString auth_user = user; struct passwd *pw = getpwnam(user); if (pw == 0L) { kdError(1206) << "User " << user << " does not exist\n"; exit(1); } bool change_uid = (getuid() != pw->pw_uid); // If file is writeable, do not change uid QString file = QFile::decodeName(args->getOption("f")); if (change_uid && !file.isEmpty()) { if (file.at(0) != '/') { KStandardDirs dirs; dirs.addKDEDefaults(); file = dirs.findResource("config", file); if (file.isEmpty()) { kdError(1206) << "Config file not found: " << file << "\n"; exit(1); } } QFileInfo fi(file); if (!fi.exists()) { kdError(1206) << "File does not exist: " << file << "\n"; exit(1); } change_uid = !fi.isWritable(); } // Get priority/scheduler QCString tmp = args->getOption("p"); bool ok; int priority = tmp.toInt(&ok); if (!ok || (priority < 0) || (priority > 100)) { KCmdLineArgs::usage(i18n("Illegal priority: %1").arg(tmp)); exit(1); } int scheduler = SuProcess::SchedNormal; if (args->isSet("r")) scheduler = SuProcess::SchedRealtime; if ((priority > 50) || (scheduler != SuProcess::SchedNormal)) { change_uid = true; auth_user = "******"; } // Get command if (args->isSet("c")) { command = args->getOption("c"); for (int i=0; i<args->count(); i++) { QString arg = QFile::decodeName(args->arg(i)); KRun::shellQuote(arg); command += " "; command += QFile::encodeName(arg); } } else { if( args->count() == 0 ) { KCmdLineArgs::usage(i18n("No command specified.")); exit(1); } command = args->arg(0); for (int i=1; i<args->count(); i++) { QString arg = QFile::decodeName(args->arg(i)); KRun::shellQuote(arg); command += " "; command += QFile::encodeName(arg); } } // Don't change uid if we're don't need to. if (!change_uid) { int result = system(command); result = WEXITSTATUS(result); return result; } // Check for daemon and start if necessary bool just_started = false; bool have_daemon = true; KDEsuClient client; if (!client.isServerSGID()) { kdWarning(1206) << "Daemon not safe (not sgid), not using it.\n"; have_daemon = false; } else if (client.ping() == -1) { if (client.startServer() == -1) { kdWarning(1206) << "Could not start daemon, reduced functionality.\n"; have_daemon = false; } just_started = true; } // Try to exec the command with kdesud. bool keep = !args->isSet("n") && have_daemon; bool terminal = args->isSet("t"); bool new_dcop = args->isSet("newdcop"); bool withIgnoreButton = args->isSet("ignorebutton"); QCStringList env; QCString options; env << ( "DESKTOP_STARTUP_ID=" + kapp->startupId()); if (pw->pw_uid) { // Only propagate KDEHOME for non-root users, // root uses KDEROOTHOME // Translate the KDEHOME of this user to the new user. QString kdeHome = KGlobal::dirs()->relativeLocation("home", KGlobal::dirs()->localkdedir()); if (kdeHome[0] != '/') kdeHome.prepend("~/"); else kdeHome=QString::null; // Use default env << ("KDEHOME="+ QFile::encodeName(kdeHome)); } KUser u; env << (QCString) ("KDESU_USER="******"KDESYCOCA="+QFile::encodeName(locateLocal("cache", "ksycoca")); env << ksycoca; options += "xf"; // X-only, dcop forwarding enabled. } if (keep && !terminal && !just_started) { client.setPriority(priority); client.setScheduler(scheduler); int result = client.exec(command, user, options, env); if (result == 0) { result = client.exitCode(); return result; } } // Set core dump size to 0 because we will have // root's password in memory. struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = 0; if (setrlimit(RLIMIT_CORE, &rlim)) { kdError(1206) << "rlimit(): " << ERR << "\n"; exit(1); } // Read configuration KConfig *config = KGlobal::config(); config->setGroup("Passwords"); int timeout = config->readNumEntry("Timeout", defTimeout); // Check if we need a password SuProcess proc; proc.setUser(auth_user); int needpw = proc.checkNeedPassword(); if (needpw < 0) { QString err = i18n("Su returned with an error.\n"); KMessageBox::error(0L, err); exit(1); } if (needpw == 0) { keep = 0; kdDebug() << "Don't need password!!\n"; } // Start the dialog QCString password; if (needpw) { KStartupInfoId id; id.initId( kapp->startupId()); KStartupInfoData data; data.setSilent( KStartupInfoData::Yes ); KStartupInfo::sendChange( id, data ); KDEsuDialog dlg(user, auth_user, keep && !terminal,icon, withIgnoreButton); if (prompt) dlg.addLine(i18n("Command:"), command); if ((priority != 50) || (scheduler != SuProcess::SchedNormal)) { QString prio; if (scheduler == SuProcess::SchedRealtime) prio += i18n("realtime: "); prio += QString("%1/100").arg(priority); if (prompt) dlg.addLine(i18n("Priority:"), prio); } int ret = dlg.exec(); if (ret == KDEsuDialog::Rejected) { KStartupInfo::sendFinish( id ); exit(0); } if (ret == KDEsuDialog::AsUser) change_uid = false; password = dlg.password(); keep = dlg.keep(); data.setSilent( KStartupInfoData::No ); KStartupInfo::sendChange( id, data ); } // Some events may need to be handled (like a button animation) kapp->processEvents(); // Run command if (!change_uid) { int result = system(command); result = WEXITSTATUS(result); return result; } else if (keep && have_daemon) { client.setPass(password, timeout); client.setPriority(priority); client.setScheduler(scheduler); int result = client.exec(command, user, options, env); if (result == 0) { result = client.exitCode(); return result; } } else { SuProcess proc; proc.setTerminal(terminal); proc.setErase(true); proc.setUser(user); if (!new_dcop) { proc.setXOnly(true); proc.setDCOPForwarding(true); } proc.setEnvironment(env); proc.setPriority(priority); proc.setScheduler(scheduler); proc.setCommand(command); int result = proc.exec(password); return result; } return -1; }
void Editor::triggerAutoComplete() { if( !d->autoCompleteEnabled ) return; // tokenize the expression (don't worry, this is very fast) // faster now that it uses flex. ;) int para = 0, curPos = 0; getCursorPosition( ¶, &curPos ); QString subtext = text().left( curPos ); Tokens tokens = Evaluator::scan( subtext ); if(!tokens.valid()) { kdWarning() << "invalid tokens.\n"; return; } if(tokens.isEmpty() || subtext.endsWith(" ")) return; Token lastToken = tokens[ tokens.count()-1 ]; // last token must be an identifier if( !lastToken.isIdentifier() ) return; QString id = lastToken.text(); if( id.isEmpty() ) return; // find matches in function names QStringList fnames = FunctionManager::instance()->functionList(FunctionManager::All); QStringList choices; for( unsigned i=0; i<fnames.count(); i++ ) if( fnames[i].startsWith( id, false ) ) { QString str = fnames[i]; ::Function* f = FunctionManager::instance()->function( str ); if( f && !f->description.isEmpty() ) str.append( ':' ).append( f->description ); choices.append( str ); } choices.sort(); // find matches in variables names QStringList vchoices; QStringList values = NumeralModel::instance()->valueNames(); for(QStringList::ConstIterator it = values.begin(); it != values.end(); ++it) if( (*it).startsWith( id, false ) ) { QString choice = NumeralModel::description(*it); if(choice.isEmpty()) choice = NumeralModel::instance()->value(*it).toString(); vchoices.append( QString("%1:%2").arg( *it, choice ) ); } vchoices.sort(); choices += vchoices; // no match, don't bother with completion if( !choices.count() ) return; // one match, complete it for the user if( choices.count()==1 ) { QString str = QStringList::split( ':', choices[0] )[0]; // single perfect match, no need to give choices. if(str == id.lower()) return; str = str.remove( 0, id.length() ); int para = 0, curPos = 0; getCursorPosition( ¶, &curPos ); blockSignals( true ); insert( str ); setSelection( 0, curPos, 0, curPos+str.length() ); blockSignals( false ); return; } // present the user with completion choices d->completion->showCompletion( choices ); }
bool KArchive::addLocalFile(const QString &fileName, const QString &destName) { QFileInfo fileInfo(fileName); if(!fileInfo.isFile() && !fileInfo.isSymLink()) { kdWarning() << "KArchive::addLocalFile " << fileName << " doesn't exist or is not a regular file." << endl; return false; } KDE_struct_stat fi; if(KDE_lstat(QFile::encodeName(fileName), &fi) == -1) { kdWarning() << "KArchive::addLocalFile stating " << fileName << " failed: " << strerror(errno) << endl; return false; } if(fileInfo.isSymLink()) { return writeSymLink(destName, fileInfo.readLink(), fileInfo.owner(), fileInfo.group(), fi.st_mode, fi.st_atime, fi.st_mtime, fi.st_ctime); } /*end if*/ uint size = fileInfo.size(); // the file must be opened before prepareWriting is called, otherwise // if the opening fails, no content will follow the already written // header and the tar file is effectively f*cked up QFile file(fileName); if(!file.open(IO_ReadOnly)) { kdWarning() << "KArchive::addLocalFile couldn't open file " << fileName << endl; return false; } if(!prepareWriting(destName, fileInfo.owner(), fileInfo.group(), size, fi.st_mode, fi.st_atime, fi.st_mtime, fi.st_ctime)) { kdWarning() << "KArchive::addLocalFile prepareWriting " << destName << " failed" << endl; return false; } // Read and write data in chunks to minimize memory usage QByteArray array(8 * 1024); int n; uint total = 0; while((n = file.readBlock(array.data(), array.size())) > 0) { if(!writeData(array.data(), n)) { kdWarning() << "KArchive::addLocalFile writeData failed" << endl; return false; } total += n; } Q_ASSERT(total == size); if(!doneWriting(size)) { kdWarning() << "KArchive::addLocalFile doneWriting failed" << endl; return false; } return true; }
void PluginKateKJSWrapper::addView(Kate::MainWindow *win) { PluginKateKJSWrapperView * view=getViewObject(win); // this is needed to ensure correct caching the javascript object KJS::Interpreter *js = m_part->interpreter(); KJS::ExecState *exec = js->globalExec(); exec->clearException(); kdDebug()<<"****************************************************************************************"<<endl; kdDebug()<<"PluginKateKJSWrapper::addView"<<endl; kdDebug()<<"****************************************************************************************"<<endl; kdDebug()<<"checking for newWindowHandler"<<endl; if (!m_newWindowHandler.isNull()) { KJS::List param; param.append(view->winObj); KJS::Object newWinFunc=m_newWindowHandler.toObject(exec); if (exec->hadException()) { exec->clearException(); } else { if (newWinFunc.implementsCall()) { newWinFunc.call(exec,js->globalObject(),param); if (exec->hadException()) { kdDebug()<<"Error while calling newWindowHandler"<<endl; exec->clearException(); } } } } if (exec->hadException()) kdDebug()<<"void PluginKateKJSWrapper::addView(Kate::MainWindow *win): exec had an exception - 1"<<endl; kdDebug()<<"checking for toolview constructors"<<endl; if (! (m_toolViewConstructors.isNull() || (m_toolViewConstructors.type()==KJS::NullType))) { KJS::Object constrs=m_toolViewConstructors.toObject(exec); if (!exec->hadException()) { if (QString(constrs.classInfo()->className)=="Array") { kdDebug()<<"Toolview constructor array detected"<<endl; int size=constrs.get(exec,KJS::Identifier("length")).toInteger(exec); if (exec->hadException()) { exec->clearException(); kdDebug()<<"Error while retrieving array length"<<endl; } else { for (int i=0;i<size;i++) { KJS::Object constrO=constrs.get(exec,i).toObject(exec); if (exec->hadException()) { exec->clearException(); } else { KMDI::ToolViewAccessor *w=createToolView(m_part->factory(),js,win,view->winObj,constrO); if (w) { view->toolviews.append(QGuardedPtr<KMDI::ToolViewAccessor>(w)); } exec->clearException(); } } } } else { kdDebug()<<"Single toolview constructor detected"<<endl; if (!constrs.implementsConstruct()) { kdWarning()<<"wrong object type"<<endl; } else { KMDI::ToolViewAccessor *w=createToolView(m_part->factory(),js,win,view->winObj,constrs); if (w) { view->toolviews.append(QGuardedPtr<KMDI::ToolViewAccessor>(w)); } exec->clearException(); } } } } else kdDebug()<<"void PluginKateKJSWrapper::addView(Kate::MainWindow *win): no toolview constructors"<<endl; if (exec->hadException()) kdDebug()<<"void PluginKateKJSWrapper::addView(Kate::MainWindow *win): exec had an exception - 2"<<endl; view->setInstance (new KInstance("kate")); view->setXMLFile(QString("plugins/%1/%2.rc").arg(m_scriptname).arg(m_scriptname)); win->guiFactory()->addClient (view); }
bool PakProtocol::checkNewFile(const KURL &url, QString &path, KIO::Error &errorNum) { QString fullPath = url.path(); kdDebug(PAK_DEBUG_ID) << "Entering checkNewFile() - " << fullPath << endl; // Are we already looking at that file ? if ( _pakFile && _pakFileName == fullPath.left(_pakFileName.length()) ) { // Has it changed ? KDE_struct_stat statbuf; if ( KDE_stat( QFile::encodeName( _pakFileName ), &statbuf ) == 0 ) { if ( _pakFileTime == statbuf.st_mtime ) { // It hasn't changed, so just return path = fullPath.mid( _pakFileName.length() ); kdDebug(PAK_DEBUG_ID) << "checkNewFile() returning " << path << endl; return true; } } } kdDebug(PAK_DEBUG_ID) << "Need to open a new file or check if dir" << endl; // Close previous file if ( _pakFile ) { _pakFile->close(); delete _pakFile; _pakFile = NULL; } kdDebug(PAK_DEBUG_ID) << "Going to find full path" << endl; // Find where the tar file is in the full path int pos = 0; QString archiveFile; path = QString::null; int len = fullPath.length(); if ( len != 0 && fullPath[ len - 1 ] != '/' ) fullPath += '/'; kdDebug(PAK_DEBUG_ID) << "the full path is " << fullPath << endl; KDE_struct_stat statbuf; statbuf.st_mode = 0; // be sure to clear the directory bit while ( (pos=fullPath.find( '/', pos+1 )) != -1 ) { QString tryPath = fullPath.left( pos ); kdDebug(PAK_DEBUG_ID) << fullPath << " trying " << tryPath << endl; if ( KDE_stat( QFile::encodeName(tryPath), &statbuf ) == -1 ) { // We are not in the file system anymore, either we have already enough data or we will never get any useful data anymore break; } if ( !S_ISDIR(statbuf.st_mode) ) { archiveFile = tryPath; _pakFileTime = statbuf.st_mtime; path = fullPath.mid( pos + 1 ); kdDebug(PAK_DEBUG_ID) << "fullPath=" << fullPath << " path=" << path << endl; len = path.length(); if ( len > 1 ) { if ( path[ len - 1 ] == '/' ) path.truncate( len - 1 ); } else path = QString::fromLatin1("/"); kdDebug(PAK_DEBUG_ID) << "Found. archiveFile=" << archiveFile << " path=" << path << endl; break; } } if ( archiveFile.isEmpty() ) { kdDebug(PAK_DEBUG_ID) << "checkNewFile(): not found" << endl; if ( S_ISDIR(statbuf.st_mode) ) // Was the last stat about a directory? { // Too bad, it is a directory, not an archive. kdDebug(PAK_DEBUG_ID) << "Path is a directory, not an archive." << endl; errorNum = KIO::ERR_IS_DIRECTORY; } else errorNum = KIO::ERR_DOES_NOT_EXIST; return false; } if (url.protocol() == "pak") { kdDebug(PAK_DEBUG_ID) << "Creating a KPak object on " << archiveFile << endl; _pakFile = new KPak(archiveFile); } else { kdWarning(PAK_DEBUG_ID) << "Protocol " << url.protocol() << " not supported by this IOSlave" << endl; errorNum = KIO::ERR_UNSUPPORTED_PROTOCOL; return false; } if ( !_pakFile->open(IO_ReadOnly) ) { kdDebug(PAK_DEBUG_ID) << "Opening " << archiveFile << "failed." << endl; delete _pakFile; _pakFile = NULL; errorNum = KIO::ERR_CANNOT_OPEN_FOR_READING; return false; } _pakFileName = archiveFile; return true; }
KDModule::KDModule(QWidget *parent, const char *name, const QStringList &) : KCModule(KDMFactory::instance(), parent, name), minshowuid(0), maxshowuid(0), updateOK(false) { KAboutData *about = new KAboutData(I18N_NOOP("kcmkdm"), I18N_NOOP("KDE Login Manager Config Module"), 0, 0, KAboutData::License_GPL, I18N_NOOP("(c) 1996 - 2005 The KDM Authors")); about->addAuthor("Thomas Tanghus", I18N_NOOP("Original author"), "*****@*****.**"); about->addAuthor("Steffen Hansen", 0, "*****@*****.**"); about->addAuthor("Oswald Buddenhagen", I18N_NOOP("Current maintainer"), "*****@*****.**"); setQuickHelp( i18n("<h1>Login Manager</h1> In this module you can configure the " "various aspects of the KDE Login Manager. This includes " "the look and feel as well as the users that can be " "selected for login. Note that you can only make changes " "if you run the module with superuser rights. If you have not started the KDE " "Control Center with superuser rights (which is absolutely the right thing to " "do, by the way), click on the <em>Modify</em> button to acquire " "superuser rights. You will be asked for the superuser password." "<h2>Appearance</h2> On this tab page, you can configure how " "the Login Manager should look, which language it should use, and which " "GUI style it should use. The language settings made here have no influence on " "the user's language settings." "<h2>Font</h2>Here you can choose the fonts that the Login Manager should use " "for various purposes like greetings and user names. " "<h2>Background</h2>If you want to set a special background for the login " "screen, this is where to do it." "<h2>Shutdown</h2> Here you can specify who is allowed to shutdown/reboot the machine " "and whether a boot manager should be used." "<h2>Users</h2>On this tab page, you can select which users the Login Manager " "will offer you for logging in." "<h2>Convenience</h2> Here you can specify a user to be logged in automatically, " "users not needing to provide a password to log in, and other convenience features.<br>" "Note, that these settings are security holes by their nature, so use them very carefully.")); setAboutData(about); setlocale(LC_COLLATE, "C"); KGlobal::locale()->insertCatalogue("kcmbackground"); QStringList sl; QMap< gid_t, QStringList > tgmap; QMap< gid_t, QStringList >::Iterator tgmapi; QMap< gid_t, QStringList >::ConstIterator tgmapci; QMap< QString, QPair< int, QStringList > >::Iterator umapi; struct passwd *ps; for(setpwent(); (ps = getpwent());) { QString un(QFile::decodeName(ps->pw_name)); if(usermap.find(un) == usermap.end()) { usermap.insert(un, QPair< int, QStringList >(ps->pw_uid, sl)); if((tgmapi = tgmap.find(ps->pw_gid)) != tgmap.end()) (*tgmapi).append(un); else tgmap[ps->pw_gid] = un; } } endpwent(); struct group *grp; for(setgrent(); (grp = getgrent());) { QString gn(QFile::decodeName(grp->gr_name)); bool delme = false; if((tgmapi = tgmap.find(grp->gr_gid)) != tgmap.end()) { if((*tgmapi).count() == 1 && (*tgmapi).first() == gn) delme = true; else for(QStringList::ConstIterator it = (*tgmapi).begin(); it != (*tgmapi).end(); ++it) usermap[*it].second.append(gn); tgmap.remove(tgmapi); } if(!*grp->gr_mem || (delme && !grp->gr_mem[1] && gn == QFile::decodeName(*grp->gr_mem))) continue; do { QString un(QFile::decodeName(*grp->gr_mem)); if((umapi = usermap.find(un)) != usermap.end()) { if((*umapi).second.find(gn) == (*umapi).second.end()) (*umapi).second.append(gn); } else kdWarning() << "group '" << gn << "' contains unknown user '" << un << "'" << endl; } while(*++grp->gr_mem); } endgrent(); for(tgmapci = tgmap.begin(); tgmapci != tgmap.end(); ++tgmapci) kdWarning() << "user(s) '" << tgmapci.data().join(",") << "' have unknown GID " << tgmapci.key() << endl; config = new KSimpleConfig(QString::fromLatin1(KDE_CONFDIR "/kdm/kdmrc")); QVBoxLayout *top = new QVBoxLayout(this); tab = new QTabWidget(this); // ***** // _don't_ add a theme configurator until the theming engine is _really_ done!! // ***** appearance = new KDMAppearanceWidget(this); tab->addTab(appearance, i18n("A&ppearance")); connect(appearance, SIGNAL(changed(bool)), SIGNAL(changed(bool))); font = new KDMFontWidget(this); tab->addTab(font, i18n("&Font")); connect(font, SIGNAL(changed(bool)), SIGNAL(changed(bool))); background = new KBackground(this); tab->addTab(background, i18n("&Background")); connect(background, SIGNAL(changed(bool)), SIGNAL(changed(bool))); sessions = new KDMSessionsWidget(this); tab->addTab(sessions, i18n("&Shutdown")); connect(sessions, SIGNAL(changed(bool)), SIGNAL(changed(bool))); users = new KDMUsersWidget(this, 0); tab->addTab(users, i18n("&Users")); connect(users, SIGNAL(changed(bool)), SIGNAL(changed(bool))); connect(users, SIGNAL(setMinMaxUID(int, int)), SLOT(slotMinMaxUID(int, int))); connect(this, SIGNAL(addUsers(const QMap< QString, int > &)), users, SLOT(slotAddUsers(const QMap< QString, int > &))); connect(this, SIGNAL(delUsers(const QMap< QString, int > &)), users, SLOT(slotDelUsers(const QMap< QString, int > &))); connect(this, SIGNAL(clearUsers()), users, SLOT(slotClearUsers())); convenience = new KDMConvenienceWidget(this, 0); tab->addTab(convenience, i18n("Con&venience")); connect(convenience, SIGNAL(changed(bool)), SIGNAL(changed(bool))); connect(this, SIGNAL(addUsers(const QMap< QString, int > &)), convenience, SLOT(slotAddUsers(const QMap< QString, int > &))); connect(this, SIGNAL(delUsers(const QMap< QString, int > &)), convenience, SLOT(slotDelUsers(const QMap< QString, int > &))); connect(this, SIGNAL(clearUsers()), convenience, SLOT(slotClearUsers())); load(); if(getuid() != 0 || !config->checkConfigFilesWritable(true)) { appearance->makeReadOnly(); font->makeReadOnly(); background->makeReadOnly(); users->makeReadOnly(); sessions->makeReadOnly(); convenience->makeReadOnly(); } top->addWidget(tab); }
int KMobileGnokii::readCalendarEntry( int index, KCal::Event &event ) { if (index < 0 || index >= GN_CALNOTE_MAX_NUMBER) return KIO::ERR_DOES_NOT_EXIST; gn_data_clear(&data); gn_calnote entry; memset(&entry, 0, sizeof(entry)); entry.location = index+1; data.calnote = &entry; data.calnote_list = &calnote_list; gn_error error = gn_sm_functions(GN_OP_GetCalendarNote, &data, &state); GNOKII_CHECK_ERROR(error); if (error != GN_ERR_NONE) return gn_error2kio_error(error); print_calnote( entry ); QDateTime dt_start = timestamp_2_QDateTime(entry.time); QDateTime dt_end = dt_start.addSecs( 60*60 ); // XXX: assume one hour event.setDtStart( dt_start ); event.setDtEnd( dt_end ); event.setSummary( QString::fromUtf8(entry.text) ); // type: switch (entry.type) { case GN_CALNOTE_MEETING: event.setCategories(i18n("MEETING")); break; case GN_CALNOTE_CALL: event.setCategories(i18n("PHONE CALL")); event.setDescription(QString::fromUtf8(entry.phone_number)); break; case GN_CALNOTE_BIRTHDAY: event.setCategories(i18n("BIRTHDAY")); break; case GN_CALNOTE_REMINDER: event.setCategories(i18n("REMINDER")); break; default: kdWarning() << "unknown calendar GN_CALNOTE_XXXX type #" << entry.type << endl; } // alarm: if (entry.alarm.enabled) { QDateTime at = timestamp_2_QDateTime(entry.alarm.timestamp); if (at.isValid() && dt_start.isValid()) { int seconds = abs(at.secsTo(dt_start)); seconds %= 60*60*24; /* max. 1 day in advance... */ KCal::Alarm *eventalarm = event.newAlarm(); eventalarm->setStartOffset(KCal::Duration(seconds)); } } // recurrence: switch (entry.recurrence) { case GN_CALNOTE_NEVER: break; case GN_CALNOTE_DAILY: event.recurrence()->setDaily(1,-1); break; case GN_CALNOTE_WEEKLY: case GN_CALNOTE_2WEEKLY: event.recurrence()->setDaily( 7 + (entry.recurrence==GN_CALNOTE_2WEEKLY ? 7:0) , -1); break; case GN_CALNOTE_MONTHLY: event.recurrence()->setMonthly(KCal::Recurrence::rMonthlyPos, 1, -1); break; case GN_CALNOTE_YEARLY: event.recurrence()->setYearly(KCal::Recurrence::rYearlyPos, 1, -1); break; default: // hourly event.recurrence()->setHourly(entry.recurrence, -1); break; } return 0; }
bool KSharedPixmap::x11Event(XEvent *event) { if (event->type != SelectionNotify) return false; XSelectionEvent *ev = &event->xselection; if (ev->selection != d->selection) return false; if ((ev->target != d->pixmap) || (ev->property == None)) { kdWarning(270) << k_funcinfo << "illegal selection notify event.\n"; d->selection = None; emit done(false); return true; } // Read pixmap handle from ev->property int dummy, format; unsigned long nitems, ldummy; unsigned char *pixmap_id = 0; Atom type; XGetWindowProperty(qt_xdisplay(), winId(), ev->property, 0, 1, false, d->pixmap, &type, &format, &nitems, &ldummy, &pixmap_id); if (nitems != 1 || !pixmap_id) { kdWarning(270) << k_funcinfo << "could not read property, nitems = " << nitems << "\n"; emit done(false); return true; } Window root; unsigned int width, height, udummy; void *drawable_id = (void *) pixmap_id; Drawable pixmap = *(Drawable*) drawable_id; Status status = XGetGeometry(qt_xdisplay(), pixmap, &root, &dummy, &dummy, &width, &height, &udummy, &udummy); if (status == BadDrawable) return false; if (d->rect.isEmpty()) { QPixmap::resize(width, height); XCopyArea(qt_xdisplay(), pixmap, ((KPixmap*)this)->handle(), qt_xget_temp_gc(qt_xscreen(), false), 0, 0, width, height, 0, 0); XFree(pixmap_id); XDeleteProperty(qt_xdisplay(), winId(), ev->property); d->selection = None; emit done(true); return true; } // Do some more processing here: Generate a tile that can be used as a // background tile for the rectangle "rect". //Check for origin off screen QPoint origin(0, 0); if( d->rect.topLeft().x() < 0 || d->rect.topLeft().y() < 0 ) { //Save the offset and relocate the rect corners QPoint tl = d->rect.topLeft(); QPoint br = d->rect.bottomRight(); if( tl.x() < 0 ) { origin.setX( abs( tl.x() ) ); tl.setX( 0 ); } if( tl.y() < 0 ) { origin.setY( abs( tl.y() ) ); tl.setY( 0 ); } QRect adjustedRect( tl, br ); d->rect = adjustedRect; } unsigned w = d->rect.width(), h = d->rect.height(); unsigned tw = QMIN(width, w), th = QMIN(height, h); unsigned xa = d->rect.x() % width, ya = d->rect.y() % height; unsigned t1w = QMIN(width-xa,tw), t1h = QMIN(height-ya,th); QPixmap::resize( tw+origin.x(), th+origin.y() ); XCopyArea(qt_xdisplay(), pixmap, ((KPixmap*)this)->handle(), qt_xget_temp_gc(qt_xscreen(), false), xa, ya, t1w+origin.x(), t1h+origin.y(), origin.x(), origin.y() ); XCopyArea(qt_xdisplay(), pixmap, ((KPixmap*)this)->handle(), qt_xget_temp_gc(qt_xscreen(), false), 0, ya, tw-t1w, t1h, t1w, 0); XCopyArea(qt_xdisplay(), pixmap, ((KPixmap*)this)->handle(), qt_xget_temp_gc(qt_xscreen(), false), xa, 0, t1w, th-t1h, 0, t1h); XCopyArea(qt_xdisplay(), pixmap, ((KPixmap*)this)->handle(), qt_xget_temp_gc(qt_xscreen(), false), 0, 0, tw-t1w, th-t1h, t1w, t1h); XFree(pixmap_id); d->selection = None; XDeleteProperty(qt_xdisplay(), winId(), ev->property); emit done(true); return true; }
/* * How does the search work * ------------------------ * We do the search respecting the current metacontact filter item. To do this, we iterate over the * elements in the KListView (KListViewDateItems) and, for each one, we iterate over its subcontacts, * manually searching the log files of each one. To avoid searching files twice, the months that have * been searched already are stored in searchedMonths. The matches are placed in the matches QMap. * Finally, the current date item is checked in the matches QMap, and if it is present, it is shown. * * Keyword highlighting is done in setMessages() : if the search field isn't empty, we highlight the * search keyword. * * The search is _not_ case sensitive */ void HistoryDialog::slotSearch() { if (mMainWidget->dateListView->childCount() == 0) return; QRegExp rx("^ <msg.*time=\"(\\d+) \\d+:\\d+:\\d+\" >([^<]*)<"); QMap<QDate, QValueList<Kopete::MetaContact*> > monthsSearched; QMap<QDate, QValueList<Kopete::MetaContact*> > matches; // cancel button pressed if (mSearching) { listViewShowElements(true); goto searchFinished; } listViewShowElements(false); initProgressBar(i18n("Searching..."), mMainWidget->dateListView->childCount()); mMainWidget->searchButton->setText(i18n("&Cancel")); mSearching = true; // iterate over items in the date list widget for(KListViewDateItem *curItem = static_cast<KListViewDateItem*>(mMainWidget->dateListView->firstChild()); curItem != 0; curItem = static_cast<KListViewDateItem *>(curItem->nextSibling()) ) { qApp->processEvents(); if (!mSearching) return; QDate month(curItem->date().year(),curItem->date().month(),1); // if we haven't searched the relevant history logs, search them now if (!monthsSearched[month].contains(curItem->metaContact())) { monthsSearched[month].push_back(curItem->metaContact()); QPtrList<Kopete::Contact> contacts = curItem->metaContact()->contacts(); for(QPtrListIterator<Kopete::Contact> it( contacts ); it.current(); ++it) { // get filename and open file QString filename(HistoryLogger::getFileName(*it, curItem->date())); if (!QFile::exists(filename)) continue; QFile file(filename); file.open(IO_ReadOnly); if (!file.isOpen()) { kdWarning(14310) << k_funcinfo << "Error opening " << file.name() << ": " << file.errorString() << endl; continue; } QTextStream stream(&file); QString textLine; while(!stream.atEnd()) { textLine = stream.readLine(); if (textLine.contains(mMainWidget->searchLine->text(), false)) { if(rx.search(textLine) != -1) { // only match message body if (rx.cap(2).contains(mMainWidget->searchLine->text())) matches[QDate(curItem->date().year(),curItem->date().month(),rx.cap(1).toInt())].push_back(curItem->metaContact()); } // this will happen when multiline messages are searched, properly // parsing the files would fix this else { } } qApp->processEvents(); if (!mSearching) return; } file.close(); } } // relevant logfiles have been searched now, check if current date matches if (matches[curItem->date()].contains(curItem->metaContact())) curItem->setVisible(true); // Next date item mMainWidget->searchProgress->advance(1); } searchFinished: mMainWidget->searchButton->setText(i18n("Se&arch")); mSearching = false; doneProgressBar(); }
const QPixmap& ResizeHandle::handlePixmap( DrawType drawType, bool hover ) { const char * resize_forwardsDiagonal_hover_xpm[] = { "13 13 3 1", " c None", ". c #000000", "+ c #8EA5D0", " ", " ....... ", " ..+++. ", " .++++. ", " .+++++. ", " . .+++++.. ", " ...+++++... ", " ..+++++. . ", " .+++++. ", " .++++. ", " .+++.. ", " ....... ", " "}; static QPixmap pixmap_forwardsDiagonal_hover(resize_forwardsDiagonal_hover_xpm); const char * resize_forwardsDiagonal_nohover_xpm[] = { "13 13 2 1", " c None", ". c #000000", " ", " ....... ", " ...... ", " ...... ", " ....... ", " . ........ ", " ........... ", " ........ . ", " ....... ", " ...... ", " ...... ", " ....... ", " "}; static QPixmap pixmap_forwardsDiagonal_nohover(resize_forwardsDiagonal_nohover_xpm); const char * resize_backwardsDiagonal_hover_xpm[] = { "13 13 3 1", " c None", ". c #000000", "+ c #8EA5D0", " ", " ....... ", " .+++.. ", " .++++. ", " .+++++. ", " ..+++++. . ", " ...+++++... ", " . .+++++.. ", " .+++++. ", " .++++. ", " ..+++. ", " ....... ", " "}; static QPixmap pixmap_backwardsDiagonal_hover(resize_backwardsDiagonal_hover_xpm); const char * resize_backwardsDiagonal_nohover_xpm[] = { "13 13 2 1", " c None", ". c #000000", " ", " ....... ", " ...... ", " ...... ", " ....... ", " ........ . ", " ........... ", " . ........ ", " ....... ", " ...... ", " ...... ", " ....... ", " "}; static QPixmap pixmap_backwardsDiagonal_nohover(resize_backwardsDiagonal_nohover_xpm); const char * resize_vertical_hover_xpm[] = { "13 13 3 1", " c None", ". c #000000", "+ c #8EA5D0", " . ", " ... ", " ..+.. ", " ..+++.. ", " ..+++++.. ", " .+++. ", " .+++. ", " .+++. ", " ..+++++.. ", " ..+++.. ", " ..+.. ", " ... ", " . "}; static QPixmap pixmap_vertical_hover(resize_vertical_hover_xpm); const char * resize_vertical_nohover_xpm[] = { "13 13 2 1", " c None", ". c #000000", " . ", " ... ", " ..... ", " ....... ", " ......... ", " ..... ", " ..... ", " ..... ", " ......... ", " ....... ", " ..... ", " ... ", " . "}; static QPixmap pixmap_vertical_nohover(resize_vertical_nohover_xpm); const char * resize_horizontal_hover_xpm[] = { "13 13 3 1", " c None", ". c #000000", "+ c #8EA5D0", " ", " ", " . . ", " .. .. ", " ..+...+.. ", " ..+++++++.. ", "..+++++++++..", " ..+++++++.. ", " ..+...+.. ", " .. .. ", " . . ", " ", " "}; static QPixmap pixmap_horizontal_hover(resize_horizontal_hover_xpm); const char * resize_horizontal_nohover_xpm[] = { "13 13 2 1", " c None", ". c #000000", " ", " ", " . . ", " .. .. ", " ......... ", " ........... ", ".............", " ........... ", " ......... ", " .. .. ", " . . ", " ", " "}; static QPixmap pixmap_horizontal_nohover(resize_horizontal_nohover_xpm); const char * point_rect_hover_xpm[] = { "13 13 3 1", " c None", ". c #000000", "+ c #8EA5D0", " ", " ", " ", " ", " ", " ..... ", " .+++. ", " .+++. ", " .+++. ", " ..... ", " ", " ", " "}; static QPixmap pixmap_point_rect_hover(point_rect_hover_xpm); const char * point_rect_nohover_xpm[] = { "13 13 3 1", " c None", ". c #000000", "+ c #FFFFFF", " ", " ", " ", " ", " ", " ..... ", " .+++. ", " .+++. ", " .+++. ", " ..... ", " ", " ", " "}; static QPixmap pixmap_point_rect_nohover(point_rect_nohover_xpm); if (hover) { switch(drawType) { case ResizeHandle::dt_resize_forwardsDiagonal: return pixmap_forwardsDiagonal_hover; case ResizeHandle::dt_resize_backwardsDiagonal: return pixmap_backwardsDiagonal_hover; case ResizeHandle::dt_resize_vertical: return pixmap_vertical_hover; case ResizeHandle::dt_resize_horizontal: return pixmap_horizontal_hover; case ResizeHandle::dt_point_rect: return pixmap_point_rect_hover; case ResizeHandle::dt_point_crosshair: case ResizeHandle::dt_rotate_topLeft: case ResizeHandle::dt_rotate_topRight: case ResizeHandle::dt_rotate_bottomRight: case ResizeHandle::dt_rotate_bottomLeft: kdWarning() << k_funcinfo << "ResizeHandle of type " << drawType << " does not have an image." << endl; } } else { switch(drawType) { case ResizeHandle::dt_resize_forwardsDiagonal: return pixmap_forwardsDiagonal_nohover; case ResizeHandle::dt_resize_backwardsDiagonal: return pixmap_backwardsDiagonal_nohover; case ResizeHandle::dt_resize_vertical: return pixmap_vertical_nohover; case ResizeHandle::dt_resize_horizontal: return pixmap_horizontal_nohover; case ResizeHandle::dt_point_rect: return pixmap_point_rect_nohover; case ResizeHandle::dt_point_crosshair: case ResizeHandle::dt_rotate_topLeft: case ResizeHandle::dt_rotate_topRight: case ResizeHandle::dt_rotate_bottomRight: case ResizeHandle::dt_rotate_bottomLeft: kdWarning() << k_funcinfo << "ResizeHandle of type " << drawType << " does not have an image." << endl; } } static QPixmap blank; return blank; }