23 files changed, 82 insertions, 88 deletions
diff --git a/noncore/apps/advancedfm/advancedfmMenu.cpp b/noncore/apps/advancedfm/advancedfmMenu.cpp index 26bc36d..78f9da2 100644 --- a/noncore/apps/advancedfm/advancedfmMenu.cpp +++ b/noncore/apps/advancedfm/advancedfmMenu.cpp @@ -1,854 +1,850 @@ /*************************************************************************** AdvancedFm.cpp ------------------- ** Created: Sat Mar 9 23:33:09 2002 copyright : (C) 2002 by ljp email : ljp@llornkcor.com * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #include "advancedfm.h" #include "output.h" #include "filePermissions.h" #include <opie/otabwidget.h> #include <opie/oprocess.h> #include <qpe/lnkproperties.h> #include <qpe/qpeapplication.h> #include <qpe/resource.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/applnk.h> #include <qpe/ir.h> #include <qmessagebox.h> #include <qmultilineedit.h> #include <qstring.h> #include <qlayout.h> #include <qpixmap.h> #include <qcombobox.h> #include <qpopupmenu.h> #include <qtabwidget.h> #include <qtoolbutton.h> #include <qlineedit.h> #include <qlistview.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <dirent.h> #include <sys/sendfile.h> #include <fcntl.h> void AdvancedFm::doDirChange() { QString pathItem = CurrentView()->currentItem()->text(0); if( pathItem == "../") { ListClicked( CurrentView()->currentItem()); } else { if( pathItem.find(" -> ",0,TRUE) != -1) pathItem = dealWithSymName((const QString&)pathItem)+"/"; // qWarning(pathItem); gotoDirectory( CurrentDir()->path()+"/"+pathItem.left( pathItem.length() - 1) ); } } void AdvancedFm::showMenuHidden() { if (b) { CurrentDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All); OtherDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All); fileMenu->setItemChecked( fileMenu->idAt(0),TRUE); } else { CurrentDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All); OtherDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All); fileMenu->setItemChecked( fileMenu->idAt(0),FALSE); } b = !b; populateView(); } void AdvancedFm::showHidden() { if (b) { CurrentDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All); OtherDir()->setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All); } else { CurrentDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All); OtherDir()->setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All); } populateView(); } QString AdvancedFm::dealWithSymName(const QString &fileName) { QString strItem = fileName; return strItem.right( (strItem.length() - strItem.find("->",0,TRUE)) - 4); } void AdvancedFm::runThis() { if( !CurrentView()->currentItem()) return; QString fs; QDir *thisDir = CurrentDir(); QString curFile = CurrentView()->currentItem()->text(0); QString path = thisDir->canonicalPath(); if( curFile.find("@",0,TRUE) !=-1 || curFile.find("->",0,TRUE) !=-1 ) //if symlink curFile = dealWithSymName((const QString&)curFile); if(curFile != "../") { fs = getFileSystemType((const QString &) path); QFileInfo fileInfo( path + "/" + curFile); // qDebug( fileInfo.owner()); if( (fileInfo.permission( QFileInfo::ExeUser) | fileInfo.permission( QFileInfo::ExeGroup) | fileInfo.permission( QFileInfo::ExeOther)) // & fs.find("vfat",0,TRUE) == -1) { | fs == "vfat" && fileInfo.filePath().contains("/bin") ) { QCopEnvelope e("QPE/System", "execute(QString)" ); e << curFile; } else { curFile = path + "/" + curFile; DocLnk nf(curFile); QString execStr = nf.exec(); // qDebug( execStr); if( execStr.isEmpty() ) { } else { nf.execute(); } } } } void AdvancedFm::runText() { if( !CurrentView()->currentItem()) return; QString curFile = CurrentView()->currentItem()->text(0); if(curFile != "../") { if( curFile.find("@",0,TRUE) !=-1 || curFile.find("->",0,TRUE) !=-1 ) //if symlink curFile = dealWithSymName((const QString&)curFile); curFile = CurrentDir()->canonicalPath()+"/"+curFile; QCopEnvelope e("QPE/Application/textedit", "setDocument(QString)" ); e << curFile; } } void AdvancedFm::makeDir() { InputDialog *fileDlg; fileDlg = new InputDialog(this,tr("Make Directory"),TRUE, 0); fileDlg->exec(); if( fileDlg->result() == 1 ) { QDir *thisDir = CurrentDir(); QString filename = fileDlg->LineEdit1->text(); thisDir->mkdir( thisDir->canonicalPath()+"/"+filename); } populateView(); } void AdvancedFm::doDelete() { QStringList curFileList = getPath(); bool doMsg=true; int count = curFileList.count(); if( count > 0) { if(count > 1 ) { QString msg; msg=tr("Really delete\n%1 files?").arg(count); switch ( QMessageBox::warning(this,tr("Delete"),msg ,tr("Yes"),tr("No"),0,0,1) ) { case 0: doMsg=false; break; case 1: return; break; }; } QString myFile; for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { myFile = (*it); if( myFile.find(" -> ",0,TRUE) != -1) myFile = myFile.left( myFile.find(" -> ",0,TRUE)); QString f = CurrentDir()->canonicalPath(); if(f.right(1).find("/",0,TRUE) == -1) f += "/"; f += myFile; if(QDir(f).exists() && !QFileInfo(f).isSymLink() ) { //if file is a directory switch ( QMessageBox::warning( this, tr("Delete Directory?"), tr("Really delete %1\nand all it's contents ?" ).arg( f ) , tr("Yes"), tr("No"), 0, 0, 1) ) { case 0: { f=f.left(f.length()-1); QString cmd="rm -rf "+f; startProcess( (const QString)cmd.latin1() ); populateView(); } break; case 1: // exit break; }; } else { if(doMsg) { switch ( QMessageBox::warning(this,tr("Delete"), tr("Really delete\n%1?").arg( myFile ), tr("Yes"), tr("No"), 0, 0, 1) ) { case 1: return; break; }; } QString cmd="rm "+f; QFile file(f); QFileInfo fi(myFile); if( fi.fileName().find("../",0,TRUE)==-1) { // qDebug("remove link files "+myFile); // DocLnk lnk(f); DocLnk *lnk; lnk = new DocLnk(f); // qDebug("Deleting doclnk " + lnk->linkFile()); if(lnk->isValid()) lnk->removeLinkFile(); // delete lnk; file.remove(); } } } } populateView(); } void AdvancedFm::filePerms() { QStringList curFileList = getPath(); QString filePath; filePath = CurrentDir()->canonicalPath()+"/"; for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { filePermissions *filePerm; filePerm = new filePermissions(this, "Permissions",true,0,(const QString &)(filePath+*it)); - filePerm->showMaximized(); - filePerm->exec(); + QPEApplication::execDialog( filePerm );
if( filePerm) delete filePerm; } populateView(); } void AdvancedFm::doProperties() { #if defined(QT_QWS_OPIE) QStringList curFileList = getPath(); QString filePath; filePath = CurrentDir()->canonicalPath()+"/"; // qDebug("%d",curFileList.count()); for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { // qDebug((filePath+*it)); DocLnk lnk( (filePath+*it)); LnkProperties prop( &lnk ); - prop.showMaximized(); - prop.exec(); + QPEApplication::execDialog( &prop );
} #endif } void AdvancedFm::upDir() { QDir *thisDir = CurrentDir(); QString current = thisDir->canonicalPath(); QDir dir(current); dir.cdUp(); current = dir.canonicalPath(); chdir( current.latin1() ); thisDir->cd( current, TRUE); populateView(); update(); } void AdvancedFm::copy() { qApp->processEvents(); QStringList curFileList = getPath(); QDir *thisDir = CurrentDir(); QDir *thatDir = OtherDir(); bool doMsg=true; int count=curFileList.count(); if( count > 0) { if(count > 1 ){ QString msg; msg=tr("Really copy\n%1 files?").arg(count); switch ( QMessageBox::warning(this,tr("Copy"),msg ,tr("Yes"),tr("No"),0,0,1) ) { case 0: doMsg=false; break; case 1: return; break; }; } QString curFile, item, destFile; for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { item=(*it); if(item.find("->",0,TRUE)) //symlink item = item.left(item.find("->",0,TRUE)); curFile = thisDir->canonicalPath()+"/"+ item; destFile = thatDir->canonicalPath()+"/"+ item; // qDebug("Destination file is "+destFile); // qDebug("CurrentFile file is " + curFile); QFile f(destFile); if( f.exists()) { if(doMsg) { switch ( QMessageBox::warning(this,tr("File Exists!"), tr("%1 exists. Ok to overwrite?").arg( item ), tr("Yes"),tr("No"),0,0,1) ) { case 1: return; break; }; } f.remove(); } if( !copyFile( curFile, destFile) ) { QMessageBox::message("AdvancedFm", tr( "Could not copy %1 to %2").arg( curFile ).arg( destFile ) ); return; } } setOtherTabCurrent(); rePopulate(); } } void AdvancedFm::copyAs() { qApp->processEvents(); QStringList curFileList = getPath(); QString curFile, item; InputDialog *fileDlg; QDir *thisDir = CurrentDir(); QDir *thatDir = OtherDir(); for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { QString destFile; item=(*it); curFile = thisDir->canonicalPath()+"/"+(*it); fileDlg = new InputDialog( this, tr("Copy "+curFile+" As"), TRUE, 0); fileDlg->setInputText((const QString &) destFile ); fileDlg->exec(); if( fileDlg->result() == 1 ) { QString filename = fileDlg->LineEdit1->text(); destFile = thatDir->canonicalPath()+"/"+filename; QFile f( destFile); if( f.exists()) { switch (QMessageBox::warning(this,tr("File Exists!"), item+tr("\nexists. Ok to overwrite?"), tr("Yes"),tr("No"),0,0,1) ) { case 0: f.remove(); break; case 1: return; break; }; } if( !copyFile( curFile, destFile) ) { QMessageBox::message("AdvancedFm",tr("Could not copy\n") +curFile +tr("to\n")+destFile); return; } } delete fileDlg; } rePopulate(); setOtherTabCurrent(); } void AdvancedFm::copySameDir() { qApp->processEvents(); QStringList curFileList = getPath(); QString curFile, item, destFile; InputDialog *fileDlg; QDir *thisDir = CurrentDir(); for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { item=(*it); curFile = thisDir->canonicalPath()+"/"+ item; fileDlg = new InputDialog(this,tr("Copy ")+curFile+tr(" As"),TRUE, 0); fileDlg->setInputText((const QString &) destFile ); fileDlg->exec(); if( fileDlg->result() == 1 ) { QString filename = fileDlg->LineEdit1->text(); destFile = thisDir->canonicalPath()+"/"+filename; QFile f(destFile); if( f.exists()) { switch (QMessageBox::warning(this,tr("Delete"), destFile+tr(" already exists.\nDo you really want to delete it?"), tr("Yes"),tr("No"),0,0,1) ) { case 0: f.remove(); break; case 1: return; break; }; } if(!copyFile( curFile,destFile) ) { QMessageBox::message("AdvancedFm",tr("Could not copy\n") +curFile +tr("to\n")+destFile); return; } // qDebug("copy "+curFile+" as "+destFile); } delete fileDlg; } rePopulate(); } void AdvancedFm::move() { qApp->processEvents(); QStringList curFileList = getPath(); if( curFileList.count() > 0) { QString curFile, destFile, item; QDir *thisDir = CurrentDir(); QDir *thatDir = OtherDir(); for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { item=(*it); QString destFile = thatDir->canonicalPath(); if(destFile.right(1).find("/",0,TRUE) == -1) destFile+="/"; destFile += item; // qDebug("Destination file is "+destFile); curFile = thisDir->canonicalPath(); if(curFile.right(1).find("/",0,TRUE) == -1) curFile +="/"; curFile+= item; // qDebug("CurrentFile file is " + curFile); if(QFileInfo(curFile).isDir()) { moveDirectory( curFile, destFile ); rePopulate(); return; } QFile f( curFile); if( f.exists()) { if( !copyFile( curFile, destFile) ) { QMessageBox::message(tr("Note"),tr("Could not move\n")+curFile); return; } else QFile::remove(curFile); } } } rePopulate(); setOtherTabCurrent(); } bool AdvancedFm::moveDirectory( const QString & src, const QString & dest ) { int err = 0; if( copyDirectory( src, dest ) ) { QString cmd = "rm -rf " + src; err = system((const char*)cmd); } else err = -1; if(err!=0) { QMessageBox::message(tr("Note"),tr("Could not move\n") + src); return false; } return true; } bool AdvancedFm::copyDirectory( const QString & src, const QString & dest ) { QString cmd = "/bin/cp -fpR " + src + " " + dest; qWarning(cmd); int err = system( (const char *) cmd ); if ( err != 0 ) { QMessageBox::message("AdvancedFm", tr( "Could not copy \n%1 \nto \n%2").arg( src ).arg( dest ) ); return false; } return true; } bool AdvancedFm::copyFile( const QString & src, const QString & dest ) { if(QFileInfo(src).isDir()) { if( copyDirectory( src, dest )) { setOtherTabCurrent(); populateView(); return true; } else return false; } bool success = true; struct stat status; QFile srcFile(src); QFile destFile(dest); int err=0; int read_fd=0; int write_fd=0; struct stat stat_buf; off_t offset = 0; if(!srcFile.open( IO_ReadOnly|IO_Raw)) { // qWarning("open failed"); return success = false; } read_fd = srcFile.handle(); if(read_fd != -1) { fstat (read_fd, &stat_buf); if( !destFile.open( IO_WriteOnly|IO_Raw ) ) { // qWarning("destfile open failed"); return success = false; } write_fd = destFile.handle(); if(write_fd != -1) { err = sendfile(write_fd, read_fd, &offset, stat_buf.st_size); if( err == -1) { QString msg; switch(err) { case EBADF : msg = "The input file was not opened for reading or the output file was not opened for writing. "; case EINVAL: msg = "Descriptor is not valid or locked. "; case ENOMEM: msg = "Insufficient memory to read from in_fd."; case EIO: msg = "Unspecified error while reading from in_fd."; }; success = false; // qWarning(msg); } } else { success = false; } } else { success = false; } srcFile.close(); destFile.close(); // Set file permissions if( stat( (const char *) src, &status ) == 0 ) { chmod( (const char *) dest, status.st_mode ); } return success; } void AdvancedFm::runCommand() { if( !CurrentView()->currentItem()) return; QDir *thisDir = CurrentDir(); QString curFile; curFile = thisDir->canonicalPath() +"/"+ CurrentView()->currentItem()->text(0); InputDialog *fileDlg; fileDlg = new InputDialog(this,tr("Run Command"),TRUE, 0); fileDlg->setInputText(curFile); fileDlg->exec(); //QString command; if( fileDlg->result() == 1 ) { // qDebug(fileDlg->LineEdit1->text()); QStringList command; command << "/bin/sh"; command << "-c"; command << fileDlg->LineEdit1->text(); Output *outDlg; outDlg = new Output( command, this, tr("AdvancedFm Output"), true); - outDlg->showMaximized(); - outDlg->exec(); + QPEApplication::execDialog( outDlg );
qApp->processEvents(); } } void AdvancedFm::runCommandStd() { if( !CurrentView()->currentItem()) return; QString curFile; QDir *thisDir = CurrentDir(); QListView *thisView = CurrentView(); if( thisView->currentItem()) curFile = thisDir->canonicalPath() +"/"+ thisView->currentItem()->text(0); InputDialog *fileDlg; fileDlg = new InputDialog(this,tr("Run Command"),TRUE, 0); fileDlg->setInputText(curFile); fileDlg->exec(); if( fileDlg->result() == 1 ) { qApp->processEvents(); startProcess( (const QString)fileDlg->LineEdit1->text().latin1()); } } void AdvancedFm::fileStatus() { if( !CurrentView()->currentItem()) return; QString curFile; curFile = CurrentView()->currentItem()->text(0); QStringList command; command << "/bin/sh"; command << "-c"; command << "stat -l "+ curFile; Output *outDlg; outDlg = new Output( command, this, tr("AdvancedFm Output"), true); - outDlg->showMaximized(); - outDlg->exec(); + QPEApplication::execDialog( outDlg );
qApp->processEvents(); } void AdvancedFm::mkDir() { makeDir(); } void AdvancedFm::rn() { renameIt(); } void AdvancedFm::del() { doDelete(); } void AdvancedFm::mkSym() { QString cmd; QStringList curFileList = getPath(); if( curFileList.count() > 0) { QDir *thisDir = CurrentDir(); QDir * thatDir = OtherDir(); for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { QString destName = thatDir->canonicalPath()+"/"+(*it); if(destName.right(1) == "/") { destName = destName.left( destName.length() -1); } QString curFile = thisDir->canonicalPath()+"/"+(*it); if( curFile.right(1) == "/") { curFile = curFile.left( curFile.length() -1); } cmd = "ln -s "+curFile+" "+destName; // qDebug(cmd); startProcess( (const QString)cmd ); } rePopulate(); setOtherTabCurrent(); } } void AdvancedFm::doBeam() { Ir ir; if(!ir.supported()) { } else { QStringList curFileList = getPath(); if( curFileList.count() > 0) { for ( QStringList::Iterator it = curFileList.begin(); it != curFileList.end(); ++it ) { QString curFile = (*it); QString curFilePath = CurrentDir()->canonicalPath()+"/"+curFile; if( curFilePath.right(1) == "/") { curFilePath = curFilePath.left( curFilePath.length() -1); } Ir *file = new Ir(this, "IR"); connect(file, SIGNAL(done(Ir*)), this, SLOT( fileBeamFinished( Ir * ))); file->send( curFilePath, curFile ); } } } } void AdvancedFm::fileBeamFinished( Ir *) { QMessageBox::message( tr("Advancedfm Beam out"), tr("Ir sent.") ,tr("Ok") ); } void AdvancedFm::selectAll() { QListView *thisView = CurrentView(); thisView->selectAll(true); thisView->setSelected( thisView->firstChild(),false); } void AdvancedFm::startProcess(const QString & cmd) { QStringList command; OProcess *process; process = new OProcess(); connect(process, SIGNAL(processExited(OProcess *)), this, SLOT( processEnded(OProcess *))); connect(process, SIGNAL( receivedStderr(OProcess *, char *, int)), this, SLOT( oprocessStderr(OProcess *, char *, int))); command << "/bin/sh"; command << "-c"; command << cmd.latin1(); *process << command; if(!process->start(OProcess::NotifyOnExit, OProcess::All) ) qDebug("could not start process"); } void AdvancedFm::processEnded(OProcess *) { rePopulate(); } void AdvancedFm::oprocessStderr(OProcess*, char *buffer, int ) { // qWarning("received stderrt %d bytes", buflen); QString lineStr = buffer; QMessageBox::warning( this, tr("Error"), lineStr ,tr("Ok") ); } bool AdvancedFm::eventFilter( QObject * o, QEvent * e ) { if ( o->inherits( "QLineEdit" ) ) { if ( e->type() == QEvent::KeyPress ) { QKeyEvent *ke = (QKeyEvent*)e; if ( ke->key() == Key_Return || ke->key() == Key_Enter ) { okRename(); return true; } else if ( ke->key() == Key_Escape ) { cancelRename(); return true; } } else if ( e->type() == QEvent::FocusOut ) { cancelRename(); return true; } } if ( o->inherits( "QListView" ) ) { if ( e->type() == QEvent::FocusIn ) { if( o == Local_View) { //keep track of which view whichTab=1; } else { whichTab=2; } } OtherView()->setSelected( OtherView()->currentItem(), FALSE );//make sure there's correct selection } return QWidget::eventFilter( o, e ); } void AdvancedFm::cancelRename() { // qDebug("cancel rename"); QListView * view; view = CurrentView(); bool resetFocus = view->viewport()->focusProxy() == renameBox; delete renameBox; renameBox = 0; if ( resetFocus ) { view->viewport()->setFocusProxy( view); view->setFocus(); } } void AdvancedFm::doRename(QListView * view) { if( !CurrentView()->currentItem()) return; QRect r = view->itemRect( view->currentItem( )); r = QRect( view->viewportToContents( r.topLeft() ), r.size() ); r.setX( view->contentsX() ); if ( r.width() > view->visibleWidth() ) r.setWidth( view->visibleWidth() ); renameBox = new QLineEdit( view->viewport(), "qt_renamebox" ); renameBox->setFrame(true); renameBox->setText( view->currentItem()->text(0) ); renameBox->selectAll(); renameBox->installEventFilter( this ); view->addChild( renameBox, r.x(), r.y() ); renameBox->resize( r.size() ); view->viewport()->setFocusProxy( renameBox ); renameBox->setFocus(); renameBox->show(); } void AdvancedFm::renameIt() { if( !CurrentView()->currentItem()) return; QListView *thisView = CurrentView(); oldName = thisView->currentItem()->text(0); doRename( thisView ); } void AdvancedFm::okRename() { if( !CurrentView()->currentItem()) return; QString newName = renameBox->text(); cancelRename(); QListView * view = CurrentView(); QString path = CurrentDir()->canonicalPath() + "/"; oldName = path + oldName; newName = path + newName; if( rename( oldName.latin1(), newName.latin1())== -1) QMessageBox::message(tr("Note"),tr("Could not rename")); else oldName = ""; view->takeItem( view->currentItem() ); delete view->currentItem(); rePopulate(); } void AdvancedFm::openSearch() { QMessageBox::message(tr("Note"),tr("Not Yet Implemented")); } diff --git a/noncore/apps/checkbook/checkbook.cpp b/noncore/apps/checkbook/checkbook.cpp index a42c824..a5492e4 100644 --- a/noncore/apps/checkbook/checkbook.cpp +++ b/noncore/apps/checkbook/checkbook.cpp @@ -230,560 +230,558 @@ QWidget *Checkbook::initTransactions() tranTable->setColumnWidthMode( COL_SORTDATE, QListView::Manual ); tranTable->setColumnWidth( COL_SORTDATE, 0); tranTable->addColumn( tr( "Num" ) ); tranTable->addColumn( tr( "Date" ) ); //tranTable->addColumn( tr( "Cleared" ) ); tranTable->addColumn( tr( "Description" ) ); int column = tranTable->addColumn( tr( "Amount" ) ); tranTable->setColumnAlignment( column, Qt::AlignRight ); column=tranTable->addColumn( tr("Balance") ); tranTable->setColumnAlignment( column, Qt::AlignRight ); tranTable->setAllColumnsShowFocus( TRUE ); tranTable->setSorting( -1 ); layout->addMultiCellWidget( tranTable, 1, 1, 0, 2 ); QPEApplication::setStylusOperation( tranTable->viewport(), QPEApplication::RightOnHold ); connect( tranTable, SIGNAL( rightButtonPressed( QListViewItem *, const QPoint &, int ) ), this, SLOT( slotMenuTran(QListViewItem *, const QPoint &) ) ); connect( tranTable, SIGNAL( doubleClicked( QListViewItem * ) ), this, SLOT( slotEditTran() ) ); _sortCol=COL_ID; // Buttons QPushButton *btn = new QPushButton( Resource::loadPixmap( "new" ), tr( "New" ), control ); QWhatsThis::add( btn, tr( "Click here to add a new transaction." ) ); connect( btn, SIGNAL( clicked() ), this, SLOT( slotNewTran() ) ); layout->addWidget( btn, 2, 0 ); btn = new QPushButton( Resource::loadPixmap( "edit" ), tr( "Edit" ), control ); QWhatsThis::add( btn, tr( "Select a transaction and then click here to edit it." ) ); connect( btn, SIGNAL( clicked() ), this, SLOT( slotEditTran() ) ); layout->addWidget( btn, 2, 1 ); btn = new QPushButton( Resource::loadPixmap( "trash" ), tr( "Delete" ), control ); QWhatsThis::add( btn, tr( "Select a checkbook and then click here to delete it." ) ); connect( btn, SIGNAL( clicked() ), this, SLOT( slotDeleteTran() ) ); layout->addWidget( btn, 2, 2 ); return( control ); } // --- initCharts ------------------------------------------------------------- QWidget *Checkbook::initCharts() { graphInfo = 0x0; QWidget *control = new QWidget( mainWidget, tr("Charts") ); QGridLayout *layout = new QGridLayout( control ); layout->setSpacing( 2 ); layout->setMargin( 4 ); graphWidget = new Graph( control ); QWhatsThis::add( graphWidget, tr( "Select the desired chart below and then click on the Draw button." ) ); layout->addMultiCellWidget( graphWidget, 0, 0, 0, 2 ); graphList = new QComboBox( control ); QWhatsThis::add( graphList, tr( "Click here to select the desired chart type." ) ); graphList->insertItem( tr( "Account balance" ) ); graphList->insertItem( tr( "Withdrawals by category" ) ); graphList->insertItem( tr( "Deposits by category" ) ); layout->addMultiCellWidget( graphList, 1, 1, 0, 1 ); QPushButton *btn = new QPushButton( Resource::loadPixmap( "checkbook/drawbtn" ), tr( "Draw" ), control ); QWhatsThis::add( btn, tr( "Click here to draw the selected chart." ) ); connect( btn, SIGNAL( clicked() ), this, SLOT( slotDrawGraph() ) ); layout->addWidget( btn, 1, 2 ); return control; } // --- loadCheckbook ---------------------------------------------------------- void Checkbook::loadCheckbook() { if ( !info ) { return; } tranList = info->transactions(); passwordCB->setChecked( !info->password().isNull() ); nameEdit->setText( info->name() ); QString temptext = info->type(); int i = typeList->count(); while ( i > 0 ) { i--; typeList->setCurrentItem( i ); if ( typeList->currentText() == temptext ) { break; } } if( i<=0 ) { typeList->insertItem( temptext, 0 ); typeList->setCurrentItem(0); } bankEdit->setText( info->bank() ); acctNumEdit->setText( info->account() ); pinNumEdit->setText( info->pin() ); temptext.setNum( info->startingBalance(), 'f', 2 ); balanceEdit->setText( temptext ); notesEdit->setText( info->notes() ); // Load transactions float amount; QString stramount; for ( TranInfo *tran = tranList->first(); tran; tran = tranList->next() ) { amount = tran->amount(); if ( tran->withdrawal() ) { amount *= -1; } stramount.sprintf( "%s%.2f", _pCfg->getCurrencySymbol().latin1(), amount ); ( void ) new CBListItem( tran, tranTable, tran->getIdStr(), tran->datestr(false), tran->number(), tran->datestr(true), tran->desc(), stramount ); } // set sort order bool bOk=false; for(int i=0; i<_cbSortType->count(); i++) { if( _cbSortType->text(i)==info->getSortOrder() ) { _cbSortType->setCurrentItem(i); slotSortChanged( info->getSortOrder() ); bOk=true; break; } } if( !bOk ) { _cbSortType->setCurrentItem(0); slotSortChanged( _cbSortType->currentText() ); } // calc running balance adjustBalance(); } // --- adjustBalance ---------------------------------------------------------- void Checkbook::adjustBalance() { // update running balance in register QString sRunning; float bal=info->startingBalance(); for(CBListItem *item=(CBListItem *)tranTable->firstChild(); item; item=(CBListItem *)item->nextSibling() ) { TranInfo *tran=item->getTranInfo(); bal=bal + (tran->withdrawal() ? -1 : 1)*tran->amount() - tran->fee(); sRunning.sprintf( "%s%.2f", _pCfg->getCurrencySymbol().latin1(), bal ); item->setText( COL_BAL, sRunning); } } // --- resort ----------------------------------------------------------------- void Checkbook::resort() { tranTable->setSorting(_sortCol); tranTable->sort(); tranTable->setSorting(-1); } // --- accept ----------------------------------------------------------------- void Checkbook::accept() { info->setName( nameEdit->text() ); info->setType( typeList->currentText() ); info->setBank( bankEdit->text() ); info->setAccount( acctNumEdit->text() ); info->setPin( pinNumEdit->text() ); bool ok; info->setStartingBalance( balanceEdit->text().toFloat( &ok ) ); info->setNotes( notesEdit->text() ); QDialog::accept(); } // --- slotPasswordClicked ---------------------------------------------------- void Checkbook::slotPasswordClicked() { if ( info->password().isNull() && passwordCB->isChecked() ) { Password *pw = new Password( this, tr( "Enter password" ), tr( "Please enter your password:" ) ); if ( pw->exec() != QDialog::Accepted ) { passwordCB->setChecked( FALSE ); delete pw; return; } info->setPassword( pw->password ); delete pw; pw = new Password( this, tr( "Confirm password" ), tr( "Please confirm your password:" ) ); if ( pw->exec() != QDialog::Accepted || pw->password != info->password() ) { passwordCB->setChecked( FALSE ); info->setPassword( QString::null ); } delete pw; } else if ( !info->password().isNull() && !passwordCB->isChecked() ) { Password *pw = new Password( this, tr( "Enter password" ), tr( "Please enter your password to confirm removal of password protection:" ) ); if ( pw->exec() == QDialog::Accepted && pw->password == info->password() ) { info->setPassword( QString::null ); delete pw; return; } else { passwordCB->setChecked( TRUE ); } delete pw; } } void Checkbook::slotNameChanged( const QString &newname ) { info->setName( newname ); // TODO - need filedir // QString namestr = filedir; // namestr.append( newname ); // namestr.append( ".qcb" ); // info->setFilename( namestr ); QString namestr = newname; namestr.append( " - " ); namestr.append( tr( "Checkbook" ) ); setCaption( namestr ); } // ---slotStartingBalanceChanged ---------------------------------------------- void Checkbook::slotStartingBalanceChanged( const QString &newbalance ) { bool ok; info->setStartingBalance( newbalance.toFloat( &ok ) ); adjustBalance(); } // --- slotNewTran ------------------------------------------------------------ void Checkbook::slotNewTran() { TranInfo *traninfo = new TranInfo( info->getNextNumber() ); if( !_dLastNew.isNull() ) traninfo->setDate(_dLastNew); Transaction *currtran = new Transaction( this, true, info->name(), traninfo, _pCfg ); - currtran->showMaximized(); - if ( currtran->exec() == QDialog::Accepted ) + if ( QPEApplication::execDialog( currtran ) == QDialog::Accepted ) { // Add to transaction list info->addTransaction( traninfo ); // Add to transaction table float amount; QString stramount; amount = (traninfo->withdrawal() ? -1 : 1)*traninfo->amount(); stramount.sprintf( "%s%.2f", _pCfg->getCurrencySymbol().latin1(), amount ); ( void ) new CBListItem( traninfo, tranTable, traninfo->getIdStr(), traninfo->datestr(false), traninfo->number(), traninfo->datestr(true), traninfo->desc(), stramount ); resort(); adjustBalance(); // save last date _dLastNew = traninfo->date(); // save description in list of payees, if not in there QStringList *pLst=&_pCfg->getPayees(); if( _pCfg->getSavePayees() && pLst->contains(traninfo->desc())==0 ) { pLst->append( traninfo->desc() ); pLst->sort(); _pCfg->setDirty(true); } } else { delete traninfo; } } // --- slotEditTran ----------------------------------------------------------- void Checkbook::slotEditTran() { QListViewItem *curritem = tranTable->currentItem(); if ( !curritem ) return; TranInfo *traninfo=info->findTransaction( curritem->text(COL_ID) ); Transaction *currtran = new Transaction( this, false, info->name(), traninfo, _pCfg ); - currtran->showMaximized(); - if ( currtran->exec() == QDialog::Accepted ) + if ( QPEApplication::execDialog( currtran ) == QDialog::Accepted ) { curritem->setText( COL_NUM, traninfo->number() ); curritem->setText( COL_SORTDATE, traninfo->datestr(false) ); curritem->setText( COL_DATE, traninfo->datestr(true) ); curritem->setText( COL_DESC, traninfo->desc() ); float amount = traninfo->amount(); if ( traninfo->withdrawal() ) { amount *= -1; } QString stramount; stramount.sprintf( "%s%.2f", _pCfg->getCurrencySymbol().latin1(), amount ); curritem->setText( COL_AMOUNT, stramount ); resort(); adjustBalance(); // save description in list of payees, if not in there QStringList *pLst=&_pCfg->getPayees(); if( _pCfg->getSavePayees() && pLst->contains(traninfo->desc())==0 ) { pLst->append( traninfo->desc() ); pLst->sort(); _pCfg->setDirty(true); } } delete currtran; } // --- slotMenuTran ----------------------------------------------------------- void Checkbook::slotMenuTran(QListViewItem *item, const QPoint &pnt) { // active item? if( !item ) return; // Display menu QPopupMenu m; m.insertItem( QWidget::tr( "Edit" ), 1 ); m.insertItem( QWidget::tr( "New" ), 2 ); m.insertItem( QWidget::tr( "Delete" ), 3 ); int r = m.exec( pnt ); switch(r) { case 1: slotEditTran(); break; case 2: slotNewTran(); break; case 3: slotDeleteTran(); break; } } // --- slotDeleteTran --------------------------------------------------------- void Checkbook::slotDeleteTran() { QListViewItem *curritem = tranTable->currentItem(); if ( !curritem ) return; TranInfo *traninfo = info->findTransaction( curritem->text(COL_ID) ); if ( QPEMessageBox::confirmDelete ( this, tr( "Delete transaction" ), traninfo->desc() ) ) { info->removeTransaction( traninfo ); delete curritem; adjustBalance(); } } void Checkbook::slotDrawGraph() { if ( graphInfo ) { delete graphInfo; } switch ( graphList->currentItem() ) { case 0 : drawBalanceChart(); break; case 1 : drawCategoryChart( TRUE ); break; case 2 : drawCategoryChart( FALSE ); break; }; graphWidget->setGraphInfo( graphInfo ); graphWidget->drawGraph( TRUE ); } void Checkbook::drawBalanceChart() { DataPointList *list = new DataPointList(); float balance = info->startingBalance(); float amount; QString label; int i = 0; int count = tranList->count(); for ( TranInfo *tran = tranList->first(); tran; tran = tranList->next() ) { i++; balance -= tran->fee(); amount = tran->amount(); if ( tran->withdrawal() ) { amount *= -1; } balance += amount; if ( i == 1 || i == count / 2 || i == count ) { label = tran->datestr(true); } else { label = ""; } list->append( new DataPointInfo( label, balance ) ); } graphInfo = new GraphInfo( GraphInfo::BarChart, list ); } void Checkbook::drawCategoryChart( bool withdrawals ) { DataPointList *list = new DataPointList(); TranInfo *tran = tranList->first(); if ( tran && tran->withdrawal() == withdrawals ) { list->append( new DataPointInfo( tran->category(), tran->amount() ) ); } tran = tranList->next(); DataPointInfo *cat; for ( ; tran; tran = tranList->next() ) { if ( tran->withdrawal() == withdrawals ) { // Find category in list for ( cat = list->first(); cat; cat = list->next() ) { if ( cat->label() == tran->category() ) { break; } } if ( cat && cat->label() == tran->category() ) { // Found category, add to transaction to category total cat->addToValue( tran->amount() ); } else { // Didn't find category, add category to list list->append( new DataPointInfo( tran->category(), tran->amount() ) ); } } } graphInfo = new GraphInfo( GraphInfo::PieChart, list ); } CBListItem::CBListItem( TranInfo *pTran, QListView *parent, QString label1, QString label2, QString label3, QString label4, QString label5, QString label6, QString label7, QString label8 ) : QListViewItem( parent, label1, label2, label3, label4, label5, label6, label7, label8 ) { _pTran=pTran; m_known = FALSE; owner = parent; } void CBListItem::paintCell( QPainter *p, const QColorGroup &cg, int column, int width, int align ) { QColorGroup _cg = cg; const QPixmap *pm = listView()->viewport()->backgroundPixmap(); if ( pm && !pm->isNull() ) { _cg.setBrush( QColorGroup::Base, QBrush( cg.base(), *pm ) ); p->setBrushOrigin( -listView()->contentsX(), -listView()->contentsY() ); } else if ( isAltBackground() ) _cg.setColor(QColorGroup::Base, cg.background() ); QListViewItem::paintCell(p, _cg, column, width, align); } // --- CBListItem::isAltBackground -------------------------------------------- bool CBListItem::isAltBackground() { QListView *lv = static_cast<QListView *>( listView() ); if ( lv ) { CBListItem *above = 0; above = (CBListItem *)( itemAbove() ); m_known = above ? above->m_known : true; if ( m_known ) { m_odd = above ? !above->m_odd : false; } else { CBListItem *item; bool previous = true; if ( parent() ) { item = (CBListItem *)( parent() ); if ( item ) previous = item->m_odd; item = (CBListItem *)( parent()->firstChild() ); } else { item = (CBListItem *)( lv->firstChild() ); } while(item) { item->m_odd = previous = !previous; item->m_known = true; item = (CBListItem *)( item->nextSibling() ); } } return m_odd; } return false; } // --- slotTab ---------------------------------------------------------------- void Checkbook::slotTab(QWidget *tab) { if( !tab || !info ) return; info->setLastTab( tab->name() ); } // --- slotSortChanged --------------------------------------------------------- void Checkbook::slotSortChanged( const QString &selc ) { if( selc==tr("Entry Order") ) { _sortCol=COL_ID; } else if( selc==tr("Number") ) { _sortCol=COL_NUM; } else if( selc==tr("Date") ) { _sortCol=COL_SORTDATE; } info->setSortOrder( selc ); resort(); } diff --git a/noncore/apps/checkbook/mainwindow.cpp b/noncore/apps/checkbook/mainwindow.cpp index f29001a..60aea42 100644 --- a/noncore/apps/checkbook/mainwindow.cpp +++ b/noncore/apps/checkbook/mainwindow.cpp @@ -1,365 +1,362 @@ /* This file is part of the OPIE Project =. .=l. Copyright (c) 2002 Dan Williams <drw@handhelds.org> .>+-= _;:, .> :=|. This file is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This file is distributed in the hope that + . -:. = it will be useful, but WITHOUT ANY WARRANTY; : .. .:, . . . without even the implied warranty of =_ + =;=|` MERCHANTABILITY or FITNESS FOR A _.=:. : :=>`: PARTICULAR PURPOSE. See the GNU General ..}^=.= = ; Public License for more details. ++= -. .` .: : = ...= . :.=- You should have received a copy of the GNU -. .:....=;==+<; General Public License along with this file; -_. . . )=. = see the file COPYING. If not, write to the -- :-=` Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "mainwindow.h" #include "cbinfo.h" #include "configuration.h" #include "password.h" #include "checkbook.h" #include "listedit.h" #include <qpe/config.h> #include <qpe/global.h> #include <qpe/qpeapplication.h> -#include <qmenubar.h> #include <qpe/qpemessagebox.h> #include <qpe/qpetoolbar.h> #include <qpe/resource.h> +#include <qmenubar.h> #include <qaction.h> #include <qcheckbox.h> #include <qdir.h> #include <qlineedit.h> #include <qwhatsthis.h> MainWindow::MainWindow( QWidget* parent, const char* name, WFlags /*fl*/ ) : QMainWindow( parent, name, WStyle_ContextHelp ) { setCaption( tr( "Checkbook" ) ); cbDir = Global::applicationFileName( "checkbook", "" ); lockIcon = Resource::loadPixmap( "locked" ); // Load configuration options Config config( "checkbook" ); _cfg.readConfig( config ); // Build menu and tool bars setToolBarsMovable( FALSE ); QToolBar *bar = new QToolBar( this ); bar->setHorizontalStretchable( TRUE ); QMenuBar *mb = new QMenuBar( bar ); mb->setMargin( 0 ); QPopupMenu *popup = new QPopupMenu( this ); bar = new QToolBar( this ); QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 ); a->setWhatsThis( tr( "Click here to create a new checkbook.\n\nYou also can select New from the Checkbook menu." ) ); connect( a, SIGNAL( activated() ), this, SLOT( slotNew() ) ); a->addTo( popup ); a->addTo( bar ); actionOpen = new QAction( tr( "Edit" ), Resource::loadPixmap( "edit" ), QString::null, 0, this, 0 ); actionOpen->setWhatsThis( tr( "Select a checkbook and then click here to edit it.\n\nYou also can select Edit from the Checkbook menu, or click and hold on a checkbook name." ) ); connect( actionOpen, SIGNAL( activated() ), this, SLOT( slotEdit() ) ); actionOpen->addTo( popup ); actionOpen->addTo( bar ); actionDelete = new QAction( tr( "Delete" ), Resource::loadPixmap( "trash" ), QString::null, 0, this, 0 ); actionDelete->setWhatsThis( tr( "Select a checkbook and then click here delete it.\n\nYou also can select Delete from the Checkbook menu." ) ); connect( actionDelete, SIGNAL( activated() ), this, SLOT( slotDelete() ) ); actionDelete->addTo( popup ); actionDelete->addTo( bar ); popup->insertSeparator(); a = new QAction( tr( "Configure" ), Resource::loadPixmap( "SettingsIcon" ), QString::null, 0, this, 0 ); a->setWhatsThis( tr( "Click here to configure this app." ) ); connect( a, SIGNAL( activated() ), this, SLOT( slotConfigure() ) ); a->addTo( popup ); a->addTo( bar ); mb->insertItem( tr( "Checkbook" ), popup ); // Load Checkbook selection list checkbooks = new CBInfoList(); QDir checkdir( cbDir ); if (checkdir.exists() == true) { QStringList cblist = checkdir.entryList( "*.qcb", QDir::Files|QDir::Readable|QDir::Writable, QDir::Time ); CBInfo *cb = 0x0; QString filename; for ( QStringList::Iterator it = cblist.begin(); it != cblist.end(); it++ ) { filename = cbDir; filename.append( (*it) ); cb = new CBInfo( (*it).remove( (*it).find('.'), (*it).length() ), filename ); checkbooks->inSort( cb ); } } // Build Checkbook selection list control cbList = 0x0; buildList(); // open last book? if( _cfg.isOpenLastBook() ) { this->show(); this->showMaximized(); QListViewItem *itm=cbList->firstChild(); while( itm ) { if( itm->text(posName)==_cfg.getLastBook() ) { openBook( itm ); break; } itm=itm->nextSibling(); } } } // --- ~MainWindow ------------------------------------------------------------ MainWindow::~MainWindow() { writeConfig(); } // --- buildList -------------------------------------------------------------- void MainWindow::buildList() { if ( cbList ) delete cbList; cbList = new QListView( this ); QWhatsThis::add( cbList, tr( "This is a listing of all checkbooks currently available." ) ); if ( _cfg.getShowLocks() ) { cbList->addColumn( Resource::loadIconSet( "locked" ), "", 24 ); posName = 1; } else { posName = 0; } cbList->addColumn( tr( "Checkbook Name" ) ); if ( _cfg.getShowBalances() ) { int colnum = cbList->addColumn( tr( "Balance" ) ); cbList->setColumnAlignment( colnum, Qt::AlignRight ); } cbList->setAllColumnsShowFocus( TRUE ); cbList->setSorting( posName ); QPEApplication::setStylusOperation( cbList->viewport(), QPEApplication::RightOnHold ); connect( cbList, SIGNAL( rightButtonPressed( QListViewItem *, const QPoint &, int ) ), this, SLOT( slotEdit() ) ); setCentralWidget( cbList ); for ( CBInfo *cb = checkbooks->first(); cb; cb = checkbooks->next() ) { addCheckbook( cb ); } } void MainWindow::addCheckbook( CBInfo *cb ) { QListViewItem *lvi = new QListViewItem( cbList ); if ( _cfg.getShowLocks() && !cb->password().isNull() ) { lvi->setPixmap( 0, lockIcon ); } lvi->setText( posName, cb->name() ); if ( _cfg.getShowBalances() ) { QString balance; balance.sprintf( "%s%.2f", _cfg.getCurrencySymbol().latin1(), cb->balance() ); lvi->setText( posName + 1, balance ); } } void MainWindow::buildFilename( const QString &name ) { tempFilename = cbDir; tempFilename.append( name ); tempFilename.append( ".qcb" ); } void MainWindow::slotNew() { CBInfo *cb = new CBInfo(); Checkbook *currcb = new Checkbook( this, cb, &_cfg ); - currcb->showMaximized(); - if ( currcb->exec() == QDialog::Accepted ) + if ( QPEApplication::execDialog( currcb ) == QDialog::Accepted ) { // Save new checkbook buildFilename( cb->name() ); _cfg.setLastBook( cb->name() ); cb->setFilename( tempFilename ); cb->write(); // Add to listbox checkbooks->inSort( cb ); addCheckbook( cb ); } delete currcb; } // --- slotEdit --------------------------------------------------------------- void MainWindow::slotEdit() { // get name and open it QListViewItem *curritem = cbList->currentItem(); if ( !curritem ) return; openBook( curritem ); } // --- openBook --------------------------------------------------------------- void MainWindow::openBook(QListViewItem *curritem) { // find book in List QString currname=curritem->text(posName); CBInfo *cb = checkbooks->first(); while ( cb ) { if ( cb->name() == currname ) break; cb = checkbooks->next(); } if ( !cb ) return; // buildFilename( currname ); float currbalance = cb->balance(); bool currlock = !cb->password().isNull(); if ( currlock ) { Password *pw = new Password( this, tr( "Enter password" ), tr( "Please enter your password:" ) ); if ( pw->exec() != QDialog::Accepted || pw->password != cb->password() ) { delete pw; return; } delete pw; } _cfg.setLastBook( currname ); Checkbook *currcb = new Checkbook( this, cb, &_cfg ); - currcb->showMaximized(); - if ( currcb->exec() == QDialog::Accepted ) + if ( QPEApplication::execDialog( currcb ) == QDialog::Accepted ) { QString newname = cb->name(); if ( currname != newname ) { // Update name if changed if( curritem ) { curritem->setText( posName, newname ); cbList->sort(); } _cfg.setLastBook( newname ); // Remove old file QFile f( tempFilename ); if ( f.exists() ) f.remove(); // Get new filename buildFilename( newname ); cb->setFilename( tempFilename ); } cb->write(); // Update lock if changed if ( _cfg.getShowLocks() && !cb->password().isNull() != currlock ) { if ( !cb->password().isNull() ) curritem->setPixmap( 0, lockIcon ); else curritem->setPixmap( 0, nullIcon ); } // Update balance if changed if ( _cfg.getShowBalances() && cb->balance() != currbalance ) { QString tempstr; tempstr.sprintf( "%s%.2f", _cfg.getCurrencySymbol().latin1(), cb->balance() ); curritem->setText( posName + 1, tempstr ); } // write config, if needed if( _cfg.isDirty() ) { Config config("checkbook"); _cfg.writeConfig( config ); } } delete currcb; } // --- slotDelete ------------------------------------------------------------- void MainWindow::slotDelete() { QString currname = cbList->currentItem()->text( posName ); if ( QPEMessageBox::confirmDelete ( this, tr( "Delete checkbook" ), currname ) ) { buildFilename( currname ); QFile f( tempFilename ); if ( f.exists() ) { f.remove(); } delete cbList->currentItem(); } } // --- slotConfigure ---------------------------------------------------------- void MainWindow::slotConfigure() { Configuration *cfgdlg = new Configuration( this, _cfg ); - cfgdlg->showMaximized(); - if ( cfgdlg->exec() == QDialog::Accepted ) + if ( QPEApplication::execDialog( cfgdlg ) == QDialog::Accepted ) { // read data from config dialog & save it cfgdlg->saveConfig( _cfg ); writeConfig(); buildList(); } delete cfgdlg; } // --- writeConfig -------------------------------------------------------------- void MainWindow::writeConfig() { Config config("checkbook"); _cfg.writeConfig( config ); } diff --git a/noncore/apps/odict/configdlg.cpp b/noncore/apps/odict/configdlg.cpp index 2103df9..b12a395 100644 --- a/noncore/apps/odict/configdlg.cpp +++ b/noncore/apps/odict/configdlg.cpp @@ -1,107 +1,108 @@ /*************************************************************************** application: : ODict begin : December 2002 copyright : ( C ) 2002, 2003 by Carsten Niehaus email : cniehaus@handhelds.org **************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * ( at your option ) any later version. * * * **************************************************************************/ #include "configdlg.h" #include "searchmethoddlg.h" -#include <qdialog.h> +#include <qpe/qpeapplication.h> #include <qpe/config.h> -#include <qlayout.h> +#include <qdialog.h> +#include <qlayout.h> #include <qhbox.h> #include <qvbox.h> #include <qlabel.h> #include <qlistview.h> #include <qpushbutton.h> #include <qlineedit.h> #include <qstringlist.h> ConfigDlg::ConfigDlg(QWidget *parent, const char *name, bool modal) : QDialog(parent, name, modal) { setCaption( tr( "Options" ) ); QVBoxLayout *vbox_layout = new QVBoxLayout( this ); search_tab = new QWidget( this , "search_tab" ); QVBoxLayout *vbox_layout_searchtab = new QVBoxLayout( search_tab, 4 , 4 ,"blah" ); QHBox *hbox = new QHBox( search_tab ); list = new QListView( hbox ); list->addColumn( tr( "Searchmethod" ) ); loadSearchMethodNames(); QVBox *vbox = new QVBox( hbox ); new_button = new QPushButton( tr( "New" ) , vbox ); change_button = new QPushButton( tr( "Change" ) , vbox ); delete_button = new QPushButton( tr( "Delete" ) , vbox ); connect( new_button, SIGNAL( clicked() ), this, SLOT( slotNewMethod() ) ); connect( change_button, SIGNAL( clicked() ), this, SLOT( slotChangeMethod() )); connect( delete_button, SIGNAL( clicked() ), this, SLOT( slotDeleteMethod() )); vbox_layout_searchtab->addWidget( hbox ); vbox_layout->addWidget( search_tab ); - showMaximized(); + QPEApplication::execDialog( this ); } void ConfigDlg::slotNewMethod() { SearchMethodDlg dlg( this, "SearchMethodDlg", true ); if ( dlg.exec() == QDialog::Accepted ) { dlg.saveItem(); QListViewItem *item = new QListViewItem( list ); item->setText( 0 , dlg.nameLE->text() ); } } void ConfigDlg::slotChangeMethod() { if ( list->selectedItem() ) { SearchMethodDlg dlg( this, "SearchMethodDlg", true, list->selectedItem()->text( 0 ) ); if ( dlg.exec() == QDialog::Accepted ) { dlg.saveItem(); QListViewItem *item = list->selectedItem(); item->setText( 0 , dlg.nameLE->text() ); } } } void ConfigDlg::slotDeleteMethod() { if ( list->selectedItem() ) { Config cfg ( "odict" ); cfg.setGroup( "Method_"+list->selectedItem()->text(0) ); cfg.clearGroup(); //FIXME: this only removes the entries but not the group itself list->takeItem( list->selectedItem() ); } } void ConfigDlg::loadSearchMethodNames() { Config cfg( "odict" ); QStringList groupListCfg = cfg.groupList().grep( "Method_" ); for ( QStringList::Iterator it = groupListCfg.begin() ; it != groupListCfg.end() ; ++it ) { QListViewItem *item = new QListViewItem( list ); cfg.setGroup( *it ); item->setText( 0 , cfg.readEntry( "Name" ) ); } } diff --git a/noncore/apps/odict/searchmethoddlg.cpp b/noncore/apps/odict/searchmethoddlg.cpp index 99cd8db..8ed7152 100644 --- a/noncore/apps/odict/searchmethoddlg.cpp +++ b/noncore/apps/odict/searchmethoddlg.cpp @@ -1,108 +1,109 @@ /*************************************************************************** application: : ODict begin : December 2002 copyright : ( C ) 2002, 2003 by Carsten Niehaus email : cniehaus@handhelds.org **************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * ( at your option ) any later version. * * * **************************************************************************/ #include "searchmethoddlg.h" -#include <qdialog.h> #include <qpe/config.h> -#include <qlayout.h> +#include <qpe/qpeapplication.h> +#include <qdialog.h> +#include <qlayout.h> #include <qhbox.h> #include <qvbox.h> #include <qlabel.h> #include <qpushbutton.h> #include <qstring.h> #include <qlineedit.h> #include <qdir.h> #include <opie/ofileselector.h> #include <opie/ofiledialog.h> SearchMethodDlg::SearchMethodDlg(QWidget *parent, const char *name, bool modal, QString itemname) : QDialog(parent, name, modal) { QVBoxLayout *vbox_layout = new QVBoxLayout( this, 4,4,"vbox_layout" ); QVBox *vbox = new QVBox( this ); QHBox *hbox1 = new QHBox( vbox ); QLabel *nameLabel = new QLabel( tr( "Name:" ) , hbox1 ); nameLE = new QLineEdit( hbox1 ); QLabel *dictLabel = new QLabel( tr( "Dictionary file" ), vbox ); QHBox *hbox2 = new QHBox( vbox ); dictFileLE = new QLineEdit( hbox2 ); QPushButton *browseButton = new QPushButton( tr( "Browse" ) , hbox2 ); connect( browseButton, SIGNAL( clicked() ), this, SLOT( slotBrowse() ) ); QWidget *dummywidget = new QWidget( vbox ); QLabel *lag1 = new QLabel( tr( "Language 1" ),dummywidget); QLabel *devider = new QLabel( tr( "Decollator" ),dummywidget); QLabel *lag2 = new QLabel( tr( "Language 2" ),dummywidget); lang1 = new QLineEdit( dummywidget ); lang2 = new QLineEdit( dummywidget ); trenner = new QLineEdit( dummywidget ); trenner->setText( "::" ); QGridLayout *grid = new QGridLayout( dummywidget, 2,3 ); grid->addWidget( lag1, 0,0 ); grid->addWidget( devider, 0,1 ); grid->addWidget( lag2, 0,2 ); grid->addWidget( lang1, 1,0 ); grid->addWidget( trenner, 1,1 ); grid->addWidget( lang2, 1,2 ); vbox_layout->addWidget( vbox ); - showMaximized(); + QPEApplication::execDialog ( this ); if( !itemname ) setCaption( tr( "New Searchmethod" ) ); else { setCaption( tr( "Change Searchmethod" ) ); itemName = itemname; setupEntries(itemname); } } void SearchMethodDlg::setupEntries( QString item ) { Config cfg( "odict" ); cfg.setGroup( "Method_"+itemName ); trenner->setText( cfg.readEntry( "Seperator" ) ); lang1->setText( cfg.readEntry( "Lang1" ) ); lang2->setText( cfg.readEntry( "Lang2" ) ); nameLE->setText( itemName ); dictFileLE->setText( cfg.readEntry( "file" ) ); } void SearchMethodDlg::slotBrowse() { itemName=OFileDialog::getOpenFileName( OFileSelector::EXTENDED,QDir::homeDirPath()); dictFileLE->setText( itemName ); } void SearchMethodDlg::saveItem() { QString name = nameLE->text(); Config cfg( "odict" ); cfg.setGroup( "Method_"+name ); cfg.writeEntry( "Name", name ); cfg.writeEntry( "Seperator", trenner->text() ); cfg.writeEntry( "Lang1", lang1->text() ); cfg.writeEntry( "Lang2", lang2->text() ); cfg.writeEntry( "file", dictFileLE->text() ); } diff --git a/noncore/apps/opie-bartender/bartender.cpp b/noncore/apps/opie-bartender/bartender.cpp index 8c4ee93..cd0a364 100644 --- a/noncore/apps/opie-bartender/bartender.cpp +++ b/noncore/apps/opie-bartender/bartender.cpp @@ -1,447 +1,443 @@ /**************************************************************************** ** ** Created: Sat Jul 20 08:10:53 2002 ** by: L.J. Potter <ljp@llornkcor.com> ** copyright : (C) 2002 by ljp email : ljp@llornkcor.com * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #include "bartender.h" #include "newdrinks.h" #include "showdrinks.h" #include "inputDialog.h" #include "searchresults.h" #include "bac.h" #include <qpe/qpetoolbar.h> #include <qmenubar.h> #include <opie/colorpopupmenu.h> #include <qpe/qpeapplication.h> #include <qpe/resource.h> #include <qcstring.h> #include <qlineedit.h> #include <qdir.h> #include <qpushbutton.h> #include <qlistbox.h> #include <qstringlist.h> #include <qmultilineedit.h> #include <qmessagebox.h> #include <qfile.h> #include <qtextstream.h> #include <qfile.h> #include <qaction.h> #include <qheader.h> #include <qlistview.h> #include <qwidget.h> #include <qlayout.h> #include <qvariant.h> #include <qtooltip.h> #include <qwhatsthis.h> #include <qimage.h> #include <qpixmap.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> Bartender::Bartender( QWidget* parent, const char* name, WFlags fl ) : QMainWindow( parent, name, fl ) { if ( !name ) setName( "Bartender" ); QGridLayout *layout = new QGridLayout( this ); layout->setSpacing( 2); layout->setMargin( 2); connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); setCaption( tr( "Bartender" ) ); ToolBar1 = new QToolBar( this, "ToolBar1" ); ToolBar1->setFixedHeight(22); layout->addMultiCellWidget( ToolBar1, 0, 0, 0, 4 ); QMenuBar *menuBar = new QMenuBar( ToolBar1 ); QPopupMenu *fileMenu; fileMenu = new QPopupMenu( this); menuBar->insertItem( tr("File"), fileMenu ); fileMenu->insertItem(tr("New Drink")); fileMenu->insertItem(tr("Open Drink")); fileMenu->insertItem(tr("Find by Drink Name")); fileMenu->insertItem(tr("Find by Alcohol")); QPopupMenu *editMenu; editMenu = new QPopupMenu( this); menuBar->insertItem( tr("Edit"), editMenu ); editMenu->insertItem(tr("edit")); connect( fileMenu, SIGNAL( activated(int) ), this, SLOT( fileMenuActivated(int) )); connect( editMenu, SIGNAL( activated(int) ), this, SLOT( editMenuActivated(int) )); QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), "New", 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( fileNew() ) ); a->addTo( ToolBar1 ); a = new QAction( tr( "Open" ), Resource::loadPixmap( "bartender/bartender_sm" ), "open", 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( openCurrentDrink() ) ); a->addTo( ToolBar1 ); a = new QAction( tr( "Find" ), Resource::loadPixmap( "find" ), "Find", 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( askSearch() ) ); a->addTo( ToolBar1 ); a = new QAction( tr( "Edit" ), Resource::loadPixmap( "edit" ),"Edit", 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( doEdit() ) ); a->addTo( ToolBar1 ); QPushButton *t; t= new QPushButton( "BAC", ToolBar1, "bacButtin"); connect( t, SIGNAL( clicked() ), this, SLOT( doBac() ) ); DrinkView = new QListView( this, "DrinkView" ); DrinkView->addColumn( tr( "Name of Drink" ) ); // DrinkView->setRootIsDecorated( TRUE ); DrinkView->header()->hide(); QPEApplication::setStylusOperation( DrinkView->viewport(),QPEApplication::RightOnHold); connect(DrinkView, SIGNAL( doubleClicked(QListViewItem*)),this,SLOT(showDrink( QListViewItem*))); connect(DrinkView, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int)), this,SLOT( showDrink(int, QListViewItem *, const QPoint&, int))); layout->addMultiCellWidget( DrinkView, 1, 2, 0, 4 ); if(QDir("db").exists()) { dbFile.setName( "db/drinkdb.txt"); } else dbFile.setName( QPEApplication::qpeDir()+"/etc/bartender/drinkdb.txt"); initDrinkDb(); } Bartender::~Bartender() { } /* this happens right before exit */ void Bartender::cleanUp() { dbFile.close(); } void Bartender::initDrinkDb() { if(!dbFile.isOpen()) if ( !dbFile.open( IO_ReadOnly)) { QMessageBox::message( (tr("Note")), (tr("Drink database not opened sucessfully.\n")) ); return; } fillList(); } void Bartender::fillList() { dbFile.at(1); DrinkView->clear(); int i=0; QListViewItem * item ; QTextStream t( &dbFile); QString s; while ( !t.eof()) { s = t.readLine(); if(s.find("#",0,TRUE) != -1) { // qDebug(s.right(s.length()-2)); item= new QListViewItem( DrinkView, 0 ); item->setText( 0, s.right(s.length()-2)); i++; } } qDebug("there are currently %d of drinks", i); } void Bartender::fileNew() { New_Drink *newDrinks; newDrinks = new New_Drink(this,"New Drink....", TRUE); QString newName, newIng; - newDrinks->showMaximized(); - newDrinks->exec(); + QPEApplication::execDialog( newDrinks ); newName = newDrinks->LineEdit1->text(); newIng= newDrinks->MultiLineEdit1->text(); if(dbFile.isOpen()) dbFile.close(); if ( !dbFile.open( IO_WriteOnly| IO_Append)) { QMessageBox::message( (tr("Note")), (tr("Drink database not opened sucessfully.\n")) ); return; } if(newDrinks ->result() == 1 ) { QString newDrink="\n# "+newName+"\n"; newDrink.append(newIng+"\n"); qDebug("writing "+newDrink); dbFile.writeBlock( newDrink.latin1(), newDrink.length()); clearList(); dbFile.close(); initDrinkDb(); } delete newDrinks; } void Bartender::showDrink(int mouse, QListViewItem * item, const QPoint&, int) { switch (mouse) { case 1: // showDrink(item); break; case 2: showDrink(item); break; } } void Bartender::showDrink( QListViewItem *item) { if(item==NULL) return; dbFile.at(0); Show_Drink *showDrinks; QString myDrink=item->text(0); showDrinks = new Show_Drink(this, myDrink, TRUE); QTextStream t( &dbFile); QString s, s2; while ( !t.eof()) { s = t.readLine(); if(s.find( myDrink, 0, TRUE) != -1) { for(int i=0;s2.find( "#", 0, TRUE) == -1;i++) { s2 = t.readLine(); if(s2.find("#",0,TRUE) == -1 || dbFile.atEnd() ) { // qDebug(s2); showDrinks->MultiLineEdit1->append(s2); } if( dbFile.atEnd() ) break; } } } - showDrinks->showMaximized(); - showDrinks->exec(); + QPEApplication::execDialog( showDrinks ); if(showDrinks ->result() ==0) { doEdit(); } delete showDrinks; } void Bartender::askSearch() { switch ( QMessageBox::warning(this,tr("Find"),tr("Search by drink name\n")+ "\nor alcohol ?" ,tr("Drink Name"),tr("Alcohol"),0,0,1) ) { case 0: doSearchByName(); break; case 1: doSearchByDrink(); break; }; } /* search by name */ void Bartender::doSearchByName() { // if( DrinkView->currentItem() == NULL) return; QStringList searchList; QString searchForDrinkName; InputDialog *fileDlg; fileDlg = new InputDialog(this,tr("Find by Drink Name"),TRUE, 0); fileDlg->exec(); if( fileDlg->result() == 1 ) { searchForDrinkName = fileDlg->LineEdit1->text(); QListViewItemIterator it( DrinkView ); for ( ; it.current(); ++it ) { if ( it.current()->text(0).find( searchForDrinkName, 0, TRUE) != -1 ) { // qDebug( it.current()->text(0)); searchList.append(it.current()->text(0)); } } if(searchList.count() >0) showSearchResult(searchList); else QMessageBox::message(tr("Search"),tr("Sorry no results for\n")+searchForDrinkName); }//end Inputdialog delete fileDlg; } void Bartender::doSearchByDrink() { // if( DrinkView->currentItem() == NULL) return; QStringList searchList; QString searchForDrinkName, lastDrinkName, tempName; InputDialog *fileDlg; fileDlg = new InputDialog(this,tr("Find by Alcohol"),TRUE, 0); fileDlg->exec(); if( fileDlg->result() == 1 ) { searchForDrinkName = fileDlg->LineEdit1->text(); dbFile.at(0); QTextStream t( &dbFile); QString s, s2; while ( !t.eof()) { s = t.readLine(); if(s.find("#",0,TRUE) != -1) { lastDrinkName=s.right(s.length()-2); // qDebug("last drink name "+lastDrinkName); } else if( s.find( searchForDrinkName ,0, FALSE) != -1 && lastDrinkName != tempName ) { // qDebug("appending "+lastDrinkName); searchList.append( lastDrinkName); tempName=lastDrinkName; } // if( dbFile.atEnd() ) break; } //oef if(searchList.count() >0) showSearchResult(searchList); else QMessageBox::message(tr("Search"),tr("Sorry no results for\n")+ searchForDrinkName); } delete fileDlg; } void Bartender::showSearchResult(QStringList &searchList) { QString result; Search_Results *searchDlg; searchList.sort(); searchDlg = new Search_Results(this, "Search Results", TRUE); - searchDlg->showMaximized(); searchDlg->ListBox1->insertStringList( searchList,-1); - searchDlg->exec(); + QPEApplication::execDialog( searchDlg ); if( searchDlg->result() == 1 ) { result= searchDlg->ListBox1->currentText(); } QListViewItemIterator it2( DrinkView ); for ( ; it2.current(); ++it2 ) { if ( it2.current()->text(0)== result ) { // qDebug( it2.current()->text(0)); showDrink(it2.current()); } } delete searchDlg; } void Bartender::doEdit() { if(DrinkView->currentItem() == NULL) { fileNew(); } QString myDrink; myDrink= DrinkView->currentItem()->text(0); dbFile.at(0); int foundAt=0; New_Drink *newDrinks; newDrinks = new New_Drink(this,"Edit Drink....", TRUE); QString newName, newIng; - newDrinks->showMaximized(); + QPEApplication::showDialog( newDrinks ); QTextStream t( &dbFile); QString s, s2; while ( !t.eof()) { s = t.readLine(); if(s.find( myDrink, 0, TRUE) != -1) { foundAt = dbFile.at() - (s.length()+1); for(int i=0;s2.find( "#", 0, TRUE) == -1;i++) { s2 = t.readLine(); if(s2.find("#",0,TRUE) == -1 || dbFile.atEnd() ) { // qDebug(s2); newDrinks->MultiLineEdit1->append(s2); newDrinks->LineEdit1->setText(myDrink); } if( dbFile.atEnd() ) break; } } } newDrinks->exec(); newName = newDrinks->LineEdit1->text(); newIng= newDrinks->MultiLineEdit1->text(); if( newDrinks ->result() == 1 ) { if(dbFile.isOpen()) dbFile.close(); if ( !dbFile.open( IO_ReadWrite )) { QMessageBox::message( (tr("Note")), (tr("Drink database not opened sucessfully.\n")) ); return; } int fd = dbFile.handle(); lseek( fd, foundAt, SEEK_SET); // dbFile.at( foundAt); #warning FIXME problems with editing drinks db ////////// FIXME write to user file QString newDrink="# "+newName+"\n"; newDrink.append(newIng+"\n"); qDebug("writing "+newDrink); dbFile.writeBlock( newDrink.latin1(), newDrink.length()); clearList(); dbFile.flush(); initDrinkDb(); } } void Bartender::clearList() { DrinkView->clear(); } void Bartender::doBac() { BacDialog *bacDlg; bacDlg = new BacDialog(this,"BAC",TRUE); - bacDlg->showMaximized(); - bacDlg->exec(); + QPEApplication::execDialog( bacDlg ); delete bacDlg; } void Bartender::openCurrentDrink() { if(DrinkView->currentItem() == NULL) return; showDrink(DrinkView->currentItem()); } void Bartender::fileMenuActivated( int item) { qDebug("Item %d", item); switch(item) { case -3: // new -3 fileNew(); break; case -4:// open -4 openCurrentDrink(); break; case -5:// drink -5 doSearchByName(); break; case -6:// alcohol -6 doSearchByDrink(); break; } } void Bartender::editMenuActivated(int item) { qDebug("Item %d", item); /* edit -8 */ switch(item) { case -8: doEdit() ; break; } } diff --git a/noncore/apps/opie-console/configdialog.cpp b/noncore/apps/opie-console/configdialog.cpp index b23f4d0..882cd3d 100644 --- a/noncore/apps/opie-console/configdialog.cpp +++ b/noncore/apps/opie-console/configdialog.cpp @@ -1,111 +1,111 @@ -#include <qlistview.h> +#include <qpe/qpeapplication.h> + +#include <qlistview.h> #include "configdialog.h" #include "profileeditordialog.h" class ConfigListItem : public QListViewItem { public: ConfigListItem( QListView* item, const Profile& ); ~ConfigListItem(); Profile profile()const; private: Profile m_prof; }; ConfigListItem::ConfigListItem( QListView* item, const Profile& prof ) : QListViewItem( item ), m_prof( prof ) { setText(0, prof.name() ); } ConfigListItem::~ConfigListItem() { } Profile ConfigListItem::profile()const { return m_prof; } /* Dialog */ ConfigDialog::ConfigDialog( const Profile::ValueList& lis, MetaFactory* fa, QWidget* parent ) : ConfigureBase( parent, 0, TRUE ), m_fact( fa ) { //init(); { Profile::ValueList::ConstIterator it; for (it = lis.begin(); it != lis.end(); ++it ) { new ConfigListItem( lstView, (*it) ); } } } ConfigDialog::~ConfigDialog() { } Profile::ValueList ConfigDialog::list()const { /* iterate over the list */ Profile::ValueList lst; QListViewItemIterator it(lstView); for ( ; it.current(); ++it ) { ConfigListItem* item = (ConfigListItem*)it.current(); lst.append( item->profile() ); } return lst; } /* our slots */ void ConfigDialog::slotRemove() { ConfigListItem* item = (ConfigListItem*)lstView->currentItem(); if (!item ) return; lstView->takeItem( item ); delete item; } void ConfigDialog::slotEdit() { Profile p; if(!lstView->currentItem()) return; // Load profile p = ((ConfigListItem*)lstView->currentItem())->profile(); ProfileEditorDialog dlg(m_fact, p); dlg.setCaption(tr("Edit Connection Profile")); - dlg.showMaximized(); - int ret = dlg.exec(); + int ret = QPEApplication::execDialog( &dlg ); if(ret == QDialog::Accepted) { if(lstView->currentItem()) delete lstView->currentItem(); // use dlg.terminal()! Profile p = dlg.profile(); new ConfigListItem(lstView, p); } } void ConfigDialog::slotAdd() { ProfileEditorDialog dlg(m_fact); dlg.setCaption(tr("New Connection")); - dlg.showMaximized(); - int ret = dlg.exec(); + int ret = QPEApplication::execDialog( &dlg ); if(ret == QDialog::Accepted) { // TODO: Move into general profile save part // assignments //QString type = dlg.term_type(); //if(type == "VT102") profile = Profile::VT102; // get profile from editor Profile p = dlg.profile(); new ConfigListItem(lstView, p); } } diff --git a/noncore/apps/opie-console/mainwindow.cpp b/noncore/apps/opie-console/mainwindow.cpp index 2673335..3fe9040 100644 --- a/noncore/apps/opie-console/mainwindow.cpp +++ b/noncore/apps/opie-console/mainwindow.cpp @@ -1,686 +1,685 @@ #include <assert.h> #include <qaction.h> #include <qmenubar.h> #include <qtoolbar.h> #include <qmessagebox.h> #include <qwhatsthis.h> #include <qfileinfo.h> #include <qpe/filemanager.h> +#include <qpe/qpeapplication.h> #include <opie/ofiledialog.h> #include "TEmulation.h" #include "profileeditordialog.h" #include "configdialog.h" #include "default.h" #include "profilemanager.h" #include "mainwindow.h" #include "tabwidget.h" #include "transferdialog.h" #include "function_keyboard.h" #include "emulation_handler.h" #include "script.h" MainWindow::MainWindow(QWidget *parent, const char *name, WFlags) : QMainWindow(parent, name, WStyle_ContextHelp) { KeyTrans::loadAll(); for (int i = 0; i < KeyTrans::count(); i++ ) { KeyTrans* s = KeyTrans::find(i ); assert( s ); } m_factory = new MetaFactory(); Default def(m_factory); m_sessions.setAutoDelete( TRUE ); m_curSession = 0; m_manager = new ProfileManager( m_factory ); m_manager->load(); m_scriptsData.setAutoDelete(TRUE); initUI(); populateProfiles(); populateScripts(); } void MainWindow::initUI() { setToolBarsMovable( FALSE ); /* tool bar for the menu */ m_tool = new QToolBar( this ); m_tool->setHorizontalStretchable( TRUE ); m_bar = new QMenuBar( m_tool ); m_console = new QPopupMenu( this ); m_scripts = new QPopupMenu( this ); m_sessionsPop= new QPopupMenu( this ); m_scriptsPop = new QPopupMenu( this ); /* add a toolbar for icons */ m_icons = new QToolBar(this); /* * the settings action */ m_setProfiles = new QAction(tr("Configure Profiles"), Resource::loadPixmap( "SettingsIcon" ), QString::null, 0, this, 0); m_setProfiles->addTo( m_console ); connect( m_setProfiles, SIGNAL(activated() ), this, SLOT(slotConfigure() ) ); m_console->insertSeparator(); /* * new Action for new sessions */ QAction* newCon = new QAction(tr("New Profile"), Resource::loadPixmap( "new" ), QString::null, 0, this, 0); newCon->addTo( m_console ); connect( newCon, SIGNAL(activated() ), this, SLOT(slotNew() ) ); m_console->insertSeparator(); QAction *saveCon = new QAction( tr("Save Profile" ), Resource::loadPixmap( "save" ), QString::null, 0, this, 0 ); saveCon->addTo( m_console ); connect( saveCon, SIGNAL(activated() ), this, SLOT(slotSaveSession() ) ); m_console->insertSeparator(); /* * connect action */ m_connect = new QAction( tr("Connect"), Resource::loadPixmap("console/connected"), QString::null, 0, this, 0 ); m_connect->addTo( m_console ); connect(m_connect, SIGNAL(activated() ), this, SLOT(slotConnect() ) ); /* * disconnect action */ m_disconnect = new QAction( tr("Disconnect"), Resource::loadPixmap("console/notconnected"), QString::null, 0, this, 0 ); m_disconnect->addTo( m_console ); connect(m_disconnect, SIGNAL(activated() ), this, SLOT(slotDisconnect() ) ); m_console->insertSeparator(); m_quickLaunch = new QAction( tr("QuickLaunch"), Resource::loadPixmap("console/konsole_mini"), QString::null, 0, this, 0 ); m_quickLaunch->addTo( m_icons ); connect( m_quickLaunch, SIGNAL( activated() ), this, SLOT( slotQuickLaunch() ) ); QWhatsThis::add( m_icons, tr( "The shell button launches the \"default\" profile. If there is none default values are taken" ) ); m_transfer = new QAction( tr("Transfer file..."), Resource::loadPixmap("pass") , QString::null, 0, this, 0 ); m_transfer->addTo( m_console ); connect(m_transfer, SIGNAL(activated() ), this, SLOT(slotTransfer() ) ); /* * immediate change of line wrap policy */ m_isWrapped = false; m_wrap = new QAction( tr("Line wrap"), Resource::loadPixmap( "linewrap" ), QString::null, 0, this, 0 ); m_wrap->addTo( m_console ); connect( m_wrap, SIGNAL( activated() ), SLOT( slotWrap() ) ); /* * fullscreen */ m_isFullscreen = false; m_fullscreen = new QAction( tr("Full screen"), Resource::loadPixmap( "fullscreen" ) , QString::null, 0, this, 0); m_fullscreen->addTo( m_console ); connect( m_fullscreen, SIGNAL( activated() ), this, SLOT( slotFullscreen() ) ); m_console->insertSeparator(); QAction *a = new QAction(); a->setText( tr("Save history") ); a->addTo( m_console ); connect(a, SIGNAL(activated() ), this, SLOT(slotSaveHistory() ) ); /* * terminate action */ m_terminate = new QAction(); m_terminate->setText( tr("Terminate") ); m_terminate->addTo( m_console ); connect(m_terminate, SIGNAL(activated() ), this, SLOT(slotTerminate() ) ); m_closewindow = new QAction(); m_closewindow->setText( tr("Close Window") ); m_closewindow->addTo( m_console ); connect( m_closewindow, SIGNAL(activated() ), this, SLOT(slotClose() ) ); /* * script actions */ m_runScript_id = m_scripts->insertItem(tr("Run Script"), m_scriptsPop, -1, 0); connect(m_scriptsPop, SIGNAL(activated(int)), this, SLOT(slotRunScript(int))); m_recordScript = new QAction(tr("Record Script"), QString::null, 0, this, 0); m_recordScript->addTo(m_scripts); connect(m_recordScript, SIGNAL(activated()), this, SLOT(slotRecordScript())); m_saveScript = new QAction(tr("Save Script"), QString::null, 0, this, 0); m_saveScript->addTo(m_scripts); connect(m_saveScript, SIGNAL(activated()), this, SLOT(slotSaveScript())); /* * action that open/closes the keyboard */ m_openKeys = new QAction (tr("Open Keyboard..."), Resource::loadPixmap( "console/keys/keyboard_icon" ), QString::null, 0, this, 0); m_openKeys->setToggleAction(true); connect (m_openKeys, SIGNAL(toggled(bool)), this, SLOT(slotOpenKeb(bool))); /* insert the submenu */ m_console->insertItem(tr("New from Profile"), m_sessionsPop, -1, 0); /* insert the connection menu */ m_bar->insertItem( tr("Connection"), m_console ); /* the scripts menu */ m_bar->insertItem( tr("Scripts"), m_scripts ); /* and the keyboard */ m_keyBar = new QToolBar(this); addToolBar( m_keyBar, "Keyboard", QMainWindow::Top, TRUE ); m_keyBar->setHorizontalStretchable( TRUE ); m_keyBar->hide(); m_kb = new FunctionKeyboard(m_keyBar); connect(m_kb, SIGNAL(keyPressed(FKey, ushort, ushort, bool)), this, SLOT(slotKeyReceived(FKey, ushort, ushort, bool))); a = new QAction(tr("Copy"), Resource::loadPixmap("copy"), QString::null, 0, this, 0 ); //a->addTo( m_icons ); connect( a, SIGNAL(activated() ), this, SLOT(slotCopy() ) ); QAction *paste = new QAction(tr("Paste"), Resource::loadPixmap("paste"), QString::null, 0, this, 0 ); connect( paste, SIGNAL(activated() ), this, SLOT(slotPaste() ) ); newCon->addTo( m_icons ); //m_setProfiles->addTo( m_icons ); paste->addTo( m_icons ); m_openKeys->addTo(m_icons); m_fullscreen->addTo( m_icons ); m_connect->setEnabled( false ); m_disconnect->setEnabled( false ); m_terminate->setEnabled( false ); m_transfer->setEnabled( false ); m_scripts->setItemEnabled(m_runScript_id, false); m_recordScript->setEnabled( false ); m_saveScript->setEnabled( false ); m_fullscreen->setEnabled( false ); m_closewindow->setEnabled( false ); m_wrap->setEnabled( false ); /* * connect to the menu activation */ connect( m_sessionsPop, SIGNAL(activated( int ) ), this, SLOT(slotProfile( int ) ) ); m_consoleWindow = new TabWidget( this, "blah"); connect(m_consoleWindow, SIGNAL(activated(Session*) ), this, SLOT(slotSessionChanged(Session*) ) ); setCentralWidget( m_consoleWindow ); slotQuickLaunch(); } ProfileManager* MainWindow::manager() { return m_manager; } TabWidget* MainWindow::tabWidget() { return m_consoleWindow; } void MainWindow::populateProfiles() { m_sessionsPop->clear(); Profile::ValueList list = manager()->all(); for (Profile::ValueList::Iterator it = list.begin(); it != list.end(); ++it ) { m_sessionsPop->insertItem( (*it).name() ); } } void MainWindow::populateScripts() { m_scriptsPop->clear(); m_scriptsData.clear(); DocLnkSet files(QPEApplication::documentDir(), "text/plain"); QListIterator<DocLnk> dit(files.children()); for (; dit.current(); ++dit) { if (*dit && (*dit)->name().length()>0) { QFileInfo info((*dit)->file()); if (info.extension(false) == "script") { m_scriptsData.append(new DocLnk(**dit)); m_scriptsPop->insertItem((*dit)->name()); } } } } MainWindow::~MainWindow() { delete m_factory; manager()->save(); } MetaFactory* MainWindow::factory() { return m_factory; } Session* MainWindow::currentSession() { return m_curSession; } QList<Session> MainWindow::sessions() { return m_sessions; } void MainWindow::slotNew() { ProfileEditorDialog dlg(factory() ); - dlg.showMaximized(); dlg.setCaption( tr("New Connection") ); - int ret = dlg.exec(); + int ret = QPEApplication::execDialog( &dlg ); if ( ret == QDialog::Accepted ) { create( dlg.profile() ); } } void MainWindow::slotRecordScript() { if (currentSession()) { currentSession()->emulationHandler()->startRecording(); m_saveScript->setEnabled(true); m_recordScript->setEnabled(false); } } void MainWindow::slotSaveScript() { if (currentSession() && currentSession()->emulationHandler()->isRecording()) { QMap<QString, QStringList> map; QStringList text; text << "text/plain"; map.insert(tr("Script"), text ); QString filename = OFileDialog::getSaveFileName(2, QPEApplication::documentDir(), QString::null, map); if (!filename.isEmpty()) { QFileInfo info(filename); if (info.extension(FALSE) != "script") filename += ".script"; DocLnk nf; nf.setType("text/plain"); nf.setFile(filename); nf.setName(info.fileName()); FileManager fm; fm.saveFile(nf, currentSession()->emulationHandler()->script()->script()); currentSession()->emulationHandler()->clearScript(); m_saveScript->setEnabled(false); m_recordScript->setEnabled(true); populateScripts(); } } } void MainWindow::slotRunScript(int id) { if (currentSession()) { int index = m_scriptsPop->indexOf(id); DocLnk *lnk = m_scriptsData.at(index); QString filePath = lnk->file(); Script script(filePath); currentSession()->emulationHandler()->runScript(&script); } } void MainWindow::slotConnect() { if ( currentSession() ) { bool ret = currentSession()->layer()->open(); if(!ret) QMessageBox::warning(currentSession()->widgetStack(), QObject::tr("Failed"), QObject::tr("Connecting failed for this session.")); else { m_connect->setEnabled( false ); m_disconnect->setEnabled( true ); // if it does not support file transfer, disable the menu entry if ( ( m_curSession->layer() )->supports()[1] == 0 ) { m_transfer->setEnabled( false ); } else { m_transfer->setEnabled( true ); } m_recordScript->setEnabled( true ); m_scripts->setItemEnabled(m_runScript_id, true); } } } void MainWindow::slotDisconnect() { if ( currentSession() ) { currentSession()->layer()->close(); m_connect->setEnabled( true ); m_disconnect->setEnabled( false ); m_transfer->setEnabled( false ); m_recordScript->setEnabled( false); m_saveScript->setEnabled( false ); m_scripts->setItemEnabled(m_runScript_id, false); } } void MainWindow::slotTerminate() { if ( currentSession() ) currentSession()->layer()->close(); slotClose(); /* FIXME move to the next session */ } void MainWindow::slotQuickLaunch() { Profile prof = manager()->profile( "default" ); if ( prof.name() == "default" ) { create( prof ); } else { Profile newProf = Profile( "default", "console", "default" , 0, 3, 0 ); newProf.setAutoConnect( true ); create( newProf ); slotSaveSession(); } } void MainWindow::slotConfigure() { ConfigDialog conf( manager()->all(), factory() ); - conf.showMaximized(); - int ret = conf.exec(); + int ret = QPEApplication::execDialog( &conf ); if ( QDialog::Accepted == ret ) { manager()->setProfiles( conf.list() ); manager()->save(); populateProfiles(); } } /* * we will remove * this window from the tabwidget * remove it from the list * delete it * and set the currentSession() */ void MainWindow::slotClose() { if (!currentSession() ) return; Session* ses = currentSession(); qWarning("removing! currentSession %s", currentSession()->name().latin1() ); /* set to NULL to be safe, if its needed slotSessionChanged resets it automatically */ m_curSession = NULL; tabWidget()->remove( /*currentSession()*/ses ); /*it's autodelete */ m_sessions.remove( ses ); qWarning("after remove!!"); if (!currentSession() ) { m_connect->setEnabled( false ); m_disconnect->setEnabled( false ); m_terminate->setEnabled( false ); m_transfer->setEnabled( false ); m_recordScript->setEnabled( false ); m_saveScript->setEnabled( false ); m_scripts->setItemEnabled(m_runScript_id, false); m_fullscreen->setEnabled( false ); m_wrap->setEnabled( false ); m_closewindow->setEnabled( false ); } m_kb->loadDefaults(); } /* * We will get the name * Then the profile * and then we will make a profile */ void MainWindow::slotProfile( int id) { Profile prof = manager()->profile( m_sessionsPop->text( id) ); create( prof ); } void MainWindow::create( const Profile& prof ) { if(m_curSession) if(m_curSession->transferDialog()) m_curSession->transferDialog()->hide(); Session *ses = manager()->fromProfile( prof, tabWidget() ); if((!ses) || (!ses->layer()) || (!ses->widgetStack())) { QMessageBox::warning(this, QObject::tr("Session failed"), QObject::tr("<qt>Cannot open session: Not all components were found.</qt>")); //if(ses) delete ses; return; } m_sessions.append( ses ); tabWidget()->add( ses ); tabWidget()->repaint(); m_curSession = ses; // dicide if its a local term ( then no connction and no tranfer), maybe make a wrapper method out of it m_connect->setEnabled( true ); m_disconnect->setEnabled( false ); m_terminate->setEnabled( true ); m_fullscreen->setEnabled( true ); m_wrap->setEnabled( true ); m_closewindow->setEnabled( true ); m_transfer->setEnabled( false ); m_recordScript->setEnabled( false ); m_saveScript->setEnabled( false ); m_scripts->setItemEnabled(m_runScript_id, false); // is io_layer wants direct connection, then autoconnect //if ( ( m_curSession->layer() )->supports()[0] == 1 ) { if (prof.autoConnect()) { slotConnect(); } QWidget *w = currentSession()->widget(); if(w) w->setFocus(); if(currentSession()->profile().readNumEntry("Wrap", 80)){ m_isWrapped = true; } else { m_isWrapped = false; } m_kb->load(currentSession()->profile()); } void MainWindow::slotTransfer() { if ( currentSession() ) { Session *mysession = currentSession(); TransferDialog dlg(/*mysession->widgetStack()*/this, this); mysession->setTransferDialog(&dlg); //dlg.reparent(mysession->widgetStack(), QPoint(0, 0)); //dlg.showMaximized(); currentSession()->widgetStack()->addWidget(&dlg, -1); dlg.show(); //dlg.exec(); while(dlg.isRunning()) qApp->processEvents(); mysession->setTransferDialog(0l); } } void MainWindow::slotOpenKeb(bool state) { if (state) m_keyBar->show(); else m_keyBar->hide(); } void MainWindow::slotOpenButtons( bool state ) { if ( state ) { m_buttonBar->show(); } else { m_buttonBar->hide(); } } void MainWindow::slotSessionChanged( Session* ses ) { qWarning("changed!"); if(m_curSession) if(m_curSession->transferDialog()) m_curSession->transferDialog()->hide(); if(ses) if(ses->transferDialog()) ses->transferDialog()->show(); if ( ses ) { m_curSession = ses; qDebug(QString("is connected : %1").arg( m_curSession->layer()->isConnected() ) ); if ( m_curSession->layer()->isConnected() ) { m_connect->setEnabled( false ); m_disconnect->setEnabled( true ); m_recordScript->setEnabled(!m_curSession->emulationHandler()->isRecording()); m_saveScript->setEnabled(m_curSession->emulationHandler()->isRecording()); m_scripts->setItemEnabled(m_runScript_id, true); } else { m_connect->setEnabled( true ); m_disconnect->setEnabled( false ); m_recordScript->setEnabled( false ); m_saveScript->setEnabled( false ); m_scripts->setItemEnabled(m_runScript_id, false); } if ( ( m_curSession->layer() )->supports()[1] == 0 ) { m_transfer->setEnabled( false ); } else { m_transfer->setEnabled( true ); } QWidget *w = m_curSession->widget(); if(w) w->setFocus(); if(currentSession()->profile().readNumEntry("Wrap", 80)){ m_isWrapped = true; } else { m_isWrapped = false; } m_kb->load(currentSession()->profile()); } } void MainWindow::slotWrap() { if(m_curSession) { EmulationHandler *e = m_curSession->emulationHandler(); if(e) { if(m_isWrapped) { e->setWrap(80); m_isWrapped = false; } else { e->setWrap(0); m_isWrapped = true; } } } } void MainWindow::slotFullscreen() { if ( m_isFullscreen ) { ( m_curSession->widgetStack() )->reparent( savedParentFullscreen, 0, QPoint(0,0), true ); ( m_curSession->widgetStack() )->resize( savedParentFullscreen->width(), savedParentFullscreen->height() ); ( m_curSession->emulationHandler() )->cornerButton()->hide(); disconnect( ( m_curSession->emulationHandler() )->cornerButton(), SIGNAL( pressed() ), this, SLOT( slotFullscreen() ) ); } else { savedParentFullscreen = ( m_curSession->widgetStack() )->parentWidget(); ( m_curSession->widgetStack() )->setFrameStyle( QFrame::NoFrame ); ( m_curSession->widgetStack() )->reparent( 0, WStyle_Tool | WStyle_Customize | WStyle_StaysOnTop , QPoint(0,0), false ); ( m_curSession->widgetStack() )->resize( qApp->desktop()->width(), qApp->desktop()->height() ); ( m_curSession->widgetStack() )->setFocus(); ( m_curSession->widgetStack() )->show(); ( ( m_curSession->emulationHandler() )->cornerButton() )->show(); connect( ( m_curSession->emulationHandler() )->cornerButton(), SIGNAL( pressed() ), this, SLOT( slotFullscreen() ) ); } m_isFullscreen = !m_isFullscreen; } void MainWindow::slotKeyReceived(FKey k, ushort, ushort, bool pressed) { if ( m_curSession ) { QEvent::Type state; if (pressed) state = QEvent::KeyPress; else state = QEvent::KeyRelease; QKeyEvent ke(state, k.qcode, k.unicode, 0, QString(QChar(k.unicode))); // is this the best way to do this? cant figure out any other way to work QApplication::sendEvent((QObject *)m_curSession->widget(), &ke); ke.ignore(); } } void MainWindow::slotCopy() { if (!currentSession() ) return; currentSession()->emulationHandler()->copy(); } void MainWindow::slotPaste() { diff --git a/noncore/apps/opie-console/modemconfigwidget.cpp b/noncore/apps/opie-console/modemconfigwidget.cpp index e552990..3466e3a 100644 --- a/noncore/apps/opie-console/modemconfigwidget.cpp +++ b/noncore/apps/opie-console/modemconfigwidget.cpp @@ -1,255 +1,256 @@ + +#include <qpe/qpeapplication.h> + #include <qlabel.h> #include <qlayout.h> #include <qcombobox.h> #include <qpushbutton.h> #include <qhbox.h> #include "modemconfigwidget.h" #include "dialdialog.h" namespace { void setCurrent( const QString& str, QComboBox* bo ) { uint b = bo->count(); for (int i = 0; i < bo->count(); i++ ) { if ( bo->text(i) == str ) { bo->setCurrentItem( i ); return; } } bo->insertItem( str ); bo->setCurrentItem( b ); } } ModemConfigWidget::ModemConfigWidget( const QString& name, QWidget* parent, const char* na ) : ProfileDialogConnectionWidget( name, parent, na ) { m_lay = new QVBoxLayout( this ); m_device = new QLabel(tr( "Modem is attached to:" ), this ); m_deviceCmb = new QComboBox(this ); m_deviceCmb->setEditable( TRUE ); QLabel* telLabel = new QLabel( this ); telLabel->setText( tr( "Enter telefon number here:" ) ); QHBox *buttonBox = new QHBox( this ); m_telNumber = new QLineEdit( buttonBox ); QPushButton *atButton = new QPushButton( buttonBox ); atButton->setText( tr( "AT commands" ) ); connect( atButton, SIGNAL( clicked() ), this, SLOT( slotAT() ) ); QPushButton *dialButton = new QPushButton( buttonBox ); dialButton->setText( tr( "Enter number" ) ); connect( dialButton, SIGNAL( clicked() ), this, SLOT( slotDial() ) ); m_base = new IOLayerBase( this, "base" ); m_lay->addWidget( m_device ); m_lay->addWidget( m_deviceCmb ); m_lay->addWidget( telLabel ); m_lay->addWidget( buttonBox ); m_lay->addWidget( m_base ); m_lay->addStretch( 0 ); m_deviceCmb->insertItem( "/dev/ttyS0" ); m_deviceCmb->insertItem( "/dev/ttyS1" ); m_deviceCmb->insertItem( "/dev/ttyS2" ); atConf = new ATConfigDialog( this, "ATConfig", true ); } ModemConfigWidget::~ModemConfigWidget() { } void ModemConfigWidget::load( const Profile& prof ) { int rad_flow = prof.readNumEntry( "Flow" ); int rad_parity = prof.readNumEntry( "Parity" ); int speed = prof.readNumEntry( "Speed" ); int dbits = prof.readNumEntry("DataBits"); int sbits = prof.readNumEntry("StopBits"); QString number = prof.readEntry( "Number" ); if ( !number.isEmpty() ) { m_telNumber->setText( number ); } if ( rad_flow == 1 ) { m_base->setFlow( IOLayerBase::Hardware ); } else if (rad_flow == 2) { m_base->setFlow( IOLayerBase::Software ); } else if (rad_flow == 0) { m_base->setFlow( IOLayerBase::None ); } if ( rad_parity == 1 ) { m_base->setParity( IOLayerBase::Even ); } else if ( rad_parity == 2 ){ m_base->setParity( IOLayerBase::Odd ); } else { m_base->setParity( IOLayerBase::NonePar ); } switch( speed ) { case 115200: m_base->setSpeed( IOLayerBase::Baud_115200 ); break; case 57600: m_base->setSpeed( IOLayerBase::Baud_57600 ); break; case 38400: m_base->setSpeed( IOLayerBase::Baud_38400 ); break; case 19200: m_base->setSpeed( IOLayerBase::Baud_19200 ); break; case 9600: default: m_base->setSpeed( IOLayerBase::Baud_9600 ); break; } if ( dbits == 5) { m_base->setData( IOLayerBase::Data_Five ); } else if (rad_flow == 6) { m_base->setData( IOLayerBase::Data_Six ); } else if (rad_flow == 7) { m_base->setData( IOLayerBase::Data_Seven ); } else { m_base->setData( IOLayerBase::Data_Eight ); } if ( sbits == 2) { m_base->setStop( IOLayerBase::Stop_Two ); } else if ( sbits == 15 ) { m_base->setStop( IOLayerBase::Stop_OnePointFive ); } else { m_base->setStop( IOLayerBase::Stop_One ); } atConf->readConfig( prof ); if ( prof.readEntry( "Device" ).isEmpty() ) { qWarning("device empty!"); return; } setCurrent( prof.readEntry( "Device" ), m_deviceCmb ); } /* * save speed, * flow, * parity */ void ModemConfigWidget::save( Profile& prof ) { int flow, parity, speed, data, stop; flow = parity = speed = data = stop = 0; prof.writeEntry( "Device", m_deviceCmb->currentText() ); switch( m_base->flow() ) { case IOLayerBase::None: flow = 0; break; case IOLayerBase::Software: flow = 2; break; case IOLayerBase::Hardware: flow = 1; break; } switch( m_base->parity() ) { case IOLayerBase::Odd: parity = 2; break; case IOLayerBase::Even: parity = 1; break; case IOLayerBase::NonePar: parity = 0; break; } switch( m_base->speed() ) { case IOLayerBase::Baud_115200: speed = 115200; break; case IOLayerBase::Baud_57600: speed = 57600; break; case IOLayerBase::Baud_38400: speed = 38400; break; case IOLayerBase::Baud_19200: speed = 19200; break; case IOLayerBase::Baud_9600: speed = 9600; break; } switch( m_base->data() ) { case IOLayerBase::Data_Five: data = 5; break; case IOLayerBase::Data_Six: data = 6; break; case IOLayerBase::Data_Seven: data = 7; break; case IOLayerBase::Data_Eight: data = 8; break; } switch( m_base->stop() ) { case IOLayerBase::Stop_One: stop = 1; break; case IOLayerBase::Stop_OnePointFive: stop = 15; break; case IOLayerBase::Stop_Two: stop = 2; break; } prof.writeEntry( "Flow", flow ); prof.writeEntry( "Parity", parity ); prof.writeEntry( "Speed", speed ); prof.writeEntry("DataBits", data); prof.writeEntry("StopBits", stop); prof.writeEntry( "Number", m_telNumber->text() ); atConf->writeConfig(prof); } void ModemConfigWidget::slotAT() { // ATConfigDialog conf( this, "ATConfig", true ); // josef/Max I know why don't you create the stuff on the stack // but making it a TopLevel Dialog and ignoring // cancel is not fun either... // what to do? FIXME!!! -zecke - atConf->showMaximized(); - if ( atConf->exec() != QDialog::Accepted ) { + if ( QPEApplication::execDialog( atConf ) != QDialog::Accepted ) { // reload old settings } } void ModemConfigWidget::slotDial() { DialDialog dial( this, "DialConfig", true ); if(!m_telNumber->text().isEmpty()) { dial.setNumber(m_telNumber->text().replace(QRegExp("[\\-\\/\\ \\.\\,]"), "")); } - dial.showMaximized(); - if ( dial.exec() == QDialog::Accepted ) { + if ( QPEApplication::execDialog( &dial ) == QDialog::Accepted ) { m_telNumber->setText( dial.number() ); } } diff --git a/noncore/apps/opie-reader/CloseDialog.cpp b/noncore/apps/opie-reader/CloseDialog.cpp index 741fa67..d7c2652 100644 --- a/noncore/apps/opie-reader/CloseDialog.cpp +++ b/noncore/apps/opie-reader/CloseDialog.cpp @@ -1,18 +1,21 @@ #include "CloseDialog.h" #include "qlayout.h" +#include <qpe/qpeapplication.h> + CCloseDialog::CCloseDialog(const QString& fname, bool fs, QWidget* parent, const char* name) : QDialog(parent, name, true) { setCaption(tr("Tidy-up")); QVBoxLayout *tmp = new QVBoxLayout(this); QVButtonGroup* vb = new QVButtonGroup(tr("Delete"), this); tmp->addWidget(vb); QString filestring = tr("Delete") + " " + fname; file = new QCheckBox(filestring, vb); marks = new QCheckBox(tr("Delete Bookmarks"), vb); config = new QCheckBox(tr("Delete Configuration"), vb); file->setChecked(false); marks->setChecked(true); config->setChecked(true); - if (fs) showMaximized(); + if (fs) + QPEApplication::showDialog( this ); } diff --git a/noncore/apps/opie-reader/Prefs.cpp b/noncore/apps/opie-reader/Prefs.cpp index e5320d9..5150ca5 100644 --- a/noncore/apps/opie-reader/Prefs.cpp +++ b/noncore/apps/opie-reader/Prefs.cpp @@ -1,636 +1,639 @@ /**************************************************************************** ** Form implementation generated from reading ui file 'Prefs.ui' ** ** Created: Tue Feb 11 23:53:35 2003 ** by: The User Interface Compiler (uic) ** ** WARNING! All changes made in this file will be lost! ****************************************************************************/ #include "useqpe.h" #include "Prefs.h" #include <qcheckbox.h> #include <qlabel.h> #include <qpushbutton.h> #include <qspinbox.h> #include <qlayout.h> #include <qvariant.h> #include <qtooltip.h> #include <qwhatsthis.h> #include <qcombobox.h> #include <qbuttongroup.h> #include <qlineedit.h> #ifdef USEQPE #include <qpe/menubutton.h> #include <qpe/fontdatabase.h> #else #include <qfontdatabase.h> #endif +#include <qpe/qpeapplication.h> + CLayoutPrefs::CLayoutPrefs( QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { QHBoxLayout* hb = new QHBoxLayout(this); QButtonGroup* bg = new QButtonGroup(2, Qt::Horizontal, tr("Text"), this); hb->addWidget(bg); StripCR = new QCheckBox( bg ); StripCR->setText( tr( "Strip CR" ) ); Dehyphen = new QCheckBox( bg ); Dehyphen->setText( tr( "Dehyphen" ) ); SingleSpace = new QCheckBox( bg ); SingleSpace->setText( tr( "Single Space" ) ); Unindent = new QCheckBox( bg ); Unindent->setText( tr( "Unindent" ) ); Reparagraph = new QCheckBox( bg ); Reparagraph->setText( tr( "Reparagraph" ) ); DoubleSpace = new QCheckBox( bg ); DoubleSpace->setText( tr( "Double Space" ) ); Remap = new QCheckBox( bg ); Remap->setText( tr( "Remap" ) ); Embolden = new QCheckBox( bg ); Embolden->setText( tr( "Embolden" ) ); FullJustify = new QCheckBox( bg ); FullJustify->setText( tr( "Full Justify" ) ); } /* * Destroys the object and frees any allocated resources */ CLayoutPrefs::~CLayoutPrefs() { // no need to delete child widgets, Qt does it all for us } CLayoutPrefs2::CLayoutPrefs2( QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { QVBoxLayout* vb = new QVBoxLayout(this); QGridLayout* gl = new QGridLayout(vb, 4, 3); QLabel *TextLabel; TextLabel = new QLabel( this, "TextLabel1" ); TextLabel->setText( tr( "Indent" ) ); gl->addWidget(TextLabel, 0, 0); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Page\nOverlap" ) ); gl->addWidget(TextLabel, 0, 1); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Graphics\nZoom" ) ); gl->addWidget(TextLabel, 0, 2); Indent = new QSpinBox( this, "Indent" ); Indent->setRange(0,20); gl->addWidget(Indent, 1, 0); pageoverlap = new QSpinBox( this ); pageoverlap->setRange(0,20); gl->addWidget(pageoverlap, 1, 1); gfxzoom = new QSpinBox( this ); gfxzoom->setRange(0,100); gl->addWidget(gfxzoom, 1, 2); TextLabel = new QLabel( this, "TextLabel4" ); TextLabel->setText( tr( "Margin" ) ); gl->addWidget(TextLabel, 2, 0); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Paragraph\nLeading" ) ); gl->addWidget(TextLabel, 2, 1); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Line\nLeading" ) ); gl->addWidget(TextLabel, 2, 2); Margin = new QSpinBox( this, "Margin" ); Margin->setRange(0, 100); gl->addWidget(Margin, 3, 0); ParaLead = new QSpinBox( this ); ParaLead->setRange(-5, 50); gl->addWidget(ParaLead, 3, 1); LineLead = new QSpinBox( this ); LineLead->setRange(-5, 50); gl->addWidget(LineLead, 3, 2); gl = new QGridLayout(vb, 2, 2); TextLabel = new QLabel( this); TextLabel->setText( tr( "Markup" ) ); gl->addWidget(TextLabel, 0, 0, Qt::AlignBottom); TextLabel = new QLabel( this); TextLabel->setText( tr( "Font" ) ); gl->addWidget(TextLabel, 0, 1, Qt::AlignBottom); #ifdef USECOMBO Markup = new QComboBox( this); #else Markup = new MenuButton( this); #endif Markup->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); Markup->insertItem("Auto"); Markup->insertItem("None"); Markup->insertItem("Text"); Markup->insertItem("HTML"); Markup->insertItem("PML"); gl->addWidget(Markup, 1, 0, Qt::AlignTop); #ifdef USECOMBO fontselector = new QComboBox( this); #else fontselector = new MenuButton( this); #endif fontselector->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); { #ifdef USEQPE FontDatabase f; #else QFontDatabase f; #endif QStringList flist = f.families(); for (QStringList::Iterator nm = flist.begin(); nm != flist.end(); nm++) { fontselector->insertItem(*nm); } } // delete the FontDatabase!!! gl->addWidget(fontselector, 1, 1, Qt::AlignTop); } /* CLayoutPrefs2::CLayoutPrefs2( QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { QHBoxLayout* hb = new QHBoxLayout(this); QVBoxLayout* vb = new QVBoxLayout; hb->addLayout(vb); QLabel *TextLabel; TextLabel = new QLabel( this, "TextLabel1" ); TextLabel->setText( tr( "Indent" ) ); vb->addWidget( TextLabel, 0, Qt::AlignBottom ); Indent = new QSpinBox( this, "Indent" ); Indent->setRange(0,20); vb->addWidget( Indent, 0, Qt::AlignLeft ); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Page\nOverlap" ) ); vb->addWidget( TextLabel, 0, Qt::AlignBottom ); pageoverlap = new QSpinBox( this ); pageoverlap->setRange(0,20); vb->addWidget( pageoverlap, 0, Qt::AlignLeft ); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Graphics\nZoom" ) ); vb->addWidget( TextLabel, 0, Qt::AlignBottom ); gfxzoom = new QSpinBox( this ); gfxzoom->setRange(0,100); vb->addWidget( gfxzoom, 0, Qt::AlignLeft ); vb->addStretch(); vb = new QVBoxLayout; hb->addLayout(vb); TextLabel = new QLabel( this, "TextLabel4" ); TextLabel->setText( tr( "Margin" ) ); vb->addWidget( TextLabel, 0, Qt::AlignBottom ); Margin = new QSpinBox( this, "Margin" ); Margin->setRange(0, 100); vb->addWidget( Margin, 0, Qt::AlignLeft ); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Paragraph\nLeading" ) ); vb->addWidget( TextLabel, 0, Qt::AlignBottom ); ParaLead = new QSpinBox( this ); ParaLead->setRange(-5, 50); vb->addWidget( ParaLead, 0, Qt::AlignLeft ); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Line\nLeading" ) ); vb->addWidget( TextLabel, 0, Qt::AlignBottom ); LineLead = new QSpinBox( this ); LineLead->setRange(-5, 50); vb->addWidget( LineLead, 0, Qt::AlignLeft ); vb->addStretch(); vb = new QVBoxLayout; hb->addLayout(vb); TextLabel = new QLabel( this); TextLabel->setText( tr( "Markup" ) ); vb->addWidget( TextLabel, 0, Qt::AlignBottom ); Markup = new MenuButton( this); Markup->insertItem("Auto"); Markup->insertItem("None"); Markup->insertItem("Text"); Markup->insertItem("HTML"); Markup->insertItem("PML"); vb->addWidget( Markup, 0, Qt::AlignLeft ); TextLabel = new QLabel( this); TextLabel->setText( tr( "Font" ) ); vb->addWidget( TextLabel, 0, Qt::AlignBottom ); fontselector = new MenuButton( this); fontselector->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); { FontDatabase f; QStringList flist = f.families(); for (QStringList::Iterator nm = flist.begin(); nm != flist.end(); nm++) { fontselector->insertItem(*nm); } } // delete the FontDatabase!!! vb->addWidget( fontselector, 0, Qt::AlignLeft ); vb->addStretch(); } */ /* * Destroys the object and frees any allocated resources */ CLayoutPrefs2::~CLayoutPrefs2() { // no need to delete child widgets, Qt does it all for us } /* CPluckerPrefs::CPluckerPrefs( QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { Layout11 = new QVBoxLayout(this); Layout11->setMargin( 0 ); Depluck = new QCheckBox( this, "Depluck" ); Depluck->setText( tr( "Depluck" ) ); Layout11->addWidget( Depluck ); Dejpluck = new QCheckBox( this, "Dejpluck" ); Dejpluck->setText( tr( "Dejpluck" ) ); Layout11->addWidget( Dejpluck ); Continuous = new QCheckBox( this, "Continuous" ); Continuous->setText( tr( "Continuous" ) ); Layout11->addWidget( Continuous ); } CPluckerPrefs::~CPluckerPrefs() { // no need to delete child widgets, Qt does it all for us } */ /* CMiscPrefs::CMiscPrefs( QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { QVBoxLayout* Layout11 = new QVBoxLayout(this); Layout11->setMargin( 0 ); QHBoxLayout* hl = new QHBoxLayout; QLabel* TextLabel = new QLabel( this ); TextLabel->setText( tr( "Action for\nSelect Button" ) ); hl->addWidget(TextLabel); action = new QComboBox( this ); action->insertItem("Open file"); action->insertItem("Autoscroll"); action->insertItem("Mark"); action->insertItem("Annotate"); action->insertItem("Fullscreen"); hl->addWidget( action ); Layout11->addLayout(hl); hl = new QHBoxLayout; TextLabel = new QLabel( this ); TextLabel->setText( tr( "Dictionary\nApplication" ) ); hl->addWidget(TextLabel); target = new QLineEdit(this); hl->addWidget( target ); Layout11->addLayout(hl); QButtonGroup* bg = new QButtonGroup(1, Qt::Horizontal, "Selection Target", this); Layout11->addWidget( bg ); annotation = new QCheckBox( bg ); annotation->setText( tr( "Annotation" ) ); dictionary = new QCheckBox( bg ); dictionary->setText( tr( "Dictionary" ) ); clipboard = new QCheckBox( bg ); clipboard->setText( tr( "Clipboard" ) ); } CMiscPrefs::~CMiscPrefs() { // no need to delete child widgets, Qt does it all for us } */ CMiscPrefs::CMiscPrefs( QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { QGridLayout* hl = new QGridLayout(this,1,2); hl->setMargin( 0 ); QGroupBox* gb = new QGroupBox(1, Qt::Horizontal, tr("Select Action"), this); hl->addWidget( gb, 0, 0 ); annotation = new QCheckBox( gb ); annotation->setText( tr( "Annotation" ) ); dictionary = new QCheckBox( gb ); dictionary->setText( tr( "Dictionary" ) ); clipboard = new QCheckBox( gb ); clipboard->setText( tr( "Clipboard" ) ); QButtonGroup* bg = new QButtonGroup(1, Qt::Horizontal, tr("Plucker"), this); hl->addWidget( bg, 0 , 1 ); Depluck = new QCheckBox( bg ); Depluck->setText( tr( "Depluck" ) ); Dejpluck = new QCheckBox( bg ); Dejpluck->setText( tr( "Dejpluck" ) ); Continuous = new QCheckBox( bg ); Continuous->setText( tr( "Continuous" ) ); /* QGroupBox* gb = new QGroupBox(1, Qt::Horizontal, "Navigation", this); TextLabel = new QLabel( gb ); TextLabel->setText( tr( "Overlap" ) ); QSpinBox* sb = new QSpinBox( gb ); Internationalisation Ideogram/Word Set Width Set Encoding Set Font */ } CMiscPrefs::~CMiscPrefs() { // no need to delete child widgets, Qt does it all for us } CPrefs::CPrefs(bool fs, QWidget* parent, const char* name) : QDialog(parent, name, true) { setCaption(tr( "OpieReader Settings" ) ); QTabWidget* td = new QTabWidget(this); layout = new CLayoutPrefs(this); layout2 = new CLayoutPrefs2(this); misc = new CMiscPrefs(this); button = new CButtonPrefs(this); inter = new CInterPrefs(this); td->addTab(layout, tr("Layout")); td->addTab(layout2, tr("Layout(2)")); td->addTab(inter, tr("Locale")); td->addTab(misc, tr("Misc")); td->addTab(button, tr("Buttons")); QVBoxLayout* v = new QVBoxLayout(this); v->addWidget(td); - if (fs) showMaximized(); + if (fs) + QPEApplication::showDialog( this ); } /* Unicode Ideo/Word Width Encoding */ #include "CEncoding_tables.h" CInterPrefs::CInterPrefs( QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { QHBoxLayout* hb = new QHBoxLayout(this); QGroupBox* gb = new QGroupBox(1, Qt::Horizontal, tr("International"), this); hb->addWidget(gb); QLabel *TextLabel; ideogram = new QCheckBox( gb ); ideogram->setText( tr( "Ideograms" ) ); TextLabel = new QLabel( gb ); TextLabel->setText( tr( "Ideogram Width" ) ); ideogramwidth = new QSpinBox( gb ); ideogramwidth->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); ideogramwidth->setRange(1,200); propfontchange = new QCheckBox( gb ); propfontchange->setText( tr( "Apply font\nto dialogs" ) ); TextLabel = new QLabel( gb ); TextLabel->setText( tr( "Encoding" ) ); #ifdef USECOMBO encoding = new QComboBox(gb); #else encoding = new MenuButton(gb); #endif encoding->insertItem("Ascii"); encoding->insertItem("UTF-8"); encoding->insertItem("UCS-2(BE)"); encoding->insertItem("USC-2(LE)"); encoding->insertItem("Palm"); for (unicodetable::iterator iter = unicodetable::begin(); iter != unicodetable::end(); iter++) { encoding->insertItem(iter->mime); } QVBoxLayout* vb = new QVBoxLayout; gb = new QGroupBox(1, Qt::Horizontal, tr("Dictionary"), this); TextLabel = new QLabel( gb ); TextLabel->setText( tr( "Application" ) ); application = new QLineEdit(gb); application->setFixedWidth(80); TextLabel = new QLabel( gb ); TextLabel->setText( tr( "Message" ) ); message = new QLineEdit(gb); message->setFixedWidth(80); // message->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); twotouch = new QCheckBox( gb ); twotouch->setText( tr( "Two/One\nTouch" ) ); SwapMouse = new QCheckBox( gb ); SwapMouse->setText(tr("Swap Tap\nActions") ); vb->addWidget(gb); // vb->addStretch(); hb->addLayout(vb); } CInterPrefs::~CInterPrefs() { // no need to delete child widgets, Qt does it all for us } #ifdef USECOMBO void CButtonPrefs::populate(QComboBox *mb) #else void CButtonPrefs::populate(MenuButton *mb) #endif { mb->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); mb->insertItem(tr("<Nothing>") ); mb->insertItem(tr("Open file") ); mb->insertItem(tr("Autoscroll") ); mb->insertItem(tr("Bookmark") ); mb->insertItem(tr("Annotate") ); mb->insertItem(tr("Fullscreen") ); mb->insertItem(tr("Zoom in") ); mb->insertItem(tr("Zoom out") ); mb->insertItem(tr("Back") ); mb->insertItem(tr("Forward") ); mb->insertItem(tr("Home") ); mb->insertItem(tr("Page up") ); mb->insertItem(tr("Page down") ); mb->insertItem(tr("Line up") ); mb->insertItem(tr("Line down") ); mb->insertItem(tr("Beginning") ); mb->insertItem(tr("End") ); } CButtonPrefs::CButtonPrefs( QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { QGridLayout* hl = new QGridLayout(this,10,2); hl->setMargin( 0 ); QLabel* ql = new QLabel(tr("Escape Button"), this); hl->addWidget(ql, 0, 0, Qt::AlignBottom); #ifdef USECOMBO escapeAction = new QComboBox( this ); #else escapeAction = new MenuButton( this ); #endif populate(escapeAction); hl->addWidget(escapeAction, 1, 0, Qt::AlignTop | Qt::AlignLeft); ql = new QLabel(tr("Space Button"), this); hl->addWidget(ql, 2, 0, Qt::AlignBottom); #ifdef USECOMBO spaceAction = new QComboBox( this ); #else spaceAction = new MenuButton( this ); #endif populate(spaceAction); hl->addWidget(spaceAction, 3, 0, Qt::AlignTop | Qt::AlignLeft); ql = new QLabel(tr("Return Button"), this); hl->addWidget(ql, 2, 1, Qt::AlignBottom); #ifdef USECOMBO returnAction = new QComboBox( this ); #else returnAction = new MenuButton( this ); #endif populate(returnAction); hl->addWidget(returnAction, 3, 1, Qt::AlignTop | Qt::AlignLeft); ql = new QLabel(tr("Left Arrow"), this); hl->addWidget(ql, 4, 0, Qt::AlignBottom); #ifdef USECOMBO leftAction = new QComboBox( this ); #else leftAction = new MenuButton( this ); #endif populate(leftAction); hl->addWidget(leftAction, 5, 0, Qt::AlignTop | Qt::AlignLeft); leftScroll = new QCheckBox( tr("Scroll Speed"), this ); hl->addWidget(leftScroll, 6, 0, Qt::AlignTop | Qt::AlignLeft); ql = new QLabel(tr("Right Arrow"), this); hl->addWidget(ql, 4, 1, Qt::AlignBottom); #ifdef USECOMBO rightAction = new QComboBox( this ); #else rightAction = new MenuButton( this ); #endif populate(rightAction); hl->addWidget(rightAction, 5, 1, Qt::AlignTop | Qt::AlignLeft); rightScroll = new QCheckBox( tr("Scroll Speed"), this ); hl->addWidget(rightScroll, 6, 1, Qt::AlignTop | Qt::AlignLeft); ql = new QLabel(tr("Down Arrow"), this); hl->addWidget(ql, 7, 0, Qt::AlignBottom); #ifdef USECOMBO downAction = new QComboBox( this ); #else downAction = new MenuButton( this ); #endif populate(downAction); hl->addWidget(downAction, 8, 0, Qt::AlignTop | Qt::AlignLeft); downScroll = new QCheckBox( tr("Scroll Speed"), this ); hl->addWidget(downScroll, 9, 0, Qt::AlignTop | Qt::AlignLeft); ql = new QLabel(tr("Up Arrow"), this); hl->addWidget(ql, 7, 1, Qt::AlignBottom); #ifdef USECOMBO upAction = new QComboBox( this ); #else upAction = new MenuButton( this ); #endif populate(upAction); hl->addWidget(upAction, 8, 1, Qt::AlignTop | Qt::AlignLeft); upScroll = new QCheckBox( tr("Scroll Speed"), this ); hl->addWidget(upScroll, 9, 1, Qt::AlignTop | Qt::AlignLeft); } CButtonPrefs::~CButtonPrefs() { // no need to delete child widgets, Qt does it all for us } diff --git a/noncore/apps/opie-reader/QTReaderApp.cpp b/noncore/apps/opie-reader/QTReaderApp.cpp index f10020a..07af597 100644 --- a/noncore/apps/opie-reader/QTReaderApp.cpp +++ b/noncore/apps/opie-reader/QTReaderApp.cpp diff --git a/noncore/apps/opie-reader/ToolbarPrefs.cpp b/noncore/apps/opie-reader/ToolbarPrefs.cpp index 361bf97..d878829 100644 --- a/noncore/apps/opie-reader/ToolbarPrefs.cpp +++ b/noncore/apps/opie-reader/ToolbarPrefs.cpp @@ -1,302 +1,304 @@ /**************************************************************************** ** Form implementation generated from reading ui file 'Prefs.ui' ** ** Created: Tue Feb 11 23:53:35 2003 ** by: The User Interface Compiler (uic) ** ** WARNING! All changes made in this file will be lost! ****************************************************************************/ #include "useqpe.h"
#include "ToolbarPrefs.h" #include <qcheckbox.h> #include <qlabel.h> #include <qpushbutton.h> #include <qspinbox.h> #include <qlayout.h> #include <qvariant.h> #include <qtooltip.h> #include <qwhatsthis.h> #include <qcombobox.h> #include <qbuttongroup.h> #include <qlineedit.h> #ifdef USEQPE
#include <qpe/menubutton.h> #endif
+#include <qpe/qpeapplication.h> CBarPrefs::CBarPrefs(const QString& appdir, bool fs, QWidget* parent, const char* name) : QDialog(parent, name, true), config( appdir ) { setCaption(tr( "Toolbar Settings" ) ); QTabWidget* td = new QTabWidget(this); misc = new CMiscBarPrefs(this); filebar = new CFileBarPrefs(config, this); navbar = new CNavBarPrefs(config, this); viewbar = new CViewBarPrefs(config, this); markbar = new CMarkBarPrefs(config, this); indbar = new CIndBarPrefs(config, this); td->addTab(filebar, tr("File")); td->addTab(navbar, tr("Navigation")); td->addTab(viewbar, tr("View")); td->addTab(markbar, tr("Marks")); td->addTab(indbar, tr("Indicators")); td->addTab(misc, tr("Policy")); QVBoxLayout* v = new QVBoxLayout(this); v->addWidget(td); - if (fs) showMaximized(); + if (fs) + QPEApplication::showDialog( this ); } /* CBarPrefs1::CBarPrefs1( Config& _config, QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ), config(_config) { config.setGroup( "Toolbar" ); QVBoxLayout* vb = new QVBoxLayout(this); QGroupBox* bg = new QGroupBox(3, Qt::Horizontal, "File", this); vb->addWidget(bg); open = new QCheckBox( tr("Open"), bg ); open->setChecked(config.readBoolEntry( "Open", false )); connect(open, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); close = new QCheckBox( tr("Close"), bg ); close->setChecked(config.readBoolEntry( "Close", false )); connect(close, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); info = new QCheckBox( tr("Info"), bg ); info->setChecked(config.readBoolEntry( "Info", false )); connect(info, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); twotouch = new QCheckBox( tr("Two/One\nTouch"), bg ); twotouch->setChecked(config.readBoolEntry( "Two/One Touch", false )); connect(twotouch, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); find = new QCheckBox( tr("Find"), bg ); find->setChecked(config.readBoolEntry( "Find", false )); connect(find, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); bg = new QGroupBox(2, Qt::Horizontal, "Navigation", this); vb->addWidget(bg); scroll = new QCheckBox( tr("Scroll"), bg ); scroll->setChecked(config.readBoolEntry( "Scroll", false )); connect(scroll, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); navigation = new QCheckBox( tr("Back/Home/Forward"), bg ); navigation->setChecked(config.readBoolEntry( "Back/Home/Forward", false )); connect(navigation, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); page = new QCheckBox( tr("Page\nUp/Down"), bg ); page->setChecked(config.readBoolEntry( "Page Up/Down", false )); connect(page, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); startend = new QCheckBox( tr("Goto Start/End"), bg ); startend->setChecked(config.readBoolEntry( "Goto Start/End", false )); connect(startend, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); jump = new QCheckBox( tr("Jump"), bg ); jump->setChecked(config.readBoolEntry( "Jump", false )); connect(jump, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); pageline = new QCheckBox( tr("Page/Line Scroll"), bg ); pageline->setChecked(config.readBoolEntry( "Page/Line Scroll", false )); connect(pageline, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); m_isChanged = false; } void CBarPrefs1::saveall() { config.setGroup( "Toolbar" ); config.writeEntry( "Open", open->isChecked()); config.writeEntry( "Close", close->isChecked()); config.writeEntry( "Info", info->isChecked()); config.writeEntry( "Two/One Touch", twotouch->isChecked()); config.writeEntry( "Find", find->isChecked()); config.writeEntry( "Scroll", scroll->isChecked()); config.writeEntry( "Back/Home/Forward", navigation->isChecked()); config.writeEntry( "Page Up/Down", page->isChecked()); config.writeEntry( "Goto Start/End", startend->isChecked()); config.writeEntry( "Jump", jump->isChecked()); config.writeEntry( "Page/Line Scroll", pageline->isChecked()); } CBarPrefs1::~CBarPrefs1() { } */ /* CBarPrefs2::CBarPrefs2( Config& _config, QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ), config(_config) { QVBoxLayout* vb = new QVBoxLayout(this); QGroupBox* bg = new QGroupBox(3, Qt::Horizontal, "View", this); vb->addWidget(bg); config.setGroup( "Toolbar" ); fullscreen = new QCheckBox( tr("Fullscreen"), bg ); fullscreen->setChecked(config.readBoolEntry( "Fullscreen", false )); connect(fullscreen, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); zoom = new QCheckBox( tr("Zoom"), bg ); zoom->setChecked(config.readBoolEntry( "Zoom In/Out", false )); connect(zoom, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); setfont = new QCheckBox( tr("Set Font"), bg ); setfont->setChecked(config.readBoolEntry( "Set Font", false )); connect(setfont, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); encoding = new QCheckBox( tr("Encoding"), bg ); encoding->setChecked(config.readBoolEntry("Encoding Select", false)); connect(encoding, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); ideogram = new QCheckBox( tr("Ideogram"), bg ); ideogram->setChecked(config.readBoolEntry("Ideogram Mode", false)); connect(ideogram, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); bg = new QGroupBox(3, Qt::Horizontal, "Marks", this); vb->addWidget(bg); mark = new QCheckBox( tr("Bookmark"), bg ); mark->setChecked(config.readBoolEntry( "Mark", false )); connect(mark, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); annotate = new QCheckBox( tr("Annotate"), bg ); annotate->setChecked(config.readBoolEntry( "Annotate", false )); connect(annotate, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); go_to = new QCheckBox( tr("Goto"), bg ); go_to->setChecked(config.readBoolEntry( "Goto", false )); connect(go_to, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); Delete = new QCheckBox( tr("Delete"), bg ); Delete->setChecked(config.readBoolEntry( "Delete", false )); connect(Delete, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); autogen = new QCheckBox( tr("Autogen"), bg ); autogen->setChecked(config.readBoolEntry( "Autogen", false )); connect(autogen, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); clear = new QCheckBox( tr("Clear"), bg ); clear->setChecked(config.readBoolEntry( "Clear", false )); connect(clear, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); save = new QCheckBox( tr("Save"), bg ); save->setChecked(config.readBoolEntry( "Save", false )); connect(save, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); tidy = new QCheckBox( tr("Tidy"), bg ); tidy->setChecked(config.readBoolEntry( "Tidy", false )); connect(tidy, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); block = new QCheckBox( tr("Mark/Copy"), bg ); block->setChecked(config.readBoolEntry( "Start/Copy Block", false )); connect(block, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); bg = new QGroupBox(1, Qt::Horizontal, "Indicators", this); vb->addWidget(bg); indannotate = new QCheckBox( tr("Annotation"), bg ); indannotate->setChecked(config.readBoolEntry( "Annotation indicator", false )); connect(indannotate, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); m_isChanged = false; } void CBarPrefs2::saveall() { config.setGroup( "Toolbar" ); config.writeEntry( "Fullscreen", fullscreen->isChecked()); config.writeEntry( "Zoom In/Out", zoom->isChecked()); config.writeEntry( "Set Font", setfont->isChecked()); config.writeEntry("Encoding Select", encoding->isChecked()); config.writeEntry("Ideogram Mode", ideogram->isChecked()); config.writeEntry( "Mark", mark->isChecked()); config.writeEntry( "Annotate", annotate->isChecked()); config.writeEntry( "Goto", go_to->isChecked()); config.writeEntry( "Delete", Delete->isChecked()); config.writeEntry( "Autogen", autogen->isChecked()); config.writeEntry( "Clear", clear->isChecked()); config.writeEntry( "Save", save->isChecked()); config.writeEntry( "Tidy", tidy->isChecked()); config.writeEntry( "Start/Copy Block", block->isChecked()); config.writeEntry( "Annotation indicator", indannotate->isChecked()); } CBarPrefs2::~CBarPrefs2() { } */ CFileBarPrefs::CFileBarPrefs( Config& _config, QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ), config(_config) { config.setGroup( "Toolbar" ); QVBoxLayout* vb = new QVBoxLayout(this); QGroupBox* bg = new QGroupBox(2, Qt::Horizontal, "File", this); vb->addWidget(bg); open = new QCheckBox( tr("Open"), bg ); open->setChecked(config.readBoolEntry( "Open", false )); connect(open, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); close = new QCheckBox( tr("Close"), bg ); close->setChecked(config.readBoolEntry( "Close", false )); connect(close, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); info = new QCheckBox( tr("Info"), bg ); info->setChecked(config.readBoolEntry( "Info", false )); connect(info, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); twotouch = new QCheckBox( tr("Two/One\nTouch"), bg ); twotouch->setChecked(config.readBoolEntry( "Two/One Touch", false )); connect(twotouch, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); find = new QCheckBox( tr("Find"), bg ); find->setChecked(config.readBoolEntry( "Find", false )); connect(find, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); m_isChanged = false; } void CFileBarPrefs::saveall() { config.setGroup( "Toolbar" ); config.writeEntry( "Open", open->isChecked()); config.writeEntry( "Close", close->isChecked()); config.writeEntry( "Info", info->isChecked()); config.writeEntry( "Two/One Touch", twotouch->isChecked()); config.writeEntry( "Find", find->isChecked()); } CFileBarPrefs::~CFileBarPrefs() { } CNavBarPrefs::CNavBarPrefs( Config& _config, QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ), config(_config) { config.setGroup( "Toolbar" ); QVBoxLayout* vb = new QVBoxLayout(this); QGroupBox* bg = new QGroupBox(2, Qt::Horizontal, "Navigation", this); vb->addWidget(bg); scroll = new QCheckBox( tr("Scroll"), bg ); scroll->setChecked(config.readBoolEntry( "Scroll", false )); connect(scroll, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); navback = new QCheckBox( tr("Back"), bg ); navback->setChecked(config.readBoolEntry( "Back", false )); connect(navback, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); navhome = new QCheckBox( tr("Home"), bg ); navhome->setChecked(config.readBoolEntry( "Home", false )); connect(navhome, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); navforward = new QCheckBox( tr("Forward"), bg ); navforward->setChecked(config.readBoolEntry( "Forward", false )); connect(navforward, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); pageup = new QCheckBox( tr("Page Up"), bg ); pageup->setChecked(config.readBoolEntry( "Page Up", false )); connect(pageup, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); pagedown = new QCheckBox( tr("Page Down"), bg ); pagedown->setChecked(config.readBoolEntry( "Page Down", false )); connect(pagedown, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); gotostart = new QCheckBox( tr("Goto Start"), bg ); gotostart->setChecked(config.readBoolEntry( "Goto Start", false )); connect(gotostart, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); gotoend = new QCheckBox( tr("Goto End"), bg ); gotoend->setChecked(config.readBoolEntry( "Goto End", false )); connect(gotoend, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); jump = new QCheckBox( tr("Jump"), bg ); jump->setChecked(config.readBoolEntry( "Jump", false )); connect(jump, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); pageline = new QCheckBox( tr("Page/Line Scroll"), bg ); pageline->setChecked(config.readBoolEntry( "Page/Line Scroll", false )); connect(pageline, SIGNAL(stateChanged(int)), this, SLOT( isChanged(int) ) ); m_isChanged = false; } void CNavBarPrefs::saveall() { config.setGroup( "Toolbar" ); config.writeEntry( "Scroll", scroll->isChecked()); config.writeEntry( "Back", navback->isChecked()); config.writeEntry( "Home", navhome->isChecked()); config.writeEntry( "Forward", navforward->isChecked()); config.writeEntry( "Page Up", pageup->isChecked()); config.writeEntry( "Page Down", pagedown->isChecked()); diff --git a/noncore/apps/opie-reader/URLDialog.cpp b/noncore/apps/opie-reader/URLDialog.cpp index dd4568b..e572c80 100644 --- a/noncore/apps/opie-reader/URLDialog.cpp +++ b/noncore/apps/opie-reader/URLDialog.cpp @@ -1,14 +1,17 @@ #include "URLDialog.h" #include "qlayout.h" +#include <qpe/qpeapplication.h>
+
CURLDialog::CURLDialog(const QString& fname, bool fs, QWidget* parent, const char* name) : QDialog(parent, name, true) { setCaption(tr("Save URL")); QVBoxLayout *tmp = new QVBoxLayout(this); QVButtonGroup* vb = new QVButtonGroup(fname, this); tmp->addWidget(vb); m_clipboard = new QCheckBox(tr("Clipboard"), vb); m_localfile = new QCheckBox(tr("Local file"), vb); m_globalfile = new QCheckBox(tr("Global file"), vb); - if (fs) showMaximized(); + if (fs)
+ QPEApplication::showDialog( this );
} diff --git a/noncore/apps/opie-reader/fileBrowser.cpp b/noncore/apps/opie-reader/fileBrowser.cpp index 9cd371d..05f2c31 100644 --- a/noncore/apps/opie-reader/fileBrowser.cpp +++ b/noncore/apps/opie-reader/fileBrowser.cpp @@ -1,266 +1,269 @@ /**************************************************************************** Derived from a file browser which was ** copyright 2001 ljp ljp@llornkcor.com Extensive modification by Tim Wentford to allow it to work in rotated mode ****************************************************************************/ #include "fileBrowser.h" #include "QtrListView.h" #include <qlineedit.h> #include <qpushbutton.h> #include <qfile.h> #include <qmessagebox.h> #ifndef _WINDOWS #include <unistd.h> #endif #include <qlayout.h> #ifdef _WINDOWS #include <direct.h> #endif +#include <qpe/qpeapplication.h> + #include "opie.h" fileBrowser::fileBrowser( bool allownew, QWidget* parent, const char* name, bool modal, WFlags fl , const QString filter, const QString iPath ) : QDialog( parent, name, true, fl/* | WStyle_Customize | WStyle_Tool*/), filterspec(QDir::All) { // showMaximized(); if ( !name ) setName( "fileBrowser" ); /* if (parent != NULL) { #ifdef OPIE move(0,0); resize( parent->width(), parent->height() ); #else setGeometry(parent->x(), parent->y(), parent->width(), parent->height() ); #endif } */ // showFullScreen(); setCaption(tr( "Browse for file" ) ); filterStr=filter; buttonOk = new QPushButton( this, "buttonOk" ); buttonOk->setFixedSize( 25, 25 ); buttonOk->setAutoDefault( false ); buttonOk->setText( tr( "/" ) ); buttonShowHidden = new QPushButton( this, "buttonShowHidden" ); // buttonShowHidden->setFixedSize( 50, 25 ); buttonShowHidden->setText( tr( "Hidden" ) ); buttonShowHidden->setAutoDefault( false ); buttonShowHidden->setToggleButton( true ); buttonShowHidden->setOn( false ); dirLabel = new QLabel(this, "DirLabel"); dirLabel->setAlignment(AlignLeft | AlignVCenter | ExpandTabs | WordBreak); dirLabel->setText(currentDir.canonicalPath()); ListView = new QtrListView( this, "ListView" ); ListView->addColumn( tr( "Name" ) ); ListView->setSorting( 2, FALSE); ListView->addColumn( tr( "Size" ) ); ListView->setSelectionMode(QListView::Single); ListView->setAllColumnsShowFocus( TRUE ); ListView->setColumnWidthMode(0, QListView::Manual); ListView->setColumnWidthMode(1, QListView::Manual); // signals and slots connections connect( buttonShowHidden, SIGNAL( toggled(bool) ), this, SLOT( setHidden(bool) ) ); connect( buttonOk, SIGNAL( clicked() ), this, SLOT( OnRoot() ) ); connect( ListView, SIGNAL(doubleClicked( QListViewItem*)), SLOT(listDoubleClicked(QListViewItem *)) ); connect( ListView, SIGNAL(clicked( QListViewItem*)), SLOT(listClicked(QListViewItem *)) ); connect( ListView, SIGNAL(OnOKButton( QListViewItem*)), SLOT(listClicked(QListViewItem *)) ); connect( ListView, SIGNAL(OnCentreButton( QListViewItem*)), SLOT(listClicked(QListViewItem *)) ); connect( ListView, SIGNAL(OnCancelButton()), SLOT(OnCancel()) ); QVBoxLayout* grid = new QVBoxLayout(this); QHBoxLayout* hgrid = new QHBoxLayout(grid); hgrid->addWidget(dirLabel,1); hgrid->addWidget(buttonShowHidden); hgrid->addWidget(buttonOk); grid->addWidget(ListView,1); if (allownew) { m_filename = new QLineEdit(this); grid->addWidget(m_filename); connect( m_filename, SIGNAL( returnPressed() ), this, SLOT( onReturn() )); } else { m_filename = NULL; } if (QFileInfo(iPath).exists()) { currentDir.setPath(iPath); #ifdef _WINDOWS _chdir(iPath.latin1()); #else chdir(iPath.latin1()); #endif } else { currentDir.setPath(QDir::currentDirPath()); chdir(QDir::currentDirPath().latin1()); } populateList(); - if (modal) showMaximized(); + if (modal) + QPEApplication::showDialog( this ); } void fileBrowser::resizeEvent(QResizeEvent* e) { ListView->setColumnWidth(1,(ListView->width())/4); ListView->setColumnWidth(0,ListView->width()-20-ListView->columnWidth(1)); } fileBrowser::~fileBrowser() { } void fileBrowser::populateList() { ListView->clear(); ////qDebug(currentDir.canonicalPath()); // currentDir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::NoSymLinks ); currentDir.setFilter( filterspec ); currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst); currentDir.setMatchAllDirs(TRUE); currentDir.setNameFilter(filterStr); // currentDir.setNameFilter("*.txt;*.etx"); QString fileL, fileS; const QFileInfoList *list = currentDir.entryInfoList(); QFileInfoListIterator it(*list); QFileInfo *fi; while ( (fi=it.current()) ) { if (fi->fileName() != ".") { fileS.sprintf( "%10li", fi->size() ); fileL.sprintf( "%s",fi->fileName().data() ); if( fi->isDir() ) { fileL+="/"; } else { //// qDebug("Not a dir: "+currentDir.canonicalPath()+fileL); } new QListViewItem( ListView,fileL,fileS ); } ++it; } ListView->setSorting( 2, FALSE); dirLabel->setText("Current Directory:\n"+currentDir.canonicalPath()); ListView->setFocus(); } void fileBrowser::upDir() { //// qDebug(currentDir.canonicalPath()); } void fileBrowser::listClicked(QListViewItem *selectedItem) { if (selectedItem == NULL) return; QString strItem=selectedItem->text(0); //// qDebug("%s", (const char*)strItem); QString strSize=selectedItem->text(1); strSize.stripWhiteSpace(); bool ok; QFileInfo fi(strItem); while (fi.isSymLink()) fi.setFile(fi.readLink()); if (fi.isDir()) { strItem=QDir::cleanDirPath(currentDir.canonicalPath()+"/"+strItem); if(QDir(strItem).exists()) { currentDir.cd(strItem, TRUE); populateList(); } } else { QListViewItem *selectedItem = ListView->selectedItem(); if (selectedItem == NULL) { filename = ""; } else { filename = QDir::cleanDirPath(currentDir.canonicalPath()+"/"+selectedItem->text(0)); } OnOK(); } chdir(strItem.latin1()); // } // you may want to switch these 2 functions. I like single clicks void fileBrowser::listDoubleClicked(QListViewItem *selectedItem) { } QString fileBrowser::getCurrentFile() { return filename; } void fileBrowser::OnOK() { accept(); } void fileBrowser::OnRoot() { currentDir.cd("/", TRUE); populateList(); chdir("/"); } void fileBrowser::OnCancel() { reject(); } void fileBrowser::setHidden(bool _hidden) { if (_hidden) filterspec = QDir::All | QDir::Hidden; else filterspec = QDir::All; populateList(); } void fileBrowser::onReturn() { QListViewItem *selectedItem = ListView->selectedItem(); if (selectedItem == NULL) { filename = m_filename->text(); } else { filename = QDir::cleanDirPath(currentDir.canonicalPath()+"/"+m_filename->text()); } OnOK(); } diff --git a/noncore/apps/opie-sheet/mainwindow.cpp b/noncore/apps/opie-sheet/mainwindow.cpp index bd98aca..3d3c688 100644 --- a/noncore/apps/opie-sheet/mainwindow.cpp +++ b/noncore/apps/opie-sheet/mainwindow.cpp @@ -1,279 +1,282 @@ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ /* * Opie Sheet (formerly Sheet/Qt) * by Serdar Ozler <sozler@sitebest.com> */ #include "mainwindow.h" #include <qpe/filemanager.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/resource.h> +#include <qpe/qpeapplication.h> + #include <qmessagebox.h> #include <qfile.h> #include <qtranslator.h> #include <qradiobutton.h> + #include "cellformat.h" #include "numberdlg.h" #include "textdlg.h" #include "sortdlg.h" #include "finddlg.h" #define DEFAULT_NUM_ROWS 300 #define DEFAULT_NUM_COLS (26*3) #define DEFAULT_NUM_SHEETS 3 MainWindow::MainWindow(QWidget *parent, const char* n, WFlags fl) :QMainWindow(parent, n, fl) { // initialize variables documentModified=FALSE; // construct objects currentDoc=0; fileSelector=new FileSelector("application/sheet-qt", this, QString::null); ExcelSelector=new FileSelector("application/excel",this,QString::null,FALSE); connect(fileSelector, SIGNAL(closeMe()), this, SLOT(selectorHide())); connect(fileSelector, SIGNAL(newSelected(const DocLnk &)), this, SLOT(selectorFileNew(const DocLnk &))); connect(fileSelector, SIGNAL(fileSelected(const DocLnk &)), this, SLOT(selectorFileOpen(const DocLnk &))); connect(ExcelSelector,SIGNAL(fileSelected(const DocLnk &)),this,SLOT(slotImportExcel(const DocLnk &))); connect(ExcelSelector,SIGNAL(closeMe()), this, SLOT(ExcelSelectorHide())); listSheets.setAutoDelete(TRUE); initActions(); initMenu(); initEditToolbar(); initFunctionsToolbar(); initStandardToolbar(); initSheet(); // set window title setCaption(tr("Opie Sheet")); // create sheets selectorFileNew(DocLnk()); } MainWindow::~MainWindow() { if (currentDoc) delete currentDoc; } void MainWindow::documentSave(DocLnk *lnkDoc) { FileManager fm; QByteArray streamBuffer; QDataStream stream(streamBuffer, IO_WriteOnly); typeSheet *currentSheet=findSheet(sheet->getName()); if (!currentSheet) { QMessageBox::critical(this, tr("Error"), tr("Inconsistency error!")); return; } sheet->copySheetData(¤tSheet->data); stream.writeRawBytes("SQT100", 6); stream << (Q_UINT32)listSheets.count(); for (typeSheet *tempSheet=listSheets.first(); tempSheet; tempSheet=listSheets.next()) { stream << tempSheet->name << (Q_UINT32)tempSheet->data.count(); for (typeCellData *tempCell=tempSheet->data.first(); tempCell; tempCell=tempSheet->data.next()) stream << (Q_UINT32)tempCell->col << (Q_UINT32)tempCell->row << tempCell->borders.right << tempCell->borders.bottom << tempCell->background << (Q_UINT32)tempCell->alignment << tempCell->fontColor << tempCell->font << tempCell->data; } lnkDoc->setType("application/sheet-qt"); if (!fm.saveFile(*lnkDoc, streamBuffer)) { QMessageBox::critical(this, tr("Error"), tr("File cannot be saved!")); return; } documentModified=FALSE; } void MainWindow::documentOpen(const DocLnk &lnkDoc) { FileManager fm; QByteArray streamBuffer; if (!lnkDoc.isValid() || !fm.loadFile(lnkDoc, streamBuffer)) { QMessageBox::critical(this, tr("Error"), tr("File cannot be opened!")); documentModified=FALSE; selectorFileNew(DocLnk()); return; } QDataStream stream(streamBuffer, IO_ReadOnly); Q_UINT32 countSheet, countCell, i, j, row, col, alignment; typeSheet *newSheet; typeCellData *newCell; char fileFormat[7]; stream.readRawBytes(fileFormat, 6); fileFormat[6]=0; if ((QString)fileFormat!="SQT100") { QMessageBox::critical(this, tr("Error"), tr("Invalid file format!")); documentModified=FALSE; selectorFileNew(DocLnk()); return; } stream >> countSheet; for (i=0; i<countSheet; ++i) { newSheet=new typeSheet; newSheet->data.setAutoDelete(TRUE); stream >> newSheet->name >> countCell; comboSheets->insertItem(newSheet->name); for (j=0; j<countCell; ++j) { newCell=new typeCellData; stream >> col >> row >> newCell->borders.right >> newCell->borders.bottom >> newCell->background >> alignment >> newCell->fontColor >> newCell->font >> newCell->data; newCell->col=col; newCell->row=row; newCell->alignment=(Qt::AlignmentFlags)alignment; newSheet->data.append(newCell); } listSheets.append(newSheet); if (i==0) { sheet->setName(newSheet->name); sheet->setSheetData(&newSheet->data); } } } int MainWindow::saveCurrentFile(bool ask) { if (ask) { int result=QMessageBox::information(this, tr("Save File"), tr("Do you want to save the current file?"), QMessageBox::Yes, QMessageBox::No, QMessageBox::Cancel); if (result!=QMessageBox::Yes) return result; } if (!currentDoc->isValid()) { TextDialog dialogText(this); if (dialogText.exec(tr("Save File"), tr("&File Name:"), tr("UnnamedFile"))!=QDialog::Accepted || dialogText.getValue().isEmpty()) return QMessageBox::Cancel; currentDoc->setName(dialogText.getValue()); currentDoc->setFile(QString::null); currentDoc->setLinkFile(QString::null); } documentSave(currentDoc); return QMessageBox::Yes; } void MainWindow::selectorFileNew(const DocLnk &lnkDoc) { selectorHide(); if (documentModified && saveCurrentFile()==QMessageBox::Cancel) return; if (currentDoc) delete currentDoc; currentDoc = new DocLnk(lnkDoc); editData->clear(); listSheets.clear(); comboSheets->clear(); typeSheet *newSheet=createNewSheet(); newSheet->data.setAutoDelete(TRUE); sheet->setName(newSheet->name); sheet->setSheetData(&newSheet->data); for (int i=1; i<DEFAULT_NUM_SHEETS; ++i) createNewSheet(); documentModified=FALSE; } void MainWindow::closeEvent(QCloseEvent *e) { if (documentModified && saveCurrentFile()==QMessageBox::Cancel) e->ignore(); else e->accept(); } void MainWindow::selectorFileOpen(const DocLnk &lnkDoc) { selectorHide(); if (documentModified && saveCurrentFile()==QMessageBox::Cancel) return; if (currentDoc) delete currentDoc; currentDoc = new DocLnk(); listSheets.clear(); comboSheets->clear(); documentOpen(lnkDoc); documentModified=FALSE; } void MainWindow::selectorShow() { sheet->hide(); setCentralWidget(fileSelector); fileSelector->show(); fileSelector->reread(); } void MainWindow::selectorHide() { fileSelector->hide(); setCentralWidget(sheet); sheet->show(); } void MainWindow::slotFileNew() { selectorFileNew(DocLnk()); } void MainWindow::slotFileOpen() { selectorShow(); } void MainWindow::slotImportExcelOpen() { sheet->hide(); setCentralWidget(ExcelSelector); ExcelSelector->show(); ExcelSelector->reread(); } void MainWindow::ExcelSelectorHide() { ExcelSelector->hide(); setCentralWidget(sheet); sheet->show(); } void MainWindow::slotFileSave() { saveCurrentFile(FALSE); } void MainWindow::setDocument(const QString &applnk_filename) { selectorFileOpen(DocLnk(applnk_filename)); } void MainWindow::initActions() { fileNew=new QAction(tr("New File"), Resource::loadPixmap( "new" ), tr("&New"), 0, this); connect(fileNew, SIGNAL(activated()), this, SLOT(slotFileNew())); fileOpen=new QAction(tr("Open File"), Resource::loadPixmap( "fileopen" ), tr("&Open"), 0, this); connect(fileOpen, SIGNAL(activated()), this, SLOT(slotFileOpen())); fileSave=new QAction(tr("Save File"),Resource::loadPixmap( "save" ), tr("&Save"), 0, this); connect(fileSave, SIGNAL(activated()), this, SLOT(slotFileSave())); fileSaveAs=new QAction(tr("Save File As"), Resource::loadPixmap( "save" ), tr("Save &As"), 0, this); connect(fileSaveAs, SIGNAL(activated()), this, SLOT(slotFileSaveAs())); @@ -494,515 +497,515 @@ void MainWindow::initMenu() submenuFuncTrig->insertSeparator(); addFlyAction(tr("SINH(x)"), tr("SINH(x)"), "SINH(", submenuFuncTrig); addFlyAction(tr("COSH(x)"), tr("COSH(x)"), "COSH(", submenuFuncTrig); addFlyAction(tr("TANH(x)"), tr("TANH(x)"), "TANH(", submenuFuncTrig); addFlyAction(tr("ACOSH(x)"), tr("ACOSH(x)"), "ACOSH(", submenuFuncTrig); addFlyAction(tr("ASINH(x)"), tr("ASINH(x)"), "ASINH(", submenuFuncTrig); addFlyAction(tr("ATANH(x)"), tr("ATANH(x)"), "ATANH(", submenuFuncTrig); submenuFunc->insertItem(tr("&Trigonometric"), submenuFuncTrig); submenuFuncString=new QPopupMenu; addFlyAction(tr("LEN(s)"), tr("LEN(s)"), "LEN(",submenuFuncString); addFlyAction(tr("LEFT(s,num)"), tr("LEFT(s,num)"), "LEFT(",submenuFuncString); addFlyAction(tr("RIGHT(s,num)"), tr("RIGHT(s,num)"), "RIGHT(",submenuFuncString); addFlyAction(tr("MID(s,pos,len)"), tr("MID(s,pos,len)"), "MID(",submenuFuncString); submenuFuncString->insertSeparator(); addFlyAction(tr("CONCATENATE(s1,s2..)"), tr("CONCATENATE(s1,s2..)"), "CONCATENATE(",submenuFuncString); addFlyAction(tr("EXACT(s1,s2)"), tr("EXACT(s1,s2)"), "EXACT(",submenuFuncString); addFlyAction(tr("FIND(what,where,pos)"), tr("FIND(what,where,pos)"), "FIND(",submenuFuncString); addFlyAction(tr("REPLACE(s,pos,len,ns)"), tr("REPLACE(s,pos,len,ns)"), "REPLACE(",submenuFuncString); addFlyAction(tr("REPT(s,n)"), tr("REPT(s,n)"), "REPT(",submenuFuncString); submenuFuncString->insertSeparator(); addFlyAction(tr("UPPER(s)"), tr("UPPER(s)"), "UPPER(",submenuFuncString); addFlyAction(tr("LOWER(s)"), tr("LOWER(s)"), "LOWER(",submenuFuncString); submenuFunc->insertItem(tr("&Strings"), submenuFuncString); submenuFuncStat=new QPopupMenu; addFlyAction(tr("AVERAGE(range)"), tr("AVERAGE(range)"), "AVERAGE(",submenuFuncStat); addFlyAction(tr("COUNT(range)"), tr("COUNT(range)"), "COUNT(",submenuFuncStat); addFlyAction(tr("COUNTIF(range,eqls)"), tr("COUNTIF(range,eqls)"), "COUNTIF(",submenuFuncStat); addFlyAction(tr("MAX(range)"), tr("MAX(range)"), "MAX(",submenuFuncStat); addFlyAction(tr("MIN(range)"), tr("MIN(range)"), "MIN(",submenuFuncStat); addFlyAction(tr("SUM(range)"), tr("SUM(range)"), "SUM(",submenuFuncStat); addFlyAction(tr("SUMSQ(range)"), tr("SUMSQ(range)"), "SUMSQ(",submenuFuncStat); submenuFuncStat->insertSeparator(); addFlyAction(tr("AVERAGE(range)"), tr("AVERAGE(range)"), "AVERAGE(",submenuFuncStat); addFlyAction(tr("VAR(range)"), tr("VAR(range)"), "VAR(",submenuFuncStat); addFlyAction(tr("VARP(range)"), tr("VARP(range)"), "VARP(",submenuFuncStat); addFlyAction(tr("STDEV(range)"), tr("STDEV(range)"), "STDEV(",submenuFuncStat); addFlyAction(tr("STDEVP(range)"), tr("STDEVP(range)"), "STDEVP(",submenuFuncStat); addFlyAction(tr("SKEW(range)"), tr("SKEW(range)"), "SKEW(",submenuFuncStat); addFlyAction(tr("KURT(range)"), tr("KURT(range)"), "KURT(",submenuFuncStat); submenuFunc->insertItem(tr("Sta&tistical"), submenuFuncStat); submenuFuncScientific=new QPopupMenu; addFlyAction(tr("BESSELI(x,n)"), tr("BESSELI(x,n)"), "BESSELI(",submenuFuncScientific); addFlyAction(tr("BESSELJ(x,n)"), tr("BESSELJ(x,n)"), "BESSELJ(",submenuFuncScientific); addFlyAction(tr("BESSELK(x,n)"), tr("BESSELK(x,n)"), "BESSELK(",submenuFuncScientific); addFlyAction(tr("BESSELY(x,n)"), tr("BESSELY(x,n)"), "BESSELY(",submenuFuncScientific); submenuFuncScientific->insertSeparator(); addFlyAction(tr("BETAI(x,a,b)"), tr("BETAI(x,a,b)"), "BETAI(",submenuFuncScientific); addFlyAction(tr("ERF(a,b)"), tr("ERF(a,b)"), "ERF(",submenuFuncScientific); addFlyAction(tr("ERFC(a,b)"), tr("ERFC(a,b)"), "ERFC(",submenuFuncScientific); addFlyAction(tr("GAMMALN(x)"), tr("GAMMALN(x)"), "GAMMALN(",submenuFuncScientific); addFlyAction(tr("GAMMAP(x,a)"), tr("GAMMAP(x,a)"), "GAMMAP(",submenuFuncScientific); addFlyAction(tr("GAMMAQ(x,a)"), tr("GAMMAQ(x,a)"), "GAMMAQ(",submenuFuncScientific); submenuFunc->insertItem(tr("Scienti&fic"), submenuFuncScientific); submenuFuncDistr=new QPopupMenu; addFlyAction(tr("BETADIST(z,a,b,Q?)"), tr("BETADIST(z,a,b,Q?)"), "BETADIST(",submenuFuncDistr); addFlyAction(tr("CHI2DIST(x,n,Q?)"), tr("CHI2DIST(x,n,Q?)"), "CHI2DIST(",submenuFuncDistr); addFlyAction(tr("CHIDIST(x,n,Q?)"), tr("CHIDIST(x,n,Q?)"), "CHIDIST(",submenuFuncDistr); addFlyAction(tr("FDIST(z,deg1,deg2,Q?)"), tr("FDIST(z,deg1,deg2,Q?)"), "FDIST(",submenuFuncDistr); addFlyAction(tr("GAMMADIST(x,a,b,Q?)"), tr("GAMMADIST(x,a,b,Q?)"), "GAMMADIST(",submenuFuncDistr); addFlyAction(tr("NORMALDIST(x,m,s,Q?)"), tr("NORMALDIST(x,m,s,Q?)"), "NORMALDIST(",submenuFuncDistr); addFlyAction(tr("PHI(x,Q?)"), tr("PHI(x,Q?)"), "PHI(",submenuFuncDistr); addFlyAction(tr("POISSON(x,n,Q?)"), tr("POISSON(x,n,Q?)"), "POISSON(",submenuFuncDistr); submenuFunc->insertItem(tr("&Distributions"), submenuFuncDistr); menuInsert->insertSeparator(); insertCells->addTo(menuInsert); insertRows->addTo(menuInsert); insertCols->addTo(menuInsert); insertSheets->addTo(menuInsert); } void MainWindow::initStandardToolbar() { toolbarStandard=new QToolBar(this); toolbarStandard->setHorizontalStretchable(TRUE); moveToolBar(toolbarStandard, Top); fileNew->addTo(toolbarStandard); fileOpen->addTo(toolbarStandard); fileSave->addTo(toolbarStandard); comboSheets=new QComboBox(toolbarStandard); toolbarStandard->setStretchableWidget(comboSheets); connect(comboSheets, SIGNAL(activated(const QString &)), this, SLOT(slotSheetChanged(const QString &))); } void MainWindow::initFunctionsToolbar() { toolbarFunctions=new QToolBar(this); toolbarFunctions->setHorizontalStretchable(TRUE); moveToolBar(toolbarFunctions, Bottom); funcEqual->addTo(toolbarFunctions); funcPlus->addTo(toolbarFunctions); funcMinus->addTo(toolbarFunctions); funcCross->addTo(toolbarFunctions); funcDivide->addTo(toolbarFunctions); funcParanOpen->addTo(toolbarFunctions); funcParanClose->addTo(toolbarFunctions); funcComma->addTo(toolbarFunctions); toolFunction=new QToolButton(toolbarFunctions); toolFunction->setPixmap(Resource::loadPixmap( "opie-sheet/func-func" )); toolFunction->setTextLabel(tr("Functions")); toolFunction->setPopup(submenuFunc); toolFunction->setPopupDelay(0); } void MainWindow::initEditToolbar() { toolbarEdit=new QToolBar(this); toolbarEdit->setHorizontalStretchable(TRUE); moveToolBar(toolbarEdit, Bottom); editAccept->addTo(toolbarEdit); editCancel->addTo(toolbarEdit); editData=new QLineEdit(toolbarEdit); toolbarEdit->setStretchableWidget(editData); connect(editData, SIGNAL(returnPressed()), this, SLOT(slotEditAccept())); editCellSelect->addTo(toolbarEdit); } void MainWindow::slotHelpAbout() { QDialog dialogAbout(this, 0, TRUE); dialogAbout.resize(width()-40, height()-80); dialogAbout.setCaption(tr("About Opie Sheet")); QLabel label(tr("Opie Sheet\nSpreadsheet Software for Opie\nQWDC Beta Winner (as Sheet/Qt)\n\nDeveloped by: Serdar Ozler\nRelease 1.0.2\nRelease Date: October 08, 2002\n\nThis product is licensed under GPL. It is freely distributable. If you want to get the latest version and also the source code, please visit the web site.\n\nhttp://qtopia.sitebest.com"), &dialogAbout); label.setGeometry(dialogAbout.rect()); label.setAlignment(Qt::AlignCenter | Qt::WordBreak); dialogAbout.exec(); } void MainWindow::initSheet() { sheet=new Sheet(DEFAULT_NUM_ROWS, DEFAULT_NUM_COLS, this); setCentralWidget(sheet); connect(sheet, SIGNAL(currentDataChanged(const QString &)), editData, SLOT(setText(const QString &))); connect(sheet, SIGNAL(cellClicked(const QString &)), this, SLOT(slotCellClicked(const QString &))); connect(sheet, SIGNAL(sheetModified()), this, SLOT(slotDocModified())); connect(editCut, SIGNAL(activated()), sheet, SLOT(editCut())); connect(editCopy, SIGNAL(activated()), sheet, SLOT(editCopy())); connect(editClear, SIGNAL(activated()), sheet, SLOT(editClear())); } void MainWindow::slotEditAccept() { sheet->setData(editData->text()); } void MainWindow::slotEditCancel() { editData->setText(sheet->getData()); } void MainWindow::slotCellSelect(bool lock) { sheet->lockClicks(lock); } void MainWindow::addToData(const QString &data) { editData->setText(editData->text().insert(editData->cursorPosition(), data)); } void MainWindow::slotFuncOutput() { if (sender()->isA("QAction")) addToData(((QAction *)sender())->toolTip()); } void MainWindow::slotInsertRows() { NumberDialog dialogNumber(this); if (dialogNumber.exec(tr("Insert Rows"), tr("&Number of rows:"))==QDialog::Accepted) sheet->insertRows(dialogNumber.getValue()); } void MainWindow::slotInsertCols() { NumberDialog dialogNumber(this); if (dialogNumber.exec(tr("Insert Columns"), tr("&Number of columns:"))==QDialog::Accepted) sheet->insertColumns(dialogNumber.getValue()); } void MainWindow::slotInsertSheets() { NumberDialog dialogNumber(this); if (dialogNumber.exec(tr("Add Sheets"), tr("&Number of sheets:"))==QDialog::Accepted) for (int i=dialogNumber.getValue(); i>0; --i) createNewSheet(); } void MainWindow::slotCellClicked(const QString &cell) { editCellSelect->setOn(FALSE); addToData(cell); } typeSheet *MainWindow::createNewSheet() { typeSheet *newSheet=new typeSheet; int currentNo=1, tempNo=0; bool ok; for (typeSheet *tempSheet=listSheets.first(); tempSheet; tempSheet=listSheets.next()) if (tempSheet->name.startsWith(tr("Sheet")) && (tempNo=tempSheet->name.mid(tr("Sheet").length()).toInt(&ok))>=currentNo && ok) currentNo=tempNo+1; newSheet->name=tr("Sheet")+QString::number(currentNo); newSheet->data.setAutoDelete(TRUE); comboSheets->insertItem(newSheet->name); listSheets.append(newSheet); return newSheet; } typeSheet *MainWindow::findSheet(const QString &name) { for (typeSheet *tempSheet=listSheets.first(); tempSheet; tempSheet=listSheets.next()) if (tempSheet->name==name) return tempSheet; return NULL; } void MainWindow::slotSheetChanged(const QString &name) { sheet->copySheetData(&findSheet(sheet->getName())->data); sheet->setName(name); sheet->setSheetData(&findSheet(name)->data); sheet->ReCalc(); } void MainWindow::addFlyAction(const QString &text, const QString &menuText, const QString &tip, QWidget *w) { QAction *action=new QAction(text, menuText, 0, this); action->setToolTip(tip); connect(action, SIGNAL(activated()), this, SLOT(slotFuncOutput())); action->addTo(w); } void MainWindow::slotFormatCells() { CellFormat dialogCellFormat(this); - dialogCellFormat.showMaximized(); + QPEApplication::showDialog( &dialogCellFormat ); dialogCellFormat.exec(sheet); } void MainWindow::slotEditPaste() { sheet->editPaste(); } void MainWindow::slotEditPasteContents() { sheet->editPaste(TRUE); } void MainWindow::slotRowHeight() { int row1, row2, col1, col2; sheet->getSelection(&row1, &col1, &row2, &col2); NumberDialog dialogNumber(this); if (dialogNumber.exec(tr("Row Height"), tr("&Height of each row:"), sheet->rowHeight(row1))==QDialog::Accepted) { int newHeight=dialogNumber.getValue(), row; for (row=row1; row<=row2; ++row) sheet->setRowHeight(row, newHeight); } } void MainWindow::slotRowAdjust() { int row1, row2, col1, col2; sheet->getSelection(&row1, &col1, &row2, &col2); for (int row=row1; row<=row2; ++row) sheet->adjustRow(row); } void MainWindow::slotRowShow() { int row1, row2, col1, col2; sheet->getSelection(&row1, &col1, &row2, &col2); for (int row=row1; row<=row2; ++row) sheet->showRow(row); } void MainWindow::slotRowHide() { int row1, row2, col1, col2; sheet->getSelection(&row1, &col1, &row2, &col2); for (int row=row1; row<=row2; ++row) sheet->hideRow(row); } void MainWindow::slotColumnWidth() { int row1, row2, col1, col2; sheet->getSelection(&row1, &col1, &row2, &col2); NumberDialog dialogNumber(this); if (dialogNumber.exec(tr("Column Width"), tr("&Width of each column:"), sheet->columnWidth(col1))==QDialog::Accepted) { int newWidth=dialogNumber.getValue(), col; for (col=col1; col<=col2; ++col) sheet->setColumnWidth(col, newWidth); } } void MainWindow::slotColumnAdjust() { int row1, row2, col1, col2; sheet->getSelection(&row1, &col1, &row2, &col2); for (int col=col1; col<=col2; ++col) sheet->adjustColumn(col); } void MainWindow::slotColumnShow() { int row1, row2, col1, col2; sheet->getSelection(&row1, &col1, &row2, &col2); for (int col=col1; col<=col2; ++col) sheet->showColumn(col); } void MainWindow::slotColumnHide() { int row1, row2, col1, col2; sheet->getSelection(&row1, &col1, &row2, &col2); for (int col=col1; col<=col2; ++col) sheet->hideColumn(col); } void MainWindow::slotFileSaveAs() { TextDialog dialogText(this); if (dialogText.exec(tr("Save File As"), tr("&File Name:"), currentDoc->name())!=QDialog::Accepted || dialogText.getValue().isEmpty()) return; currentDoc->setName(dialogText.getValue()); currentDoc->setFile(QString::null); currentDoc->setLinkFile(QString::null); documentSave(currentDoc); } void MainWindow::slotImportExcel(const DocLnk &lnkDoc) { ExcelBook file1; file1.ParseBook((char *)lnkDoc.file().ascii()); int NumOfSheets=file1.Sheets.count(); printf("OpieSheet::NumberOfSheets:%d\r\n",NumOfSheets); if (documentModified && saveCurrentFile()==QMessageBox::Cancel) return; if (currentDoc) delete currentDoc; currentDoc = new DocLnk(); listSheets.clear(); comboSheets->clear(); int w1,r,c; ExcelSheet* sh1; typeSheet* newSheet; QString* str; typeCellData* newCell; for(w1=1;w1<=NumOfSheets;w1++) { sh1=file1.Sheets[w1-1]; printf("OpieSheet:newSheet:%x,r=%d,c=%d\r\n",sh1,sh1->rows,sh1->cols); newSheet=new typeSheet; newSheet->data.setAutoDelete(TRUE); newSheet->name=sh1->name; printf("OpieSheet:Sheetname:%s\r\n",sh1->name.ascii()); comboSheets->insertItem(newSheet->name); for(r=1; r <= sh1->rows; r++) { for(c=1;c <= sh1->cols; c++) { str=file1.CellDataString(sh1,r-1,c-1); if(str!=NULL && r<DEFAULT_NUM_ROWS && c<DEFAULT_NUM_COLS) { newCell=new typeCellData; newCell->row=r-1; newCell->col=c-1; if(str!=NULL) newCell->data=QString(*str); else newCell->data=QString(""); newCell->background=QBrush(Qt::white, Qt::SolidPattern); newCell->alignment=(Qt::AlignmentFlags)(Qt::AlignLeft | Qt::AlignTop); newCell->fontColor=Qt::black; newCell->font=font(); newCell->borders.right=QPen(Qt::gray, 1, Qt::SolidLine); newCell->borders.bottom=QPen(Qt::gray, 1, Qt::SolidLine); newSheet->data.append(newCell); //there is no format parsing at the moment or style parsing //printf("OpieSheetNumber:row=%d,col=%d,val=%s\r\n",r,c,str->latin1()); }; }; }; listSheets.append(newSheet); if (w1==1)//if i==0 link sheet1 with sheetview { sheet->setName(newSheet->name); sheet->setSheetData(&newSheet->data); sheet->ReCalc(); }; }; file1.CloseFile(); printf("Excel FILE read OK\r\n"); documentModified=TRUE; } void MainWindow::slotSheetRename() { TextDialog dialogText(this); if (dialogText.exec(tr("Rename Sheet"), tr("&Sheet Name:"), sheet->getName())!=QDialog::Accepted || dialogText.getValue().isEmpty()) return; QString newName=dialogText.getValue(); typeSheet *tempSheet=findSheet(newName); if (tempSheet) { QMessageBox::critical(this, tr("Error"), tr("There is already a sheet named '"+newName+'\'')); return; } tempSheet=findSheet(sheet->getName()); for (int i=0; i<comboSheets->count(); ++i) if (comboSheets->text(i)==tempSheet->name) { comboSheets->changeItem(newName, i); break; } tempSheet->name=newName; sheet->setName(newName); } void MainWindow::slotSheetRemove() { if (comboSheets->count()<2) { QMessageBox::warning(this, tr("Error"), tr("There is only one sheet!")); return; } if (QMessageBox::information(this, tr("Remove Sheet"), tr("Are you sure?"), QMessageBox::Yes, QMessageBox::No)==QMessageBox::Yes) { typeSheet *tempSheet=findSheet(sheet->getName()); for (int i=0; i<comboSheets->count(); ++i) if (comboSheets->text(i)==tempSheet->name) { comboSheets->removeItem(i); break; } comboSheets->setCurrentItem(0); slotSheetChanged(comboSheets->currentText()); listSheets.remove(tempSheet); } } void MainWindow::slotDataSort() { SortDialog dialogSort(this); - dialogSort.showMaximized(); + QPEApplication::showDialog( &dialogSort ); dialogSort.exec(sheet); } void MainWindow::slotDocModified() { documentModified=TRUE; } void MainWindow::slotInsertCells() { QDialog dialogInsert(this, 0, TRUE); dialogInsert.resize(180, 130); dialogInsert.setCaption(tr("Insert Cells")); QVButtonGroup *group=new QVButtonGroup(tr("&Type"), &dialogInsert); group->setGeometry(10, 10, 160, 110); QRadioButton *radio=new QRadioButton(tr("Shift cells &down"), group); radio=new QRadioButton(tr("Shift cells &right"), group); radio=new QRadioButton(tr("Entire ro&w"), group); radio=new QRadioButton(tr("Entire &column"), group); group->setButton(0); if (dialogInsert.exec()==QDialog::Accepted) switch (group->id(group->selected())) { case 0: sheet->insertRows(1, FALSE); break; case 1: sheet->insertColumns(1, FALSE); break; case 2: sheet->insertRows(1, TRUE); break; case 3: sheet->insertColumns(1, TRUE); break; } } void MainWindow::slotDataFindReplace() { FindDialog dialogFind(this); - dialogFind.showMaximized(); + QPEApplication::showDialog( &dialogFind ); dialogFind.exec(sheet); } diff --git a/noncore/apps/tableviewer/ui/tveditview.cpp b/noncore/apps/tableviewer/ui/tveditview.cpp index 23e2b42..20a24c8 100644 --- a/noncore/apps/tableviewer/ui/tveditview.cpp +++ b/noncore/apps/tableviewer/ui/tveditview.cpp @@ -1,235 +1,237 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ /* The edit view widget. For each key in the DB display an * appropriate edit box, and a 'key' button to change that particular * key information (delete or edit). * * Bottem line should be a 'new key' button. Should be able to scroll * in both directions. */ #include "tveditview.h" #include "commonwidgets.h" #include <qlayout.h> #include <qgrid.h> #include <qvbox.h> #include <qlineedit.h> #include <qcheckbox.h> #include <qlist.h> #include <qlabel.h> #include <qscrollview.h> #include <qsignalmapper.h> +#include <qpe/qpeapplication.h> + TVEditView::TVEditView(TableState *s, DataElem *d, QWidget* parent, const char *name, WFlags fl ) : QDialog(parent, name, true, fl) { if (!name) setName("TVEditView"); QVBoxLayout *layout = new QVBoxLayout(this, 0); /* only so that will resize correctly in other widgets */ toggles = new QSignalMapper(this); QScrollView *sv = new QScrollView(this, 0); sv->setResizePolicy(QScrollView::AutoOneFit); layout->addWidget(sv); editDisplay = new QGrid(3, sv, 0); editDisplay->setSpacing(3); sv->addChild(editDisplay); connect(toggles, SIGNAL(mapped(int)), this, SLOT(toggleEnabled(int))); setData(s, d); #ifdef Q_WS_QWS - showMaximized(); + QPEApplication::showDialog( this ); #endif } TVEditView::~TVEditView() { } /*! set up the widgets in the grid, Set up initial values */ void TVEditView::setData(TableState *t, DataElem *d) { /* TODO need to somehow clear old children... a delete of each * child? */ keyIds.clear(); KeyListIterator it(*t->kRep); int i = 0; while(it.current()) { if (t->kRep->validIndex(it.currentKey())) { new QLabel(it.current()->name(), editDisplay); keyIds.insert(i, it.currentKey()); if (d->hasValidValue(it.currentKey())) { switch(it.current()->type()) { case TVVariant::String: { QLineEdit *edit = new QLineEdit(editDisplay, 0); edit->setText(d->getField(it.currentKey()).toString()); edits.append(edit); break; } case TVVariant::Int: { IntEdit *edit = new IntEdit(editDisplay, 0); edit->setValue(d->getField(it.currentKey()).toInt()); edits.append(edit); break; } case TVVariant::Time: { TimeEdit *edit = new TimeEdit(editDisplay, 0); edit->setTime(d->getField(it.currentKey()).toTime()); edits.append(edit); break; } case TVVariant::Date: { DateEdit *edit = new DateEdit(editDisplay, 0); edit->setDate(d->getField(it.currentKey()).toDate()); edits.append(edit); break; } default: edits.append(new QLabel("<B><I>Uknown key type</I></B>", editDisplay)); } QCheckBox *tb = new QCheckBox(editDisplay); tb->setChecked(TRUE); toggles->setMapping(tb, i); connect(tb, SIGNAL(clicked()), toggles, SLOT(map())); buttons.append(tb); } else { /* No valid value.. set to null */ switch(it.current()->type()) { case TVVariant::String: { QLineEdit *edit = new QLineEdit(editDisplay, 0); edit->setEnabled(false); edits.append(edit); break; } case TVVariant::Int: { IntEdit *edit = new IntEdit(editDisplay, 0); edit->setEnabled(false); edits.append(edit); break; } case TVVariant::Time: { TimeEdit *edit = new TimeEdit(editDisplay, 0); edit->setEnabled(false); edits.append(edit); break; } case TVVariant::Date: { DateEdit *edit = new DateEdit(editDisplay, 0); edit->setEnabled(false); edits.append(edit); break; } default: edits.append(new QLabel("<B><I>Uknown key type</I></B>", editDisplay)); } QCheckBox *tb = new QCheckBox(editDisplay); tb->setChecked(FALSE); toggles->setMapping(tb, i); connect(tb, SIGNAL(clicked()), toggles, SLOT(map())); buttons.append(tb); } i++; } ++it; } num_edits = i; } void TVEditView::toggleEnabled(int i) { if(edits.at(i)->isEnabled()) { edits.at(i)->setEnabled(false); buttons.at(i)->setChecked(FALSE); } else { edits.at(i)->setEnabled(true); buttons.at(i)->setChecked(TRUE); } } bool TVEditView::openEditItemDialog(TableState *ts, DataElem *d, QWidget *parent) { int i; int keyId; if(!ts) return 0; if(!d) return 0; if(!ts->kRep) return 0; TVEditView *dlg = new TVEditView(ts, d, parent); if (dlg->exec() == QDialog::Accepted ) { /* update the element, basically for each edits, if isEnabled, set Value, else unsetField */ for(i = 0; i < dlg->num_edits; i++) { keyId = dlg->keyIds[i]; if(dlg->edits.at(i)->isEnabled()) { switch(d->getFieldType(keyId)) { case TVVariant::String: { TVVariant value = TVVariant( ((QLineEdit *)dlg->edits.at(i))->text()); d->setField(keyId, value); break; } case TVVariant::Int: { TVVariant value = TVVariant( ((IntEdit *)dlg->edits.at(i))->value()); d->setField(keyId, value); break; } case TVVariant::Time: { TVVariant value = TVVariant( ((TimeEdit *)dlg->edits.at(i))->time()); d->setField(keyId, value); break; } case TVVariant::Date: { TVVariant value = TVVariant( ((DateEdit *)dlg->edits.at(i))->date()); d->setField(keyId, value); break; } default: break; } } else { /* unset the field */ d->unsetField(keyId); } } delete dlg; return TRUE; } return FALSE; } diff --git a/noncore/apps/tableviewer/ui/tvfilterview.cpp b/noncore/apps/tableviewer/ui/tvfilterview.cpp index 0182127..b03e846 100644 --- a/noncore/apps/tableviewer/ui/tvfilterview.cpp +++ b/noncore/apps/tableviewer/ui/tvfilterview.cpp @@ -1,304 +1,306 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "tvfilterview.h" #include <qtoolbutton.h> #include <qcombobox.h> #include <qlistview.h> #include <qlayout.h> #include <qheader.h> #include <qpushbutton.h> #include <qlabel.h> +#include <qpe/qpeapplication.h> + TVFilterView::TVFilterView(TableState *t, QWidget* parent, const char *name, WFlags fl ) : QDialog(parent, name, TRUE, fl) { if ( !name ) setName( "Filter View" ); QVBoxLayout *vlayout = new QVBoxLayout(this); display = new QListView(this, "display"); display->addColumn("Key"); display->addColumn("Constraint"); display->addColumn("Value"); display->header()->setClickEnabled(FALSE); display->header()->setResizeEnabled(FALSE); vlayout->addWidget(display); QHBoxLayout *hlayout = new QHBoxLayout; hlayout->addItem(new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum)); newFilterButton = new QPushButton(this, "new Filter"); newFilterButton->setMaximumSize(QSize(50, 32767)); newFilterButton->setText("New"); hlayout->addWidget(newFilterButton); deleteFilterButton = new QPushButton(this, "delete Filter"); deleteFilterButton->setMaximumSize(QSize(50, 32767)); deleteFilterButton->setText("Delete"); hlayout->addWidget(deleteFilterButton); clearFilterButton = new QPushButton(this, "delete Filter"); clearFilterButton->setMaximumSize(QSize(60, 32767)); clearFilterButton->setText("Clear All"); hlayout->addWidget(clearFilterButton); vlayout->addLayout(hlayout); QHBoxLayout *hlayout2 = new QHBoxLayout; keyNameCombo = new QComboBox(FALSE, this, "key name"); keyNameCombo->setEnabled(FALSE); hlayout2->addWidget(keyNameCombo); QLabel *label = new QLabel(this); label->setText("has value"); hlayout2->addWidget(label); keyEntry = new TVFilterKeyEntry(this, "key entry"); keyEntry->setEnabled(FALSE); vlayout->addLayout(hlayout2); vlayout->addWidget(keyEntry); connect(newFilterButton, SIGNAL( clicked() ), this, SLOT( newTerm() )); connect(deleteFilterButton, SIGNAL( clicked() ), this, SLOT( deleteTerm())); connect(clearFilterButton, SIGNAL( clicked() ), this, SLOT( clearTerms())); connect(keyEntry, SIGNAL(valueChanged()), this, SLOT( updateTerm() )); connect(keyNameCombo, SIGNAL(activated(int)), this, SLOT( updateTerm() )); connect(display, SIGNAL(selectionChanged(QListViewItem*)), this, SLOT(setTerm(QListViewItem *))); ts = t; current = 0; terms.setAutoDelete(true); do_filter = false; #ifdef Q_WS_QWS - showMaximized(); + QPEApplication::showDialog( this ); #endif } /*! Destroys the TVFilterView widget */ TVFilterView::~TVFilterView() { } void TVFilterView::rebuildData() { } void TVFilterView::reset() { keyNameCombo->clear(); keyIds.clear(); } void TVFilterView::rebuildKeys() { int i; if (!ts) return; if(!ts->kRep) return; keyEntry->setTableState(ts); /* set up the list of keys that can be compared on */ keyNameCombo->clear(); KeyListIterator it(*ts->kRep); i = 0; while(it.current()) { if(ts->kRep->validIndex(it.currentKey())) { keyNameCombo->insertItem(it.current()->name()); keyIds.insert(i, it.currentKey()); ++i; } ++it; } } bool TVFilterView::passesFilter(DataElem *d) { if (!filterActive()) return true; FilterTerm *t; for (t = terms.first(); t != 0; t = terms.next() ) { /* check against filter */ switch(t->ct) { case ct_less: if (!d->lessThan(t->keyIndex, t->value)) return false; break; case ct_more: if (!d->moreThan(t->keyIndex, t->value)) return false; break; case ct_equal: if (!d->equalTo(t->keyIndex, t->value)) return false; break; case ct_contains: if (!d->contains(t->keyIndex, t->value)) return false; break; case ct_startswith: if (!d->startsWith(t->keyIndex, t->value)) return false; break; case ct_endswith: if (!d->endsWith(t->keyIndex, t->value)) return false; break; default: qWarning("TVFilterView::passesFilter() " "unrecognized filter type"); return false; } } return true; } bool TVFilterView::filterActive() const { /* when button operated, also check the do_filter value return do_filter; */ if (terms.isEmpty()) return false; return true; } /* SLOTS */ void TVFilterView::newTerm() { if (!ts) return; FilterTerm *term = new FilterTerm; current = term; term->view = 0; updateTerm(); display->setSelected(term->view, true); terms.append(term); keyEntry->setEnabled(true); keyNameCombo->setEnabled(true); } void TVFilterView::updateTerm() { FilterTerm *term; /* Read the widget values (keyname, compare type, value) * and build the lists */ if (!ts) return; if (!current) return; QString keyString; QString cmpString; QString vString; term = current; /* create new list item, set initial values, enable widgets */ term->keyIndex = keyIds[keyNameCombo->currentItem()]; keyEntry->setKey(term->keyIndex); /* so the next two items make sense */ term->ct = keyEntry->getCompareType(), term->value = keyEntry->getCompareValue(); keyString = keyNameCombo->currentText(); switch(term->ct) { case ct_less: cmpString = " less than "; break; case ct_more: cmpString = " more than "; break; case ct_equal: cmpString = " equal to "; break; case ct_contains: cmpString = " containing "; break; case ct_startswith: cmpString = " starting with "; break; case ct_endswith: cmpString = " ending with "; break; default: cmpString = " ERROR "; } vString = term->value.toString(); /* remove old view */ if (term->view) delete(term->view); term->view = new QListViewItem(display, 0, keyString, cmpString, vString); display->setSelected(term->view, true); } /* deletes current term */ void TVFilterView::deleteTerm() { if(!current) return; if (current->view) delete(current->view); terms.removeRef(current); current = terms.first(); if(terms.isEmpty()) { keyEntry->setEnabled(false); keyNameCombo->setEnabled(false); } } /* clears all terminations */ void TVFilterView::clearTerms() { while(current) deleteTerm(); } void TVFilterView::setTerm(QListViewItem *target) { /* Iterate through the list to find item with view=target.. * set as current, delete */ FilterTerm *term = current; for (current = terms.first(); current != 0; current = terms.next() ) if (current->view == target) break; if (!current) { current = term; } } diff --git a/noncore/apps/tableviewer/ui/tvkeyedit.cpp b/noncore/apps/tableviewer/ui/tvkeyedit.cpp index 4849e87..c22ecd3 100644 --- a/noncore/apps/tableviewer/ui/tvkeyedit.cpp +++ b/noncore/apps/tableviewer/ui/tvkeyedit.cpp @@ -1,254 +1,256 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "tvkeyedit.h" #include <qtoolbutton.h> #include <qlineedit.h> #include <qcombobox.h> #include <qlistview.h> #include <qmessagebox.h> #include <stdlib.h> #include <qpushbutton.h> +#include <qpe/qpeapplication.h> + /* QList view item... ?? that can store and update the values that I will * be changing */ class TVKEListViewItem : public QListViewItem { public: TVKEListViewItem(QString n, TVVariant::KeyType kt, int p, QListView *parent) : QListViewItem(parent) { name = n; keyType = kt; position = p; } QString text(int i) const { if(i) { return TVVariant::typeToName(keyType); } return name; } /* always sort by key index, ignore i */ QString key(int, bool) const { return QString().sprintf("%08d", position); } void setText(int i, const QString &) { ; } QString getName() const { return name; } void setName(QString n) { name = n; repaint(); } TVVariant::KeyType getKeyType() const { return keyType; } void setKeyType(TVVariant::KeyType k) { keyType = k; repaint(); } inline int getPos() const { return position; } private: QString name; TVVariant::KeyType keyType; int position; }; TVKeyEdit::TVKeyEdit(TableState *t, QWidget* parent, const char *name, WFlags fl) : TVKeyEdit_gen(parent, name, true, fl) { int i; ts = t; if(!ts) return; if(!ts->kRep) return; working_state = *ts->kRep; i = 1; keyTypeEdit->insertItem(TVVariant::typeToName((TVVariant::KeyType)i)); i++; keyTypeEdit->insertItem(TVVariant::typeToName((TVVariant::KeyType)i)); i++; keyTypeEdit->insertItem(TVVariant::typeToName((TVVariant::KeyType)i)); i++; keyTypeEdit->insertItem(TVVariant::typeToName((TVVariant::KeyType)i)); KeyListIterator it(*ts->kRep); while(it.current()) { if(t->kRep->validIndex(it.currentKey())) { new TVKEListViewItem(it.current()->name(), it.current()->type(), it.currentKey(), display); } ++it; } num_keys = ts->kRep->getNumFields(); if(display->childCount() > 0) { display->setCurrentItem(display->firstChild()); setTerm(display->currentItem()); } else { deleteKeyButton->setEnabled(FALSE); clearKeysButton->setEnabled(FALSE); keyNameEdit->setEnabled(FALSE); keyTypeEdit->setEnabled(FALSE); } display->setSorting(0); #ifdef Q_WS_QWS - showMaximized(); + QPEApplication::showDialog( this ); #endif } /*! Destroys the TVKeyEdit widget */ TVKeyEdit::~TVKeyEdit() { } /* SLOTS */ void TVKeyEdit::newTerm() { /* new item, make current Item */ int i; i = working_state.addKey("<New Key>", TVVariant::String); //working_state.setNewFlag(i, TRUE); TVKEListViewItem *nItem = new TVKEListViewItem("<New Key>", TVVariant::String, i, display); display->setCurrentItem(nItem); setTerm(nItem); num_keys++; if(display->childCount() == 1) { deleteKeyButton->setEnabled(TRUE); clearKeysButton->setEnabled(TRUE); keyNameEdit->setEnabled(TRUE); keyTypeEdit->setEnabled(TRUE); } } void TVKeyEdit::updateTerm(const QString &newName) { /* TODO if name matches a deleted term, prompt for renewing old data instead */ TVKEListViewItem *i = (TVKEListViewItem *)display->currentItem(); if(i) { i->setName(newName); working_state.setKeyName(i->getPos(), newName); } } void TVKeyEdit::updateTerm(int t) { /* t is an index to a combo in a menu, NOT a type */ t++; /* menu counts from 0, types count from 1 */ TVKEListViewItem *i = (TVKEListViewItem *)display->currentItem(); if (i) { i->setKeyType((TVVariant::KeyType)t); working_state.setKeyType(i->getPos(), (TVVariant::KeyType)t); } } /* deletes current term * really just marks key as deleted so is now invalid. * the actual delete will happen when data is 'cleaned' * or when file is saved. */ void TVKeyEdit::deleteTerm() { TVKEListViewItem *i = (TVKEListViewItem *)display->currentItem(); if (i) { working_state.setDeleteFlag(i->getPos(), TRUE); delete i; } if(!display->childCount()) { /* disable the delete and clear buttons, etc */ deleteKeyButton->setEnabled(FALSE); clearKeysButton->setEnabled(FALSE); keyNameEdit->setEnabled(FALSE); keyTypeEdit->setEnabled(FALSE); } } /* clears all terminations */ void TVKeyEdit::clearTerms() { /* should pop up a warning */ if (QMessageBox::warning(this, "Delete all keys", "Are you sure you want to\ndelete all the keys?", "Yes", "No") == 0) { while(display->currentItem()) deleteTerm(); } } void TVKeyEdit::setTerm(QListViewItem *target) { /* need to update the widgets to show keys values */ keyNameEdit->setText(((TVKEListViewItem *)target)->getName()); int t = (int)(((TVKEListViewItem *)target)->getKeyType()); t--; keyTypeEdit->setCurrentItem(t); } KeyList* TVKeyEdit::openEditKeysDialog(TableState *t, QWidget *parent = 0) { if(!t) return 0; if(!t->kRep) return 0; TVKeyEdit *dlg = new TVKeyEdit(t, parent); if ((dlg->exec() == QDialog::Accepted) && (dlg->working_state != *t->kRep)) { return (new KeyList(dlg->working_state)); } return 0; } diff --git a/noncore/apps/tinykate/libkate/view/kateview.cpp b/noncore/apps/tinykate/libkate/view/kateview.cpp index af3b30d..794fbdb 100644 --- a/noncore/apps/tinykate/libkate/view/kateview.cpp +++ b/noncore/apps/tinykate/libkate/view/kateview.cpp @@ -1,342 +1,343 @@ /*************************************************************************** kateview.cpp - description ------------------- begin : Mon Jan 15 2001 copyright : (C) 2001 by Christoph "Crossfire" Cullmann (C) 2002 by Joseph Wenninger email : crossfire@babylon2k.de jowenn@kde.org ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ /* Copyright (C) 1998, 1999 Jochen Wilhelmy digisnap@cs.tu-berlin.de This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "kateview.h" #include "../document/katedocument.h" #include "../document/katecmd.h" #include "../document/katehighlight.h" #include "kateviewdialog.h" #include "../document/katedialogs.h" #include <kateconfig.h> #include <qfocusdata.h> #include <kdebug.h> #include <kapplication.h> #include <qscrollbar.h> #include <qiodevice.h> #include <qpopupmenu.h> #include <kpopupmenu.h> #include <qkeycode.h> #include <qintdict.h> #include <qfont.h> #include <qpainter.h> #include <qpixmap.h> #include <qfileinfo.h> #include <qfile.h> #include <qevent.h> #include <qdir.h> #include <qvbox.h> #include <qprintdialog.h> #include <qpaintdevicemetrics.h> #include <qiodevice.h> #include <qbuffer.h> #include <qfocusdata.h> #include <klocale.h> #include <kglobal.h> #include <kdebug.h> #include <kmessagebox.h> #include <qregexp.h> #include <kdialogbase.h> #include <klineeditdlg.h> #include <qapplication.h> #include <kfiledialog.h> #include <kiconloader.h> #include "../document/katetextline.h" #include "kateviewdialog.h" #include "kateundohistory.h" #include <qlayout.h> +#include <qpe/qpeapplication.h> KateViewInternal::KateViewInternal(KateView *view, KateDocument *doc) : QWidget(view) { waitForPreHighlight=-1; myView = view; myDoc = doc; iconBorderWidth = 16; iconBorderHeight = 800; QWidget::setCursor(ibeamCursor); setBackgroundMode(NoBackground); setFocusPolicy(StrongFocus); xScroll = new QScrollBar(QScrollBar::Horizontal,myView); yScroll = new QScrollBar(QScrollBar::Vertical,myView); connect(xScroll,SIGNAL(valueChanged(int)),SLOT(changeXPos(int))); connect(yScroll,SIGNAL(valueChanged(int)),SLOT(changeYPos(int))); connect(yScroll,SIGNAL(valueChanged(int)),myView,SIGNAL(scrollValueChanged(int))); connect( doc, SIGNAL (preHighlightChanged(long)),this,SLOT(slotPreHighlightUpdate(long))); xPos = 0; yPos = 0; scrollTimer = 0; cursor.x = 0; cursor.y = 0; cursorOn = false; cursorTimer = 0; cXPos = 0; cOldXPos = 0; startLine = 0; endLine = -1; exposeCursor = false; updateState = 0; numLines = 0; lineRanges = 0L; newXPos = -1; newYPos = -1; drawBuffer = new QPixmap (); drawBuffer->setOptimization (QPixmap::BestOptim); bm.sXPos = 0; bm.eXPos = -1; } KateViewInternal::~KateViewInternal() { delete [] lineRanges; delete drawBuffer; } void KateViewInternal::slotPreHighlightUpdate(long line) { //kdDebug()<<QString("slotPreHighlightUpdate - Wait for: %1, line: %2").arg(waitForPreHighlight).arg(line)<<endl; if (waitForPreHighlight!=-1) { if (line>=waitForPreHighlight) { waitForPreHighlight=-1; repaint(); } } } void KateViewInternal::doCursorCommand(VConfig &c, int cmdNum) { switch (cmdNum) { case KateView::cmLeft: cursorLeft(c); break; case KateView::cmRight: cursorRight(c); break; case KateView::cmWordLeft: wordLeft(c); break; case KateView::cmWordRight: wordRight(c); break; case KateView::cmHome: home(c); break; case KateView::cmEnd: end(c); break; case KateView::cmUp: cursorUp(c); break; case KateView::cmDown: cursorDown(c); break; case KateView::cmScrollUp: scrollUp(c); break; case KateView::cmScrollDown: scrollDown(c); break; case KateView::cmTopOfView: topOfView(c); break; case KateView::cmBottomOfView: bottomOfView(c); break; case KateView::cmPageUp: pageUp(c); break; case KateView::cmPageDown: pageDown(c); break; case KateView::cmTop: top_home(c); break; case KateView::cmBottom: bottom_end(c); break; } } void KateViewInternal::doEditCommand(VConfig &c, int cmdNum) { switch (cmdNum) { case KateView::cmCopy: myDoc->copy(c.flags); return; case KateView::cmSelectAll: myDoc->selectAll(); return; case KateView::cmDeselectAll: myDoc->deselectAll(); return; case KateView::cmInvertSelection: myDoc->invertSelection(); return; } if (myView->isReadOnly()) return; switch (cmdNum) { case KateView::cmReturn: if (c.flags & KateView::cfDelOnInput) myDoc->delMarkedText(c); myDoc->newLine(c); //emit returnPressed(); //e->ignore(); return; case KateView::cmDelete: if ((c.flags & KateView::cfDelOnInput) && myDoc->hasMarkedText()) myDoc->delMarkedText(c); else myDoc->del(c); return; case KateView::cmBackspace: if ((c.flags & KateView::cfDelOnInput) && myDoc->hasMarkedText()) myDoc->delMarkedText(c); else myDoc->backspace(c); return; case KateView::cmKillLine: myDoc->killLine(c); return; case KateView::cmCut: myDoc->cut(c); return; case KateView::cmPaste: if (c.flags & KateView::cfDelOnInput) myDoc->delMarkedText(c); myDoc->paste(c); return; case KateView::cmUndo: myDoc->undo(c); return; case KateView::cmRedo: myDoc->redo(c); return; case KateView::cmIndent: myDoc->indent(c); return; case KateView::cmUnindent: myDoc->unIndent(c); return; case KateView::cmCleanIndent: myDoc->cleanIndent(c); return; case KateView::cmComment: myDoc->comment(c); return; case KateView::cmUncomment: myDoc->unComment(c); return; } } void KateViewInternal::cursorLeft(VConfig &c) { cursor.x--; if (c.flags & KateView::cfWrapCursor && cursor.x < 0 && cursor.y > 0) { cursor.y--; cursor.x = myDoc->textLength(cursor.y); } cOldXPos = cXPos = myDoc->textWidth(cursor); changeState(c); } void KateViewInternal::cursorRight(VConfig &c) { if (c.flags & KateView::cfWrapCursor) { if (cursor.x >= myDoc->textLength(cursor.y)) { if (cursor.y == myDoc->lastLine()) return; cursor.y++; cursor.x = -1; } } cursor.x++; cOldXPos = cXPos = myDoc->textWidth(cursor); changeState(c); } void KateViewInternal::wordLeft(VConfig &c) { Highlight *highlight; highlight = myDoc->highlight(); TextLine::Ptr textLine = myDoc->getTextLine(cursor.y); if (cursor.x > 0) { do { cursor.x--; } while (cursor.x > 0 && !highlight->isInWord(textLine->getChar(cursor.x))); while (cursor.x > 0 && highlight->isInWord(textLine->getChar(cursor.x -1))) cursor.x--; } else { if (cursor.y > 0) { cursor.y--; textLine = myDoc->getTextLine(cursor.y); cursor.x = textLine->length(); } } cOldXPos = cXPos = myDoc->textWidth(cursor); changeState(c); } void KateViewInternal::wordRight(VConfig &c) { Highlight *highlight; int len; highlight = myDoc->highlight(); TextLine::Ptr textLine = myDoc->getTextLine(cursor.y); len = textLine->length(); if (cursor.x < len) { do { cursor.x++; } while (cursor.x < len && highlight->isInWord(textLine->getChar(cursor.x))); @@ -2074,514 +2075,513 @@ void KateView::replaceAgain() { void KateView::doReplaceAction(int result, bool found) { int rlen; PointStruc cursor; bool started; QString searchFor = myDoc->searchForList.first(); QString replaceWith = myDoc->replaceWithList.first(); rlen = replaceWith.length(); switch (result) { case KateView::srYes: //yes myDoc->recordStart(this, s.cursor, configFlags, KateActionGroup::ugReplace, true); myDoc->recordReplace(s.cursor, s.matchedLength, replaceWith); replaces++; if (s.cursor.y == s.startCursor.y && s.cursor.x < s.startCursor.x) s.startCursor.x += rlen - s.matchedLength; if (!(s.flags & KateView::sfBackward)) s.cursor.x += rlen; myDoc->recordEnd(this, s.cursor, configFlags | KateView::cfPersistent); break; case KateView::srNo: //no if (!(s.flags & KateView::sfBackward)) s.cursor.x += s.matchedLength; break; case KateView::srAll: //replace all deleteReplacePrompt(); do { started = false; while (found || myDoc->doSearch(s,searchFor)) { if (!started) { found = false; myDoc->recordStart(this, s.cursor, configFlags, KateActionGroup::ugReplace); started = true; } myDoc->recordReplace(s.cursor, s.matchedLength, replaceWith); replaces++; if (s.cursor.y == s.startCursor.y && s.cursor.x < s.startCursor.x) s.startCursor.x += rlen - s.matchedLength; if (!(s.flags & KateView::sfBackward)) s.cursor.x += rlen; } if (started) myDoc->recordEnd(this, s.cursor, configFlags | KateView::cfPersistent); } while (!askReplaceEnd()); return; case KateView::srCancel: //cancel deleteReplacePrompt(); return; default: replacePrompt = 0L; } do { if (myDoc->doSearch(s,searchFor)) { //text found: highlight it, show replace prompt if needed and exit cursor = s.cursor; if (!(s.flags & KateView::sfBackward)) cursor.x += s.matchedLength; myViewInternal->updateCursor(cursor); //does deselectAll() exposeFound(s.cursor,s.matchedLength,(s.flags & KateView::sfAgain) ? 0 : KateView::ufUpdateOnScroll,true); if (replacePrompt == 0L) { replacePrompt = new ReplacePrompt(this); myDoc->setPseudoModal(replacePrompt);//disable(); connect(replacePrompt,SIGNAL(clicked()),this,SLOT(replaceSlot())); replacePrompt->show(); //this is not modal } return; //exit if text found } //nothing found: repeat until user cancels "repeat from beginning" dialog } while (!askReplaceEnd()); deleteReplacePrompt(); } void KateView::exposeFound(PointStruc &cursor, int slen, int flags, bool replace) { int x1, x2, y1, y2, xPos, yPos; VConfig c; myViewInternal->getVConfig(c); myDoc->selectLength(cursor,slen,c.flags); TextLine::Ptr textLine = myDoc->getTextLine(cursor.y); x1 = myDoc->textWidth(textLine,cursor.x) -10; x2 = myDoc->textWidth(textLine,cursor.x + slen) +20; y1 = myDoc->fontHeight*cursor.y -10; y2 = y1 + myDoc->fontHeight +30; xPos = myViewInternal->xPos; yPos = myViewInternal->yPos; if (x1 < 0) x1 = 0; if (replace) y2 += 90; if (x1 < xPos || x2 > xPos + myViewInternal->width()) { xPos = x2 - myViewInternal->width(); } if (y1 < yPos || y2 > yPos + myViewInternal->height()) { xPos = x2 - myViewInternal->width(); yPos = myDoc->fontHeight*cursor.y - height()/3; } myViewInternal->setPos(xPos, yPos); myViewInternal->updateView(flags);// | ufPos,xPos,yPos); myDoc->updateViews(this); } void KateView::deleteReplacePrompt() { myDoc->setPseudoModal(0L); } bool KateView::askReplaceEnd() { QString str; int query; myDoc->updateViews(); if (s.flags & KateView::sfFinished) { // replace finished str = i18n("%1 replacement(s) made").arg(replaces); KMessageBox::information(this, str, i18n("Replace")); return true; } // ask for continue if (!(s.flags & KateView::sfBackward)) { // forward search str = i18n("%1 replacement(s) made.\n" "End of document reached.\n" "Continue from the beginning?").arg(replaces); query = KMessageBox::questionYesNo(this, str, i18n("Replace"), i18n("Continue"), i18n("Stop")); } else { // backward search str = i18n("%1 replacement(s) made.\n" "Beginning of document reached.\n" "Continue from the end?").arg(replaces); query = KMessageBox::questionYesNo(this, str, i18n("Replace"), i18n("Continue"), i18n("Stop")); } replaces = 0; continueSearch(s); return (query == KMessageBox::No); } void KateView::replaceSlot() { doReplaceAction(replacePrompt->result(),true); } void KateView::installPopup(QPopupMenu *rmb_Menu) { rmbMenu = rmb_Menu; } void KateView::readConfig() { KateConfig *config = KGlobal::config(); config->setGroup("Kate View"); searchFlags = config->readNumEntry("SearchFlags", KateView::sfPrompt); configFlags = config->readNumEntry("ConfigFlags", configFlags) & ~KateView::cfMark; // config->sync(); } void KateView::writeConfig() { KateConfig *config = KGlobal::config(); config->setGroup("Kate View"); config->writeEntry("SearchFlags",searchFlags); config->writeEntry("ConfigFlags",configFlags); // config->sync(); } void KateView::readSessionConfig(KateConfig *config) { PointStruc cursor; myViewInternal->xPos = config->readNumEntry("XPos"); myViewInternal->yPos = config->readNumEntry("YPos"); cursor.x = config->readNumEntry("CursorX"); cursor.y = config->readNumEntry("CursorY"); myViewInternal->updateCursor(cursor); myIconBorder = config->readBoolEntry("IconBorder on"); setIconBorder(myIconBorder); } void KateView::writeSessionConfig(KateConfig *config) { config->writeEntry("XPos",myViewInternal->xPos); config->writeEntry("YPos",myViewInternal->yPos); config->writeEntry("CursorX",myViewInternal->cursor.x); config->writeEntry("CursorY",myViewInternal->cursor.y); config->writeEntry("IconBorder on", myIconBorder); } void KateView::configDialog() { #warning fixme #if 1 KDialogBase *kd = new KDialogBase(KDialogBase::IconList, i18n("Configure Editor"), KDialogBase::Ok | KDialogBase::Cancel | KDialogBase::Help , KDialogBase::Ok, this, "tabdialog"); // color options QFrame *page=kd->addPage(i18n("Colors")); (new QVBoxLayout(page))->setAutoAdd(true); ColorConfig *colorConfig = new ColorConfig(page); QColor* colors = getColors(); colorConfig->setColors(colors); page = kd->addPage(i18n("Fonts")); (new QVBoxLayout(page))->setAutoAdd(true); FontConfig *fontConfig = new FontConfig(page); fontConfig->setFont (myDoc->getFont()); // indent options page=kd->addPage(i18n("Indent")); (new QVBoxLayout(page))->setAutoAdd(true); IndentConfigTab *indentConfig = new IndentConfigTab(page, this); // select options page=kd->addPage(i18n("Select")); (new QVBoxLayout(page))->setAutoAdd(true); SelectConfigTab *selectConfig = new SelectConfigTab(page, this); // edit options page=kd->addPage(i18n("Edit")); (new QVBoxLayout(page))->setAutoAdd(true); EditConfigTab *editConfig = new EditConfigTab(page, this); HighlightDialogPage *hlPage; HlManager *hlManager; HlDataList hlDataList; ItemStyleList defaultStyleList; hlManager = HlManager::self(); defaultStyleList.setAutoDelete(true); hlManager->getDefaults(defaultStyleList); hlDataList.setAutoDelete(true); //this gets the data from the KateConfig object hlManager->getHlDataList(hlDataList); page=kd->addPage(i18n("Highlighting")); (new QVBoxLayout(page))->setAutoAdd(true); hlPage = new HighlightDialogPage(hlManager, &defaultStyleList, &hlDataList, 0, page); - kd->showMaximized(); - if (kd->exec()) { + if ( QPEApplication::execDialog( kd )) { // color options colorConfig->getColors(colors); myDoc->setFont (fontConfig->getFont()); applyColors(); // indent options indentConfig->getData(this); // select options selectConfig->getData(this); // edit options editConfig->getData(this); // spell checker hlManager->setHlDataList(hlDataList); hlManager->setDefaults(defaultStyleList); hlPage->saveData(); } // delete kd; #endif } int KateView::getHl() { return myDoc->highlightNum(); } void KateView::setDontChangeHlOnSave() { myDoc->setDontChangeHlOnSave(); } void KateView::setHl(int n) { myDoc->setHighlight(n); myDoc->setDontChangeHlOnSave(); myDoc->updateViews(); } int KateView::getEol() { return myDoc->eolMode; } void KateView::setEol(int eol) { if (isReadOnly()) return; myDoc->eolMode = eol; myDoc->setModified(true); } void KateView::paintEvent(QPaintEvent *e) { int x, y; QRect updateR = e->rect(); // update rectangle // debug("Update rect = ( %i, %i, %i, %i )", // updateR.x(),updateR.y(), updateR.width(), updateR.height() ); int ux1 = updateR.x(); int uy1 = updateR.y(); int ux2 = ux1 + updateR.width(); int uy2 = uy1 + updateR.height(); QPainter paint; paint.begin(this); QColorGroup g = colorGroup(); x = width(); y = height(); paint.setPen(g.dark()); if (uy1 <= 0) paint.drawLine(0,0,x-2,0); if (ux1 <= 0) paint.drawLine(0,1,0,y-2); paint.setPen(black); if (uy1 <= 1) paint.drawLine(1,1,x-3,1); if (ux1 <= 1) paint.drawLine(1,2,1,y-3); paint.setPen(g.midlight()); if (uy2 >= y-1) paint.drawLine(1,y-2,x-3,y-2); if (ux2 >= x-1) paint.drawLine(x-2,1,x-2,y-2); paint.setPen(g.light()); if (uy2 >= y) paint.drawLine(0,y-1,x-2,y-1); if (ux2 >= x) paint.drawLine(x-1,0,x-1,y-1); x -= 2 + 16; y -= 2 + 16; if (ux2 > x && uy2 > y) { paint.fillRect(x,y,16,16,g.background()); } paint.end(); } void KateView::resizeEvent(QResizeEvent *) { // debug("Resize %d, %d",e->size().width(),e->size().height()); //myViewInternal->resize(width() -20, height() -20); myViewInternal->tagAll(); myViewInternal->updateView(0/*ufNoScroll*/); } // Applies a new pattern to the search context. void SConfig::setPattern(QString &newPattern) { bool regExp = (flags & KateView::sfRegularExpression); m_pattern = newPattern; if (regExp) { m_regExp.setCaseSensitive(flags & KateView::sfCaseSensitive); m_regExp.setPattern(m_pattern); } } // Applies the search context to the given string, and returns whether a match was found. If one is, // the length of the string matched is also returned. int SConfig::search(QString &text, int index) { bool regExp = (flags & KateView::sfRegularExpression); bool caseSensitive = (flags & KateView::sfCaseSensitive); if (flags & KateView::sfBackward) { if (regExp) { index = text.findRev(m_regExp, index); } else { index = text.findRev(m_pattern, index, caseSensitive); } } else { if (regExp) { index = text.find(m_regExp, index); } else { index = text.find(m_pattern, index, caseSensitive); } } // Work out the matched length. if (index != -1) { if (regExp) { m_regExp.match(text, index, &matchedLength, false); } else { matchedLength = m_pattern.length(); } } return index; } void KateView::setActive (bool b) { active = b; } bool KateView::isActive () { return active; } void KateView::setFocus () { QWidget::setFocus (); emit gotFocus (this); } bool KateView::eventFilter (QObject *object, QEvent *event) { if ( (event->type() == QEvent::FocusIn) ) emit gotFocus (this); if ( (event->type() == QEvent::KeyPress) ) { QKeyEvent * ke=(QKeyEvent *)event; if ((ke->key()==Qt::Key_Tab) || (ke->key()==Qt::Key_BackTab)) { myViewInternal->keyPressEvent(ke); return true; } } return QWidget::eventFilter (object, event); } void KateView::findAgain (bool back) { bool b= (searchFlags & sfBackward) > 0; initSearch(s, (searchFlags & ((b==back)?~sfBackward:~0) & ~sfFromBeginning) // clear flag for forward searching | sfPrompt | sfAgain | ((b!=back)?sfBackward:0) ); if (s.flags & sfReplace) replaceAgain(); else KateView::findAgain(s); } void KateView::slotEditCommand () { #warning fixme /* bool ok; QString cmd = KLineEditDlg::getText("Editing Command", "", &ok, this); if (ok) myDoc->cmd()->execCmd (cmd, this);*/ } void KateView::setIconBorder (bool enable) { myIconBorder = enable; if (myIconBorder) { myViewInternal->move(myViewInternal->iconBorderWidth+2, 2); myViewInternal->leftBorder->show(); } else { myViewInternal->leftBorder->hide(); myViewInternal->move(2, 2); } } void KateView::toggleIconBorder () { setIconBorder (!myIconBorder); } void KateView::gotoMark (Kate::Mark *mark) { PointStruc cursor; cursor.x = 0; cursor.y = mark->line; myDoc->needPreHighlight(cursor.y); myViewInternal->updateCursor(cursor); myViewInternal->center(); myViewInternal->updateView(KateView::ufUpdateOnScroll); myDoc->updateViews(this); } void KateView::toggleBookmark () { TextLine::Ptr line = myDoc->getTextLine (currentLine()); if (line->mark()&KateDocument::Bookmark) line->delMark(KateDocument::Bookmark); else line->addMark(KateDocument::Bookmark); myDoc->tagLines (currentLine(), currentLine()); myDoc->updateViews(); } diff --git a/noncore/apps/zsafe/scqtfileedit.cpp b/noncore/apps/zsafe/scqtfileedit.cpp index effd86b..7a3d906 100644 --- a/noncore/apps/zsafe/scqtfileedit.cpp +++ b/noncore/apps/zsafe/scqtfileedit.cpp @@ -1,417 +1,419 @@ /*************************************************************************** scqtfileedit.cpp - description ------------------- begin : Mon Sep 3 2001 copyright : (C) 2001 by Werner Schulte email : sc@schulte-ac.de ***************************************************************************/ /* $Id$ */ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <stdio.h> #include <stdlib.h> #include "qdir.h" #include "qdialog.h" #include "qpixmap.h" #include "qlistview.h" #include "qlineedit.h" #include "qtoolbutton.h" #include "scqtfileedit.h" +#include <qpe/qpeapplication.h> + // #define DEBUGFILEEDIT /* XPM */ static const char* const file_xpm[]={ "16 16 5 1", ". c #7f7f7f", "# c None", "c c #000000", "b c #bfbfbf", "a c #ffffff", "################", "..........######", ".aaaaaaaab.#####", ".aaaaaaaaba.####", ".aaaaaaaacccc###", ".aaaaaaaaaabc###", ".aaaaaaaaaabc###", ".aaaaaaaaaabc###", ".aaaaaaaaaabc###", ".aaaaaaaaaabc###", ".aaaaaaaaaabc###", ".aaaaaaaaaabc###", ".aaaaaaaaaabc###", ".aaaaaaaaaabc###", ".bbbbbbbbbbbc###", "ccccccccccccc###"}; /* XPM */ static const char * const link_file_xpm[]={ "16 16 10 1", "h c #808080", "g c #a0a0a0", "d c #c3c3c3", ". c #7f7f7f", "c c #000000", "b c #bfbfbf", "f c #303030", "e c #585858", "a c #ffffff", "# c None", "################", "..........######", ".aaaaaaaab.#####", ".aaaaaaaaba.####", ".aaaaaaaacccc###", ".aaaaaaaaaabc###", ".aaaaaaaaaabc###", ".aaaaaaaaaadc###", ".aaaaaaaaaadc###", ".aaaacccccccc###", ".aaaacaaaaaac###", ".aaaacaeaeaac###", ".aaaacaefcfac###", ".aaaacaagchac###", ".ddddcaaahaac###", "ccccccccccccc###"}; /* XPM */ static const char * const closed_xpm[]={ "16 16 6 1", ". c None", "b c #ffff00", "d c #000000", "* c #999999", "a c #cccccc", "c c #ffffff", "................", "................", "..*****.........", ".*ababa*........", "*abababa******..", "*cccccccccccc*d.", "*cbababababab*d.", "*cabababababa*d.", "*cbababababab*d.", "*cabababababa*d.", "*cbababababab*d.", "*cabababababa*d.", "*cbababababab*d.", "**************d.", ".dddddddddddddd.", "................"}; /* XPM */ static const char* const cdtoparent_xpm[]={ "15 13 3 1", ". c None", "* c #000000", "a c #ffff99", "..*****........", ".*aaaaa*.......", "***************", "*aaaaaaaaaaaaa*", "*aaaa*aaaaaaaa*", "*aaa***aaaaaaa*", "*aa*****aaaaaa*", "*aaaa*aaaaaaaa*", "*aaaa*aaaaaaaa*", "*aaaa******aaa*", "*aaaaaaaaaaaaa*", "*aaaaaaaaaaaaa*", "***************"}; ScQtFileEditDlg::ScQtFileEditDlg( QWidget *parent, const char *name, const QString &path, const QString &filter ) : ScQtFileDlg( parent, name, TRUE ), QDir( path, filter ) { // ListView->setRootIsDecorated ( TRUE ); #ifdef DEBUGFILEEDIT printf ("\nScQtFileEditDlg:: constructor name=%s", name ); printf ("\n path=%s", (const char *)path ); printf ("\n filter=%s", (const char *)filter ); printf ("\n parent=%p", parent ); fflush(stdout); #endif bpath = path; bfilter = filter; exflag = false; ListView->setAllColumnsShowFocus( TRUE ); ListView->setColumnAlignment( 1, Qt::AlignRight ); fileIcon = new QPixmap( (const char **)file_xpm); dirIcon = new QPixmap( (const char **)closed_xpm); linkIcon = new QPixmap( (const char **)link_file_xpm); cdToParentIcon = new QPixmap( (const char **)cdtoparent_xpm); #ifdef QWS - showMaximized(); + QPEApplication::execDialog( this ); #endif mkdirflag = false; MkDirButton->setEnabled( false ); initDirCombo( bpath ); initTypeCombo( bfilter ); dirstr = tr("dir"); filestr = tr("file"); linkstr = tr("link"); rFlag = false; showTimer.stop(); connect( &showTimer, SIGNAL(timeout()), SLOT( slotShowDir() ) ); fmode = QDir::All; fnfilter = false; fsorting = false; } ScQtFileEditDlg::~ScQtFileEditDlg() { #ifdef DEBUGFILEEDIT printf ("\nScQtFileEditDlg::destructor called" ); fflush(stdout); #endif if ( fileIcon != NULL ) { delete fileIcon; fileIcon = NULL; } if ( dirIcon != NULL ) { delete dirIcon; dirIcon = NULL; } if ( linkIcon != NULL ) { delete linkIcon; linkIcon = NULL; } if ( cdToParentIcon != NULL ) { delete cdToParentIcon; cdToParentIcon = NULL; } } void ScQtFileEditDlg::readIt( ) { qfil = readDir( bpath, bfilter ); slotShowDir( ); } void ScQtFileEditDlg::setAutoExtension( bool ex ) { exflag = ex; } int ScQtFileEditDlg::checkComboEntryExists( QComboBox *com, const QString &str ) { int i; if ( com ) { for ( i = 0; i < com->count(); i++ ) { if ( com->text( i ) == str ) { com->setCurrentItem( i ); return( 1 ); } } } return( 0 ); } void ScQtFileEditDlg::initDirCombo( const QString &str ) { DirComboBox->clear(); DirComboBox->insertItem( "/" ); if ( str.isEmpty() ) return; DirComboBox->insertItem( str, -1 ); } void ScQtFileEditDlg::initTypeCombo( const QString &str ) { TypeComboBox->clear(); TypeComboBox->insertItem( "*" ); if ( str.isEmpty() ) return; TypeComboBox->insertItem( str, -1 ); } void ScQtFileEditDlg::insDirCombo( const QString &str ) { if ( str.isEmpty() ) return; if ( !checkComboEntryExists( DirComboBox, str ) ) { if ( DirComboBox->count() >= MAXDIRCOMBOCOUNT ) { // 2. Item loeschen (das erste ist "/") DirComboBox->removeItem( 1 ); } // neues Item anhaengen DirComboBox->insertItem( str, -1 ); DirComboBox->setCurrentItem( DirComboBox->count() - 1 ); } } void ScQtFileEditDlg::insTypeCombo( const QString &str ) { if ( str.isEmpty() ) return; if ( !checkComboEntryExists( TypeComboBox, str ) ) { if ( TypeComboBox->count() >= MAXTYPECOMBOCOUNT ) { // 2. Item loeschen (das erste ist "/") TypeComboBox->removeItem( 1 ); } // neues Item anhaengen TypeComboBox->insertItem( str, -1 ); TypeComboBox->setCurrentItem( TypeComboBox->count() - 1 ); } } const QFileInfoList *ScQtFileEditDlg::readDir( const QString &path, const QString &filter ) { static QString qpath, qfilter; #ifdef DEBUGFILEEDIT printf ("\nScQtFileEditDlg::readDir called, path = %s", (const char *)path ); printf ("\n filter = %s", (const char *)filter ); fflush(stdout); #endif rFlag = true; if ( path.isEmpty() ) qpath = "/"; else qpath = path; if ( filter.isEmpty() ) qfilter = "*"; else qfilter = filter; insDirCombo( qpath ); insTypeCombo( qfilter ); setFilter( fmode ); if ( fsorting ) setSorting( QDir::DirsFirst | QDir::Name ); if ( fnfilter ) setNameFilter( qfilter ); setPath( qpath ); const QFileInfoList *dirlist = entryInfoList(); if ( !dirlist ) { rFlag = false; return( 0 ); } rFlag = false; return( dirlist ); } QString ScQtFileEditDlg::getResult( ) { static QString qstr; #ifdef DEBUGFILEEDIT printf ("\nScQtFileEditDlg::getResult called" ); fflush(stdout); #endif qstr = bpath + "/"; qstr = qstr + filename; bpath = cleanDirPath( qstr ); return( bpath ); } QString ScQtFileEditDlg::getFileName( ) { int a; static QString qstr; #ifdef DEBUGFILEEDIT printf ("\nScQtFileEditDlg::getFileName called" ); fflush(stdout); #endif a = bpath.findRev( "/", -1, TRUE ); if (a == -1) qstr = bpath; // Nicht gefunden else qstr = bpath.right( bpath.length() - a - 1 ); return( qstr ); } // Ab hier die Slots ----------------------------------- void ScQtFileEditDlg::slotShowDir() { static QListViewItem *qlvitem; static QString ftypestr, fsizestr; static QFileInfo *fi; // pointer for traversing if ( !qfil ) // pointer war Null return; ListView->clear(); // ersma loeschen QFileInfoListIterator it( *qfil ); // create list iterator if ( !it ) // pointer war Null return; while ( (fi=it.current()) ) { // for each file... if ( !fi ) // current war 0 return; if ( !fi->fileName().isNull() ) { if ( fi->isDir() == TRUE ) { ftypestr = dirstr; fsizestr = "" ; } else if ( fi->isSymLink() == TRUE ) { ftypestr = linkstr; fsizestr = "" ; } else if ( fi->isFile() == TRUE ) { ftypestr = filestr; fsizestr.sprintf( "%d", fi->size() ); diff --git a/noncore/apps/zsafe/zsafe.cpp b/noncore/apps/zsafe/zsafe.cpp index ee1da77..bdd2aed 100644 --- a/noncore/apps/zsafe/zsafe.cpp +++ b/noncore/apps/zsafe/zsafe.cpp @@ -522,931 +522,914 @@ ZSafe::ZSafe( QWidget* parent, const char* name, bool modal, WFlags fl ) QDir pd2(QDir::homeDirPath() + "Documents/application"); if (!pd2.mkdir("zsafe", FALSE)) { QMessageBox::critical( 0, tr("ZSafe"), #ifdef JPATCH_HDE tr("Can't create directory\n...//Documents/application/zsafe\n\nZSafe will now exit.")); #else tr("Can't create directory\n%1\n\nZSafe will now exit.").arg(d2)); #endif exitZs (1); } } // set the default filename filename=d2 + "/passwords.zsf"; // save the current filename to the config file conf->writeEntry(APP_KEY+"document", filename); saveConf(); } //if (filename == "INVALIDPWD") //filename = ""; QString ti = filename.right (filename.length() - filename.findRev ('/') - 1); #ifdef WIN32 this->setCaption("Qt ZSafe: " + ti); #else this->setCaption("ZSafe: " + ti); #endif selectedItem = NULL; lastSearchedCategory = NULL; lastSearchedItem = NULL; lastSearchedName = ""; lastSearchedUsername = ""; lastSearchedComment = ""; infoForm = new InfoForm(); categoryDialog = NULL; // add a menu bar QMenuBar *menu = new QMenuBar( this ); // add file menu // QPopupMenu *file = new QPopupMenu( this ); file = new QPopupMenu( this ); // #ifdef DESKTOP file->insertItem( new_img, tr("&New document"), this, SLOT(newDocument()) ); file->insertItem( folder_open_img, tr("&Open document"), this, SLOT(loadDocument()) ); file->insertItem( save_img, tr("&Save document as .."), this, SLOT(saveDocumentAs()) ); file->insertSeparator(); // #endif file->insertItem( save_img, tr("&Save document"), this, SLOT(saveDocumentWithoutPwd()) ); file->insertItem( save_img, tr("S&ave document with new Password"), this, SLOT(saveDocumentWithPwd()) ); file->insertSeparator(); file->insertItem( export_img, tr("&Export text file"), this, SLOT(writeAllEntries()) ); file->insertItem( import_img, tr("&Import text file"), this, SLOT(readAllEntries()) ); file->insertItem( trash_img, tr("&Remove text file"), this, SLOT(removeAsciiFile()) ); file->insertSeparator(); file->insertItem( expand_img, tr("&Open entries expanded"), this, SLOT(setExpandFlag()), 0, 'o'); file->setItemChecked('o', expandTree); file->insertSeparator(); file->insertItem( quit_icon_img, tr("E&xit"), this, SLOT(quitMe()) ); menu->insertItem( tr("&File"), file ); QPopupMenu *cat = new QPopupMenu( this ); cat->insertItem( new_img, tr("&New"), this, SLOT(addCategory()) ); cat->insertItem( edit_img, tr("&Edit"), this, SLOT(editCategory()) ); cat->insertItem( trash_img, tr("&Delete"), this, SLOT(delCategory()) ); menu->insertItem( tr("&Category"), cat ); QPopupMenu *it = new QPopupMenu( this ); it->insertItem( cut_img, tr("&Cut"), this, SLOT(cutItem()) ); it->insertItem( copy_img, tr("C&opy"), this, SLOT(copyItem()) ); it->insertItem( paste_img, tr("&Paste"), this, SLOT(pasteItem()) ); it->insertSeparator(); it->insertItem( new_img, tr("&New"), this, SLOT(newPwd()) ); it->insertItem( edit_img, tr("&Edit"), this, SLOT(editPwd()) ); it->insertItem( trash_img, tr("&Delete"), this, SLOT(deletePwd()) ); it->insertItem( find_img, tr("&Search"), this, SLOT(findPwd()) ); menu->insertItem( tr("&Entry"), it ); QPopupMenu *help = new QPopupMenu( this ); help->insertItem( help_icon_img, tr("&About"), this, SLOT(about()) ); menu->insertItem( tr("&Help"), help ); // toolbar icons New = new QToolButton( menu, "New" ); New->setGeometry( QRect( DeskW-84, 2, 20, 20 ) ); New->setMouseTracking( TRUE ); New->setText( tr( "" ) ); New->setPixmap( new_img ); QToolTip::add( New, tr( "New entry" ) ); Edit = new QToolButton( menu, "Edit" ); Edit->setGeometry( QRect( DeskW-64, 2, 20, 20 ) ); Edit->setText( tr( "" ) ); Edit->setPixmap( edit_img ); QToolTip::add( Edit, tr( "Edit category or entry" ) ); Delete = new QToolButton( menu, "Delete" ); Delete->setGeometry( QRect( DeskW-44, 2, 20, 20 ) ); Delete->setText( tr( "" ) ); Delete->setPixmap( trash_img ); QToolTip::add( Delete, tr( "Delete category or entry" ) ); Find = new QToolButton( menu, "Find" ); Find->setGeometry( QRect( DeskW-24, 2, 20, 20 ) ); Find->setText( tr( "" ) ); Find->setPixmap( find_img ); QToolTip::add( Find, tr( "Find entry" ) ); /* QBoxLayout * h = new QHBoxLayout( this ); h->addWidget (menu); h->addWidget (New); h->addWidget (Edit); h->addWidget (Delete); h->addWidget (Find); */ ListView = new ZListView( this, "ListView" ); ListView->addColumn( tr( "Name" ) ); ListView->addColumn( tr( "Field 2" ) ); ListView->addColumn( tr( "Field 3" ) ); ListView->addColumn( tr( "Comment" ) ); ListView->addColumn( tr( "Field 4" ) ); ListView->addColumn( tr( "Field 5" ) ); ListView->setAllColumnsShowFocus(TRUE); #ifdef DESKTOP ListView->setResizePolicy(QScrollView::AutoOneFit); // ListView->setGeometry( QRect( 0, 22, this->width(), this->height() - 30 ) ); #else ListView->setResizePolicy(QScrollView::AutoOneFit); // ListView->setGeometry( QRect( 0, 22, // this->width(), this->height() - 30 ) ); // ListView->setMaximumSize( QSize( 440, 290 ) ); #endif ListView->setVScrollBarMode( QListView::Auto ); QBoxLayout * l = new QVBoxLayout( this ); l->addWidget (menu); l->addWidget (ListView); #ifndef DESKTOP // start a timer (100 ms) to load the default document docuTimer.start( 100, true ); connect( &docuTimer, SIGNAL(timeout()), SLOT( slotLoadDocu() ) ); raiseFlag = true; connect( &raiseTimer, SIGNAL(timeout()), SLOT( slotRaiseTimer() ) ); #else // open the default document openDocument(filename); #endif // signals and slots connections for QTollButton connect( New, SIGNAL( clicked() ), this, SLOT( newPwd() ) ); connect( Edit, SIGNAL( clicked() ), this, SLOT( editPwd() ) ); connect( Delete, SIGNAL( clicked() ), this, SLOT( deletePwd() ) ); connect( Find, SIGNAL( clicked() ), this, SLOT( findPwd() ) ); // signals and slots connections for QListView connect( ListView, SIGNAL( selectionChanged( QListViewItem* ) ), this, SLOT( listViewSelected( QListViewItem* ) ) ); connect( ListView, SIGNAL( doubleClicked( QListViewItem* ) ), this, SLOT( showInfo( QListViewItem* ) ) ); connect( ListView, SIGNAL( returnPressed( QListViewItem* ) ), this, SLOT( showInfo( QListViewItem* ) ) ); } const QColor *ZSafe::evenRowColor = &Qt::white; // const QColor *ZSafe::oddRowColor = &Qt::lightGray; const QColor *ZSafe::oddRowColor = new QColor(216,240,255); /* * Destroys the object and frees any allocated resources */ ZSafe::~ZSafe() { // no need to delete child widgets, Qt does it all for us quitMe(); } // load the default document void ZSafe::slotLoadDocu() { openDocument (filename); } void ZSafe::deletePwd() { if (!selectedItem) return; if (!isCategory(selectedItem)) { switch( QMessageBox::information( this, tr("ZSafe"), tr("Do you want to delete?"), tr("&Delete"), tr("D&on't Delete"), 0 // Enter == button 0 ) ) { // Escape == button 2 case 0: // Delete clicked, Alt-S or Enter pressed. // Delete modified = true; selectedItem->parent()->takeItem(selectedItem); selectedItem = NULL; break; case 1: // Don't delete break; } } else { delCategory(); } } void ZSafe::editPwd() { if (!selectedItem) return; if (!isCategory(selectedItem)) { // open the 'New Entry' dialog NewDialog *dialog = new NewDialog(this, tr("Edit Entry"), TRUE); #ifdef WIN32 dialog->setCaption ("Qt " + tr("Edit Entry")); dialog->setGeometry(200, 250, 220, 310 ); #endif // set the labels dialog->Name->setText(getFieldLabel (selectedItem, "1", tr("Name"))); dialog->Username->setText(getFieldLabel (selectedItem, "2", tr("Username"))); dialog->Password->setText(getFieldLabel (selectedItem, "3", tr("Password"))); dialog->Comment->setText(getFieldLabel (selectedItem, "4", tr("Comment"))); dialog->Field5Label->setText(getFieldLabel (selectedItem,"5", tr("Field 4"))); dialog->Field6Label->setText(getFieldLabel (selectedItem,"6", tr("Field 5"))); // set the fields dialog->NameField->setText(selectedItem->text (0)); dialog->UsernameField->setText(selectedItem->text (1)); dialog->PasswordField->setText(selectedItem->text (2)); QString comment = selectedItem->text (3); comment.replace (QRegExp("<br>"), "\n"); dialog->Field5->setText(selectedItem->text (4)); dialog->Field6->setText(selectedItem->text (5)); dialog->CommentField->insertLine(comment); dialog->CommentField->setCursorPosition(0,0); -#ifdef DESKTOP -#ifndef WIN32 - dialog->show(); -#endif -#else - dialog->showMaximized(); -#endif - DialogCode result = (DialogCode) dialog->exec(); + + DialogCode result = (DialogCode) QPEApplication::execDialog( dialog ); #ifdef DESKTOP result = Accepted; #endif if (result == Accepted) { modified = true; // edit the selected item QString name = dialog->NameField->text(); selectedItem->setText (0, tr (name)); QString user = dialog->UsernameField->text(); selectedItem->setText (1, tr (user)); QString pwd = dialog->PasswordField->text(); selectedItem->setText (2, tr (pwd)); QString comment = dialog->CommentField->text(); comment.replace (QRegExp("\n"), "<br>"); selectedItem->setText (3, tr (comment)); QString f5 = dialog->Field5->text(); selectedItem->setText (4, tr (f5)); QString f6 = dialog->Field6->text(); selectedItem->setText (5, tr (f6)); } delete dialog; } else { editCategory(); } } void ZSafe::newPwd() { if (!selectedItem) return; if (!isCategory(selectedItem)) selectedItem = selectedItem->parent(); if (isCategory(selectedItem)) { QString cat = selectedItem->text(0); // open the 'New Entry' dialog NewDialog *dialog = new NewDialog(this, tr("New Entry"), TRUE); #ifdef WIN32 dialog->setCaption ("Qt " + tr("New Entry")); dialog->setGeometry(200, 250, 220, 310 ); #endif // set the labels dialog->Name->setText(getFieldLabel (selectedItem, "1", tr("Name"))); dialog->Username->setText(getFieldLabel (selectedItem, "2", tr("Username"))); dialog->Password->setText(getFieldLabel (selectedItem, "3", tr("Password"))); dialog->Comment->setText(getFieldLabel (selectedItem, "4", tr("Comment"))); dialog->Field5Label->setText(getFieldLabel (selectedItem,"5", tr("Field 4"))); dialog->Field6Label->setText(getFieldLabel (selectedItem,"6", tr("Field 5"))); retype: -#ifdef DESKTOP -#ifndef WIN32 - dialog->show(); -#endif -#else - dialog->showMaximized(); -#endif - DialogCode result = (DialogCode) dialog->exec(); + + DialogCode result = (DialogCode) QPEApplication::execDialog( dialog ); #ifdef DESKTOP result = Accepted; #endif if (result == Accepted) { QString name = dialog->NameField->text(); if (cat == name) { QMessageBox::critical( 0, tr("ZSafe"), tr("Entry name must be different\nfrom the category name.") ); goto retype; // it's not a good programming style :-) } modified = true; // add the new item QListViewItem *i = new ShadedListItem (0, selectedItem); i->setOpen (TRUE); i->setText (0, tr (name)); QString user = dialog->UsernameField->text(); i->setText (1, tr (user)); QString pwd = dialog->PasswordField->text(); i->setText (2, tr (pwd)); QString comment = dialog->CommentField->text(); comment.replace (QRegExp("\n"), "<br>"); i->setText (3, tr (comment)); QString f5 = dialog->Field5->text(); i->setText (4, tr (f5)); QString f6 = dialog->Field6->text(); i->setText (5, tr (f6)); } delete dialog; } } void ZSafe::findPwd() { // open the 'Search' dialog SearchDialog *dialog = new SearchDialog(this, tr("Search"), TRUE); #ifdef WIN32 dialog->setCaption ("Qt " + tr("Search")); #endif #ifdef DESKTOP #endif if (lastSearchedName) dialog->NameField->setText(lastSearchedName); else dialog->NameField->setText(""); if (lastSearchedUsername) dialog->UsernameField->setText(lastSearchedUsername); else dialog->UsernameField->setText(""); if (lastSearchedComment) dialog->CommentField->setText(lastSearchedComment); else dialog->CommentField->setText(""); DialogCode result = (DialogCode) dialog->exec(); #ifdef DESKTOP result = Accepted; #endif QString name; QString username; QString comment; if (result == Accepted) { name = dialog->NameField->text(); username = dialog->UsernameField->text(); comment = dialog->CommentField->text(); qWarning (name); } else { delete dialog; return; } if (!name.isEmpty() && name != lastSearchedName || lastSearchedName.isEmpty() && !name.isEmpty()) { // set search at the beginning if a new name is given lastSearchedCategory = NULL; lastSearchedItem = NULL; } lastSearchedName = name; if (!username.isEmpty() && username != lastSearchedUsername || lastSearchedUsername.isEmpty() && !username.isEmpty()) { // set search at the beginning if a new name is given lastSearchedCategory = NULL; lastSearchedItem = NULL; } lastSearchedUsername = username; if (!comment.isEmpty() && comment != lastSearchedComment || lastSearchedComment.isEmpty() && !comment.isEmpty()) { // set search at the beginning if a new name is given lastSearchedCategory = NULL; lastSearchedItem = NULL; } lastSearchedComment = comment; ListView->clearSelection(); bool found=FALSE; // step through all categories QListViewItem *i; if (lastSearchedCategory) i = lastSearchedCategory; else i = ListView->firstChild(); for (; i != NULL; i = i->nextSibling()) { qWarning (i->text(0)); i->setSelected(FALSE); // step through all subitems QListViewItem *si; if (lastSearchedItem) si = lastSearchedItem; else si = i->firstChild(); // for (si = i->firstChild(); for (; si != NULL; si = si->nextSibling()) { qWarning (si->text(0)); if (si->isSelected()) si->setSelected(FALSE); // ListView->repaintItem(si); bool n=TRUE; bool u=TRUE; bool c=TRUE; if (!name.isEmpty()) n = (si->text(0)).contains (name, FALSE); if (!username.isEmpty()) u = (si->text(1)).contains (username, FALSE); if (!comment.isEmpty()) c = (si->text(3)).contains (comment, FALSE); if ((n && u && c ) && !found) { qWarning ("Found"); selectedItem = si; si->setSelected(TRUE); ListView->setCurrentItem(si); ListView->ensureItemVisible(si); ListView->triggerUpdate(); lastSearchedCategory = i; // set to the next item lastSearchedItem = si->nextSibling(); if (!lastSearchedItem) { // no next item within category -> set next category lastSearchedCategory = i->nextSibling(); if (!lastSearchedCategory) lastSearchedItem = NULL; // END } found = TRUE; delete dialog; update(); return; } } lastSearchedCategory = i->nextSibling(); lastSearchedItem = NULL; } lastSearchedCategory = NULL; lastSearchedItem = NULL; delete dialog; update(); QMessageBox::information( this, tr("ZSafe"), tr("Entry not found"), tr("&OK"), 0); } QString ZSafe::getFieldLabel (QListViewItem *_item, QString field, QString def) { QString category; if (_item) { if (isCategory(_item)) { category = _item->text(0); } else { QListViewItem *cat = _item->parent(); category = cat->text(0); } } else { return def; } QString app_key = APP_KEY; #ifndef DESKTOP #ifndef WIN32 conf->setGroup ("fieldDefs"); #endif #else #ifndef WIN32 app_key += "/fieldDefs/"; #endif #endif // #ifndef WIN32 QString label = conf->readEntry(app_key+category+"-field"+field,def); // #else // QString label(def); // #endif #ifndef DESKTOP conf->setGroup ("zsafe"); #endif return label; } QString ZSafe::getFieldLabel (QString category, QString field, QString def) { QString app_key = APP_KEY; #ifndef DESKTOP conf->setGroup ("fieldDefs"); #else #ifndef WIN32 app_key += "/fieldDefs/"; #endif #endif // #ifndef WIN32 QString label = conf->readEntry(app_key+category+"-field"+field, def); // #else // QString label(def); // #endif #ifndef DESKTOP conf->setGroup ("zsafe"); #endif return label; } void ZSafe::showInfo( QListViewItem *_item) { if (!_item) return; if (selectedItem != NULL) selectedItem->setSelected(FALSE); selectedItem = _item; selectedItem->setSelected(TRUE); if (!isCategory(_item)) { /* QString label=selectedItem->text(0); label+="\n"; label+=selectedItem->text(1); label+="\n"; label+=selectedItem->text(2); label+="\n"; label+=selectedItem->text(3); */ QString text; QString entry; text = "<html><body><div align=""center""><u><b>"; text += selectedItem->text(0); text += "</b></u><br></div><br>"; entry = selectedItem->text(1); if (!entry.isEmpty() && entry.compare(" ")) { text += "<u><b>"; text += getFieldLabel (selectedItem, "2", tr("Username")); text += ":<br></b></u><blockquote>"; text += entry; text += "</blockquote>"; // text += "<br>"; } entry = selectedItem->text(2); if (!entry.isEmpty() && entry.compare(" ")) { text += "<u><b>"; text += getFieldLabel (selectedItem, "3", tr("Password")); text += ":<br> </b></u><blockquote>"; text += entry; text += "</blockquote>"; // text += "<br>"; } entry = selectedItem->text(4); if (!entry.isEmpty() && entry.compare(" ")) { text += "<u><b>"; text += getFieldLabel (selectedItem, "5", tr("Field 4")); text += ":<br> </b></u><blockquote>"; text += entry; text += "</blockquote>"; // text += "<br>"; } entry = selectedItem->text(5); if (!entry.isEmpty() && entry.compare(" ")) { text += "<u><b>"; text += getFieldLabel (selectedItem, "6", tr("Field 5")); text += ":<br> </b></u><blockquote>"; text += entry; text += "</blockquote>"; // text += "<br>"; } entry = selectedItem->text(3); if (!entry.isEmpty() && entry.compare(" ")) { text += "<u><b>"; text += getFieldLabel (selectedItem, "4", tr("Comment")); text += ":<br> </b></u>"; QString comment = selectedItem->text(3); comment.replace (QRegExp("\n"), "<br>"); text += comment; // text += "<br>"; } text += "</body></html>"; infoForm->InfoText->setText(text); infoForm->hide(); -#ifdef DESKTOP - infoForm->show(); -#else - infoForm->showMaximized(); -#endif - + QPEApplication::showDialog( infoForm ); } } void ZSafe::listViewSelected( QListViewItem *_item) { if (!_item) return; if (selectedItem != NULL) selectedItem->setSelected(FALSE); selectedItem = _item; #ifndef DESKTOP // set the column text dependent on the selected item ListView->setColumnText(0, getFieldLabel (selectedItem, "1", tr("Name"))); ListView->setColumnText(1, getFieldLabel (selectedItem, "2", tr("Field 2"))); ListView->setColumnText(2, getFieldLabel (selectedItem, "3", tr("Field 3"))); ListView->setColumnText(3, getFieldLabel (selectedItem, "4", tr("Comment"))); ListView->setColumnText(4, getFieldLabel (selectedItem, "5", tr("Field 4"))); ListView->setColumnText(5, getFieldLabel (selectedItem, "6", tr("Field 5"))); #endif #ifdef WIN32 // set the column text dependent on the selected item ListView->setColumnText(0, getFieldLabel (selectedItem, "1", tr("Name"))); ListView->setColumnText(1, getFieldLabel (selectedItem, "2", tr("Field 2"))); ListView->setColumnText(2, getFieldLabel (selectedItem, "3", tr("Field 3"))); ListView->setColumnText(3, getFieldLabel (selectedItem, "4", tr("Comment"))); ListView->setColumnText(4, getFieldLabel (selectedItem, "5", tr("Field 4"))); ListView->setColumnText(5, getFieldLabel (selectedItem, "6", tr("Field 5"))); #endif } bool ZSafe::isCategory(QListViewItem *_item) { if (_item == NULL) return FALSE; QString categoryName = _item->text (0); if (categories.find (categoryName)) return TRUE; else return FALSE; } void ZSafe::removeAsciiFile() { // QString fn = filename + ".txt"; // open the file dialog #ifndef DESKTOP #ifndef NO_OPIE QMap<QString, QStringList> mimeTypes; mimeTypes.insert(tr("All"), QStringList() ); mimeTypes.insert(tr("Text"), "text/*" ); QString fn = OFileDialog::getOpenFileName( OFileSelector::EXTENDED_ALL, QDir::homeDirPath() + "/Documents/application/zsafe", QString::null, mimeTypes, this, tr ("Remove text file")); #else QString fn = ScQtFileEdit::getOpenFileName(this, tr ("Remove text file"), QDir::homeDirPath() + "/Documents/application/zsafe", "*.txt"); #endif #else QString fn = QFileDialog::getOpenFileName( QDir::homeDirPath() + "/Documents/application/zsafe", "ZSafe (*.txt)", this, "ZSafe File Dialog" "Choose a text file" ); #endif if (fn && fn.length() > 0 ) { QFile f( fn ); if ( !f.remove() ) { qWarning( QString("Could not remove file %1").arg(fn), 2000 ); QMessageBox::critical( 0, tr("ZSafe"), tr("Could not remove text file.") ); return; } } } void ZSafe::writeAllEntries() { if (filename.isEmpty()) { QMessageBox::critical( 0, tr("ZSafe"), tr("No document defined.\nYou have to create a new document")); return; } // open the file dialog #ifndef DESKTOP #ifndef NO_OPIE QMap<QString, QStringList> mimeTypes; mimeTypes.insert(tr("All"), QStringList() ); mimeTypes.insert(tr("Text"), "text/*" ); QString fn = OFileDialog::getSaveFileName( OFileSelector::EXTENDED_ALL, QDir::homeDirPath() + "/Documents/application/zsafe", QString::null, mimeTypes, this, tr ("Export text file")); #else QString fn = ScQtFileEdit::getSaveAsFileName(this, tr ("Export text file"), QDir::homeDirPath() + "/Documents/application/zsafe", "*.txt"); #endif #else QString fn = QFileDialog::getSaveFileName( QDir::homeDirPath() + "/Documents/application/zsafe", "ZSafe (*.txt)", this, "ZSafe File Dialog" "Choose a text file" ); #endif // open the new document if (fn && fn.length() > 0 ) { QFile f( fn ); if ( !f.open( IO_WriteOnly ) ) { qWarning( QString("Could not write to file %1").arg(fn), 2000 ); QMessageBox::critical( 0, "ZSafe", QString("Could not export to text file.") ); return; } QTextStream t( &f ); QListViewItem *i; // step through all categories for (i = ListView->firstChild(); i != NULL; i = i->nextSibling()) { // step through all subitems QListViewItem *si; for (si = i->firstChild(); si != NULL; si = si->nextSibling()) { QString oneEntry; oneEntry += "\""; oneEntry += i->text(0); oneEntry += "\";"; oneEntry += "\""; oneEntry += si->text(0); oneEntry += "\";"; oneEntry += "\""; oneEntry += si->text(1); oneEntry += "\";"; oneEntry += "\""; oneEntry += si->text(2); oneEntry += "\";"; oneEntry += "\""; QString comment = si->text(3); comment.replace (QRegExp("\n"), "<br>"); oneEntry += comment; oneEntry += "\";"; oneEntry += "\""; oneEntry += si->text(4); oneEntry += "\";"; oneEntry += "\""; oneEntry += si->text(5); oneEntry += "\""; // qWarning (oneEntry); t << oneEntry << endl; // qWarning (si->text(0)); } } f.close(); } } void ZSafe::readAllEntries() { if (filename.isEmpty()) { QMessageBox::critical( 0, tr("ZSafe"), tr("No document defined.\nYou have to create a new document")); return; } // open the file dialog #ifndef DESKTOP #ifndef NO_OPIE QMap<QString, QStringList> mimeTypes; mimeTypes.insert(tr("All"), QStringList() ); mimeTypes.insert(tr("Text"), "text/*" ); QString fn = OFileDialog::getOpenFileName( OFileSelector::EXTENDED_ALL, QDir::homeDirPath() + "/Documents/application/zsafe", QString::null, mimeTypes, this, tr ("Import text file")); #else QString fn = ScQtFileEdit::getOpenFileName(this, tr ("Import text file"), QDir::homeDirPath() + "/Documents/application/zsafe", "*.txt"); #endif #else QString fn = QFileDialog::getOpenFileName( QDir::homeDirPath() + "/Documents/application/zsafe", "ZSafe (*.txt)", this, "ZSafe File Dialog" "Choose a text file" ); #endif if (fn && fn.length() > 0 ) { QFile f( fn ); if ( !f.open( IO_ReadOnly ) ) { qWarning( QString("Could not read file %1").arg(fn), 2000 ); QMessageBox::critical( 0, "ZSafe", QString("Could not import text file.") ); return; } modified = true; // clear the password list selectedItem = NULL; QListViewItem *i; // step through all categories for (i = ListView->firstChild(); i != NULL; i = i->nextSibling()) { // step through all subitems QListViewItem *si; for (si = i->firstChild(); si != NULL; ) // si = si->nextSibling()) { QListViewItem *_si = si; si = si->nextSibling(); i->takeItem(_si); // remove from view list if (_si) delete _si; } } qWarning ("ReadAllEntries(): "); diff --git a/noncore/comm/keypebble/kvnc.cpp b/noncore/comm/keypebble/kvnc.cpp index 25c8919..2fa8d1f 100644 --- a/noncore/comm/keypebble/kvnc.cpp +++ b/noncore/comm/keypebble/kvnc.cpp @@ -1,295 +1,292 @@ #include <qiconset.h> #include <qdialog.h> #include <qpixmap.h> #include <qdom.h> #include <qaction.h> #include <qmenubar.h> #include <qstatusbar.h> #include <qpopupmenu.h> #include <qpushbutton.h> #include <qpe/qpetoolbar.h> #include <qtimer.h> #include <qmessagebox.h> #include <qspinbox.h> #include <qlistbox.h> #include <qlineedit.h> #include <qpe/qpeapplication.h> #include <qpe/global.h> #include <qpe/qpetoolbar.h> #include <qpe/resource.h> #include <assert.h> #include "kvnc.h" #include "krfbcanvas.h" #include "krfbconnection.h" #include "kvncconndlg.h" #include "krfbserver.h" static int u_id = 1; static int get_unique_id() { return u_id++; } /* XPM */ static char * menu_xpm[] = { "12 12 5 1", " c None", ". c #000000", "+ c #FFFDAD", "@ c #FFFF00", "# c #E5E100", " ", " ", " ......... ", " .+++++++. ", " .+@@@@#. ", " .+@@@#. ", " .+@@#. ", " .+@#. ", " .+#. ", " .+. ", " .. ", " "}; const int StatusTextId = 0; KVNC::KVNC( QWidget *parent, const char *name, WFlags f) : QMainWindow( 0, name ,WStyle_ContextHelp) { setCaption( tr("VNC Viewer") ); fullscreen = false; stack = new QWidgetStack( this ); setCentralWidget( stack ); bookmarkSelector=new KVNCBookmarkDlg(); stack->addWidget(bookmarkSelector,get_unique_id()); stack->raiseWidget( bookmarkSelector ); canvas = new KRFBCanvas( stack, "canvas" ); stack->addWidget(canvas,get_unique_id()); setCentralWidget( stack ); connect( bookmarkSelector->bookmarkList, SIGNAL(clicked(QListBoxItem *)), this, SLOT(openConnection(QListBoxItem *)) ); connect( canvas->connection(), SIGNAL(statusChanged(const QString &)), this, SLOT(statusMessage(const QString &)) ); connect( canvas->connection(), SIGNAL(error(const QString &)), this, SLOT(error(const QString &)) ); connect( canvas->connection(), SIGNAL(connected()), this, SLOT(connected()) ); connect( canvas->connection(), SIGNAL(loggedIn()), this, SLOT(loggedIn()) ); connect( canvas->connection(), SIGNAL(disconnected()), this, SLOT(disconnected()) ); setupActions(); cornerButton = new QPushButton( this ); cornerButton->setPixmap( QPixmap( (const char**)menu_xpm ) ); connect( cornerButton, SIGNAL(pressed()), this, SLOT(showMenu()) ); canvas->setCornerWidget( cornerButton ); stack->raiseWidget( bookmarkSelector ); bar= new QToolBar( this ); setToolBarsMovable( false ); setRightJustification(false); QAction *n = new QAction( tr( "New Connection" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 ); connect( n, SIGNAL( activated() ), this, SLOT( newConnection() ) ); n->addTo( bar ); QAction *o = new QAction( tr( "Open Bookmark" ), Resource::loadPixmap( "fileopen" ), QString::null, 0, this, 0 ); connect( o, SIGNAL( activated() ), this, SLOT( openConnection() ) ); o->addTo( bar ); QAction *d = new QAction( tr( "Delete Bookmark" ), Resource::loadPixmap( "trash" ), QString::null, 0, this, 0 ); connect( d, SIGNAL( activated() ), this, SLOT( deleteBookmark() ) ); d->addTo( bar ); } KVNC::~KVNC() { } void KVNC::newConnection() { curServer=new KRFBServer; KVNCConnDlg dlg( curServer,this); - dlg.showMaximized(); - if ( dlg.exec()) { + if ( QPEApplication::execDialog( &dlg )) { if (!curServer->name.isEmpty()) bookmarkSelector->addBookmark(curServer); canvas->openConnection(*curServer); } else curServer=0; } void KVNC::openConnection( QString name) { curServer=bookmarkSelector->getServer(name); if (curServer) { KVNCConnDlg dlg( curServer,this); - dlg.showMaximized(); - - if ( dlg.exec() ) { + if ( QPEApplication::execDialog( &dlg ) ) { canvas->openConnection(*curServer); bookmarkSelector->writeBookmarks(); } else curServer=0; } } void KVNC::openConnection( void ) { openConnection( bookmarkSelector->selectedBookmark()); } void KVNC::openConnection( QListBoxItem * item) { if (item) openConnection(item->text()); } void KVNC::setupActions() { cornerMenu = new QPopupMenu( this ); fullScreenAction = new QAction( tr("Full Screen"), QString::null, 0, 0 ); connect( fullScreenAction, SIGNAL(activated()), this, SLOT( toggleFullScreen() ) ); fullScreenAction->addTo( cornerMenu ); fullScreenAction->setEnabled( false ); ctlAltDelAction = new QAction( tr("Send Contrl-Alt-Delete"), QString::null, 0, 0 ); connect( ctlAltDelAction, SIGNAL(activated()), canvas, SLOT( sendCtlAltDel() ) ); ctlAltDelAction->addTo( cornerMenu ); ctlAltDelAction->setEnabled( false ); disconnectAction = new QAction( tr("Disconnect"), QString::null, 0, 0 ); connect( disconnectAction, SIGNAL(activated()), this, SLOT( closeConnection() ) ); disconnectAction->addTo( cornerMenu ); disconnectAction->setEnabled( false ); doubleClickAction = new QAction( tr("Next Click is Double Click"), QString::null, 0, 0 ); connect( doubleClickAction, SIGNAL(activated()), canvas, SLOT( markDoubleClick() ) ); doubleClickAction->addTo( cornerMenu ); doubleClickAction->setEnabled( false ); rightClickAction = new QAction( tr("Next Click is Right Click"), QString::null, 0, 0 ); connect( rightClickAction, SIGNAL(activated()), canvas, SLOT( markRightClick() ) ); rightClickAction->addTo( cornerMenu ); rightClickAction->setEnabled( false ); } void KVNC::toggleFullScreen() { if ( fullscreen ) { canvas->releaseKeyboard(); canvas->reparent( stack, 0, QPoint(0,0), false ); canvas->setFrameStyle( QFrame::Panel | QFrame::Sunken ); setCentralWidget( stack ); stack->addWidget(canvas,get_unique_id()); stack->raiseWidget(canvas); canvas->show(); stack->show(); fullScreenAction->setText( tr("Full Screen") ); } else { canvas->setFrameStyle( QFrame::NoFrame ); stack->removeWidget(canvas); canvas->reparent( 0,WStyle_Tool | WStyle_Customize | WStyle_StaysOnTop, QPoint(0,0),false); canvas->resize(qApp->desktop()->width(), qApp->desktop()->height()); canvas->raise(); canvas->setFocus(); canvas->grabKeyboard(); canvas->show(); fullScreenAction->setText( tr("Stop Full Screen") ); } fullscreen = !fullscreen; } void KVNC::closeConnection() { if ( fullscreen ) toggleFullScreen(); canvas->closeConnection(); } void KVNC::showMenu() { QPoint pt = mapToGlobal(cornerButton->pos()); QSize s = cornerMenu->sizeHint(); pt.ry() -= s.height(); pt.rx() -= s.width(); cornerMenu->popup( pt ); } void KVNC::connected() { static QString msg = tr( "Connected to remote host" ); statusMessage( msg ); ctlAltDelAction->setEnabled(true); disconnectAction->setEnabled( true ); fullScreenAction->setEnabled( true ); doubleClickAction->setEnabled( false ); rightClickAction->setEnabled( true ); stack->raiseWidget(canvas); bar->hide(); } void KVNC::loggedIn() { static QString msg = tr( "Logged in to remote host" ); statusMessage( msg ); } void KVNC::disconnected() { if ( fullscreen ) toggleFullScreen(); static QString msg = tr( "Connection closed" ); statusMessage( msg ); ctlAltDelAction->setEnabled(false); disconnectAction->setEnabled( false ); fullScreenAction->setEnabled( false ); doubleClickAction->setEnabled( false ); rightClickAction->setEnabled( false ); stack->raiseWidget(bookmarkSelector); bar->show(); } void KVNC::statusMessage( const QString &m ) { Global::statusMessage( m ); } void KVNC::error( const QString &msg ) { statusMessage( msg ); QMessageBox::warning( this, tr("VNC Viewer"), msg ); } void KVNC::deleteBookmark(void) { bookmarkSelector->deleteBookmark(bookmarkSelector->selectedBookmark()); } |