-rw-r--r-- | core/apps/textedit/textedit.cpp | 33 | ||||
-rw-r--r-- | core/launcher/qprocess_unix.cpp | 6 | ||||
-rw-r--r-- | core/launcher/server.cpp | 19 | ||||
-rw-r--r-- | core/settings/launcher/menusettings.cpp | 5 | ||||
-rw-r--r-- | core/settings/launcher/taskbarsettings.cpp | 13 | ||||
-rw-r--r-- | libopie2/opiecore/oglobal.cpp | 2 | ||||
-rw-r--r-- | libopie2/opiecore/oprocess.cpp | 2 | ||||
-rw-r--r-- | library/global.cpp | 63 | ||||
-rw-r--r-- | noncore/apps/advancedfm/output.cpp | 5 | ||||
-rw-r--r-- | noncore/apps/tinykate/libkate/document/katebuffer.cpp | 5 | ||||
-rw-r--r-- | noncore/settings/usermanager/userdialog.cpp | 9 |
11 files changed, 94 insertions, 68 deletions
diff --git a/core/apps/textedit/textedit.cpp b/core/apps/textedit/textedit.cpp index 759e440..61beac5 100644 --- a/core/apps/textedit/textedit.cpp +++ b/core/apps/textedit/textedit.cpp @@ -1,1212 +1,1213 @@ /********************************************************************** // textedit.cpp ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Opie 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. ** **********************************************************************/ // changes added by L. J. Potter Sun 02-17-2002 21:31:31 #include "textedit.h" #include "filePermissions.h" /* OPIE */ #include <opie2/odebug.h> #include <opie2/ofileselector.h> #include <opie2/ofiledialog.h> #include <opie2/ofontselector.h> #include <opie2/oresource.h> #include <qpe/config.h> #include <qpe/qpeapplication.h> /* QT */ #include <qmenubar.h> #include <qtoolbar.h> #include <qtextstream.h> #include <qclipboard.h> #include <qaction.h> #include <qlineedit.h> #include <qmessagebox.h> #include <qlayout.h> #include <qtimer.h> #include <qdir.h> /* STD */ #include <unistd.h> #include <sys/stat.h> #include <stdlib.h> //getenv using namespace Opie::Core; using namespace Opie::Ui; #if QT_VERSION < 0x030000 class QpeEditor : public QMultiLineEdit { public: QpeEditor( QWidget *parent, const char * name = 0 ) : QMultiLineEdit( parent, name ) { clearTableFlags(); setTableFlags( Tbl_vScrollBar | Tbl_autoHScrollBar ); } void find( const QString &txt, bool caseSensitive, bool backwards ); protected: bool markIt; int line1, line2, col1, col2; void mousePressEvent( QMouseEvent * ); void mouseReleaseEvent( QMouseEvent * ); //public slots: /* signals: void notFound(); void searchWrapped(); */ private: }; void QpeEditor::mousePressEvent( QMouseEvent *e ) { switch(e->button()) { case RightButton: { //rediculous workaround for qt popup menu //and the hold right click mechanism this->setSelection( line1, col1, line2, col2); QMultiLineEdit::mousePressEvent( e ); markIt = false; } break; default: { if(!markIt) { int line, col; this->getCursorPosition(&line, &col); line1=line2=line; col1=col2=col; } QMultiLineEdit::mousePressEvent( e ); } break; }; } void QpeEditor::mouseReleaseEvent( QMouseEvent * ) { if(this->hasMarkedText()) { markIt = true; this->getMarkedRegion( &line1, &col1, &line2, & col2 ); } else { markIt = false; } } void QpeEditor::find ( const QString &txt, bool caseSensitive, bool backwards ) { static bool wrap = false; int line, col; if ( wrap ) { if ( !backwards ) line = col = 0; wrap = false; // emit searchWrapped(); } else { getCursorPosition( &line, &col ); } //ignore backwards for now.... if ( !backwards ) { for ( ; ; ) { if ( line >= numLines() ) { wrap = true; //emit notFound(); break; } int findCol = getString( line )->find( txt, col, caseSensitive ); if ( findCol >= 0 ) { setCursorPosition( line, findCol, false ); col = findCol + txt.length(); setCursorPosition( line, col, true ); //found = true; break; } line++; col = 0; } } } #else #error "Must make a QpeEditor that inherits QTextEdit" #endif static const int nfontsizes = 6; static const int fontsize[nfontsizes] = {8,10,12,14,18,24}; TextEdit::TextEdit( QWidget *parent, const char *name, WFlags f ) : QMainWindow( parent, name, f ), bFromDocView( false ) { doc = 0; edited=false; fromSetDocument=false; setToolBarsMovable( false ); connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); channel = new QCopChannel( "QPE/Application/textedit", this ); connect( channel, SIGNAL(received(const QCString&,const QByteArray&)), this, SLOT(receive(const QCString&,const QByteArray&)) ); setIcon( Opie::Core::OResource::loadPixmap( "textedit/TextEditor", Opie::Core::OResource::SmallIcon ) ); QToolBar *bar = new QToolBar( this ); bar->setHorizontalStretchable( true ); menu = bar; QMenuBar *mb = new QMenuBar( bar ); QPopupMenu *file = new QPopupMenu( this ); QPopupMenu *edit = new QPopupMenu( this ); QPopupMenu *advancedMenu = new QPopupMenu(this); font = new QPopupMenu( this ); bar = new QToolBar( this ); editBar = bar; QAction *a = new QAction( tr( "New" ), Opie::Core::OResource::loadPixmap( "new", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( fileNew() ) ); // a->addTo( bar ); a->addTo( file ); a = new QAction( tr( "Open" ), Opie::Core::OResource::loadPixmap( "fileopen", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( fileOpen() ) ); a->addTo( bar ); a->addTo( file ); a = new QAction( tr( "Save" ), Opie::Core::OResource::loadPixmap( "save", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( save() ) ); file->insertSeparator(); a->addTo( bar ); a->addTo( file ); a = new QAction( tr( "Save As" ), Opie::Core::OResource::loadPixmap( "save", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( saveAs() ) ); a->addTo( file ); a = new QAction( tr( "Cut" ), Opie::Core::OResource::loadPixmap( "cut", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editCut() ) ); a->addTo( editBar ); a->addTo( edit ); a = new QAction( tr( "Copy" ), Opie::Core::OResource::loadPixmap( "copy", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editCopy() ) ); a->addTo( editBar ); a->addTo( edit ); a = new QAction( tr( "Paste" ), Opie::Core::OResource::loadPixmap( "paste", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editPaste() ) ); a->addTo( editBar ); a->addTo( edit ); #ifndef QT_NO_CLIPBOARD a = new QAction( tr( "Insert Time and Date" ), Opie::Core::OResource::loadPixmap( "paste", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editPasteTimeDate() ) ); a->addTo( edit ); #endif a = new QAction( tr( "Goto Line..." ), Opie::Core::OResource::loadPixmap( "find", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( gotoLine() ) ); edit->insertSeparator(); a->addTo( edit ); a = new QAction( tr( "Find..." ), Opie::Core::OResource::loadPixmap( "find", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editFind() ) ); a->addTo( bar ); a->addTo( edit ); zin = new QAction( tr("Zoom in"), QString::null, 0, this, 0 ); connect( zin, SIGNAL( activated() ), this, SLOT( zoomIn() ) ); zin->addTo( font ); zout = new QAction( tr("Zoom out"), QString::null, 0, this, 0 ); connect( zout, SIGNAL( activated() ), this, SLOT( zoomOut() ) ); zout->addTo( font ); font->insertSeparator(); font->insertItem(tr("Font"), this, SLOT(changeFont()) ); font->insertSeparator(); font->insertItem(tr("Advanced Features"), advancedMenu); QAction *wa = new QAction( tr("Wrap lines"), QString::null, 0, this, 0 ); connect( wa, SIGNAL( toggled(bool) ), this, SLOT( setWordWrap(bool) ) ); wa->setToggleAction(true); wa->addTo( advancedMenu); nStart = new QAction( tr("Start with new file"), QString::null, 0, this, 0 ); connect( nStart, SIGNAL( toggled(bool) ), this, SLOT( changeStartConfig(bool) ) ); nStart->setToggleAction(true); nStart->addTo( advancedMenu ); nStart->setEnabled(false); nAdvanced = new QAction( tr("Prompt on Exit"), QString::null, 0, this, 0 ); connect( nAdvanced, SIGNAL( toggled(bool) ), this, SLOT( doPrompt(bool) ) ); nAdvanced->setToggleAction(true); nAdvanced->addTo( advancedMenu ); desktopAction = new QAction( tr("Always open linked file"), QString::null, 0, this, 0 ); connect( desktopAction, SIGNAL( toggled(bool) ), this, SLOT( doDesktop(bool) ) ); desktopAction->setToggleAction(true); desktopAction->addTo( advancedMenu); filePermAction = new QAction( tr("File Permissions"), QString::null, 0, this, 0 ); connect( filePermAction, SIGNAL( toggled(bool) ), this, SLOT( doFilePerms(bool) ) ); filePermAction->setToggleAction(true); filePermAction->addTo( advancedMenu); searchBarAction = new QAction( tr("Search Bar Open"), QString::null, 0, this, 0 ); connect( searchBarAction, SIGNAL( toggled(bool) ), this, SLOT( setSearchBar(bool) ) ); searchBarAction->setToggleAction(true); searchBarAction->addTo( advancedMenu); nAutoSave = new QAction( tr("Auto Save 5 min."), QString::null, 0, this, 0 ); connect( nAutoSave, SIGNAL( toggled(bool) ), this, SLOT( doTimer(bool) ) ); nAutoSave->setToggleAction(true); nAutoSave->addTo( advancedMenu); //font->insertSeparator(); //font->insertItem(tr("About"), this, SLOT( doAbout()) ); mb->insertItem( tr( "File" ), file ); mb->insertItem( tr( "Edit" ), edit ); mb->insertItem( tr( "View" ), font ); searchBar = new QToolBar(this); addToolBar( searchBar, "Search", QMainWindow::Top, true ); searchBar->setHorizontalStretchable( true ); searchEdit = new QLineEdit( searchBar, "searchEdit" ); searchBar->setStretchableWidget( searchEdit ); connect( searchEdit, SIGNAL( textChanged(const QString&) ), this, SLOT( search() ) ); a = new QAction( tr( "Find Next" ), Opie::Core::OResource::loadPixmap( "next", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( findNext() ) ); a->addTo( searchBar ); a->addTo( edit ); a = new QAction( tr( "Close Find" ), Opie::Core::OResource::loadPixmap( "close", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( findClose() ) ); a->addTo( searchBar ); edit->insertSeparator(); a = new QAction( tr( "Delete" ), Opie::Core::OResource::loadPixmap( "close", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editDelete() ) ); a->addTo( edit ); searchBar->hide(); editor = new QpeEditor( this ); setCentralWidget( editor ); editor->setFrameStyle( QFrame::Panel | QFrame::Sunken ); connect( editor, SIGNAL( textChanged() ), this, SLOT( editorChanged() ) ); QPEApplication::setStylusOperation( editor, QPEApplication::RightOnHold); Config cfg("TextEdit"); cfg. setGroup ( "Font" ); QFont defaultFont = editor-> font ( ); QString family = cfg. readEntry ( "Family", defaultFont. family ( )); int size = cfg. readNumEntry ( "Size", defaultFont. pointSize ( )); int weight = cfg. readNumEntry ( "Weight", defaultFont. weight ( )); bool italic = cfg. readBoolEntry ( "Italic", defaultFont. italic ( )); defaultFont = QFont ( family, size, weight, italic ); editor-> setFont ( defaultFont ); // updateCaption(); cfg.setGroup ( "View" ); promptExit = cfg.readBoolEntry ( "PromptExit", false ); openDesktop = cfg.readBoolEntry ( "OpenDesktop", true ); filePerms = cfg.readBoolEntry ( "FilePermissions", false ); useSearchBar = cfg.readBoolEntry ( "SearchBar", false ); startWithNew = cfg.readBoolEntry ( "startNew", true); featureAutoSave = cfg.readBoolEntry( "autosave", false); if(useSearchBar) searchBarAction->setOn(true); if(promptExit) nAdvanced->setOn( true ); if(openDesktop) desktopAction->setOn( true ); if(filePerms) filePermAction->setOn( true ); if(startWithNew) nStart->setOn( true ); if(featureAutoSave) nAutoSave->setOn(true); // { // doTimer(true); // } bool wrap = cfg. readBoolEntry ( "Wrap", true ); wa-> setOn ( wrap ); setWordWrap ( wrap ); ///////////////// if( qApp->argc() > 1) { currentFileName=qApp->argv()[1]; QFileInfo fi(currentFileName); if(fi.baseName().left(1) == "") { openDotFile(currentFileName); } else { openFile(currentFileName); } } else { edited1=false; openDotFile(""); } viewSelection = cfg.readNumEntry( "FileView", 0 ); } TextEdit::~TextEdit() { if( edited1 && !promptExit) { switch( savePrompt() ) { case 1: { saveAs(); } break; }; } delete editor; } void TextEdit::closeEvent(QCloseEvent *) { if( promptExit) { switch( savePrompt() ) { case 1: { saveAs(); qApp->quit(); } break; case 2: { qApp->quit(); } break; case -1: break; }; } else qApp->quit(); } void TextEdit::cleanUp() { Config cfg ( "TextEdit" ); cfg. setGroup ( "Font" ); QFont f = editor->font(); cfg.writeEntry ( "Family", f. family ( )); cfg.writeEntry ( "Size", f. pointSize ( )); cfg.writeEntry ( "Weight", f. weight ( )); cfg.writeEntry ( "Italic", f. italic ( )); cfg.setGroup ( "View" ); cfg.writeEntry ( "Wrap", editor->wordWrap() == QMultiLineEdit::WidgetWidth ); cfg.writeEntry ( "FileView", viewSelection ); cfg.writeEntry ( "PromptExit", promptExit ); cfg.writeEntry ( "OpenDesktop", openDesktop ); cfg.writeEntry ( "FilePermissions", filePerms ); cfg.writeEntry ( "SearchBar", useSearchBar ); cfg.writeEntry ( "startNew", startWithNew ); } void TextEdit::accept() { if( edited1) saveAs(); qApp->quit(); } void TextEdit::zoomIn() { setFontSize(editor->font().pointSize()+1,false); } void TextEdit::zoomOut() { setFontSize(editor->font().pointSize()-1,true); } void TextEdit::setFontSize(int sz, bool round_down_not_up) { int s=10; for (int i=0; i<nfontsizes; i++) { if ( fontsize[i] == sz ) { s = sz; break; } else if ( round_down_not_up ) { if ( fontsize[i] < sz ) s = fontsize[i]; } else { if ( fontsize[i] > sz ) { s = fontsize[i]; break; } } } QFont f = editor->font(); f.setPointSize(s); editor->setFont(f); zin->setEnabled(s != fontsize[nfontsizes-1]); zout->setEnabled(s != fontsize[0]); } void TextEdit::setBold(bool y) { QFont f = editor->font(); f.setBold(y); editor->setFont(f); } void TextEdit::setItalic(bool y) { QFont f = editor->font(); f.setItalic(y); editor->setFont(f); } void TextEdit::setWordWrap(bool y) { bool state = editor->edited(); QString captionStr = caption(); bool b1 = edited1; bool b2 = edited; editor->setWordWrap(y ? QMultiLineEdit::WidgetWidth : QMultiLineEdit::NoWrap ); editor->setEdited( state ); edited1=b1; edited=b2; setCaption(captionStr); } void TextEdit::setSearchBar(bool b) { useSearchBar=b; Config cfg("TextEdit"); cfg.setGroup("View"); cfg.writeEntry ( "SearchBar", b ); searchBarAction->setOn(b); if(b) searchBar->show(); else searchBar->hide(); editor->setFocus(); } void TextEdit::fileNew() { // if( !bFromDocView ) { // saveAs(); // } newFile(DocLnk()); } void TextEdit::fileOpen() { Config cfg("TextEdit"); cfg. setGroup ( "View" ); QMap<QString, QStringList> map; map.insert(tr("All"), QStringList() ); QStringList text; text << "text/*"; map.insert(tr("Text"), text ); text << "*"; map.insert(tr("All"), text ); QString str = OFileDialog::getOpenFileName( 2, QString::null , QString::null, map); if( !str.isEmpty() && QFile(str).exists() && !QFileInfo(str).isDir() ) { openFile( str ); } else updateCaption(); } void TextEdit::doSearchBar() { if(!useSearchBar) searchBar->hide(); else searchBar->show(); } #if 0 void TextEdit::slotFind() { FindDialog frmFind( tr("Text Editor"), this ); connect( &frmFind, SIGNAL(signalFindClicked(const QString&,bool,bool,int)), editor, SLOT(slotDoFind(const QString&,bool,bool))); //case sensitive, backwards, [category] connect( editor, SIGNAL(notFound()), &frmFind, SLOT(slotNotFound()) ); connect( editor, SIGNAL(searchWrapped()), &frmFind, SLOT(slotWrapAround()) ); frmFind.exec(); } #endif void TextEdit::fileRevert() { clear(); fileOpen(); } void TextEdit::editCut() { #ifndef QT_NO_CLIPBOARD editor->cut(); #endif } void TextEdit::editCopy() { #ifndef QT_NO_CLIPBOARD editor->copy(); #endif } void TextEdit::editPaste() { #ifndef QT_NO_CLIPBOARD editor->paste(); #endif } void TextEdit::editFind() { searchBar->show(); searchEdit->setFocus(); } void TextEdit::findNext() { editor->find( searchEdit->text(), false, false ); } void TextEdit::findClose() { searchBar->hide(); } void TextEdit::search() { editor->find( searchEdit->text(), false, false ); } void TextEdit::newFile( const DocLnk &f ) { DocLnk nf = f; nf.setType("text/plain"); clear(); setWState (WState_Reserved1 ); editor->setFocus(); doc = new DocLnk(nf); currentFileName = "Unnamed"; odebug << "newFile "+currentFileName << oendl; updateCaption( currentFileName); // editor->setEdited( false); } void TextEdit::openDotFile( const QString &f ) { if(!currentFileName.isEmpty()) { - currentFileName=f; - - odebug << "openFile dotfile " + currentFileName << oendl; - QString txt; - QFile file(f); - file.open(IO_ReadWrite); - QTextStream t(&file); - while ( !t.atEnd()) { - txt+=t.readLine()+"\n"; - } - editor->setText(txt); - editor->setEdited( false); - edited1=false; - edited=false; - - + currentFileName=f; + + odebug << "openFile dotfile " + currentFileName << oendl; + QString txt; + QFile file(f); + if (!file.open(IO_ReadWrite)) + owarn << "Failed to open file " << file.name() << oendl; + else { + QTextStream t(&file); + while ( !t.atEnd()) { + txt+=t.readLine()+"\n"; + } + editor->setText(txt); + editor->setEdited( false); + edited1=false; + edited=false; + } } updateCaption( currentFileName); } void TextEdit::openFile( const QString &f ) { odebug << "filename is "+ f << oendl; QString filer; QFileInfo fi( f); // bFromDocView = true; if(f.find(".desktop",0,true) != -1 && !openDesktop ) { switch ( QMessageBox::warning(this,tr("Text Editor"),tr("Text Editor has detected<BR>you selected a <B>.desktop</B>file.<BR>Open<B>.desktop</B> file or <B>linked</B> file?"),tr(".desktop File"),tr("Linked Document"),0,1,1) ) { case 0: //desktop filer = f; break; case 1: //linked DocLnk sf(f); filer = sf.file(); break; }; } else if(fi.baseName().left(1) == "") { odebug << "opening dotfile" << oendl; currentFileName=f; openDotFile(currentFileName); return; } /* * The problem is a file where Config(f).isValid() and it does not * end with .desktop will be treated as desktop file */ else if (f.find(".desktop",0,true) != -1 ) { DocLnk sf(f); filer = sf.file(); if(filer.right(1) == "/") filer = f; } else filer = f; DocLnk nf; nf.setType("text/plain"); nf.setFile(filer); currentFileName=filer; nf.setName(fi.baseName()); openFile(nf); odebug << "openFile string "+currentFileName << oendl; showEditTools(); // Show filename in caption QString name = filer; int sep = name.findRev( '/' ); if ( sep > 0 ) name = name.mid( sep+1 ); updateCaption( name ); } void TextEdit::openFile( const DocLnk &f ) { // clear(); // bFromDocView = true; FileManager fm; QString txt; currentFileName=f.file(); odebug << "openFile doclnk " + currentFileName << oendl; if ( !fm.loadFile( f, txt ) ) { // ####### could be a new file odebug << "Cannot open file" << oendl; } // fileNew(); if ( doc ) delete doc; doc = new DocLnk(f); editor->setText(txt); editor->setEdited( false); edited1=false; edited=false; doc->setName(currentFileName); updateCaption(); setTimer(); } void TextEdit::showEditTools() { menu->show(); editBar->show(); if(!useSearchBar) searchBar->hide(); else searchBar->show(); setWState (WState_Reserved1 ); } /*! unprompted save */ bool TextEdit::save() { QString name, file; odebug << "saveAsFile " + currentFileName << oendl; if(currentFileName.isEmpty()) { saveAs(); return false; } name = currentFileName; if(doc) { file = doc->file(); odebug << "saver file "+file << oendl; name = doc->name(); odebug << "File named "+name << oendl; } else { file = currentFileName; name = QFileInfo(currentFileName).baseName(); } QString rt = editor->text(); if( !rt.isEmpty() ) { if(name.isEmpty()) { saveAs(); } else { currentFileName = name; odebug << "saveFile "+currentFileName << oendl; struct stat buf; mode_t mode; stat(file.latin1(), &buf); mode = buf.st_mode; if(!fileIs) { doc->setName( name); FileManager fm; if ( !fm.saveFile( *doc, rt ) ) { QMessageBox::message(tr("Text Edit"),tr("Save Failed")); return false; } } else { odebug << "regular save file" << oendl; QFile f(file); if( f.open(IO_WriteOnly)) { QCString crt = rt.utf8(); f.writeBlock(crt,crt.length()); } else { QMessageBox::message(tr("Text Edit"),tr("Write Failed")); return false; } } editor->setEdited( false); edited1=false; edited=false; if(caption().left(1)=="*") setCaption(caption().right(caption().length()-1)); chmod( file.latin1(), mode); } return true; } return false; } /*! prompted save */ bool TextEdit::saveAs() { if(caption() == tr("Text Editor")) return false; odebug << "saveAsFile " + currentFileName << oendl; // case of nothing to save... // if ( !doc && !currentFileName.isEmpty()) { // //|| !bFromDocView) // odebug << "no doc" << oendl; // return true; // } // if ( !editor->edited() ) { // delete doc; // doc = 0; // return true; // } QString rt = editor->text(); odebug << currentFileName << oendl; if( currentFileName.isEmpty() || currentFileName == tr("Unnamed") || currentFileName == tr("Text Editor")) { odebug << "do silly TT filename thing" << oendl; // if ( doc && doc->name().isEmpty() ) { QString pt = rt.simplifyWhiteSpace(); int i = pt.find( ' ' ); QString docname = pt; if ( i > 0 ) docname = pt.left( i ); // remove "." at the beginning while( docname.startsWith( "." ) ) docname = docname.mid( 1 ); docname.replace( QRegExp("/"), "_" ); // cut the length. filenames longer than that //don't make sense and something goes wrong when they get too long. if ( docname.length() > 40 ) docname = docname.left(40); if ( docname.isEmpty() ) docname = tr("Unnamed"); if(doc) doc->setName(docname); currentFileName=docname; // } // else // odebug << "hmmmmmm" << oendl; } QMap<QString, QStringList> map; map.insert(tr("All"), QStringList() ); QStringList text; text << "text/*"; map.insert(tr("Text"), text ); text << "*"; map.insert(tr("All"), text ); QFileInfo cuFi( currentFileName); QString filee = cuFi.fileName(); QString dire = cuFi.dirPath(); if(dire==".") dire = QPEApplication::documentDir(); QString str; if( !featureAutoSave) { str = OFileDialog::getSaveFileName( 2, dire, filee, map); } else str = currentFileName; if(!str.isEmpty()) { QString fileNm=str; odebug << "saving filename "+fileNm << oendl; QFileInfo fi(fileNm); currentFileName=fi.fileName(); if(doc) // QString file = doc->file(); // doc->removeFiles(); delete doc; DocLnk nf; nf.setType("text/plain"); nf.setFile( fileNm); doc = new DocLnk(nf); // editor->setText(rt); odebug << "Saving file as "+currentFileName << oendl; doc->setName( fi.baseName() /*currentFileName*/); updateCaption( currentFileName); FileManager fm; if ( !fm.saveFile( *doc, rt ) ) { QMessageBox::message(tr("Text Edit"),tr("Save Failed")); return false; } if( filePerms ) { filePermissions *filePerm; filePerm = new filePermissions(this, tr("Permissions"),true, 0,(const QString &)fileNm); QPEApplication::execDialog( filePerm ); if( filePerm) delete filePerm; } // } editor->setEdited( false); edited1 = false; edited = false; if(caption().left(1)=="*") setCaption(caption().right(caption().length()-1)); return true; } odebug << "returning false" << oendl; currentFileName = ""; return false; } //end saveAs void TextEdit::clear() { delete doc; doc = 0; editor->clear(); } void TextEdit::updateCaption( const QString &name ) { if ( name.isEmpty() ) setCaption( tr("Text Editor") ); else { QString s = name; if ( s.isNull() ) s = doc->name(); if ( s.isEmpty() ) { s = tr( "Unnamed" ); currentFileName=s; } // if(s.left(1) == "/") // s = s.right(s.length()-1); setCaption( tr("%1 - Text Editor").arg( s ) ); } } void TextEdit::setDocument(const QString& fileref) { if(fileref != "Unnamed") { currentFileName=fileref; odebug << "setDocument" << oendl; QFileInfo fi(currentFileName); odebug << "basename:"+fi.baseName()+": current filenmame "+currentFileName << oendl; if( (fi.baseName().left(1)).isEmpty() ) { openDotFile(currentFileName); } else { odebug << "setDoc open" << oendl; bFromDocView = true; openFile(fileref); editor->setEdited(true); edited1=false; edited=true; // fromSetDocument=false; // doSearchBar(); } } updateCaption( currentFileName); } void TextEdit::changeFont() { QDialog *d = new QDialog ( this, "FontDialog", true ); d-> setCaption ( tr( "Choose font" )); QBoxLayout *lay = new QVBoxLayout ( d ); OFontSelector *ofs = new OFontSelector ( true, d ); lay-> addWidget ( ofs ); ofs-> setSelectedFont ( editor-> font ( )); if ( QPEApplication::execDialog( d ) == QDialog::Accepted ) editor-> setFont ( ofs-> selectedFont ( )); delete d; } void TextEdit::editDelete() { switch ( QMessageBox::warning(this,tr("Text Editor"), tr("Do you really want<BR>to <B>delete</B> " "the current file\nfrom the disk?<BR>This is " "<B>irreversable!</B>"), tr("Yes"),tr("No"),0,0,1) ) { case 0: if(doc) { doc->removeFiles(); clear(); setCaption( tr("Text Editor") ); } break; case 1: // exit break; }; } void TextEdit::changeStartConfig( bool b ) { startWithNew=b; Config cfg("TextEdit"); cfg.setGroup("View"); cfg.writeEntry("startNew",b); update(); } void TextEdit::editorChanged() { // odebug << "editor changed" << oendl; if( /*editor->edited() &&*/ /*edited && */!edited1) { setCaption( "*"+caption()); edited1=true; } edited=true; } void TextEdit::receive(const QCString&msg, const QByteArray &) { odebug << "QCop "+msg << oendl; if ( msg == "setDocument(QString)" ) { odebug << "bugger all" << oendl; } } void TextEdit::doAbout() { QMessageBox::about(0,tr("Text Edit"),tr("Text Edit is copyright<BR>" "2000 Trolltech AS, and<BR>" "2002 by <B>L. J. Potter <BR>llornkcor@handhelds.org</B><BR>" "and is licensed under the GPL")); } void TextEdit::doPrompt(bool b) { promptExit=b; Config cfg("TextEdit"); cfg.setGroup ( "View" ); cfg.writeEntry ( "PromptExit", b); } void TextEdit::doDesktop(bool b) { openDesktop=b; Config cfg("TextEdit"); cfg.setGroup ( "View" ); cfg.writeEntry ( "OpenDesktop", b); } void TextEdit::doFilePerms(bool b) { filePerms=b; Config cfg("TextEdit"); cfg.setGroup ( "View" ); cfg.writeEntry ( "FilePermissions", b); } void TextEdit::editPasteTimeDate() { #ifndef QT_NO_CLIPBOARD QClipboard *cb = QApplication::clipboard(); QDateTime dt = QDateTime::currentDateTime(); cb->setText( dt.toString()); editor->paste(); #endif } int TextEdit::savePrompt() { switch( QMessageBox::information( 0, (tr("Textedit")), (tr("Textedit detected\n" "you have unsaved changes\n" "Go ahead and save?\n")), (tr("Save")), (tr("Don't Save")), (tr("&Cancel")), 2, 2 ) ) { case 0: { return 1; } break; case 1: { return 2; } break; case 2: { return -1; } break; }; return 0; } void TextEdit::timerCrank() { if(featureAutoSave && edited1) { if(currentFileName.isEmpty()) { currentFileName = QDir::homeDirPath()+"/textedit.tmp"; saveAs(); } else { // odebug << "autosave" << oendl; save(); } setTimer(); } } void TextEdit::doTimer(bool b) { Config cfg("TextEdit"); cfg.setGroup ( "View" ); cfg.writeEntry ( "autosave", b); featureAutoSave = b; nAutoSave->setOn(b); if(b) { // odebug << "doTimer true" << oendl; setTimer(); } // else // odebug << "doTimer false" << oendl; } void TextEdit::setTimer() { if(featureAutoSave) { // odebug << "setting autosave" << oendl; QTimer *timer = new QTimer(this ); connect( timer, SIGNAL(timeout()), this, SLOT(timerCrank()) ); timer->start( 300000, true); //5 minutes } } void TextEdit::gotoLine() { if( editor->length() < 1) return; QWidget *d = QApplication::desktop(); gotoEdit = new QLineEdit( 0, "Goto line"); gotoEdit->move( (d->width()/2) - ( gotoEdit->width()/2) , (d->height()/2) - (gotoEdit->height()/2)); gotoEdit->setFrame(true); gotoEdit->show(); connect (gotoEdit,SIGNAL(returnPressed()), this, SLOT(doGoto())); } void TextEdit::doGoto() { QString number = gotoEdit->text(); gotoEdit->hide(); if(gotoEdit) { delete gotoEdit; gotoEdit = 0; } bool ok; int lineNumber = number.toInt(&ok, 10); if( editor->numLines() < lineNumber) QMessageBox::message(tr("Text Edit"),tr("Not enough lines")); else { editor->setCursorPosition(lineNumber, 0, false); } } diff --git a/core/launcher/qprocess_unix.cpp b/core/launcher/qprocess_unix.cpp index 97c0460..3125bcc 100644 --- a/core/launcher/qprocess_unix.cpp +++ b/core/launcher/qprocess_unix.cpp @@ -1,1173 +1,1177 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the 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. ** **********************************************************************/ // Solaris redefines connect -> __xnet_connect with _XOPEN_SOURCE_EXTENDED. #if defined(connect) #undef connect #endif #include "qprocess.h" /* OPIE */ #include <opie2/odebug.h> using namespace Opie::Core; /* QT */ #ifndef QT_NO_PROCESS #include <qapplication.h> #include <qqueue.h> #include <qlist.h> #include <qsocketnotifier.h> #include <qtimer.h> #include <qregexp.h> #include "qcleanuphandler_p.h" /* STD */ #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <sys/wait.h> #include <sys/fcntl.h> #include <errno.h> #ifdef Q_OS_MACX #include <sys/time.h> #endif #include <sys/resource.h> #ifdef __MIPSEL__ # ifndef SOCK_DGRAM # define SOCK_DGRAM 1 # endif # ifndef SOCK_STREAM # define SOCK_STREAM 2 # endif #endif //#define QT_QPROCESS_DEBUG #ifdef Q_C_CALLBACKS extern "C" { #endif // Q_C_CALLBACKS #define QT_SIGNAL_RETTYPE void #define QT_SIGNAL_ARGS int #define QT_SIGNAL_IGNORE SIG_IGN QT_SIGNAL_RETTYPE qt_C_sigchldHnd(QT_SIGNAL_ARGS); QT_SIGNAL_RETTYPE qt_C_sigpipeHnd(QT_SIGNAL_ARGS); #ifdef Q_C_CALLBACKS } #endif // Q_C_CALLBACKS class QProc; class QProcessManager; class QProcessPrivate { public: QProcessPrivate(); ~QProcessPrivate(); void closeOpenSocketsForChild(); void newProc( pid_t pid, QProcess *process ); QByteArray bufStdout; QByteArray bufStderr; QQueue<QByteArray> stdinBuf; QSocketNotifier *notifierStdin; QSocketNotifier *notifierStdout; QSocketNotifier *notifierStderr; ssize_t stdinBufRead; QProc *proc; bool exitValuesCalculated; bool socketReadCalled; static QProcessManager *procManager; }; /*********************************************************************** * * QProc * **********************************************************************/ /* The class QProcess does not necessarily map exactly to the running child processes: if the process is finished, the QProcess class may still be there; furthermore a user can use QProcess to start more than one process. The helper-class QProc has the semantics that one instance of this class maps directly to a running child process. */ class QProc { public: QProc( pid_t p, QProcess *proc=0 ) : pid(p), process(proc) { #if defined(QT_QPROCESS_DEBUG) odebug << "QProc: Constructor for pid " << pid << " and QProcess " << process << "" << oendl; #endif socketStdin = 0; socketStdout = 0; socketStderr = 0; } ~QProc() { #if defined(QT_QPROCESS_DEBUG) odebug << "QProc: Destructor for pid " << pid << " and QProcess " << process << "" << oendl; #endif if ( process != 0 ) { if ( process->d->notifierStdin ) process->d->notifierStdin->setEnabled( FALSE ); if ( process->d->notifierStdout ) process->d->notifierStdout->setEnabled( FALSE ); if ( process->d->notifierStderr ) process->d->notifierStderr->setEnabled( FALSE ); process->d->proc = 0; } if( socketStdin != 0 ) ::close( socketStdin ); // ### close these sockets even on parent exit or is it better only on // sigchld (but what do I have to do with them on exit then)? if( socketStdout != 0 ) ::close( socketStdout ); if( socketStderr != 0 ) ::close( socketStderr ); } pid_t pid; int socketStdin; int socketStdout; int socketStderr; QProcess *process; }; /*********************************************************************** * * QProcessManager * **********************************************************************/ class QProcessManager : public QObject { Q_OBJECT public: QProcessManager(); ~QProcessManager(); void append( QProc *p ); void remove( QProc *p ); void cleanup(); public slots: void removeMe(); void sigchldHnd( int ); public: struct sigaction oldactChld; struct sigaction oldactPipe; QList<QProc> *procList; int sigchldFd[2]; }; QCleanupHandler<QProcessManager> qprocess_cleanup_procmanager; QProcessManager::QProcessManager() { procList = new QList<QProc>; procList->setAutoDelete( TRUE ); // The SIGCHLD handler writes to a socket to tell the manager that // something happened. This is done to get the processing in sync with the // event reporting. if ( ::socketpair( AF_UNIX, SOCK_STREAM, 0, sigchldFd ) ) { sigchldFd[0] = 0; sigchldFd[1] = 0; } else { #if defined(QT_QPROCESS_DEBUG) odebug << "QProcessManager: install socket notifier (" << sigchldFd[1] << ")" << oendl; #endif QSocketNotifier *sn = new QSocketNotifier( sigchldFd[1], QSocketNotifier::Read, this ); connect( sn, SIGNAL(activated(int)), this, SLOT(sigchldHnd(int)) ); sn->setEnabled( TRUE ); } // install a SIGCHLD handler and ignore SIGPIPE struct sigaction act; #if defined(QT_QPROCESS_DEBUG) odebug << "QProcessManager: install a SIGCHLD handler" << oendl; #endif act.sa_handler = qt_C_sigchldHnd; sigemptyset( &(act.sa_mask) ); sigaddset( &(act.sa_mask), SIGCHLD ); act.sa_flags = SA_NOCLDSTOP; #if defined(SA_RESTART) act.sa_flags |= SA_RESTART; #endif if ( sigaction( SIGCHLD, &act, &oldactChld ) != 0 ) owarn << "Error installing SIGCHLD handler" << oendl; #if defined(QT_QPROCESS_DEBUG) odebug << "QProcessManager: install a SIGPIPE handler (SIG_IGN)" << oendl; #endif /* Using qt_C_sigpipeHnd rather than SIG_IGN is a workaround for a strange problem where GNU tar (called by backuprestore) would hang on filesystem-full. Strangely, the qt_C_sigpipeHnd is never even called, yet this avoids the hang. */ act.sa_handler = qt_C_sigpipeHnd; sigemptyset( &(act.sa_mask) ); sigaddset( &(act.sa_mask), SIGPIPE ); act.sa_flags = 0; if ( sigaction( SIGPIPE, &act, &oldactPipe ) != 0 ) owarn << "Error installing SIGPIPE handler" << oendl; } QProcessManager::~QProcessManager() { delete procList; if ( sigchldFd[0] != 0 ) ::close( sigchldFd[0] ); if ( sigchldFd[1] != 0 ) ::close( sigchldFd[1] ); // restore SIGCHLD handler #if defined(QT_QPROCESS_DEBUG) odebug << "QProcessManager: restore old sigchild handler" << oendl; #endif if ( sigaction( SIGCHLD, &oldactChld, 0 ) != 0 ) owarn << "Error restoring SIGCHLD handler" << oendl; #if defined(QT_QPROCESS_DEBUG) odebug << "QProcessManager: restore old sigpipe handler" << oendl; #endif if ( sigaction( SIGPIPE, &oldactPipe, 0 ) != 0 ) owarn << "Error restoring SIGPIPE handler" << oendl; } void QProcessManager::append( QProc *p ) { procList->append( p ); #if defined(QT_QPROCESS_DEBUG) odebug << "QProcessManager: append process (procList.count(): " << procList->count() << ")" << oendl; #endif } void QProcessManager::remove( QProc *p ) { procList->remove( p ); #if defined(QT_QPROCESS_DEBUG) odebug << "QProcessManager: remove process (procList.count(): " << procList->count() << ")" << oendl; #endif cleanup(); } void QProcessManager::cleanup() { if ( procList->count() == 0 ) { QTimer::singleShot( 0, this, SLOT(removeMe()) ); } } void QProcessManager::removeMe() { if ( procList->count() == 0 ) { qprocess_cleanup_procmanager.remove( &QProcessPrivate::procManager ); QProcessPrivate::procManager = 0; delete this; } } void QProcessManager::sigchldHnd( int fd ) { char tmp; - ::read( fd, &tmp, sizeof(tmp) ); + if (::read( fd, &tmp, sizeof(tmp) ) < 0) +#if defined(QT_QPROCESS_DEBUG) + odebug << "QProcessManager::sigchldHnd() failed dummy read of file descriptor" << oendl; +#endif + ; #if defined(QT_QPROCESS_DEBUG) odebug << "QProcessManager::sigchldHnd()" << oendl; #endif QProc *proc; QProcess *process; bool removeProc; proc = procList->first(); while ( proc != 0 ) { removeProc = FALSE; process = proc->process; QProcess *process_exit_notify=0; if ( process != 0 ) { if ( !process->isRunning() ) { #if defined(QT_QPROCESS_DEBUG) odebug << "QProcessManager::sigchldHnd() (PID: " << proc->pid << "): process exited (QProcess available)" << oendl; #endif // read pending data int nbytes = 0; if ( ::ioctl(proc->socketStdout, FIONREAD, (char*)&nbytes)==0 && nbytes>0 ) { #if defined(QT_QPROCESS_DEBUG) odebug << "QProcessManager::sigchldHnd() (PID: " << proc->pid << "): reading " << nbytes << " bytes of pending data on stdout" << oendl; #endif process->socketRead( proc->socketStdout ); } nbytes = 0; if ( ::ioctl(proc->socketStderr, FIONREAD, (char*)&nbytes)==0 && nbytes>0 ) { #if defined(QT_QPROCESS_DEBUG) odebug << "QProcessManager::sigchldHnd() (PID: " << proc->pid << "): reading " << nbytes << " bytes of pending data on stderr" << oendl; #endif process->socketRead( proc->socketStderr ); } if ( process->notifyOnExit ) process_exit_notify = process; removeProc = TRUE; } } else { int status; if ( ::waitpid( proc->pid, &status, WNOHANG ) == proc->pid ) { #if defined(QT_QPROCESS_DEBUG) odebug << "QProcessManager::sigchldHnd() (PID: " << proc->pid << "): process exited (QProcess not available)" << oendl; #endif removeProc = TRUE; } } if ( removeProc ) { QProc *oldproc = proc; proc = procList->next(); remove( oldproc ); } else { proc = procList->next(); } if ( process_exit_notify ) emit process_exit_notify->processExited(); } } #include "qprocess_unix.moc" /*********************************************************************** * * QProcessPrivate * **********************************************************************/ QProcessManager *QProcessPrivate::procManager = 0; QProcessPrivate::QProcessPrivate() { #if defined(QT_QPROCESS_DEBUG) odebug << "QProcessPrivate: Constructor" << oendl; #endif stdinBufRead = 0; notifierStdin = 0; notifierStdout = 0; notifierStderr = 0; exitValuesCalculated = FALSE; socketReadCalled = FALSE; proc = 0; } QProcessPrivate::~QProcessPrivate() { #if defined(QT_QPROCESS_DEBUG) odebug << "QProcessPrivate: Destructor" << oendl; #endif if ( proc != 0 ) { if ( proc->socketStdin != 0 ) { ::close( proc->socketStdin ); proc->socketStdin = 0; } proc->process = 0; } while ( !stdinBuf.isEmpty() ) { delete stdinBuf.dequeue(); } delete notifierStdin; delete notifierStdout; delete notifierStderr; } /* Closes all open sockets in the child process that are not needed by the child process. Otherwise one child may have an open socket on standard input, etc. of another child. */ void QProcessPrivate::closeOpenSocketsForChild() { if ( procManager != 0 ) { if ( procManager->sigchldFd[0] != 0 ) ::close( procManager->sigchldFd[0] ); if ( procManager->sigchldFd[1] != 0 ) ::close( procManager->sigchldFd[1] ); // close also the sockets from other QProcess instances QProc *proc; for ( proc=procManager->procList->first(); proc!=0; proc=procManager->procList->next() ) { ::close( proc->socketStdin ); ::close( proc->socketStdout ); ::close( proc->socketStderr ); } } } void QProcessPrivate::newProc( pid_t pid, QProcess *process ) { proc = new QProc( pid, process ); if ( procManager == 0 ) { procManager = new QProcessManager; qprocess_cleanup_procmanager.add( &procManager ); } // the QProcessManager takes care of deleting the QProc instances procManager->append( proc ); } /*********************************************************************** * * sigchld handler callback * **********************************************************************/ QT_SIGNAL_RETTYPE qt_C_sigchldHnd( QT_SIGNAL_ARGS ) { if ( QProcessPrivate::procManager == 0 ) return; if ( QProcessPrivate::procManager->sigchldFd[0] == 0 ) return; char a = 1; ::write( QProcessPrivate::procManager->sigchldFd[0], &a, sizeof(a) ); } QT_SIGNAL_RETTYPE qt_C_sigpipeHnd( QT_SIGNAL_ARGS ) { // Ignore (but in a way somehow different to SIG_IGN). } /*********************************************************************** * * QProcess * **********************************************************************/ /*! This private class does basic initialization. */ void QProcess::init() { d = new QProcessPrivate(); exitStat = 0; exitNormal = FALSE; } /*! This private class resets the process variables, etc. so that it can be used for another process to start. */ void QProcess::reset() { delete d; d = new QProcessPrivate(); exitStat = 0; exitNormal = FALSE; d->bufStdout.resize( 0 ); d->bufStderr.resize( 0 ); } QByteArray* QProcess::bufStdout() { if ( d->proc && d->proc->socketStdout ) { // ### can this cause a blocking behaviour (maybe do a ioctl() to see // if data is available)? socketRead( d->proc->socketStdout ); } return &d->bufStdout; } QByteArray* QProcess::bufStderr() { if ( d->proc && d->proc->socketStderr ) { // ### can this cause a blocking behaviour (maybe do a ioctl() to see // if data is available)? socketRead( d->proc->socketStderr ); } return &d->bufStderr; } void QProcess::consumeBufStdout( int consume ) { uint n = d->bufStdout.size(); if ( consume==-1 || (uint)consume >= n ) { d->bufStdout.resize( 0 ); } else { QByteArray tmp( n - consume ); memcpy( tmp.data(), d->bufStdout.data()+consume, n-consume ); d->bufStdout = tmp; } } void QProcess::consumeBufStderr( int consume ) { uint n = d->bufStderr.size(); if ( consume==-1 || (uint)consume >= n ) { d->bufStderr.resize( 0 ); } else { QByteArray tmp( n - consume ); memcpy( tmp.data(), d->bufStderr.data()+consume, n-consume ); d->bufStderr = tmp; } } /*! Destroys the class. If the process is running, it is NOT terminated! Standard input, standard output and standard error of the process are closed. You can connect the destroyed() signal to the kill() slot, if you want the process to be terminated automatically when the class is destroyed. \sa tryTerminate() kill() */ QProcess::~QProcess() { delete d; } /*! Tries to run a process for the command and arguments that were specified with setArguments(), addArgument() or that were specified in the constructor. The command is searched in the path for executable programs; you can also use an absolute path to the command. If \a env is null, then the process is started with the same environment as the starting process. If \a env is non-null, then the values in the stringlist are interpreted as environment setttings of the form \c {key=value} and the process is started in these environment settings. For convenience, there is a small exception to this rule: under Unix, if \a env does not contain any settings for the environment variable \c LD_LIBRARY_PATH, then this variable is inherited from the starting process; under Windows the same applies for the enverionment varialbe \c PATH. Returns TRUE if the process could be started, otherwise FALSE. You can write data to standard input of the process with writeToStdin(), you can close standard input with closeStdin() and you can terminate the process tryTerminate() resp. kill(). You can call this function even when there already is a running process in this object. In this case, QProcess closes standard input of the old process and deletes pending data, i.e., you loose all control over that process, but the process is not terminated. This applies also if the process could not be started. (On operating systems that have zombie processes, Qt will also wait() on the old process.) \sa launch() closeStdin() */ bool QProcess::start( QStringList *env ) { #if defined(QT_QPROCESS_DEBUG) odebug << "QProcess::start()" << oendl; #endif reset(); int sStdin[2]; int sStdout[2]; int sStderr[2]; // open sockets for piping if ( (comms & Stdin) && ::socketpair( AF_UNIX, SOCK_STREAM, 0, sStdin ) == -1 ) { return FALSE; } if ( (comms & Stderr) && ::socketpair( AF_UNIX, SOCK_STREAM, 0, sStderr ) == -1 ) { return FALSE; } if ( (comms & Stdout) && ::socketpair( AF_UNIX, SOCK_STREAM, 0, sStdout ) == -1 ) { return FALSE; } // the following pipe is only used to determine if the process could be // started int fd[2]; if ( pipe( fd ) < 0 ) { // non critical error, go on fd[0] = 0; fd[1] = 0; } // construct the arguments for exec QCString *arglistQ = new QCString[ _arguments.count() + 1 ]; const char** arglist = new const char*[ _arguments.count() + 1 ]; int i = 0; for ( QStringList::Iterator it = _arguments.begin(); it != _arguments.end(); ++it ) { arglistQ[i] = (*it).local8Bit(); arglist[i] = arglistQ[i]; #if defined(QT_QPROCESS_DEBUG) odebug << "QProcess::start(): arg " << i << " = " << arglist[i] << "" << oendl; #endif i++; } arglist[i] = 0; // Must make sure signal handlers are installed before exec'ing // in case the process exits quickly. if ( d->procManager == 0 ) { d->procManager = new QProcessManager; qprocess_cleanup_procmanager.add( &d->procManager ); } // fork and exec QApplication::flushX(); pid_t pid = fork(); if ( pid == 0 ) { // child d->closeOpenSocketsForChild(); if ( comms & Stdin ) { ::close( sStdin[1] ); ::dup2( sStdin[0], STDIN_FILENO ); } if ( comms & Stdout ) { ::close( sStdout[0] ); ::dup2( sStdout[1], STDOUT_FILENO ); } if ( comms & Stderr ) { ::close( sStderr[0] ); ::dup2( sStderr[1], STDERR_FILENO ); } if ( comms & DupStderr ) { ::dup2( STDOUT_FILENO, STDERR_FILENO ); } #ifndef QT_NO_DIR ::chdir( workingDir.absPath().latin1() ); #endif if ( fd[0] ) ::close( fd[0] ); if ( fd[1] ) ::fcntl( fd[1], F_SETFD, FD_CLOEXEC ); // close on exec shows sucess if ( env == 0 ) { // inherit environment and start process ::execvp( arglist[0], (char*const*)arglist ); // ### cast not nice } else { // start process with environment settins as specified in env // construct the environment for exec int numEntries = env->count(); bool setLibraryPath = env->grep( QRegExp( "^LD_LIBRARY_PATH=" ) ).isEmpty() && getenv( "LD_LIBRARY_PATH" ) != 0; if ( setLibraryPath ) numEntries++; QCString *envlistQ = new QCString[ numEntries + 1 ]; const char** envlist = new const char*[ numEntries + 1 ]; int i = 0; if ( setLibraryPath ) { envlistQ[i] = QString( "LD_LIBRARY_PATH=%1" ).arg( getenv( "LD_LIBRARY_PATH" ) ).local8Bit(); envlist[i] = envlistQ[i]; i++; } for ( QStringList::Iterator it = env->begin(); it != env->end(); ++it ) { envlistQ[i] = (*it).local8Bit(); envlist[i] = envlistQ[i]; i++; } envlist[i] = 0; // look for the executable in the search path if ( _arguments.count()>0 && getenv("PATH")!=0 ) { QString command = _arguments[0]; if ( !command.contains( '/' ) ) { QStringList pathList = QStringList::split( ':', getenv( "PATH" ) ); for (QStringList::Iterator it = pathList.begin(); it != pathList.end(); ++it ) { QString dir = *it; #ifdef Q_OS_MACX if(QFile::exists(dir + "/" + command + ".app")) //look in a bundle dir += "/" + command + ".app/Contents/MacOS"; #endif #ifndef QT_NO_DIR QFileInfo fileInfo( dir, command ); #else QFileInfo fileInfo( dir + "/" + command ); #endif if ( fileInfo.isExecutable() ) { arglistQ[0] = fileInfo.filePath().local8Bit(); arglist[0] = arglistQ[0]; break; } } } } ::execve( arglist[0], (char*const*)arglist, (char*const*)envlist ); // ### casts not nice } if ( fd[1] ) { char buf = 0; ::write( fd[1], &buf, 1 ); ::close( fd[1] ); } ::exit( -1 ); } else if ( pid == -1 ) { // error forking goto error; } // test if exec was successful if ( fd[1] ) ::close( fd[1] ); if ( fd[0] ) { char buf; for ( ;; ) { int n = ::read( fd[0], &buf, 1 ); if ( n==1 ) { // socket was not closed => error d->proc = 0; goto error; } else if ( n==-1 ) { if ( errno==EAGAIN || errno==EINTR ) // try it again continue; } break; } ::close( fd[0] ); } d->newProc( pid, this ); if ( comms & Stdin ) { ::close( sStdin[0] ); d->proc->socketStdin = sStdin[1]; d->notifierStdin = new QSocketNotifier( sStdin[1], QSocketNotifier::Write ); connect( d->notifierStdin, SIGNAL(activated(int)), this, SLOT(socketWrite(int)) ); // setup notifiers for the sockets if ( !d->stdinBuf.isEmpty() ) { d->notifierStdin->setEnabled( TRUE ); } } if ( comms & Stdout ) { ::close( sStdout[1] ); d->proc->socketStdout = sStdout[0]; d->notifierStdout = new QSocketNotifier( sStdout[0], QSocketNotifier::Read ); connect( d->notifierStdout, SIGNAL(activated(int)), this, SLOT(socketRead(int)) ); if ( ioRedirection ) d->notifierStdout->setEnabled( TRUE ); } if ( comms & Stderr ) { ::close( sStderr[1] ); d->proc->socketStderr = sStderr[0]; d->notifierStderr = new QSocketNotifier( sStderr[0], QSocketNotifier::Read ); connect( d->notifierStderr, SIGNAL(activated(int)), this, SLOT(socketRead(int)) ); if ( ioRedirection ) d->notifierStderr->setEnabled( TRUE ); } // cleanup and return delete[] arglistQ; delete[] arglist; return TRUE; error: #if defined(QT_QPROCESS_DEBUG) odebug << "QProcess::start(): error starting process" << oendl; #endif if ( d->procManager ) d->procManager->cleanup(); if ( comms & Stdin ) { ::close( sStdin[1] ); ::close( sStdin[0] ); } if ( comms & Stdout ) { ::close( sStdout[0] ); ::close( sStdout[1] ); } if ( comms & Stderr ) { ::close( sStderr[0] ); ::close( sStderr[1] ); } ::close( fd[0] ); ::close( fd[1] ); delete[] arglistQ; delete[] arglist; return FALSE; } /*! Asks the process to terminate. Processes can ignore this wish. If you want to be sure that the process really terminates, you must use kill() instead. The slot returns immediately: it does not wait until the process has finished. When the process really exited, the signal processExited() is emitted. \sa kill() processExited() */ void QProcess::tryTerminate() const { if ( d->proc != 0 ) ::kill( d->proc->pid, SIGTERM ); } /*! Terminates the process. This is not a safe way to end a process since the process will not be able to do cleanup. tryTerminate() is a safer way to do it, but processes might ignore a tryTerminate(). The nice way to end a process and to be sure that it is finished, is doing something like this: \code process->tryTerminate(); QTimer::singleShot( 5000, process, SLOT( kill() ) ); \endcode This tries to terminate the process the nice way. If the process is still running after 5 seconds, it terminates the process the hard way. The timeout should be chosen depending on the time the process needs to do all the cleanup: use a higher value if the process is likely to do heavy computation on cleanup. The slot returns immediately: it does not wait until the process has finished. When the process really exited, the signal processExited() is emitted. \sa tryTerminate() processExited() */ void QProcess::kill() const { if ( d->proc != 0 ) ::kill( d->proc->pid, SIGKILL ); } /*! Returns TRUE if the process is running, otherwise FALSE. \sa normalExit() exitStatus() processExited() */ bool QProcess::isRunning() const { if ( d->exitValuesCalculated ) { #if defined(QT_QPROCESS_DEBUG) odebug << "QProcess::isRunning(): FALSE (already computed)" << oendl; #endif return FALSE; } if ( d->proc == 0 ) return FALSE; int status; if ( ::waitpid( d->proc->pid, &status, WNOHANG ) == d->proc->pid ) { // compute the exit values QProcess *that = (QProcess*)this; // mutable that->exitNormal = WIFEXITED( status ) != 0; if ( exitNormal ) { that->exitStat = (char)WEXITSTATUS( status ); } d->exitValuesCalculated = TRUE; #if defined(QT_QPROCESS_DEBUG) odebug << "QProcess::isRunning() (PID: " << d->proc->pid << "): FALSE" << oendl; #endif return FALSE; } #if defined(QT_QPROCESS_DEBUG) odebug << "QProcess::isRunning() (PID: " << d->proc->pid << "): TRUE" << oendl; #endif return TRUE; } /*! Writes the data \a buf to the standard input of the process. The process may or may not read this data. This function returns immediately; the QProcess class might write the data at a later point (you have to enter the event loop for that). When all the data is written to the process, the signal wroteToStdin() is emitted. This does not mean that the process really read the data, since this class only detects when it was able to write the data to the operating system. \sa wroteToStdin() closeStdin() readStdout() readStderr() */ void QProcess::writeToStdin( const QByteArray& buf ) { #if defined(QT_QPROCESS_DEBUG) // odebug << "QProcess::writeToStdin(): write to stdin (" << d->socketStdin << ")" << oendl; #endif d->stdinBuf.enqueue( new QByteArray(buf) ); if ( d->notifierStdin != 0 ) d->notifierStdin->setEnabled( TRUE ); } /*! Closes standard input of the process. This function also deletes pending data that is not written to standard input yet. \sa wroteToStdin() */ void QProcess::closeStdin() { if ( d->proc == 0 ) return; if ( d->proc->socketStdin !=0 ) { while ( !d->stdinBuf.isEmpty() ) { delete d->stdinBuf.dequeue(); } delete d->notifierStdin; d->notifierStdin = 0; if ( ::close( d->proc->socketStdin ) != 0 ) { owarn << "Could not close stdin of child process" << oendl; } #if defined(QT_QPROCESS_DEBUG) odebug << "QProcess::closeStdin(): stdin (" << d->proc->socketStdin << ") closed" << oendl; #endif d->proc->socketStdin = 0; } } /* This private slot is called when the process has outputted data to either standard output or standard error. */ void QProcess::socketRead( int fd ) { if ( d->socketReadCalled ) { // the slots that are connected to the readyRead...() signals might // trigger a recursive call of socketRead(). Avoid this since you get a // blocking read otherwise. return; } #if defined(QT_QPROCESS_DEBUG) odebug << "QProcess::socketRead(): " << fd << "" << oendl; #endif if ( fd == 0 ) return; const int bufsize = 4096; QByteArray *buffer = 0; uint oldSize; int n; if ( fd == d->proc->socketStdout ) { buffer = &d->bufStdout; } else if ( fd == d->proc->socketStderr ) { buffer = &d->bufStderr; } else { // this case should never happen, but just to be safe return; } // read data oldSize = buffer->size(); buffer->resize( oldSize + bufsize ); n = ::read( fd, buffer->data()+oldSize, bufsize ); if ( n > 0 ) buffer->resize( oldSize + n ); else buffer->resize( oldSize ); // eof or error? if ( n == 0 || n == -1 ) { if ( fd == d->proc->socketStdout ) { #if defined(QT_QPROCESS_DEBUG) odebug << "QProcess::socketRead(): stdout (" << fd << ") closed" << oendl; #endif d->notifierStdout->setEnabled( FALSE ); delete d->notifierStdout; d->notifierStdout = 0; ::close( d->proc->socketStdout ); d->proc->socketStdout = 0; return; } else if ( fd == d->proc->socketStderr ) { #if defined(QT_QPROCESS_DEBUG) odebug << "QProcess::socketRead(): stderr (" << fd << ") closed" << oendl; #endif d->notifierStderr->setEnabled( FALSE ); delete d->notifierStderr; d->notifierStderr = 0; ::close( d->proc->socketStderr ); d->proc->socketStderr = 0; return; } } // read all data that is available while ( n == bufsize ) { oldSize = buffer->size(); buffer->resize( oldSize + bufsize ); n = ::read( fd, buffer->data()+oldSize, bufsize ); if ( n > 0 ) buffer->resize( oldSize + n ); else buffer->resize( oldSize ); } d->socketReadCalled = TRUE; if ( fd == d->proc->socketStdout ) { #if defined(QT_QPROCESS_DEBUG) odebug << "QProcess::socketRead(): " << buffer->size()-oldSize << "bytes read from stdout (" << fd << ")" << oendl; #endif emit readyReadStdout(); } else if ( fd == d->proc->socketStderr ) { #if defined(QT_QPROCESS_DEBUG) odebug << "QProcess::socketRead(): " << buffer->size()-oldSize << " bytes read from stderr (" << fd << ")" << oendl; #endif emit readyReadStderr(); } d->socketReadCalled = FALSE; } /* This private slot is called when the process tries to read data from standard input. */ void QProcess::socketWrite( int fd ) { if ( fd != d->proc->socketStdin || d->proc->socketStdin == 0 ) return; if ( d->stdinBuf.isEmpty() ) { d->notifierStdin->setEnabled( FALSE ); return; } #if defined(QT_QPROCESS_DEBUG) odebug << "QProcess::socketWrite(): write to stdin (" << fd << ")" << oendl; #endif ssize_t ret = ::write( fd, d->stdinBuf.head()->data() + d->stdinBufRead, d->stdinBuf.head()->size() - d->stdinBufRead ); if ( ret > 0 ) d->stdinBufRead += ret; if ( d->stdinBufRead == (ssize_t)d->stdinBuf.head()->size() ) { d->stdinBufRead = 0; delete d->stdinBuf.dequeue(); if ( wroteToStdinConnected && d->stdinBuf.isEmpty() ) emit wroteToStdin(); socketWrite( fd ); } } /*! \internal Flushes standard input. This is useful if you want to use QProcess in a synchronous manner. This function should probably go into the public API. */ void QProcess::flushStdin() { socketWrite( d->proc->socketStdin ); } /* This private slot is only used under Windows (but moc does not know about #if defined()). */ void QProcess::timeout() { } /* This private function is used by connectNotify() and disconnectNotify() to change the value of ioRedirection (and related behaviour) */ void QProcess::setIoRedirection( bool value ) { ioRedirection = value; if ( ioRedirection ) { if ( d->notifierStdout ) d->notifierStdout->setEnabled( TRUE ); if ( d->notifierStderr ) d->notifierStderr->setEnabled( TRUE ); } else { if ( d->notifierStdout ) d->notifierStdout->setEnabled( FALSE ); if ( d->notifierStderr ) d->notifierStderr->setEnabled( FALSE ); } } /* This private function is used by connectNotify() and disconnectNotify() to change the value of notifyOnExit (and related behaviour) */ void QProcess::setNotifyOnExit( bool value ) { notifyOnExit = value; } /* This private function is used by connectNotify() and disconnectNotify() to change the value of wroteToStdinConnected (and related behaviour) */ void QProcess::setWroteStdinConnected( bool value ) { wroteToStdinConnected = value; } /*! \enum QProcess::PID \internal */ /*! Returns platform dependent information about the process. This can be used together with platform specific system calls. Under Unix the return value is the PID of the process, or -1 if no process is belonging to this object. Under Windows it is a pointer to the \c PROCESS_INFORMATION struct, or 0 if no process is belonging to this object. */ QProcess::PID QProcess::processIdentifier() { if ( d->proc == 0 ) return -1; return d->proc->pid; } int QProcess::priority() const { if ( d->proc ) return getpriority(PRIO_PROCESS,d->proc->pid); return 0; } void QProcess::setPriority(int p) { if ( d->proc ) setpriority(PRIO_PROCESS,d->proc->pid,p); } #endif // QT_NO_PROCESS diff --git a/core/launcher/server.cpp b/core/launcher/server.cpp index 921b790..c45265a 100644 --- a/core/launcher/server.cpp +++ b/core/launcher/server.cpp @@ -1,1006 +1,1015 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the 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 "server.h" #include "serverapp.h" #include "startmenu.h" #include "launcher.h" #include "transferserver.h" #include "qcopbridge.h" #include "irserver.h" #include "packageslave.h" #include "calibrate.h" #include "qrsync.h" #include "syncdialog.h" #include "shutdownimpl.h" #include "applauncher.h" #if 0 #include "suspendmonitor.h" #endif #include "documentlist.h" #include "qrr.h" /* OPIE */ #include <opie2/odebug.h> #include <opie2/odevicebutton.h> #include <opie2/odevice.h> #include <opie2/oprocess.h> #include <qtopia/applnk.h> #include <qtopia/private/categories.h> #include <qtopia/mimetype.h> #include <qtopia/config.h> #include <qtopia/resource.h> #include <qtopia/version.h> #include <qtopia/storage.h> #include <qtopia/qcopenvelope_qws.h> #include <qtopia/global.h> using namespace Opie::Core; /* QT */ #include <qmainwindow.h> #include <qmessagebox.h> #include <qtimer.h> #include <qtextstream.h> #include <qwindowsystem_qws.h> #include <qgfx_qws.h> /* STD */ #include <unistd.h> #include <stdlib.h> extern QRect qt_maxWindowRect; static QWidget *calibrate(bool) { #ifdef Q_WS_QWS Calibrate *c = new Calibrate; c->show(); return c; #else return 0; #endif } #define FACTORY(T) \ static QWidget *new##T( bool maximized ) { \ QWidget *w = new T( 0, 0, QWidget::WDestructiveClose | QWidget::WGroupLeader ); \ if ( maximized ) { \ if ( qApp->desktop()->width() <= 350 ) { \ w->showMaximized(); \ } else { \ w->resize( QSize( 300, 300 ) ); \ } \ } \ w->show(); \ return w; \ } #ifdef SINGLE_APP #define APP(a,b,c,d) FACTORY(b) #include "apps.h" #undef APP #endif // SINGLE_APP static Global::Command builtins[] = { #ifdef SINGLE_APP #define APP(a,b,c,d) { a, new##b, c, d }, #include "apps.h" #undef APP #endif /* FIXME defines need to be defined*/ #if !defined(OPIE_NO_BUILTIN_CALIBRATE) { "calibrate", calibrate, 1, 0 }, // No tr #endif #if !defined(OPIE_NO_BUILTIN_SHUTDOWN) { "shutdown", Global::shutdown, 1, 0 }, // No tr // { "run", run, 1, 0 }, // No tr #endif { 0, calibrate, 0, 0 }, }; #ifdef QPE_HAVE_DIRECT_ACCESS extern void readyDirectAccess(QString cardInfo, QString installLocations); extern const char *directAccessQueueFile(); #endif //--------------------------------------------------------------------------- //=========================================================================== Server::Server() : QWidget( 0, 0, WStyle_Tool | WStyle_Customize ), qcopBridge( 0 ), transferServer( 0 ), packageHandler( 0 ), syncDialog( 0 ), process( 0 ) { Global::setBuiltinCommands(builtins); tid_xfer = 0; /* ### FIXME ### */ /* tid_today = startTimer(3600*2*1000);*/ last_today_show = QDate::currentDate(); #warning FIXME support TempScreenSaverMode #if 0 tsmMonitor = new TempScreenSaverMode(); connect( tsmMonitor, SIGNAL(forceSuspend()), qApp, SIGNAL(power()) ); #endif serverGui = new Launcher; serverGui->createGUI(); docList = new DocumentList( serverGui ); appLauncher = new AppLauncher(this); connect(appLauncher, SIGNAL(launched(int,const QString&)), this, SLOT(applicationLaunched(int,const QString&)) ); connect(appLauncher, SIGNAL(terminated(int,const QString&)), this, SLOT(applicationTerminated(int,const QString&)) ); connect(appLauncher, SIGNAL(connected(const QString&)), this, SLOT(applicationConnected(const QString&)) ); storage = new StorageInfo( this ); connect( storage, SIGNAL(disksChanged()), this, SLOT(storageChanged()) ); #ifdef QPE_HAVE_DIRECT_ACCESS QCopChannel *desktopChannel = new QCopChannel( "QPE/Desktop", this ); connect( desktopChannel, SIGNAL(received( const QCString &, const QByteArray & )), this, SLOT(desktopMessage( const QCString &, const QByteArray & )) ); #endif soundServerExited(); // start services startTransferServer(); (void) new IrServer( this ); packageHandler = new PackageHandler( this ); connect(qApp, SIGNAL(activate(const Opie::Core::ODeviceButton*,bool)), this,SLOT(activate(const Opie::Core::ODeviceButton*,bool))); setGeometry( -10, -10, 9, 9 ); QCopChannel *channel = new QCopChannel("QPE/System", this); connect(channel, SIGNAL(received(const QCString&,const QByteArray&)), this, SLOT(systemMsg(const QCString&,const QByteArray&)) ); QCopChannel *tbChannel = new QCopChannel( "QPE/TaskBar", this ); connect( tbChannel, SIGNAL(received(const QCString&,const QByteArray&)), this, SLOT(receiveTaskBar(const QCString&,const QByteArray&)) ); connect( qApp, SIGNAL(prepareForRestart()), this, SLOT(terminateServers()) ); connect( qApp, SIGNAL(timeChanged()), this, SLOT(pokeTimeMonitors()) ); preloadApps(); } void Server::show() { ServerApplication::login(TRUE); QWidget::show(); } Server::~Server() { serverGui->destroyGUI(); delete docList; delete qcopBridge; delete transferServer; delete serverGui; #if 0 delete tsmMonitor; #endif } static bool hasVisibleWindow(const QString& clientname, bool partial) { #ifdef QWS const QList<QWSWindow> &list = qwsServer->clientWindows(); QWSWindow* w; for (QListIterator<QWSWindow> it(list); (w=it.current()); ++it) { if ( w->client()->identity() == clientname ) { if ( partial && !w->isFullyObscured() ) return TRUE; if ( !partial && !w->isFullyObscured() && !w->isPartiallyObscured() ) { # if QT_VERSION < 0x030000 QRect mwr = qt_screen->mapToDevice(qt_maxWindowRect, QSize(qt_screen->width(),qt_screen->height()) ); # else QRect mwr = qt_maxWindowRect; # endif if ( mwr.contains(w->requested().boundingRect()) ) return TRUE; } } } #endif return FALSE; } void Server::activate(const ODeviceButton* button, bool held) { Global::terminateBuiltin("calibrate"); // No tr OQCopMessage om; if ( held ) { om = button->heldAction(); } else { om = button->pressedAction(); } if ( om.channel() != "ignore" ) om.send(); // A button with no action defined, will return a null ServiceRequest. Don't attempt // to send/do anything with this as it will crash /* ### FIXME */ #if 0 if ( !sr.isNull() ) { QString app = sr.app(); bool vis = hasVisibleWindow(app, app != "qpe"); if ( sr.message() == "raise()" && vis ) { sr.setMessage("nextView()"); } else { // "back door" sr << (int)vis; } sr.send(); } #endif } #ifdef Q_WS_QWS typedef struct KeyOverride { ushort scan_code; QWSServer::KeyMap map; }; static const KeyOverride jp109keys[] = { { 0x03, { Qt::Key_2, '2' , 0x22 , 0xffff } }, { 0x07, { Qt::Key_6, '6' , '&' , 0xffff } }, { 0x08, { Qt::Key_7, '7' , '\'' , 0xffff } }, { 0x09, { Qt::Key_8, '8' , '(' , 0xffff } }, { 0x0a, { Qt::Key_9, '9' , ')' , 0xffff } }, { 0x0b, { Qt::Key_0, '0' , 0xffff, 0xffff } }, { 0x0c, { Qt::Key_Minus, '-' , '=' , 0xffff } }, { 0x0d, { Qt::Key_AsciiCircum, '^' , '~' , '^'-64 } }, { 0x1a, { Qt::Key_At, '@' , '`' , 0xffff } }, { 0x1b, { Qt::Key_BraceLeft, '[' , '{' , '['-64 } }, { 0x27, { Qt::Key_Semicolon, ';' , '+' , 0xffff } }, { 0x28, { Qt::Key_Colon, ':' , '*' , 0xffff } }, { 0x29, { Qt::Key_Zenkaku_Hankaku, 0xffff, 0xffff, 0xffff } }, { 0x2b, { Qt::Key_BraceRight, ']' , '}' , ']'-64 } }, { 0x70, { Qt::Key_Hiragana_Katakana, 0xffff, 0xffff, 0xffff } }, { 0x73, { Qt::Key_Backslash, '\\' , '_' , 0xffff } }, { 0x79, { Qt::Key_Henkan, 0xffff, 0xffff, 0xffff } }, { 0x7b, { Qt::Key_Muhenkan, 0xffff, 0xffff, 0xffff } }, { 0x7d, { Qt::Key_yen, 0x00a5, '|' , 0xffff } }, { 0x00, { 0, 0xffff, 0xffff, 0xffff } } }; bool Server::setKeyboardLayout( const QString &kb ) { //quick demo version that can be extended QIntDict<QWSServer::KeyMap> *om = 0; if ( kb == "us101" ) { // No tr om = 0; } else if ( kb == "jp109" ) { om = new QIntDict<QWSServer::KeyMap>(37); const KeyOverride *k = jp109keys; while ( k->scan_code ) { om->insert( k->scan_code, &k->map ); k++; } } QWSServer::setOverrideKeys( om ); return TRUE; } #endif void Server::systemMsg(const QCString &msg, const QByteArray &data) { QDataStream stream( data, IO_ReadOnly ); if ( msg == "securityChanged()" ) { if ( transferServer ) transferServer->authorizeConnections(); if ( qcopBridge ) qcopBridge->authorizeConnections(); #warning FIXME support TempScreenSaverMode #if 0 } else if ( msg == "setTempScreenSaverMode(int,int)" ) { int mode, pid; stream >> mode >> pid; tsmMonitor->setTempMode(mode, pid); #endif } else if ( msg == "linkChanged(QString)" ) { QString link; stream >> link; odebug << "desktop.cpp systemMsg -> linkchanged( " << link << " )" << oendl; docList->linkChanged(link); } else if (msg =="reforceDocuments()") { docList->reforceDocuments(); } else if ( msg == "serviceChanged(QString)" ) { MimeType::updateApplications(); } else if ( msg == "mkdir(QString)" ) { QString dir; stream >> dir; if ( !dir.isEmpty() ) mkdir( dir ); } else if ( msg == "rdiffGenSig(QString,QString)" ) { QString baseFile, sigFile; stream >> baseFile >> sigFile; QRsync::generateSignature( baseFile, sigFile ); } else if ( msg == "rdiffGenDiff(QString,QString,QString)" ) { QString baseFile, sigFile, deltaFile; stream >> baseFile >> sigFile >> deltaFile; QRsync::generateDiff( baseFile, sigFile, deltaFile ); } else if ( msg == "rdiffApplyPatch(QString,QString)" ) { QString baseFile, deltaFile; stream >> baseFile >> deltaFile; + bool fileWasCreated = false; if ( !QFile::exists( baseFile ) ) { QFile f( baseFile ); - f.open( IO_WriteOnly ); + fileWasCreated = f.open( IO_WriteOnly ); f.close(); } - QRsync::applyDiff( baseFile, deltaFile ); + if ( fileWasCreated ) { + QRsync::applyDiff( baseFile, deltaFile ); #ifndef QT_NO_COP - QCopEnvelope e( "QPE/Desktop", "patchApplied(QString)" ); - e << baseFile; + QCopEnvelope e( "QPE/Desktop", "patchApplied(QString)" ); + e << baseFile; #endif + } else { +#ifndef QT_NO_COP + QCopEnvelope e( "QPE/Desktop", "patchUnapplied(QString)" ); + e << baseFile; +#endif + } } else if ( msg == "rdiffCleanup()" ) { mkdir( "/tmp/rdiff" ); QDir dir; dir.setPath( "/tmp/rdiff" ); QStringList entries = dir.entryList(); for ( QStringList::Iterator it = entries.begin(); it != entries.end(); ++it ) dir.remove( *it ); } else if ( msg == "sendHandshakeInfo()" ) { QString home = getenv( "HOME" ); #ifndef QT_NO_COP QCopEnvelope e( "QPE/Desktop", "handshakeInfo(QString,bool)" ); e << home; int locked = (int) ServerApplication::screenLocked(); e << locked; #endif } else if ( msg == "sendVersionInfo()" ) { /* * @&$*! Qtopiadesktop relies on the major number * to start with 1. (or 2 as the case of version 2.1 will be) * we need to fake 1.7 to be able * to sync with Qtopiadesktop 1.7. * We'll send it Opie's version in the platform string for now, * until such time when QD gets rewritten correctly. */ QCopEnvelope e( "QPE/Desktop", "versionInfo(QString,QString)" ); QString opiename = "Opie "+QString(QPE_VERSION); QString QDVersion="1.7"; e << QDVersion << opiename; } else if ( msg == "sendCardInfo()" ) { #ifndef QT_NO_COP QCopEnvelope e( "QPE/Desktop", "cardInfo(QString)" ); #endif storage->update(); const QList<FileSystem> &fs = storage->fileSystems(); QListIterator<FileSystem> it ( fs ); QString s; QString homeDir = getenv("HOME"); QString homeFs, homeFsPath; for ( ; it.current(); ++it ) { int k4 = (*it)->blockSize()/256; if ( (*it)->isRemovable() ) { s += (*it)->name() + "=" + (*it)->path() + "/Documents " // No tr + QString::number( (*it)->availBlocks() * k4/4 ) + "K " + (*it)->options() + ";"; } else if ( homeDir.contains( (*it)->path() ) && (*it)->path().length() > homeFsPath.length() ) { homeFsPath = (*it)->path(); homeFs = (*it)->name() + "=" + homeDir + "/Documents " // No tr + QString::number( (*it)->availBlocks() * k4/4 ) + "K " + (*it)->options() + ";"; } } if ( !homeFs.isEmpty() ) s += homeFs; #ifndef QT_NO_COP e << s; #endif } else if ( msg == "sendInstallLocations()" ) { #ifndef QT_NO_COP QCopEnvelope e( "QPE/Desktop", "installLocations(QString)" ); e << installLocationsString(); #endif } else if ( msg == "sendSyncDate(QString)" ) { QString app; stream >> app; Config cfg( "qpe" ); cfg.setGroup("SyncDate"); #ifndef QT_NO_COP QCopEnvelope e( "QPE/Desktop", "syncDate(QString,QString)" ); e << app << cfg.readEntry( app ); #endif //odebug << "QPE/System sendSyncDate for " << app.latin1() << ": response " // << cfg.readEntry( app ).latin1() << oendl; } else if ( msg == "setSyncDate(QString,QString)" ) { QString app, date; stream >> app >> date; Config cfg( "qpe" ); cfg.setGroup("SyncDate"); cfg.writeEntry( app, date ); //odebug << "setSyncDate(QString,QString) " << app << " " << date << "" << oendl; } else if ( msg == "startSync(QString)" ) { QString what; stream >> what; delete syncDialog; syncDialog = new SyncDialog( this, what ); syncDialog->show(); connect( syncDialog, SIGNAL(cancel()), SLOT(cancelSync()) ); } else if ( msg == "stopSync()") { delete syncDialog; syncDialog = 0; } else if (msg == "restoreDone(QString)") { docList->restoreDone(); } else if ( msg == "getAllDocLinks()" ) { docList->sendAllDocLinks(); } #ifdef QPE_HAVE_DIRECT_ACCESS else if ( msg == "prepareDirectAccess()" ) { prepareDirectAccess(); } else if ( msg == "postDirectAccess()" ) { postDirectAccess(); } #endif #ifdef Q_WS_QWS else if ( msg == "setMouseProto(QString)" ) { QString mice; stream >> mice; setenv("QWS_MOUSE_PROTO",mice.latin1(),1); qwsServer->openMouse(); } else if ( msg == "setKeyboard(QString)" ) { QString kb; stream >> kb; setenv("QWS_KEYBOARD",kb.latin1(),1); qwsServer->openKeyboard(); } else if ( msg == "setKeyboardAutoRepeat(int,int)" ) { int delay, period; stream >> delay >> period; qwsSetKeyboardAutoRepeat( delay, period ); Config cfg( "qpe" ); cfg.setGroup("Keyboard"); cfg.writeEntry( "RepeatDelay", delay ); cfg.writeEntry( "RepeatPeriod", period ); } else if ( msg == "setKeyboardLayout(QString)" ) { QString kb; stream >> kb; setKeyboardLayout( kb ); Config cfg( "qpe" ); cfg.setGroup("Keyboard"); cfg.writeEntry( "Layout", kb ); } else if ( msg == "autoStart(QString)" ) { QString appName; stream >> appName; Config cfg( "autostart" ); cfg.setGroup( "AutoStart" ); if ( appName.compare("clear") == 0){ cfg.writeEntry("Apps", ""); } } else if ( msg == "autoStart(QString,QString)" ) { QString modifier, appName; stream >> modifier >> appName; Config cfg( "autostart" ); cfg.setGroup( "AutoStart" ); if ( modifier.compare("add") == 0 ){ // only add if appname is entered if (!appName.isEmpty()) { cfg.writeEntry("Apps", appName); } } else if (modifier.compare("remove") == 0 ) { // need to change for multiple entries // actually remove is right now simular to clear, but in future there // should be multiple apps in autostart possible. QString checkName; checkName = cfg.readEntry("Apps", ""); if (checkName == appName) { cfg.writeEntry("Apps", ""); } } // case the autostart feature should be delayed } else if ( msg == "autoStart(QString,QString,QString)") { QString modifier, appName, delay; stream >> modifier >> appName >> delay; Config cfg( "autostart" ); cfg.setGroup( "AutoStart" ); if ( modifier.compare("add") == 0 ){ // only add it appname is entered if (!appName.isEmpty()) { cfg.writeEntry("Apps", appName); cfg.writeEntry("Delay", delay); } } } #endif } QString Server::cardInfoString() { storage->update(); const QList<FileSystem> &fs = storage->fileSystems(); QListIterator<FileSystem> it ( fs ); QString s; QString homeDir = getenv("HOME"); QString homeFs, homeFsPath; for ( ; it.current(); ++it ) { int k4 = (*it)->blockSize()/256; if ( (*it)->isRemovable() ) { s += (*it)->name() + "=" + (*it)->path() + "/Documents " // No tr + QString::number( (*it)->availBlocks() * k4/4 ) + "K " + (*it)->options() + ";"; } else if ( homeDir.contains( (*it)->path() ) && (*it)->path().length() > homeFsPath.length() ) { homeFsPath = (*it)->path(); homeFs = (*it)->name() + "=" + homeDir + "/Documents " // No tr + QString::number( (*it)->availBlocks() * k4/4 ) + "K " + (*it)->options() + ";"; } } if ( !homeFs.isEmpty() ) s += homeFs; return s; } QString Server::installLocationsString() { storage->update(); const QList<FileSystem> &fs = storage->fileSystems(); QListIterator<FileSystem> it ( fs ); QString s; QString homeDir = getenv("HOME"); QString homeFs, homeFsPath; for ( ; it.current(); ++it ) { int k4 = (*it)->blockSize()/256; if ( (*it)->isRemovable() ) { s += (*it)->name() + "=" + (*it)->path() + " " // No tr + QString::number( (*it)->availBlocks() * k4/4 ) + "K " + (*it)->options() + ";"; } else if ( homeDir.contains( (*it)->path() ) && (*it)->path().length() > homeFsPath.length() ) { homeFsPath = (*it)->path(); homeFs = (*it)->name() + "=" + homeDir + " " // No tr + QString::number( (*it)->availBlocks() * k4/4 ) + "K " + (*it)->options() + ";"; } } if ( !homeFs.isEmpty() ) s = homeFs + s; return s; } void Server::receiveTaskBar(const QCString &msg, const QByteArray &data) { QDataStream stream( data, IO_ReadOnly ); if ( msg == "reloadApps()" ) { docList->reloadAppLnks(); } else if ( msg == "soundAlarm()" ) { ServerApplication::soundAlarm(); } else if ( msg == "setLed(int,bool)" ) { int led, status; stream >> led >> status; QValueList <OLed> ll = ODevice::inst ( )-> ledList ( ); if ( ll. count ( )) { OLed l = ll. contains ( Led_Mail ) ? Led_Mail : ll [0]; bool canblink = ODevice::inst ( )-> ledStateList ( l ). contains ( Led_BlinkSlow ); ODevice::inst ( )-> setLedState ( l, status ? ( canblink ? Led_BlinkSlow : Led_On ) : Led_Off ); } } } void Server::cancelSync() { #ifndef QT_NO_COP QCopEnvelope e( "QPE/Desktop", "cancelSync()" ); #endif delete syncDialog; syncDialog = 0; } bool Server::mkdir(const QString &localPath) { QDir fullDir(localPath); if (fullDir.exists()) return true; // at this point the directory doesn't exist // go through the directory tree and start creating the direcotories // that don't exist; if we can't create the directories, return false QString dirSeps = "/"; int dirIndex = localPath.find(dirSeps); QString checkedPath; // didn't find any seps; weird, use the cur dir instead if (dirIndex == -1) { //odebug << "No seperators found in path " << localPath << "" << oendl; checkedPath = QDir::currentDirPath(); } while (checkedPath != localPath) { // no more seperators found, use the local path if (dirIndex == -1) { checkedPath = localPath; } else { // the next directory to check checkedPath = localPath.left(dirIndex) + "/"; // advance the iterator; the next dir seperator dirIndex = localPath.find(dirSeps, dirIndex+1); } QDir checkDir(checkedPath); if (!checkDir.exists()) { //odebug << "mkdir making dir " << checkedPath << "" << oendl; if (!checkDir.mkdir(checkedPath)) { odebug << "Unable to make directory " << checkedPath << "" << oendl; return FALSE; } } } return TRUE; } void Server::styleChange( QStyle &s ) { QWidget::styleChange( s ); } void Server::startTransferServer() { if ( !qcopBridge ) { // start qcop bridge server qcopBridge = new QCopBridge( 4243 ); if ( qcopBridge->ok() ) { // ... OK connect( qcopBridge, SIGNAL(connectionClosed(const QHostAddress&)), this, SLOT(syncConnectionClosed(const QHostAddress&)) ); } else { delete qcopBridge; qcopBridge = 0; } } if ( !transferServer ) { // start transfer server transferServer = new TransferServer( 4242 ); if ( transferServer->ok() ) { // ... OK } else { delete transferServer; transferServer = 0; } if ( !qcopBridge ) tid_xfer = startTimer( 2000 ); } } void Server::timerEvent( QTimerEvent *e ) { if ( e->timerId() == tid_xfer ) { killTimer( tid_xfer ); tid_xfer = 0; startTransferServer(); } #if 0 /* ### FIXME today startin */ else if ( e->timerId() == tid_today ) { QDate today = QDate::currentDate(); if ( today != last_today_show ) { last_today_show = today; Config cfg("today"); cfg.setGroup("Start"); #ifndef QPE_DEFAULT_TODAY_MODE #define QPE_DEFAULT_TODAY_MODE "Never" #endif if ( cfg.readEntry("Mode",QPE_DEFAULT_TODAY_MODE) == "Daily" ) { QCopEnvelope env(Service::channel("today"),"raise()"); } } } #endif } void Server::terminateServers() { delete transferServer; delete qcopBridge; transferServer = 0; qcopBridge = 0; } void Server::syncConnectionClosed( const QHostAddress & ) { odebug << "Lost sync connection" << oendl; delete syncDialog; syncDialog = 0; } void Server::pokeTimeMonitors() { #if 0 // inform all TimeMonitors QStrList tms = Service::channels("TimeMonitor"); for (const char* ch = tms.first(); ch; ch=tms.next()) { QString t = getenv("TZ"); QCopEnvelope e(ch, "timeChange(QString)"); e << t; } #endif } void Server::applicationLaunched(int, const QString &app) { serverGui->applicationStateChanged( app, ServerInterface::Launching ); } void Server::applicationTerminated(int pid, const QString &app) { serverGui->applicationStateChanged( app, ServerInterface::Terminated ); #if 0 tsmMonitor->applicationTerminated( pid ); #else Q_UNUSED( pid ) #endif } void Server::applicationConnected(const QString &app) { serverGui->applicationStateChanged( app, ServerInterface::Running ); } void Server::storageChanged() { system( "opie-update-symlinks" ); serverGui->storageChanged( storage->fileSystems() ); docList->storageChanged(); } void Server::preloadApps() { Config cfg("Launcher"); cfg.setGroup("Preload"); QStringList apps = cfg.readListEntry("Apps",','); for (QStringList::ConstIterator it=apps.begin(); it!=apps.end(); ++it) { #ifndef QT_NO_COP QCopEnvelope e("QPE/Application/"+(*it).local8Bit(), "enablePreload()"); #endif } } // This is only called if QPE_HAVE_DIRECT_ACCESS is defined void Server::prepareDirectAccess() { qDebug( "Server::prepareDirectAccess()" ); // Put up a pretty dialog syncDialog = new SyncDialog( this, tr("USB Lock") ); syncDialog->show(); // Prevent the PDA from acting as a PDA terminateServers(); // suspend the mtab monitor #ifndef QT_NO_COP { QCopEnvelope e( "QPE/Stabmon", "suspendMonitor()" ); } #endif // send out a flush message // once flushes are done call runDirectAccess() // We just count the number of apps and set a timer. // Either the timer expires or the correct number of apps responds. // Note: quicklauncher isn't in the runningApps list but it responds // to the flush so we start the counter at 1 pendingFlushes = 1; directAccessRun = FALSE; for ( QMap<int,QString>::ConstIterator it = appLauncher->runningApplications().begin(); it != appLauncher->runningApplications().end(); ++it ) { pendingFlushes++; } #ifndef QT_NO_COP QCopEnvelope e1( "QPE/System", "flush()" ); #endif QTimer::singleShot( 10000, this, SLOT(runDirectAccess()) ); #warning FIXME support TempScreenSaverMode #if 0 QPEApplication::setTempScreenSaverMode(QPEApplication::DisableSuspend); #endif } // This is only connected if QPE_HAVE_DIRECT_ACCESS is defined // It fakes the presence of Qtopia Desktop void Server::desktopMessage( const QCString &message, const QByteArray &data ) { QDataStream stream( data, IO_ReadOnly ); if ( message == "flushDone(QString)" ) { QString app; stream >> app; qDebug( "flushDone from %s", app.latin1() ); if ( --pendingFlushes == 0 ) { qDebug( "pendingFlushes == 0, all the apps responded" ); runDirectAccess(); } } else if ( message == "installStarted(QString)" ) { QString package; stream >> package; qDebug( "\tInstall Started for package %s", package.latin1() ); } else if ( message == "installStep(QString)" ) { QString step; stream >> step; qDebug( "\tInstall Step %s", step.latin1() ); } else if ( message == "installDone(QString)" ) { QString package; stream >> package; qDebug( "\tInstall Finished for package %s", package.latin1() ); } else if ( message == "installFailed(QString,int,QString)" ) { QString package, error; int status; stream >> package >> status >> error; qDebug( "\tInstall Failed for package %s with error code %d and error message %s", package.latin1(), status, error.latin1() ); } else if ( message == "removeStarted(QString)" ) { QString package; stream >> package; qDebug( "\tRemove Started for package %s", package.latin1() ); } else if ( message == "removeDone(QString)" ) { QString package; stream >> package; qDebug( "\tRemove Finished for package %s", package.latin1() ); } else if ( message == "removeFailed(QString)" ) { QString package; stream >> package; qDebug( "\tRemove Failed for package %s", package.latin1() ); } if ( qrr && qrr->waitingForMessages ) qrr->desktopMessage( message, data ); } // This is only connected if QPE_HAVE_DIRECT_ACCESS is defined void Server::runDirectAccess() { #ifdef QPE_HAVE_DIRECT_ACCESS // The timer must have fired after all the apps responded // with flushDone(). Just ignore it. if ( directAccessRun ) return; directAccessRun = TRUE; ::readyDirectAccess(cardInfoString(), installLocationsString()); #endif } // This is only called if QPE_HAVE_DIRECT_ACCESS is defined void Server::postDirectAccess() { #ifdef QPE_HAVE_DIRECT_ACCESS qDebug( "Server::postDirectAccess()" ); // Categories may have changed QCopEnvelope e1( "QPE/System", "categoriesChanged()" ); // Apps need to reload their data QCopEnvelope e2( "QPE/System", "reload()" ); // Reload DocLinks docList->storageChanged(); // Restart the PDA server stuff startTransferServer(); // restart the mtab monitor #ifndef QT_NO_COP { QCopEnvelope e( "QPE/Stabmon", "restartMonitor()" ); } #endif // Process queued requests const char *queueFile = ::directAccessQueueFile(); QFile *file = new QFile( queueFile ); if ( !file->exists() ) { delete file; // Get rid of the dialog if ( syncDialog ) { delete syncDialog; syncDialog = 0; } #warning FIXME support TempScreenSaverMode #if 0 QPEApplication::setTempScreenSaverMode(QPEApplication::Enable); #endif } else { qrr = new QueuedRequestRunner( file, syncDialog ); connect( qrr, SIGNAL(finished()), this, SLOT(finishedQueuedRequests()) ); QTimer::singleShot( 100, qrr, SLOT(process()) ); // qrr will remove the sync dialog later } #endif } void Server::finishedQueuedRequests() { if ( qrr->readyToDelete ) { delete qrr; qrr = 0; // Get rid of the dialog if ( syncDialog ) { delete syncDialog; syncDialog = 0; } #warning FIXME support TempScreenSaverMode #if 0 QPEApplication::setTempScreenSaverMode(QPEApplication::Enable); #endif } else { qrr->readyToDelete = TRUE; QTimer::singleShot( 0, this, SLOT(finishedQueuedRequests()) ); } } void Server::startSoundServer() { if ( !process ) { process = new Opie::Core::OProcess( this ); connect(process, SIGNAL(processExited(Opie::Core::OProcess*)), SLOT(soundServerExited())); } process->clearArguments(); *process << QPEApplication::qpeDir() + "bin/qss"; - process->start(); + if (!process->start()) + owarn << "Sound server process did not start" << oendl; } void Server::soundServerExited() { QTimer::singleShot(5000, this, SLOT(startSoundServer())); } diff --git a/core/settings/launcher/menusettings.cpp b/core/settings/launcher/menusettings.cpp index 29ce841..d63b203 100644 --- a/core/settings/launcher/menusettings.cpp +++ b/core/settings/launcher/menusettings.cpp @@ -1,178 +1,181 @@ /* This file is part of the OPIE Project =. Copyright (c) 2002 Trolltech AS <info@trolltech.com> .=l. Copyright (c) 2002 Robert Griebl <sandman@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 "menusettings.h" #include <qpe/config.h> #include <qpe/qlibrary.h> #include <qpe/qpeapplication.h> #include <qpe/menuappletinterface.h> #include <qpe/qcopenvelope_qws.h> +#include <opie2/odebug.h> #include <qdir.h> #include <qlistview.h> #include <qcheckbox.h> #include <qheader.h> #include <qlayout.h> #include <qlabel.h> #include <qwhatsthis.h> #include <stdlib.h> MenuSettings::MenuSettings ( QWidget *parent, const char *name ) : QWidget ( parent, name ) { m_applets_changed = false; QBoxLayout *lay = new QVBoxLayout ( this, 4, 4 ); QLabel *l = new QLabel ( tr( "Load applets in O-Menu:" ), this ); lay-> addWidget ( l ); m_list = new QListView ( this ); m_list-> addColumn ( "foobar" ); m_list-> header ( )-> hide ( ); lay-> addWidget ( m_list ); m_menutabs = new QCheckBox ( tr( "Show Launcher tabs in O-Menu" ), this ); lay-> addWidget ( m_menutabs ); m_menusubpopup = new QCheckBox ( tr( "Show Applications in Subpopups" ), this ); lay-> addWidget ( m_menusubpopup ); QWhatsThis::add ( m_list, tr( "Check the applets that you want to have included in the O-Menu." )); QWhatsThis::add ( m_menutabs, tr( "Adds the contents of the Launcher Tabs as menus in the O-Menu." )); connect ( m_list, SIGNAL( clicked(QListViewItem*)), this, SLOT( appletChanged())); init ( ); } void MenuSettings::init ( ) { Config cfg ( "StartMenu" ); cfg. setGroup ( "Applets" ); QStringList exclude = cfg. readListEntry ( "ExcludeApplets", ',' ); QString path = QPEApplication::qpeDir ( ) + "plugins/applets"; #ifdef Q_OS_MACX QStringList list = QDir ( path, "lib*.dylib" ). entryList ( ); #else QStringList list = QDir ( path, "lib*.so" ). entryList ( ); #endif /* Q_OS_MACX */ for ( QStringList::Iterator it = list. begin ( ); it != list. end ( ); ++it ) { QString name; QPixmap icon; MenuAppletInterface *iface = 0; QLibrary *lib = new QLibrary ( path + "/" + *it ); - lib-> queryInterface ( IID_MenuApplet, (QUnknownInterface**) &iface ); + QRESULT retVal = QS_OK; + if ((retVal = lib-> queryInterface ( IID_MenuApplet, (QUnknownInterface**)(&iface) )) != QS_OK ) + owarn << "queryInterface failed with " << retVal << oendl; if ( iface ) { QString lang = getenv( "LANG" ); QTranslator *trans = new QTranslator ( qApp ); QString type = (*it). left ((*it). find (".")); QString tfn = QPEApplication::qpeDir ( ) + "i18n/" + lang + "/" + type + ".qm"; if ( trans-> load ( tfn )) qApp-> installTranslator ( trans ); else delete trans; name = iface-> name ( ); icon = iface-> icon ( ). pixmap (); iface-> release ( ); lib-> unload ( ); QCheckListItem *item; item = new QCheckListItem ( m_list, name, QCheckListItem::CheckBox ); if ( !icon. isNull ( )) item-> setPixmap ( 0, icon ); item-> setOn ( exclude. find ( *it ) == exclude. end ( )); m_applets [*it] = item; } else { delete lib; } } cfg. setGroup ( "Menu" ); m_menutabs->setChecked( cfg.readBoolEntry( "LauncherTabs", true ) ); m_menusubpopup->setChecked( cfg.readBoolEntry( "LauncherSubPopup", true ) ); m_menusubpopup->setEnabled( m_menutabs->isChecked() ); connect( m_menutabs, SIGNAL( stateChanged(int) ), m_menusubpopup, SLOT( setEnabled(bool) ) ); } void MenuSettings::appletChanged() { m_applets_changed = true; } void MenuSettings::accept ( ) { bool apps_changed = false; Config cfg ( "StartMenu" ); cfg. setGroup ( "Applets" ); if ( m_applets_changed ) { QStringList exclude; QMap <QString, QCheckListItem *>::Iterator it; for ( it = m_applets. begin ( ); it != m_applets. end ( ); ++it ) { if ( !(*it)-> isOn ( )) exclude << it. key ( ); } cfg. writeEntry ( "ExcludeApplets", exclude, ',' ); } cfg. writeEntry ( "SafeMode", false ); cfg. setGroup ( "Menu" ); if ( m_menutabs-> isChecked ( ) != cfg. readBoolEntry ( "LauncherTabs", true )) { apps_changed = true; cfg. writeEntry ( "LauncherTabs", m_menutabs-> isChecked ( )); } if ( m_menusubpopup-> isChecked ( ) != cfg. readBoolEntry ( "LauncherSubPopup", true )) { apps_changed = true; cfg. writeEntry ( "LauncherSubPopup", m_menusubpopup-> isChecked ( )); } cfg. write ( ); if ( m_applets_changed ) { QCopEnvelope ( "QPE/TaskBar", "reloadApplets()" ); m_applets_changed = false; } if ( apps_changed ) { // currently use reloadApplets() since reloadApps is now used exclusive for server // to refresh the tabs. But what we want here is also a refresh of the startmenu entries QCopEnvelope ( "QPE/TaskBar", "reloadApps()" ); QCopEnvelope ( "QPE/TaskBar", "reloadApplets()" ); } } diff --git a/core/settings/launcher/taskbarsettings.cpp b/core/settings/launcher/taskbarsettings.cpp index 861ff3a..c2b82b9 100644 --- a/core/settings/launcher/taskbarsettings.cpp +++ b/core/settings/launcher/taskbarsettings.cpp @@ -1,176 +1,179 @@ /* This file is part of the OPIE Project =. Copyright (c) 2002 Trolltech AS <info@trolltech.com> .=l. Copyright (c) 2002 Robert Griebl <sandman@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 "taskbarsettings.h" /* OPIE */ #include <qpe/config.h> #include <qpe/qlibrary.h> #include <qpe/qpeapplication.h> #include <qpe/taskbarappletinterface.h> #include <qpe/qcopenvelope_qws.h> #include <opie2/odebug.h> /* QT */ #include <qdir.h> #include <qlistview.h> #include <qheader.h> #include <qlayout.h> #include <qlabel.h> #include <qwhatsthis.h> /* STD */ #include <stdlib.h> TaskbarSettings::TaskbarSettings ( QWidget *parent, const char *name ) : QWidget ( parent, name ) { m_applets_changed = false; QBoxLayout *lay = new QVBoxLayout ( this, 4, 4 ); QLabel *l = new QLabel ( tr( "Load applets in Taskbar:" ), this ); lay-> addWidget ( l ); m_list = new QListView ( this ); m_list-> addColumn ( "foobar" ); m_list-> header ( )-> hide ( ); lay-> addWidget ( m_list ); QWhatsThis::add ( m_list, tr( "Check the applets that you want displayed in the Taskbar." )); connect ( m_list, SIGNAL( clicked(QListViewItem*)), this, SLOT( appletChanged())); init ( ); } void TaskbarSettings::init ( ) { Config cfg ( "Taskbar" ); cfg. setGroup ( "Applets" ); QStringList exclude = cfg. readListEntry ( "ExcludeApplets", ',' ); QString path = QPEApplication::qpeDir ( ) + "plugins/applets"; #ifdef Q_OS_MACX QStringList list = QDir ( path, "lib*.dylib" ). entryList ( ); #else QStringList list = QDir ( path, "lib*.so" ). entryList ( ); #endif /* Q_OS_MACX */ for ( QStringList::Iterator it = list. begin ( ); it != list. end ( ); ++it ) { QString name; QPixmap icon; TaskbarNamedAppletInterface *iface = 0; owarn << "Load applet: " << (*it) << "" << oendl; QLibrary *lib = new QLibrary ( path + "/" + *it ); - lib-> queryInterface ( IID_TaskbarNamedApplet, (QUnknownInterface**) &iface ); + QRESULT retVal = QS_OK; + if ((retVal = lib-> queryInterface ( IID_TaskbarNamedApplet, (QUnknownInterface**)(&iface) )) != QS_OK) + owarn << "<0>" << oendl; owarn << "<1>" << oendl; if ( iface ) { owarn << "<2>" << oendl; QString lang = getenv( "LANG" ); QTranslator *trans = new QTranslator ( qApp ); QString type = (*it). left ((*it). find (".")); QString tfn = QPEApplication::qpeDir ( ) + "i18n/" + lang + "/" + type + ".qm"; if ( trans-> load ( tfn )) qApp-> installTranslator ( trans ); else delete trans; name = iface-> name ( ); icon = iface-> icon ( ); iface-> release ( ); } owarn << "<3>" << oendl; if ( !iface ) { owarn << "<4>" << oendl; - lib-> queryInterface ( IID_TaskbarApplet, (QUnknownInterface**) &iface ); + if ((retVal = lib-> queryInterface ( IID_TaskbarApplet, (QUnknownInterface**)(&iface))) != QS_OK) + owarn << "<5>" << oendl; if ( iface ) { - owarn << "<5>" << oendl; + owarn << "<6>" << oendl; name = (*it). mid ( 3 ); owarn << "Found applet: " << name << "" << oendl; #ifdef Q_OS_MACX int sep = name. find( ".dylib" ); #else int sep = name. find( ".so" ); #endif /* Q_OS_MACX */ if ( sep > 0 ) name. truncate ( sep ); sep = name. find ( "applet" ); if ( sep == (int) name.length ( ) - 6 ) name. truncate ( sep ); name[0] = name[0]. upper ( ); iface-> release ( ); } } - owarn << "<6>" << oendl; + owarn << "<7>" << oendl; if ( iface ) { - owarn << "<7>" << oendl; + owarn << "<8>" << oendl; QCheckListItem *item; item = new QCheckListItem ( m_list, name, QCheckListItem::CheckBox ); if ( !icon. isNull ( )) item-> setPixmap ( 0, icon ); item-> setOn ( exclude. find ( *it ) == exclude. end ( )); m_applets [*it] = item; } lib-> unload ( ); delete lib; } } void TaskbarSettings::appletChanged() { m_applets_changed = true; } void TaskbarSettings::accept ( ) { Config cfg ( "Taskbar" ); cfg. setGroup ( "Applets" ); if ( m_applets_changed ) { QStringList exclude; QMap <QString, QCheckListItem *>::Iterator it; for ( it = m_applets. begin ( ); it != m_applets. end ( ); ++it ) { if ( !(*it)-> isOn ( )) exclude << it. key ( ); } cfg. writeEntry ( "ExcludeApplets", exclude, ',' ); } cfg. writeEntry ( "SafeMode", false ); cfg. write ( ); if ( m_applets_changed ) { QCopEnvelope e ( "QPE/TaskBar", "reloadApplets()" ); m_applets_changed = false; } } diff --git a/libopie2/opiecore/oglobal.cpp b/libopie2/opiecore/oglobal.cpp index 706ac6c..b7d59fc 100644 --- a/libopie2/opiecore/oglobal.cpp +++ b/libopie2/opiecore/oglobal.cpp @@ -1,422 +1,422 @@ /* This file is part of the Opie Project Copyright (C) 2003 Michael 'Mickey' Lauer <mickey@Vanille.de> =. Copyright (C) 2004 Holger 'zecke' Freyther <zecke@handhelds.org> .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU Library 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 program 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 <opie2/oglobal.h> #include <qtextstream.h> #include <qdir.h> #include <qpe/mimetype.h> #include <qpe/qpeapplication.h> #include <qpe/storage.h> #include <unistd.h> #include <sys/types.h> using namespace Opie::Core; static const char Base64EncMap[64] = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2B, 0x2F }; static char Base64DecMap[128] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x3F, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00 }; OConfig* OGlobal::_config = 0; OConfig* OGlobal::_qpe_config = 0; void OGlobal::clean_up() { qDebug( "Oglobal clean up" ); delete OGlobal::_config; delete OGlobal::_qpe_config; OGlobal::_config = 0; OGlobal::_qpe_config = 0; } OConfig* OGlobal::config() { if ( !OGlobal::_config ) { // odebug classes are reading config, so can't use them here! qAddPostRoutine( OGlobal::clean_up ); qDebug( "OGlobal::creating global configuration instance." ); OGlobal::_config = new OConfig( "global" ); } return OGlobal::_config; } /** * Return the internal builtin Global::Command object * */ Global::Command* OGlobal::builtinCommands() { return builtin; } /** * Return the internal builtin QGuardedPtr<QWidget> object */ QGuardedPtr<QWidget>* OGlobal::builtinRunning() { return running; } /** * \brief generate a new UUID as QString * Return a new UUID as QString. UUID are global unique * * * @return the UUID or QString::null */ QString OGlobal::generateUuid() { QFile file( "/proc/sys/kernel/random/uuid" ); if (!file.open(IO_ReadOnly ) ) return QString::null; QTextStream stream(&file); return "{" + stream.read().stripWhiteSpace() + "}"; } /** * \brief Encode a QByteArray in base64 * * An Implementation of the RF1521 base64 encoding. * * The boolean argument determines if the encoded data is * going to be restricted to 76 characters or less per line * as specified by RFC 2045. If @p insertLFs is true, then * there will be 76 characters or less per line. * * If you use this to create a QCString remember that it is null terminated! * \code * QByteArray ar = OGlobal::encodeBase64(&array); * QCString str(ar.data(),ar.size()+1); // the NUL at the end * * \endcode * * @param in The QByteArray to encode * @param insertLFs Limit number of characters per line * @return The argument as base64 encoded or QByteArray() if in.isEmpty() * @see QByteArray * @see QArray * @see QMemArray * @see QCString */ /* * LGPL by Rik Hemsely of the KDE Project. taken from kmdcodec.cpp */ QByteArray OGlobal::encodeBase64(const QByteArray& in, bool insertLFs ) { if ( in.isEmpty() ) return QByteArray(); unsigned int sidx = 0; unsigned int didx = 0; const char* data = in.data(); const unsigned int len = in.size(); unsigned int out_len = ((len+2)/3)*4; // Deal with the 76 characters or less per // line limit specified in RFC 2045 on a // pre request basis. insertLFs = (insertLFs && out_len > 76); if ( insertLFs ) out_len += ((out_len-1)/76); int count = 0; QByteArray out( out_len ); // 3-byte to 4-byte conversion + 0-63 to ascii printable conversion if ( len > 1 ) { while (sidx < len-2) { if ( insertLFs ) { if ( count && (count%76) == 0 ) out[didx++] = '\n'; count += 4; } out[didx++] = Base64EncMap[(data[sidx] >> 2) & 077]; out[didx++] = Base64EncMap[(data[sidx+1] >> 4) & 017 | (data[sidx] << 4) & 077]; out[didx++] = Base64EncMap[(data[sidx+2] >> 6) & 003 | (data[sidx+1] << 2) & 077]; out[didx++] = Base64EncMap[data[sidx+2] & 077]; sidx += 3; } } if (sidx < len) { if ( insertLFs && (count > 0) && (count%76) == 0 ) out[didx++] = '\n'; out[didx++] = Base64EncMap[(data[sidx] >> 2) & 077]; if (sidx < len-1) { out[didx++] = Base64EncMap[(data[sidx+1] >> 4) & 017 | (data[sidx] << 4) & 077]; out[didx++] = Base64EncMap[(data[sidx+1] << 2) & 077]; } else { out[didx++] = Base64EncMap[(data[sidx] << 4) & 077]; } } // Add padding while (didx < out.size()) { out[didx] = '='; didx++; } return out; } /** * Decodes the given data that was encoded with the base64 * algorithm. * * * @param in the encoded data to be decoded. * @return the decoded QByteArray or QByteArray() in case of failure * @see OGlobal::encodeBase64 */ QByteArray OGlobal::decodeBase64( const QByteArray& in) { if ( in.isEmpty() ) return QByteArray(); QByteArray out; unsigned int count = 0; unsigned int len = in.size(), tail = len; const char* data = in.data(); // Deal with possible *nix "BEGIN" marker!! while ( count < len && (data[count] == '\n' || data[count] == '\r' || data[count] == '\t' || data[count] == ' ') ) count++; if ( strncasecmp(data+count, "begin", 5) == 0 ) { count += 5; while ( count < len && data[count] != '\n' && data[count] != '\r' ) count++; while ( count < len && (data[count] == '\n' || data[count] == '\r') ) count ++; data += count; tail = (len -= count); } // Find the tail end of the actual encoded data even if // there is/are trailing CR and/or LF. while ( data[tail-1] == '=' || data[tail-1] == '\n' || data[tail-1] == '\r' ) if ( data[--tail] != '=' ) len = tail; unsigned int outIdx = 0; out.resize( (count=len) ); for (unsigned int idx = 0; idx < count; idx++) { // Adhere to RFC 2045 and ignore characters // that are not part of the encoding table. unsigned char ch = data[idx]; if ( (ch > 47 && ch < 58) || (ch > 64 && ch < 91 ) || (ch > 96 && ch < 123)|| ch == '+' || ch == '/' || ch == '=') { out[outIdx++] = Base64DecMap[ch]; } else { len--; tail--; } } // kdDebug() << "Tail size = " << tail << ", Length size = " << len << endl; // 4-byte to 3-byte conversion len = (tail>(len/4)) ? tail-(len/4) : 0; unsigned int sidx = 0, didx = 0; if ( len > 1 ) { while (didx < len-2) { out[didx] = (((out[sidx] << 2) & 255) | ((out[sidx+1] >> 4) & 003)); out[didx+1] = (((out[sidx+1] << 4) & 255) | ((out[sidx+2] >> 2) & 017)); out[didx+2] = (((out[sidx+2] << 6) & 255) | (out[sidx+3] & 077)); sidx += 4; didx += 3; } } if (didx < len) out[didx] = (((out[sidx] << 2) & 255) | ((out[sidx+1] >> 4) & 003)); if (++didx < len ) out[didx] = (((out[sidx+1] << 4) & 255) | ((out[sidx+2] >> 2) & 017)); // Resize the output buffer if ( len == 0 || len < out.size() ) out.resize(len); return out; } bool OGlobal::isAppLnkFileName( const QString& str ) { if (str.isEmpty()||str.at(str.length()-1)==QDir::separator()) return false; return str.startsWith(MimeType::appsFolderName()+QDir::separator()); } /* ToDo: * This fun should check the document-path value for the mounted media * which has to be implemented later. this moment we just check for a * mounted media name. */ bool OGlobal::isDocumentFileName( const QString& file ) { if (file.isEmpty()||file.at(file.length()-1)==QDir::separator()) return false; if (file.startsWith(QPEApplication::documentDir()+QDir::separator())) return true; StorageInfo si; QList< FileSystem > fl = si.fileSystems(); FileSystem*fs; for (fs = fl.first();fs!=0;fs=fl.next()) { if (fs->isRemovable()&&file.startsWith(fs->name()+QDir::separator())) return true; } - if (file.startsWith(homeDirPath())+"/Documents/") return true; + if (file.startsWith(homeDirPath()+"/Documents/")) return true; return false; } QString OGlobal::tempDirPath() { static QString defstring="/tmp"; char * tmpp = 0; if ( (tmpp=getenv("TEMP"))) { return tmpp; } return defstring; } QString OGlobal::homeDirPath() { char * tmpp = getenv("HOME"); return (tmpp?tmpp:"/"); } bool OGlobal::weekStartsOnMonday() { OConfig*conf=OGlobal::qpe_config(); if (!conf)return false; conf->setGroup("Time"); return conf->readBoolEntry("MONDAY",true); } void OGlobal::setWeekStartsOnMonday( bool what) { OConfig*conf=OGlobal::qpe_config(); if (!conf)return; conf->setGroup("Time"); return conf->writeEntry("MONDAY",what); } bool OGlobal::useAMPM() { OConfig*conf=OGlobal::qpe_config(); if (!conf)return false; conf->setGroup("Time"); return conf->readBoolEntry("AMPM",false); } void OGlobal::setUseAMPM( bool what) { OConfig*conf=OGlobal::qpe_config(); if (!conf)return; conf->setGroup("Time"); return conf->writeEntry("AMPM",what); } OConfig* OGlobal::qpe_config() { if ( !OGlobal::_qpe_config ) { OGlobal::_qpe_config = new OConfig( "qpe" ); } return OGlobal::_qpe_config; } bool OGlobal::truncateFile( QFile &f, off_t size ) { /* or should we let enlarge Files? then remove this f.size()< part! - Alwin */ if (!f.exists()||f.size()<(unsigned)size) return false; bool closeit=false; if (!f.isOpen()) { closeit=true; f.open(IO_Raw | IO_ReadWrite | IO_Append); } if (!f.isOpen()) { return false; } int r = ftruncate(f.handle(),size); if (closeit) f.close(); return r==0; } diff --git a/libopie2/opiecore/oprocess.cpp b/libopie2/opiecore/oprocess.cpp index b3f9724..56f9883 100644 --- a/libopie2/opiecore/oprocess.cpp +++ b/libopie2/opiecore/oprocess.cpp @@ -1,951 +1,951 @@ /* This file is part of the Opie Project Copyright (C) 2002-2004 Holger Freyther <zecke@handhelds.org> and The Opie Team <opie-devel@handhelds.org> =. Based on KProcess (C) 1997 Christian Czezatke (e9025461@student.tuwien.ac.at) .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU Library 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 program 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 "oprocctrl.h" /* OPIE */ #include <opie2/oprocess.h> /* QT */ #include <qapplication.h> #include <qdir.h> #include <qmap.h> #include <qsocketnotifier.h> #include <qtextstream.h> /* STD */ #include <errno.h> #include <fcntl.h> #include <pwd.h> #include <stdlib.h> #include <signal.h> #include <stdio.h> #include <string.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <unistd.h> #ifdef HAVE_SYS_SELECT_H #include <sys/select.h> #endif #ifdef HAVE_INITGROUPS #include <grp.h> #endif using namespace Opie::Core::Internal; namespace Opie { namespace Core { namespace Internal { class OProcessPrivate { public: OProcessPrivate() : useShell( false ) { } bool useShell; QMap<QString, QString> env; QString wd; QCString shell; }; } OProcess::OProcess( QObject *parent, const char *name ) : QObject( parent, name ) { init ( ); } OProcess::OProcess( const QString &arg0, QObject *parent, const char *name ) : QObject( parent, name ) { init ( ); *this << arg0; } OProcess::OProcess( const QStringList &args, QObject *parent, const char *name ) : QObject( parent, name ) { init ( ); *this << args; } void OProcess::init ( ) { run_mode = NotifyOnExit; runs = false; pid_ = 0; status = 0; keepPrivs = false; innot = 0; outnot = 0; errnot = 0; communication = NoCommunication; input_data = 0; input_sent = 0; input_total = 0; d = 0; if ( 0 == OProcessController::theOProcessController ) { ( void ) new OProcessController(); CHECK_PTR( OProcessController::theOProcessController ); } OProcessController::theOProcessController->addOProcess( this ); out[ 0 ] = out[ 1 ] = -1; in[ 0 ] = in[ 1 ] = -1; err[ 0 ] = err[ 1 ] = -1; } void OProcess::setEnvironment( const QString &name, const QString &value ) { if ( !d ) d = new OProcessPrivate; d->env.insert( name, value ); } void OProcess::setWorkingDirectory( const QString &dir ) { if ( !d ) d = new OProcessPrivate; d->wd = dir; } void OProcess::setupEnvironment() { if ( d ) { QMap<QString, QString>::Iterator it; for ( it = d->env.begin(); it != d->env.end(); ++it ) setenv( QFile::encodeName( it.key() ).data(), QFile::encodeName( it.data() ).data(), 1 ); if ( !d->wd.isEmpty() ) chdir( QFile::encodeName( d->wd ).data() ); } } void OProcess::setRunPrivileged( bool keepPrivileges ) { keepPrivs = keepPrivileges; } bool OProcess::runPrivileged() const { return keepPrivs; } OProcess::~OProcess() { // destroying the OProcess instance sends a SIGKILL to the // child process (if it is running) after removing it from the // list of valid processes (if the process is not started as // "DontCare") OProcessController::theOProcessController->removeOProcess( this ); // this must happen before we kill the child // TODO: block the signal while removing the current process from the process list if ( runs && ( run_mode != DontCare ) ) kill( SIGKILL ); // Clean up open fd's and socket notifiers. closeStdin(); closeStdout(); closeStderr(); // TODO: restore SIGCHLD and SIGPIPE handler if this is the last OProcess delete d; } void OProcess::detach() { OProcessController::theOProcessController->removeOProcess( this ); runs = false; pid_ = 0; // Clean up open fd's and socket notifiers. closeStdin(); closeStdout(); closeStderr(); } bool OProcess::setExecutable( const QString& proc ) { if ( runs ) return false; if ( proc.isEmpty() ) return false; if ( !arguments.isEmpty() ) arguments.remove( arguments.begin() ); arguments.prepend( QFile::encodeName( proc ) ); return true; } OProcess &OProcess::operator<<( const QStringList& args ) { QStringList::ConstIterator it = args.begin(); for ( ; it != args.end() ; ++it ) arguments.append( QFile::encodeName( *it ) ); return *this; } OProcess &OProcess::operator<<( const QCString& arg ) { return operator<< ( arg.data() ); } OProcess &OProcess::operator<<( const char* arg ) { arguments.append( arg ); return *this; } OProcess &OProcess::operator<<( const QString& arg ) { arguments.append( QFile::encodeName( arg ) ); return *this; } void OProcess::clearArguments() { arguments.clear(); } bool OProcess::start( RunMode runmode, Communication comm ) { uint i; uint n = arguments.count(); char **arglist; if ( runs || ( 0 == n ) ) { return false; // cannot start a process that is already running // or if no executable has been assigned } run_mode = runmode; status = 0; QCString shellCmd; if ( d && d->useShell ) { if ( d->shell.isEmpty() ) { qWarning( "Could not find a valid shell" ); return false; } arglist = static_cast<char **>( malloc( ( 4 ) * sizeof( char * ) ) ); for ( i = 0; i < n; i++ ) { shellCmd += arguments[ i ]; shellCmd += " "; // CC: to separate the arguments } arglist[ 0 ] = d->shell.data(); arglist[ 1 ] = ( char * ) "-c"; arglist[ 2 ] = shellCmd.data(); arglist[ 3 ] = 0; } else { arglist = static_cast<char **>( malloc( ( n + 1 ) * sizeof( char * ) ) ); for ( i = 0; i < n; i++ ) arglist[ i ] = arguments[ i ].data(); arglist[ n ] = 0; } if ( !setupCommunication( comm ) ) qWarning( "Could not setup Communication!" ); // We do this in the parent because if we do it in the child process // gdb gets confused when the application runs from gdb. uid_t uid = getuid(); gid_t gid = getgid(); #ifdef HAVE_INITGROUPS struct passwd *pw = getpwuid( uid ); #endif int fd[ 2 ]; if ( 0 > pipe( fd ) ) { fd[ 0 ] = fd[ 1 ] = 0; // Pipe failed.. continue } runs = true; QApplication::flushX(); // WABA: Note that we use fork() and not vfork() because // vfork() has unclear semantics and is not standardized. pid_ = fork(); if ( 0 == pid_ ) { if ( fd[ 0 ] ) close( fd[ 0 ] ); if ( !runPrivileged() ) { setgid( gid ); #if defined( HAVE_INITGROUPS) if ( pw ) initgroups( pw->pw_name, pw->pw_gid ); #endif setuid( uid ); } // The child process if ( !commSetupDoneC() ) qWarning( "Could not finish comm setup in child!" ); setupEnvironment(); // Matthias if ( run_mode == DontCare ) setpgid( 0, 0 ); // restore default SIGPIPE handler (Harri) struct sigaction act; sigemptyset( &( act.sa_mask ) ); sigaddset( &( act.sa_mask ), SIGPIPE ); act.sa_handler = SIG_DFL; act.sa_flags = 0; sigaction( SIGPIPE, &act, 0L ); // We set the close on exec flag. // Closing of fd[1] indicates that the execvp succeeded! if ( fd[ 1 ] ) fcntl( fd[ 1 ], F_SETFD, FD_CLOEXEC ); execvp( arglist[ 0 ], arglist ); char resultByte = 1; if ( fd[ 1 ] ) write( fd[ 1 ], &resultByte, 1 ); _exit( -1 ); } else if ( -1 == pid_ ) { // forking failed runs = false; free( arglist ); return false; } else { if ( fd[ 1 ] ) close( fd[ 1 ] ); // the parent continues here // Discard any data for stdin that might still be there input_data = 0; // Check whether client could be started. if ( fd[ 0 ] ) for ( ;; ) { char resultByte; int n = ::read( fd[ 0 ], &resultByte, 1 ); if ( n == 1 ) { // Error runs = false; close( fd[ 0 ] ); free( arglist ); pid_ = 0; return false; } if ( n == -1 ) { if ( ( errno == ECHILD ) || ( errno == EINTR ) ) continue; // Ignore } break; // success } if ( fd[ 0 ] ) close( fd[ 0 ] ); if ( !commSetupDoneP() ) // finish communication socket setup for the parent qWarning( "Could not finish comm setup in parent!" ); if ( run_mode == Block ) { commClose(); // The SIGCHLD handler of the process controller will catch // the exit and set the status while ( runs ) { OProcessController::theOProcessController-> slotDoHousekeeping( 0 ); } runs = FALSE; emit processExited( this ); } } free( arglist ); return true; } bool OProcess::kill( int signo ) { bool rv = false; if ( 0 != pid_ ) rv = ( -1 != ::kill( pid_, signo ) ); // probably store errno somewhere... return rv; } bool OProcess::isRunning() const { return runs; } pid_t OProcess::pid() const { return pid_; } bool OProcess::normalExit() const { int _status = status; return ( pid_ != 0 ) && ( !runs ) && ( WIFEXITED( ( _status ) ) ); } int OProcess::exitStatus() const { int _status = status; return WEXITSTATUS( ( _status ) ); } bool OProcess::writeStdin( const char *buffer, int buflen ) { bool rv; // if there is still data pending, writing new data // to stdout is not allowed (since it could also confuse // kprocess... if ( 0 != input_data ) return false; if ( runs && ( communication & Stdin ) ) { input_data = buffer; input_sent = 0; input_total = buflen; slotSendData( 0 ); innot->setEnabled( true ); rv = true; } else rv = false; return rv; } void OProcess::flushStdin ( ) { if ( !input_data || ( input_sent == input_total ) ) return ; int d1, d2; do { d1 = input_total - input_sent; slotSendData ( 0 ); d2 = input_total - input_sent; } while ( d2 <= d1 ); } void OProcess::suspend() { if ( ( communication & Stdout ) && outnot ) outnot->setEnabled( false ); } void OProcess::resume() { if ( ( communication & Stdout ) && outnot ) outnot->setEnabled( true ); } bool OProcess::closeStdin() { bool rv; if ( communication & Stdin ) { communication = ( Communication ) ( communication & ~Stdin ); delete innot; innot = 0; close( in[ 1 ] ); rv = true; } else rv = false; return rv; } bool OProcess::closeStdout() { bool rv; if ( communication & Stdout ) { communication = ( Communication ) ( communication & ~Stdout ); delete outnot; outnot = 0; close( out[ 0 ] ); rv = true; } else rv = false; return rv; } bool OProcess::closeStderr() { bool rv; if ( communication & Stderr ) { communication = static_cast<Communication>( communication & ~Stderr ); delete errnot; errnot = 0; close( err[ 0 ] ); rv = true; } else rv = false; return rv; } void OProcess::slotChildOutput( int fdno ) { if ( !childOutput( fdno ) ) closeStdout(); } void OProcess::slotChildError( int fdno ) { if ( !childError( fdno ) ) closeStderr(); } void OProcess::slotSendData( int ) { if ( input_sent == input_total ) { innot->setEnabled( false ); input_data = 0; emit wroteStdin( this ); } else input_sent += ::write( in[ 1 ], input_data + input_sent, input_total - input_sent ); } void OProcess::processHasExited( int state ) { if ( runs ) { runs = false; status = state; commClose(); // cleanup communication sockets // also emit a signal if the process was run Blocking if ( DontCare != run_mode ) { emit processExited( this ); } } } int OProcess::childOutput( int fdno ) { if ( communication & NoRead ) { int len = -1; emit receivedStdout( fdno, len ); errno = 0; // Make sure errno doesn't read "EAGAIN" return len; } else { char buffer[ 1024 ]; int len; len = ::read( fdno, buffer, 1024 ); if ( 0 < len ) { emit receivedStdout( this, buffer, len ); } return len; } } int OProcess::childError( int fdno ) { char buffer[ 1024 ]; int len; len = ::read( fdno, buffer, 1024 ); if ( 0 < len ) emit receivedStderr( this, buffer, len ); return len; } int OProcess::setupCommunication( Communication comm ) { int ok; communication = comm; ok = 1; if ( comm & Stdin ) ok &= socketpair( AF_UNIX, SOCK_STREAM, 0, in ) >= 0; if ( comm & Stdout ) ok &= socketpair( AF_UNIX, SOCK_STREAM, 0, out ) >= 0; if ( comm & Stderr ) ok &= socketpair( AF_UNIX, SOCK_STREAM, 0, err ) >= 0; return ok; } int OProcess::commSetupDoneP() { int ok = 1; if ( communication != NoCommunication ) { if ( communication & Stdin ) close( in[ 0 ] ); if ( communication & Stdout ) close( out[ 1 ] ); if ( communication & Stderr ) close( err[ 1 ] ); // Don't create socket notifiers and set the sockets non-blocking if // blocking is requested. if ( run_mode == Block ) return ok; if ( communication & Stdin ) { // ok &= (-1 != fcntl(in[1], F_SETFL, O_NONBLOCK)); innot = new QSocketNotifier( in[ 1 ], QSocketNotifier::Write, this ); CHECK_PTR( innot ); innot->setEnabled( false ); // will be enabled when data has to be sent QObject::connect( innot, SIGNAL( activated(int) ), this, SLOT( slotSendData(int) ) ); } if ( communication & Stdout ) { // ok &= (-1 != fcntl(out[0], F_SETFL, O_NONBLOCK)); outnot = new QSocketNotifier( out[ 0 ], QSocketNotifier::Read, this ); CHECK_PTR( outnot ); QObject::connect( outnot, SIGNAL( activated(int) ), this, SLOT( slotChildOutput(int) ) ); if ( communication & NoRead ) suspend(); } if ( communication & Stderr ) { // ok &= (-1 != fcntl(err[0], F_SETFL, O_NONBLOCK)); errnot = new QSocketNotifier( err[ 0 ], QSocketNotifier::Read, this ); CHECK_PTR( errnot ); QObject::connect( errnot, SIGNAL( activated(int) ), this, SLOT( slotChildError(int) ) ); } } return ok; } int OProcess::commSetupDoneC() { int ok = 1; struct linger so; memset( &so, 0, sizeof( so ) ); if ( communication & Stdin ) close( in[ 1 ] ); if ( communication & Stdout ) close( out[ 0 ] ); if ( communication & Stderr ) close( err[ 0 ] ); if ( communication & Stdin ) ok &= dup2( in[ 0 ], STDIN_FILENO ) != -1; else { int null_fd = open( "/dev/null", O_RDONLY ); ok &= dup2( null_fd, STDIN_FILENO ) != -1; close( null_fd ); } if ( communication & Stdout ) { ok &= dup2( out[ 1 ], STDOUT_FILENO ) != -1; ok &= !setsockopt( out[ 1 ], SOL_SOCKET, SO_LINGER, ( char* ) & so, sizeof( so ) ); } else { int null_fd = open( "/dev/null", O_WRONLY ); ok &= dup2( null_fd, STDOUT_FILENO ) != -1; close( null_fd ); } if ( communication & Stderr ) { ok &= dup2( err[ 1 ], STDERR_FILENO ) != -1; ok &= !setsockopt( err[ 1 ], SOL_SOCKET, SO_LINGER, reinterpret_cast<char *>( &so ), sizeof( so ) ); } else { int null_fd = open( "/dev/null", O_WRONLY ); ok &= dup2( null_fd, STDERR_FILENO ) != -1; close( null_fd ); } return ok; } void OProcess::commClose() { if ( NoCommunication != communication ) { bool b_in = ( communication & Stdin ); bool b_out = ( communication & Stdout ); bool b_err = ( communication & Stderr ); if ( b_in ) delete innot; if ( b_out || b_err ) { // If both channels are being read we need to make sure that one socket buffer // doesn't fill up whilst we are waiting for data on the other (causing a deadlock). // Hence we need to use select. // Once one or other of the channels has reached EOF (or given an error) go back // to the usual mechanism. int fds_ready = 1; fd_set rfds; int max_fd = 0; if ( b_out ) { fcntl( out[ 0 ], F_SETFL, O_NONBLOCK ); if ( out[ 0 ] > max_fd ) max_fd = out[ 0 ]; delete outnot; outnot = 0; } if ( b_err ) { fcntl( err[ 0 ], F_SETFL, O_NONBLOCK ); if ( err[ 0 ] > max_fd ) max_fd = err[ 0 ]; delete errnot; errnot = 0; } while ( b_out || b_err ) { // * If the process is still running we block until we // receive data. (p_timeout = 0, no timeout) // * If the process has already exited, we only check // the available data, we don't wait for more. // (p_timeout = &timeout, timeout immediately) struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 0; struct timeval *p_timeout = runs ? 0 : &timeout; FD_ZERO( &rfds ); if ( b_out ) FD_SET( out[ 0 ], &rfds ); if ( b_err ) FD_SET( err[ 0 ], &rfds ); fds_ready = select( max_fd + 1, &rfds, 0, 0, p_timeout ); if ( fds_ready <= 0 ) break; if ( b_out && FD_ISSET( out[ 0 ], &rfds ) ) { int ret = 1; while ( ret > 0 ) ret = childOutput( out[ 0 ] ); if ( ( ret == -1 && errno != EAGAIN ) || ret == 0 ) b_out = false; } if ( b_err && FD_ISSET( err[ 0 ], &rfds ) ) { int ret = 1; while ( ret > 0 ) ret = childError( err[ 0 ] ); if ( ( ret == -1 && errno != EAGAIN ) || ret == 0 ) b_err = false; } } } if ( b_in ) { communication = ( Communication ) ( communication & ~Stdin ); close( in[ 1 ] ); } if ( b_out ) { communication = ( Communication ) ( communication & ~Stdout ); close( out[ 0 ] ); } if ( b_err ) { communication = ( Communication ) ( communication & ~Stderr ); close( err[ 0 ] ); } } } void OProcess::setUseShell( bool useShell, const char *shell ) { if ( !d ) d = new OProcessPrivate; d->useShell = useShell; d->shell = shell; if ( d->shell.isEmpty() ) d->shell = searchShell(); } QString OProcess::quote( const QString &arg ) { QString res = arg; res.replace( QRegExp( QString::fromLatin1( "\'" ) ), QString::fromLatin1( "'\"'\"'" ) ); res.prepend( '\'' ); res.append( '\'' ); return res; } QCString OProcess::searchShell() { QCString tmpShell = QCString( getenv( "SHELL" ) ).stripWhiteSpace(); if ( !isExecutable( tmpShell ) ) { tmpShell = "/bin/sh"; } return tmpShell; } bool OProcess::isExecutable( const QCString &filename ) { struct stat fileinfo; if ( filename.isEmpty() ) return false; // CC: we've got a valid filename, now let's see whether we can execute that file if ( -1 == stat( filename.data(), &fileinfo ) ) return false; // CC: return false if the file does not exist // CC: anyway, we cannot execute directories, block/character devices, fifos or sockets if ( ( S_ISDIR( fileinfo.st_mode ) ) || ( S_ISCHR( fileinfo.st_mode ) ) || ( S_ISBLK( fileinfo.st_mode ) ) || #ifdef S_ISSOCK // CC: SYSVR4 systems don't have that macro ( S_ISSOCK( fileinfo.st_mode ) ) || #endif ( S_ISFIFO( fileinfo.st_mode ) ) || ( S_ISDIR( fileinfo.st_mode ) ) ) { return false; } // CC: now check for permission to execute the file if ( access( filename.data(), X_OK ) != 0 ) return false; // CC: we've passed all the tests... return true; } int OProcess::processPID( const QString& process ) { QString line; QDir d = QDir( "/proc" ); QStringList dirs = d.entryList( QDir::Dirs ); QStringList::Iterator it; for ( it = dirs.begin(); it != dirs.end(); ++it ) { //qDebug( "next entry: %s", (const char*) *it ); QFile file( "/proc/"+*it+"/cmdline" ); - file.open( IO_ReadOnly ); + if ( !file.open( IO_ReadOnly ) ) continue; if ( !file.isOpen() ) continue; QTextStream t( &file ); line = t.readLine(); //qDebug( "cmdline = %s", (const char*) line ); if ( line.contains( process ) ) break; //FIXME: That may find also other process, if the name is not long enough ;) } if ( line.contains( process ) ) { //qDebug( "found process id #%d", (*it).toInt() ); return (*it).toInt(); } else { //qDebug( "process '%s' not found", (const char*) process ); return 0; } } } } diff --git a/library/global.cpp b/library/global.cpp index f7a0767..7bdd0b1 100644 --- a/library/global.cpp +++ b/library/global.cpp @@ -1,861 +1,860 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the 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. ** **********************************************************************/ #define QTOPIA_INTERNAL_LANGLIST #include <qpe/qpedebug.h> #include <qpe/global.h> #include <qpe/qdawg.h> #include <qpe/qpeapplication.h> #include <qpe/resource.h> #include <qpe/storage.h> #include <qpe/applnk.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/config.h> #include <qlabel.h> #include <qtimer.h> #include <qmap.h> #include <qdict.h> #include <qdir.h> #include <qmessagebox.h> #include <qregexp.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/wait.h> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <qwindowsystem_qws.h> // for qwsServer #include <qdatetime.h> //#include "quickexec_p.h" class Emitter : public QObject { Q_OBJECT public: Emitter( QWidget* receiver, const QString& document ) { connect(this, SIGNAL(setDocument(const QString&)), receiver, SLOT(setDocument(const QString&))); emit setDocument(document); disconnect(this, SIGNAL(setDocument(const QString&)), receiver, SLOT(setDocument(const QString&))); } signals: void setDocument(const QString&); }; class StartingAppList : public QObject { Q_OBJECT public: static void add( const QString& name ); static bool isStarting( const QString name ); private slots: void handleNewChannel( const QString &); private: StartingAppList( QObject *parent=0, const char* name=0 ) ; QDict<QTime> dict; static StartingAppList *appl; }; StartingAppList* StartingAppList::appl = 0; StartingAppList::StartingAppList( QObject *parent, const char* name ) :QObject( parent, name ) { #if QT_VERSION >= 232 && defined(QWS) connect( qwsServer, SIGNAL( newChannel(const QString&)), this, SLOT( handleNewChannel(const QString&)) ); #endif dict.setAutoDelete( TRUE ); } void StartingAppList::add( const QString& name ) { #if QT_VERSION >= 232 && !defined(QT_NO_COP) if ( !appl ) appl = new StartingAppList; QTime *t = new QTime; t->start(); appl->dict.insert( "QPE/Application/" + name, t ); #endif } bool StartingAppList::isStarting( const QString name ) { #if QT_VERSION >= 232 && !defined(QT_NO_COP) if ( appl ) { QTime *t = appl->dict.find( "QPE/Application/" + name ); if ( !t ) return FALSE; if ( t->elapsed() > 10000 ) { // timeout in case of crash or something appl->dict.remove( "QPE/Application/" + name ); return FALSE; } return TRUE; } #endif return FALSE; } void StartingAppList::handleNewChannel( const QString & name ) { #if QT_VERSION >= 232 && !defined(QT_NO_COP) dict.remove( name ); #endif } static bool docDirCreated = FALSE; static QDawg* fixed_dawg = 0; static QDict<QDawg> *named_dawg = 0; static QString qpeDir() { QString dir = getenv("OPIEDIR"); if ( dir.isEmpty() ) dir = ".."; return dir; } static QString dictDir() { return qpeDir() + "/etc/dict"; } /*! \class Global global.h \brief The Global class provides application-wide global functions. The Global functions are grouped as follows: \tableofcontents \section1 User Interface The statusMessage() function provides short-duration messages to the user. The showInputMethod() function shows the current input method, and hideInputMethod() hides the input method. \section1 Document related The findDocuments() function creates a set of \link doclnk.html DocLnk\endlink objects in a particular folder. \section1 Filesystem related Global provides an applicationFileName() function that returns the full path of an application-specific file. The execute() function runs an application. \section1 Word list related A list of words relevant to the current locale is maintained by the system. The list is held in a \link qdawg.html DAWG\endlink (implemented by the QDawg class). This list is used, for example, by the pickboard input method. The global QDawg is returned by fixedDawg(); this cannot be updated. An updatable copy of the global QDawg is returned by addedDawg(). Applications may have their own word lists stored in \l{QDawg}s which are returned by dawg(). Use addWords() to add words to the updateable copy of the global QDawg or to named application \l{QDawg}s. \section1 Quoting The shellQuote() function quotes a string suitable for passing to a shell. The stringQuote() function backslash escapes '\' and '"' characters. \section1 Hardware The implementation of the writeHWClock() function depends on the AlarmServer implementation. If the AlarmServer is using atd the clock will be synced to hardware. If opie-alarm is used the hardware clock will be synced before suspending the device. opie-alarm is used by iPAQ and Zaurii implementation \ingroup qtopiaemb */ /*! \internal */ Global::Global() { } /*! Returns the unchangeable QDawg that contains general words for the current locale. \sa addedDawg() */ const QDawg& Global::fixedDawg() { if ( !fixed_dawg ) { - if ( !docDirCreated ) - createDocDir(); - - fixed_dawg = new QDawg; - QString dawgfilename = dictDir() + "/dawg"; - QString words_lang; - QStringList langs = Global::languageList(); - for (QStringList::ConstIterator it = langs.begin(); it!=langs.end(); ++it) { - QString lang = *it; - words_lang = dictDir() + "/words." + lang; - QString dawgfilename_lang = dawgfilename + "." + lang; - if ( QFile::exists(dawgfilename_lang) || - QFile::exists(words_lang) ) { - dawgfilename = dawgfilename_lang; - break; - } - } - QFile dawgfile(dawgfilename); - - if ( !dawgfile.exists() ) { - QString fn = dictDir() + "/words"; - if ( QFile::exists(words_lang) ) - fn = words_lang; - QFile in(fn); - if ( in.open(IO_ReadOnly) ) { - fixed_dawg->createFromWords(&in); - dawgfile.open(IO_WriteOnly); - fixed_dawg->write(&dawgfile); - dawgfile.close(); + if ( !docDirCreated ) + createDocDir(); + + fixed_dawg = new QDawg; + QString dawgfilename = dictDir() + "/dawg"; + QString words_lang; + QStringList langs = Global::languageList(); + for (QStringList::ConstIterator it = langs.begin(); it!=langs.end(); ++it) { + QString lang = *it; + words_lang = dictDir() + "/words." + lang; + QString dawgfilename_lang = dawgfilename + "." + lang; + if ( QFile::exists(dawgfilename_lang) || + QFile::exists(words_lang) ) { + dawgfilename = dawgfilename_lang; + break; + } } - } else { - fixed_dawg->readFile(dawgfilename); - } + QFile dawgfile(dawgfilename); + + if ( !dawgfile.exists() ) { + QString fn = dictDir() + "/words"; + if ( QFile::exists(words_lang) ) + fn = words_lang; + QFile in(fn); + if ( in.open(IO_ReadOnly) ) { + fixed_dawg->createFromWords(&in); + if (dawgfile.open(IO_WriteOnly)) + fixed_dawg->write(&dawgfile); + dawgfile.close(); + } + } else + fixed_dawg->readFile(dawgfilename); } return *fixed_dawg; } /*! Returns the changeable QDawg that contains general words for the current locale. \sa fixedDawg() */ const QDawg& Global::addedDawg() { return dawg("local"); } /*! Returns the QDawg with the given \a name. This is an application-specific word list. \a name should not contain "/". */ const QDawg& Global::dawg(const QString& name) { createDocDir(); if ( !named_dawg ) named_dawg = new QDict<QDawg>; QDawg* r = named_dawg->find(name); if ( !r ) { r = new QDawg; named_dawg->insert(name,r); QString dawgfilename = applicationFileName("Dictionary", name ) + ".dawg"; QFile dawgfile(dawgfilename); if ( dawgfile.open(IO_ReadOnly) ) r->readFile(dawgfilename); } return *r; } /*! \overload Adds \a wordlist to the addedDawg(). Note that the addition of words persists between program executions (they are saved in the dictionary files), so you should confirm the words with the user before adding them. */ void Global::addWords(const QStringList& wordlist) { addWords("local",wordlist); } /*! \overload Adds \a wordlist to the addedDawg(). Note that the addition of words persists between program executions (they are saved in the dictionary files), so you should confirm the words with the user before adding them. */ void Global::addWords(const QString& dictname, const QStringList& wordlist) { QDawg& d = (QDawg&)dawg(dictname); QStringList all = d.allWords() + wordlist; d.createFromWords(all); QString dawgfilename = applicationFileName("Dictionary", dictname) + ".dawg"; QFile dawgfile(dawgfilename); if ( dawgfile.open(IO_WriteOnly) ) { d.write(&dawgfile); dawgfile.close(); } // #### Re-read the dawg here if we use mmap(). // #### Signal other processes to re-read. } /*! Returns the full path for the application called \a appname, with the given \a filename. Returns QString::null if there was a problem creating the directory tree for \a appname. If \a filename contains "/", it is the caller's responsibility to ensure that those directories exist. */ QString Global::applicationFileName(const QString& appname, const QString& filename) { QDir d; QString r = getenv("HOME"); r += "/Applications/"; if ( !QFile::exists( r ) ) if ( d.mkdir(r) == false ) return QString::null; r += appname; if ( !QFile::exists( r ) ) if ( d.mkdir(r) == false ) return QString::null; r += "/"; r += filename; return r; } /*! \internal */ void Global::createDocDir() { if ( !docDirCreated ) { docDirCreated = TRUE; mkdir( QPEApplication::documentDir().latin1(), 0755 ); } } /*! Displays a status \a message to the user. This usually appears in the taskbar for a short amount of time, then disappears. */ void Global::statusMessage(const QString& message) { #if !defined(QT_NO_COP) QCopEnvelope e( "QPE/TaskBar", "message(QString)" ); e << message; #endif } /*! \internal */ void Global::applyStyle() { #if !defined(QT_NO_COP) QCopChannel::send( "QPE/System", "applyStyle()" ); #else ((QPEApplication *)qApp)->applyStyle(); // apply without needing QCop for floppy version #endif } /*! \internal */ QWidget *Global::shutdown( bool ) { #if !defined(QT_NO_COP) QCopChannel::send( "QPE/System", "shutdown()" ); #endif return 0; } /*! \internal */ QWidget *Global::restart( bool ) { #if !defined(QT_NO_COP) QCopChannel::send( "QPE/System", "restart()" ); #endif return 0; } /*! Explicitly show the current input method. Input methods are indicated in the taskbar by a small icon. If the input method is activated (shown) then it takes up some proportion of the bottom of the screen, to allow the user to interact (input characters) with it. \sa hideInputMethod() */ void Global::showInputMethod() { #if !defined(QT_NO_COP) QCopChannel::send( "QPE/TaskBar", "showInputMethod()" ); #endif } /*! Explicitly hide the current input method. The current input method is still indicated in the taskbar, but no longer takes up screen space, and can no longer be interacted with. \sa showInputMethod() */ void Global::hideInputMethod() { #if !defined(QT_NO_COP) QCopChannel::send( "QPE/TaskBar", "hideInputMethod()" ); #endif } /*! \internal */ bool Global::isBuiltinCommand( const QString &name ) { if(!builtin) return FALSE; // yes, it can happen for (int i = 0; builtin[i].file; i++) { if ( builtin[i].file == name ) { return TRUE; } } return FALSE; } Global::Command* Global::builtin=0; QGuardedPtr<QWidget> *Global::running=0; /*! \class Global::Command \brief The Global::Command class is internal. \internal */ /*! \internal */ void Global::setBuiltinCommands( Command* list ) { if ( running ) delete [] running; builtin = list; int count = 0; if (!builtin) return; while ( builtin[count].file ) count++; running = new QGuardedPtr<QWidget> [ count ]; } /*! \internal */ void Global::setDocument( QWidget* receiver, const QString& document ) { Emitter emitter(receiver,document); } /*! \internal */ bool Global::terminateBuiltin( const QString& n ) { if (!builtin) return FALSE; for (int i = 0; builtin[i].file; i++) { if ( builtin[i].file == n ) { delete running[i]; return TRUE; } } return FALSE; } /*! \internal */ void Global::terminate( const AppLnk* app ) { //if ( terminateBuiltin(app->exec()) ) return; // maybe? haven't tried this #ifndef QT_NO_COP QCString channel = "QPE/Application/" + app->exec().utf8(); if ( QCopChannel::isRegistered(channel) ) { QCopEnvelope e(channel, "quit()"); } #endif } /*! Low-level function to run command \a c. \warning Do not use this function. Use execute instead. \sa execute() */ void Global::invoke(const QString &c) { // Convert the command line in to a list of arguments QStringList list = QStringList::split(QRegExp(" *"),c); #if !defined(QT_NO_COP) QString ap=list[0]; // see if the application is already running // XXX should lock file /tmp/qcop-msg-ap if ( QCopChannel::isRegistered( ("QPE/Application/" + ap).latin1() ) ) { // If the channel is already register, the app is already running, so show it. { QCopEnvelope env( ("QPE/Application/" + ap).latin1(), "raise()" ); } //QCopEnvelope e("QPE/System", "notBusy(QString)" ); //e << ap; return; } // XXX should unlock file /tmp/qcop-msg-ap //see if it is being started if ( StartingAppList::isStarting( ap ) ) { // FIXME take it out for now, since it leads to a much to short showing of wait if // some entry is clicked. // Real cause is that ::execute is called twice for document tab. But it would need some larger changes // to fix that, and with future syncs with qtopia 1.6 it will change anyway big time since somebody there // had the idea that an apploader belongs to the launcher ... //QCopEnvelope e("QPE/System", "notBusy(QString)" ); //e << ap; return; } #endif #ifdef QT_NO_QWS_MULTIPROCESS QMessageBox::warning( 0, "Error", "Could not find the application " + c, "Ok", 0, 0, 0, 1 ); #else QStrList slist; unsigned int j; for ( j = 0; j < list.count(); j++ ) slist.append( list[j].utf8() ); const char **args = new const char *[slist.count() + 1]; for ( j = 0; j < slist.count(); j++ ) args[j] = slist.at(j); args[j] = NULL; #if !defined(QT_NO_COP) // an attempt to show a wait... // more logic should be used, but this will be fine for the moment... QCopEnvelope ( "QPE/System", "busy()" ); #endif #ifdef HAVE_QUICKEXEC #ifdef Q_OS_MACX QString libexe = qpeDir()+"/binlib/lib"+args[0] + ".dylib"; #else QString libexe = qpeDir()+"/binlib/lib"+args[0] + ".so"; #endif qDebug("libfile = %s", libexe.latin1() ); if ( QFile::exists( libexe ) ) { qDebug("calling quickexec %s", libexe.latin1() ); quickexecv( libexe.utf8().data(), (const char **)args ); } else #endif { bool success = false; int pfd [2]; if ( ::pipe ( pfd ) < 0 ) pfd [0] = pfd [1] = -1; pid_t pid = ::fork ( ); if ( pid == 0 ) { // child for ( int fd = 3; fd < 100; fd++ ) { if ( fd != pfd [1] ) ::close ( fd ); } ::setpgid ( ::getpid ( ), ::getppid ( )); // Closing of fd[1] indicates that the execvp succeeded! if ( pfd [1] >= 0 ) ::fcntl ( pfd [1], F_SETFD, FD_CLOEXEC ); // Try bindir first, so that foo/bar works too ::execv ( qpeDir ( ) + "/bin/" + args [0], (char * const *) args ); ::execvp ( args [0], (char * const *) args ); char resultByte = 1; if ( pfd [1] >= 0 ) ::write ( pfd [1], &resultByte, 1 ); ::_exit ( -1 ); } else if ( pid > 0 ) { success = true; if ( pfd [1] >= 0 ) ::close ( pfd [1] ); if ( pfd [0] >= 0 ) { while ( true ) { char resultByte; int n = ::read ( pfd [0], &resultByte, 1 ); if ( n == 1 ) { success = false; break; } if (( n == -1 ) && (( errno == ECHILD ) || ( errno == EINTR ))) continue; break; // success } ::close ( pfd [0] ); } } if ( success ) StartingAppList::add( list[0] ); else QMessageBox::warning( 0, "Error", "Could not start the application " + c, "Ok", 0, 0, 0, 1 ); } #endif //QT_NO_QWS_MULTIPROCESS } /*! Executes the application identfied by \a c, passing \a document if it isn't null. Note that a better approach might be to send a QCop message to the application's QPE/Application/\e{appname} channel. */ void Global::execute( const QString &c, const QString& document ) { // ask the server to do the work #if !defined(QT_NO_COP) if ( document.isNull() ) { QCopEnvelope e( "QPE/System", "execute(QString)" ); e << c; } else { QCopEnvelope e( "QPE/System", "execute(QString,QString)" ); e << c << document; } #endif return; } /*! Returns the string \a s with the characters '\', '"', and '$' quoted by a preceeding '\'. \sa stringQuote() */ QString Global::shellQuote(const QString& s) { QString r="\""; for (int i=0; i<(int)s.length(); i++) { char c = s[i].latin1(); switch (c) { case '\\': case '"': case '$': r+="\\"; } r += s[i]; } r += "\""; return r; } /*! Returns the string \a s with the characters '\' and '"' quoted by a preceeding '\'. \sa shellQuote() */ QString Global::stringQuote(const QString& s) { QString r="\""; for (int i=0; i<(int)s.length(); i++) { char c = s[i].latin1(); switch (c) { case '\\': case '"': r+="\\"; } r += s[i]; } r += "\""; return r; } /*! Finds all documents on the system's document directories which match the filter \a mimefilter, and appends the resulting DocLnk objects to \a folder. */ void Global::findDocuments(DocLnkSet* folder, const QString &mimefilter) { QString homedocs = QString(getenv("HOME")) + "/Documents"; DocLnkSet d(homedocs,mimefilter); folder->appendFrom(d); /** let's do intellegint way of searching these files * a) the user don't want to check mediums global * b) the user wants to check but use the global options for it * c) the user wants to check it but not this medium * d) the user wants to check and this medium as well * * In all cases we need to apply a different mimefilter to * the medium. * a) mimefilter.isEmpty() we need to apply the responding filter * either the global or the one on the medium * * b) mimefilter is set to an application we need to find out if the * mimetypes are included in the mime mask of the medium */ StorageInfo storage; const QList<FileSystem> &fs = storage.fileSystems(); QListIterator<FileSystem> it ( fs ); for ( ; it.current(); ++it ) { if ( (*it)->isRemovable() ) { // let's find out if we should search on it // this is a candidate look at the cf and see if we should search on it QString path = (*it)->path(); Config conf((*it)->path() + "/.opiestorage.cf", Config::File ); conf.setGroup("main"); if (!conf.readBoolEntry("check",true)) { continue; } conf.setGroup("subdirs"); if (conf.readBoolEntry("wholemedia",true)) { DocLnkSet ide( path,mimefilter); folder->appendFrom(ide); } else { QStringList subDirs = conf.readListEntry("subdirs",':'); if (subDirs.isEmpty()) { subDirs.append("Documents"); } for (unsigned c = 0; c < subDirs.count();++c) { DocLnkSet ide( path+"/"+subDirs[c], mimefilter ); folder->appendFrom(ide); } } } else if ( (*it)->disk() == "/dev/mtdblock6" || (*it)->disk() == "tmpfs" ) { QString path = (*it)->path() + "/Documents"; DocLnkSet ide( path, mimefilter ); folder->appendFrom(ide); } } } QStringList Global::languageList() { QString lang = getenv("LANG"); QStringList langs; langs.append(lang); int i = lang.find("."); if ( i > 0 ) lang = lang.left( i ); i = lang.find( "_" ); if ( i > 0 ) langs.append(lang.left(i)); return langs; } QStringList Global::helpPath() { QString qpeDir = QPEApplication::qpeDir(); QStringList path; QStringList langs = Global::languageList(); for (QStringList::ConstIterator it = langs.fromLast(); it!=langs.end(); --it) { QString lang = *it; if ( !lang.isEmpty() ) path += qpeDir + "/help/" + lang + "/html"; } path += qpeDir + "/pics"; path += qpeDir + "/help/html"; /* we even put english into the en dir so try it as fallback as well for opie */ path += qpeDir + "/help/en/html"; path += qpeDir + "/docs"; return path; } /*! \internal Truncate file to size specified \a f must be an open file \a size must be a positive value */ bool Global::truncateFile(QFile &f, int size){ if (!f.isOpen()) return FALSE; return ::ftruncate(f.handle(), size) != -1; } // #if defined(Q_OS_UNIX) && defined(Q_WS_QWS) // extern int qws_display_id; // #endif /*! /internal Returns the default system path for storing temporary files. Note: This does not it ensure that the provided directory exists */ QString Global::tempDir() { QString result; #ifdef Q_OS_UNIX #ifdef Q_WS_QWS result = QString("/tmp/qtopia-%1/").arg(QString::number(qws_display_id)); #else result="/tmp/"; #endif #else if (getenv("TEMP")) result = getenv("TEMP"); else result = getenv("TMP"); if (result[(int)result.length() - 1] != QDir::separator()) result.append(QDir::separator()); #endif return result; } //#endif #include "global.moc" diff --git a/noncore/apps/advancedfm/output.cpp b/noncore/apps/advancedfm/output.cpp index 8c585f4..8f654d5 100644 --- a/noncore/apps/advancedfm/output.cpp +++ b/noncore/apps/advancedfm/output.cpp @@ -1,281 +1,282 @@ /**************************************************************************** ** outputEdit.cpp ** ** Copyright: Fri Apr 12 15:12:58 2002 L.J. Potter <ljp@llornkcor.com> ****************************************************************************/ #include "output.h" /* OPIE */ #include <opie2/odebug.h> #include <qpe/qpeapplication.h> #include <qpe/applnk.h> using namespace Opie::Core; /* QT */ #include <qfile.h> #include <qmultilineedit.h> #include <qpushbutton.h> #include <qlayout.h> /* STD */ #include <errno.h> /* XPM */ static char * filesave_xpm[] = { "16 16 78 1", " c None", ". c #343434", "+ c #A0A0A0", "@ c #565656", "# c #9E9E9E", "$ c #525252", "% c #929292", "& c #676767", "* c #848484", "= c #666666", "- c #D8D8D8", "; c #FFFFFF", "> c #DBDBDB", ", c #636363", "' c #989898", ") c #2D2D2D", "! c #909090", "~ c #AEAEAE", "{ c #EAEAEA", "] c #575757", "^ c #585858", "/ c #8A8A8A", "( c #828282", "_ c #6F6F6F", ": c #C9C9C9", "< c #050505", "[ c #292929", "} c #777777", "| c #616161", "1 c #3A3A3A", "2 c #BEBEBE", "3 c #2C2C2C", "4 c #7C7C7C", "5 c #F6F6F6", "6 c #FCFCFC", "7 c #6B6B6B", "8 c #959595", "9 c #4F4F4F", "0 c #808080", "a c #767676", "b c #818181", "c c #B8B8B8", "d c #FBFBFB", "e c #F9F9F9", "f c #CCCCCC", "g c #030303", "h c #737373", "i c #7A7A7A", "j c #7E7E7E", "k c #6A6A6A", "l c #FAFAFA", "m c #505050", "n c #9D9D9D", "o c #333333", "p c #7B7B7B", "q c #787878", "r c #696969", "s c #494949", "t c #555555", "u c #949494", "v c #E6E6E6", "w c #424242", "x c #515151", "y c #535353", "z c #3E3E3E", "A c #D4D4D4", "B c #0C0C0C", "C c #353535", "D c #474747", "E c #ECECEC", "F c #919191", "G c #7D7D7D", "H c #000000", "I c #404040", "J c #858585", "K c #323232", "L c #D0D0D0", "M c #1C1C1C", " ...+ ", " @#$%&..+ ", " .*=-;;>,..+ ", " ')!~;;;;;;{]..", " ^/(-;;;;;;;_:<", " [}|;;;;;;;{12$", " #34-55;;;;678$+", " 90ab=c;dd;e1fg ", " [ahij((kbl0mn$ ", " op^q^^7r&]s/$+ ", "@btu;vbwxy]zAB ", "CzDEvEv;;DssF$ ", "G.H{E{E{IxsJ$+ ", " +...vEKxzLM ", " +...z]n$ ", " +... "}; Output::Output( const QStringList commands, QWidget* parent, const char* name, bool modal, WFlags fl) : QDialog( parent, name, modal, fl ) { QStringList cmmds; // cmmds=QStringList::split( " ", commands, false); cmmds=commands; // odebug << "count " << cmmds.count() << "" << oendl; if ( !name ) setName( tr("Output")); resize( 196, 269 ); setCaption( name ); OutputLayout = new QGridLayout( this ); OutputLayout->setSpacing( 2); OutputLayout->setMargin( 2); QPushButton *docButton; docButton = new QPushButton( QPixmap(( const char** ) filesave_xpm ) ,"",this,"saveButton"); docButton->setFixedSize( QSize( 20, 20 ) ); connect( docButton,SIGNAL(released()),this,SLOT( saveOutput() )); // docButton->setFlat(TRUE); OutputLayout->addMultiCellWidget( docButton, 0,0,3,3 ); OutputEdit = new QMultiLineEdit( this, "OutputEdit" ); OutputLayout->addMultiCellWidget( OutputEdit, 1,1,0,3 ); proc = new OProcess(); connect(proc, SIGNAL(processExited(Opie::Core::OProcess*)), this, SLOT( processFinished())); connect(proc, SIGNAL(receivedStdout(Opie::Core::OProcess*,char*,int)), this, SLOT(commandStdout(Opie::Core::OProcess*,char*,int))); connect(proc, SIGNAL(receivedStderr(Opie::Core::OProcess*,char*,int)), this, SLOT(commandStderr(Opie::Core::OProcess*,char*,int))); // connect( , SIGNAL(received(const QByteArray&)), // this, SLOT(commandStdin(const QByteArray&))); // * proc << commands.latin1(); for ( QStringList::Iterator it = cmmds.begin(); it != cmmds.end(); ++it ) { odebug << "" << (*it).latin1() << "" << oendl; * proc << (*it).latin1(); } if(!proc->start(OProcess::NotifyOnExit, OProcess::All)) { OutputEdit->append(tr("Process could not start") ); OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE); perror("Error: "); QString errorMsg=tr("Error\n")+(QString)strerror(errno); OutputEdit->append( errorMsg); OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE); } } Output::~Output() { } void Output::saveOutput() { InputDialog *fileDlg; fileDlg = new InputDialog(this,tr("Save output to file (name only)"),TRUE, 0); fileDlg->exec(); if( fileDlg->result() == 1 ) { QString filename = QPEApplication::documentDir(); if(filename.right(1).find('/') == -1) filename+="/"; QString name = fileDlg->LineEdit1->text(); filename+="text/plain/"+name; odebug << filename << oendl; QFile f(filename); - f.open( IO_WriteOnly); - if( f.writeBlock( OutputEdit->text(), qstrlen( OutputEdit->text()) ) != -1) { + if ( !f.open( IO_WriteOnly ) ) + owarn << "Could no open file" << oendl; + else if( f.writeBlock( OutputEdit->text(), qstrlen( OutputEdit->text()) ) != -1) { DocLnk lnk; lnk.setName(name); //sets file name lnk.setFile(filename); //sets File property lnk.setType("text/plain"); if(!lnk.writeLink()) { odebug << "Writing doclink did not work" << oendl; } } else owarn << "Could not write file" << oendl; f.close(); } } void Output::commandStdout(OProcess*, char *buffer, int buflen) { owarn << "received stdout " << buflen << " bytes" << oendl; // QByteArray data(buflen); // data.fill(*buffer, buflen); // for (uint i = 0; i < data.count(); i++ ) { // printf("%c", buffer[i] ); // } // printf("\n"); QString lineStr = buffer; lineStr=lineStr.left(lineStr.length()-1); OutputEdit->append(lineStr); OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE); } void Output::commandStdin( const QByteArray &data) { owarn << "received stdin " << data.size() << " bytes" << oendl; // recieved data from the io layer goes to sz proc->writeStdin(data.data(), data.size()); } void Output::commandStderr(OProcess*, char *buffer, int buflen) { owarn << "received stderrt " << buflen << " bytes" << oendl; QString lineStr = buffer; // lineStr=lineStr.left(lineStr.length()-1); OutputEdit->append(lineStr); OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE); } void Output::processFinished() { delete proc; OutputEdit->append( tr("\nFinished\n") ); OutputEdit->setCursorPosition( OutputEdit->numLines() + 1,0,FALSE); // close(); // disconnect( layer(), SIGNAL(received(const QByteArray&)), // this, SLOT(commandStdin(const QByteArray&))); } //============================== InputDialog::InputDialog( QWidget* parent, const char* name, bool modal, WFlags fl ) : QDialog( parent, name, modal, fl ) { if ( !name ) setName( "InputDialog" ); resize( 234, 50 ); setMaximumSize( QSize( 240, 50 ) ); setCaption( tr(name ) ); LineEdit1 = new QLineEdit( this, "LineEdit1" ); LineEdit1->setGeometry( QRect( 10, 10, 216, 22 ) ); LineEdit1->setFocus(); LineEdit1->setFocus(); connect(LineEdit1,SIGNAL(returnPressed()),this,SLOT(returned() )); } InputDialog::~InputDialog() { inputText = LineEdit1->text(); } void InputDialog::setInputText(const QString &string) { LineEdit1->setText( string); } void InputDialog::returned() { inputText = LineEdit1->text(); this->accept(); } diff --git a/noncore/apps/tinykate/libkate/document/katebuffer.cpp b/noncore/apps/tinykate/libkate/document/katebuffer.cpp index 4c15fd0..d89edbd 100644 --- a/noncore/apps/tinykate/libkate/document/katebuffer.cpp +++ b/noncore/apps/tinykate/libkate/document/katebuffer.cpp @@ -1,180 +1,183 @@ /* This file is part of KWrite Copyright (c) 2000 Waldo Bastian <bastian@kde.org> Copyright (c) 2002 Joseph Wenninger <jowenn@kde.org> $Id$ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "katebuffer.h" #include "kdebug.h" /* OPIE */ #include <opie2/odebug.h> /* QT */ #include <qfile.h> #include <qtextstream.h> #include <qtimer.h> #include <qtextcodec.h> /* STD */ // Includes for reading file #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <assert.h> /** * Create an empty buffer. */ KWBuffer::KWBuffer() { clear(); } void KWBuffer::clear() { m_stringListIt=0; m_stringListCurrent=0; m_stringList.clear(); m_lineCount=1; m_stringListIt = m_stringList.append(new TextLine()); } /** * Insert a file at line @p line in the buffer. */ void KWBuffer::insertFile(int line, const QString &file, QTextCodec *codec) { if (line) { odebug << "insert File only supports insertion at line 0 == file opening" << oendl; return; } clear(); QFile iofile(file); - iofile.open(IO_ReadOnly); + if (!iofile.open(IO_ReadOnly)) { + owarn << "failed to open file " << iofile.name() << oendl; + return; + } QTextStream stream(&iofile); stream.setCodec(codec); QString qsl; int count=0; for (count=0;((qsl=stream.readLine())!=QString::null); count++) { if (count==0) { (*m_stringListIt)->append(qsl.unicode(),qsl.length()); } else { TextLine::Ptr tl=new TextLine(); tl ->append(qsl.unicode(),qsl.length()); m_stringListIt=m_stringList.append(tl); } } if (count!=0) { m_stringListCurrent=count-1; m_lineCount=count; } } void KWBuffer::loadFilePart() { } void KWBuffer::insertData(int line, const QByteArray &data, QTextCodec *codec) { } void KWBuffer::slotLoadFile() { loadFilePart(); // emit linesChanged(m_totalLines); emit linesChanged(20); } /** * Return the total number of lines in the buffer. */ int KWBuffer::count() { odebug << "m_stringList.count " << m_stringList.count() << "" << oendl; return m_lineCount; // return m_stringList.count(); // return m_totalLines; } void KWBuffer::seek(int i) { if (m_stringListCurrent == i) return; while(m_stringListCurrent < i) { ++m_stringListCurrent; ++m_stringListIt; } while(m_stringListCurrent > i) { --m_stringListCurrent; --m_stringListIt; } } TextLine::Ptr KWBuffer::line(int i) { if (i>=m_stringList.count()) return 0; seek(i); return *m_stringListIt; } void KWBuffer::insertLine(int i, TextLine::Ptr line) { seek(i); m_stringListIt = m_stringList.insert(m_stringListIt, line); m_stringListCurrent = i; m_lineCount++; } void KWBuffer::removeLine(int i) { seek(i); m_stringListIt = m_stringList.remove(m_stringListIt); m_stringListCurrent = i; m_lineCount--; } void KWBuffer::changeLine(int i) { } diff --git a/noncore/settings/usermanager/userdialog.cpp b/noncore/settings/usermanager/userdialog.cpp index 3654639..75a96a6 100644 --- a/noncore/settings/usermanager/userdialog.cpp +++ b/noncore/settings/usermanager/userdialog.cpp @@ -1,489 +1,492 @@ /*************************************************************************** * * * 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 "userdialog.h" #include "passwd.h" /* OPIE */ #include <opie2/odebug.h> #include <opie2/odevice.h> #include <opie2/oresource.h> #include <qpe/qpeapplication.h> using namespace Opie::Core; using namespace Opie::Ui; /* QT */ #include <qlayout.h> #include <qlabel.h> #include <qmessagebox.h> #include <qfile.h> /* STD */ #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <signal.h> /** * UserDialog constructor. Setup the dialog, fill the groupComboBox & groupsListView with all groups. * */ UserDialog::UserDialog(int viewmode, QWidget* parent, const char* name, bool modal, WFlags fl) : QDialog(parent, name, modal, fl) { vm=viewmode; QVBoxLayout *layout = new QVBoxLayout(this); myTabWidget=new QTabWidget(this,"User Tab Widget"); layout->addWidget(myTabWidget); setupTab1(); setupTab2(); accounts->groupStringList.sort(); // And also fill the listview & the combobox with all available groups. for( QStringList::Iterator it = accounts->groupStringList.begin(); it!=accounts->groupStringList.end(); ++it) { accounts->splitGroupEntry(*it); if(accounts->gr_name.find(QRegExp("^#"),0)) { // Skip commented lines. new QCheckListItem(groupsListView,accounts->gr_name,QCheckListItem::CheckBox); groupComboBox->insertItem(accounts->gr_name); } } QPEApplication::showDialog( this ); } /** * Empty destructor. * */ UserDialog::~UserDialog() {} /** * Creates the first tab, all userinfo is here. * */ void UserDialog::setupTab1() { QPixmap mypixmap; QWidget *tabpage = new QWidget(myTabWidget,"page1"); QVBoxLayout *layout = new QVBoxLayout(tabpage); layout->setMargin(5); // Picture picturePushButton = new QPushButton(tabpage,"Label"); picturePushButton->setMinimumSize(48,48); picturePushButton->setMaximumSize(48,48); picturePushButton->setPixmap(Opie::Core::OResource::loadPixmap("usermanager/usericon")); // Load default usericon. connect(picturePushButton,SIGNAL(clicked()),this,SLOT(clickedPicture())); // Clicking the picture should invoke pictureselector. // Login QLabel *loginLabel=new QLabel(tabpage,"Login: "); loginLabel->setText("Login: "); loginLineEdit=new QLineEdit(tabpage,"Login: "); // UID QLabel *uidLabel=new QLabel(tabpage,"uid: "); uidLabel->setText("UserID: "); uidLineEdit=new QLineEdit(tabpage,"uid: "); uidLineEdit->setEnabled(false); // Username (gecos) QLabel *gecosLabel=new QLabel(tabpage,"gecos"); gecosLabel->setText("Username: "); gecosLineEdit=new QLineEdit(tabpage,"gecos"); // Password QLabel *passwordLabel=new QLabel(tabpage,"password"); passwordLabel->setText("Password: "); passwordLineEdit=new QLineEdit(tabpage,"password"); passwordLineEdit->setEchoMode(QLineEdit::Password); // Shell QLabel *shellLabel=new QLabel(tabpage,"shell"); shellLabel->setText("Shell: "); shellComboBox=new QComboBox(tabpage,"shell"); shellComboBox->setEditable(true); shellComboBox->insertItem("/bin/sh"); shellComboBox->insertItem("/bin/ash"); shellComboBox->insertItem("/bin/false"); // Primary Group QLabel *groupLabel=new QLabel(tabpage,"group"); groupLabel->setText("Primary group: "); groupComboBox=new QComboBox(tabpage,"PrimaryGroup"); if(vm==VIEWMODE_NEW) { // Copy /etc/skel skelLabel=new QLabel(tabpage,"skel"); skelLabel->setText("Copy /etc/skel: "); skelCheckBox=new QCheckBox(tabpage); skelCheckBox->setChecked(true); } // Widget layout QHBoxLayout *hlayout=new QHBoxLayout(-1,"hlayout"); layout->addWidget(picturePushButton); layout->addSpacing(5); layout->addLayout(hlayout); QVBoxLayout *vlayout1=new QVBoxLayout(-1,"vlayout1"); QVBoxLayout *vlayout2=new QVBoxLayout(-1,"vlayout2"); // First column, labels vlayout1->addWidget(loginLabel); vlayout1->addSpacing(5); vlayout1->addWidget(uidLabel); vlayout1->addSpacing(5); vlayout1->addWidget(gecosLabel); vlayout1->addSpacing(5); vlayout1->addWidget(passwordLabel); vlayout1->addSpacing(5); vlayout1->addWidget(shellLabel); vlayout1->addSpacing(5); vlayout1->addWidget(groupLabel); if(vm==VIEWMODE_NEW) { vlayout1->addSpacing(5); vlayout1->addWidget(skelLabel); } // Second column, data vlayout2->addWidget(loginLineEdit); vlayout2->addSpacing(5); vlayout2->addWidget(uidLineEdit); vlayout2->addSpacing(5); vlayout2->addWidget(gecosLineEdit); vlayout2->addSpacing(5); vlayout2->addWidget(passwordLineEdit); vlayout2->addSpacing(5); vlayout2->addWidget(shellComboBox); vlayout2->addSpacing(5); vlayout2->addWidget(groupComboBox); if(vm==VIEWMODE_NEW) { vlayout2->addSpacing(5); vlayout2->addWidget(skelCheckBox); } hlayout->addLayout(vlayout1); hlayout->addLayout(vlayout2); myTabWidget->addTab(tabpage,"User Info"); } /** * Creates the second tab containing additional groups for the user. * */ void UserDialog::setupTab2() { QWidget *tabpage = new QWidget(myTabWidget,"page2"); QVBoxLayout *layout = new QVBoxLayout(tabpage); layout->setMargin(5); // Additional groups groupsListView=new QListView(tabpage,"groups"); groupsListView->addColumn("Additional groups"); groupsListView->setColumnWidthMode(0,QListView::Maximum); groupsListView->setMultiSelection(false); groupsListView->setAllColumnsShowFocus(false); layout->addSpacing(5); // Grouplist layout->addWidget(groupsListView); myTabWidget->addTab(tabpage,"User Groups"); } /** * Static function that creates the userinfo dialog. * The user will be prompted to add a user. * * @param uid This is a suggested available UID. * @param gid This is a suggested available GID. * * @return <code>true</code> if the user was successfully added, otherwise <code>false</code>. * */ bool UserDialog::addUser(int uid, int gid) { QCheckListItem *temp; QFile ozTest; int oz=false; if(ODevice::inst()->system()==System_OpenZaurus) oz=true; // viewmode is a workaround for a bug in qte-2.3.4 that gives bus error on manipulating adduserDialog's widgets here. UserDialog *adduserDialog=new UserDialog(VIEWMODE_NEW); adduserDialog->setCaption(tr("Add User")); adduserDialog->userID=uid; // Set next available UID as default uid. adduserDialog->groupID=gid; // Set next available GID as default gid. // Insert default group into groupComboBox adduserDialog->groupComboBox->insertItem("<create new group>",0); adduserDialog->uidLineEdit->setText(QString::number(uid)); // If we're running on OZ, add new users to some default groups. if(oz) { QListViewItemIterator iter( adduserDialog->groupsListView ); for ( ; iter.current(); ++iter ) { temp=(QCheckListItem*)iter.current(); if (temp->text()=="video") temp->setOn(true); if (temp->text()=="audio") temp->setOn(true); if (temp->text()=="time") temp->setOn(true); if (temp->text()=="power") temp->setOn(true); if (temp->text()=="input") temp->setOn(true); if (temp->text()=="sharp") temp->setOn(true); if (temp->text()=="tty") temp->setOn(true); } } // Show the dialog! if(!(adduserDialog->exec())) return false; if((adduserDialog->groupComboBox->currentItem()!=0)) { - accounts->findGroup(adduserDialog->groupComboBox->currentText()); - adduserDialog->groupID=accounts->gr_gid; - owarn << QString::number(accounts->gr_gid) << oendl; + // making the call findGroup() puts the group info in the accounts gr_gid + if (accounts->findGroup(adduserDialog->groupComboBox->currentText())) + { + adduserDialog->groupID=accounts->gr_gid; + owarn << QString::number(accounts->gr_gid) << oendl; + } } if(!(accounts->addUser(adduserDialog->loginLineEdit->text(), adduserDialog->passwordLineEdit->text(), adduserDialog->uidLineEdit->text().toInt(), adduserDialog->groupID, adduserDialog->gecosLineEdit->text(), QString("/home/")+adduserDialog->loginLineEdit->text() , adduserDialog->shellComboBox->currentText()))) { QMessageBox::information(0,"Ooops!","Something went wrong!\nUnable to add user."); return false; } // Add User to additional groups. QListViewItemIterator it( adduserDialog->groupsListView ); for ( ; it.current(); ++it ) { temp=(QCheckListItem*)it.current(); if (temp->isOn() ) accounts->addGroupMember(it.current()->text(0),adduserDialog->loginLineEdit->text()); } // Copy image to pics/users/ if(!(adduserDialog->userImage.isNull())) { QDir d; if(!(d.exists(QPEApplication::qpeDir() + "pics/users"))) { d.mkdir(QPEApplication::qpeDir() + "pics/users"); } QString filename= QPEApplication::qpeDir()+"pics/users/"+accounts->pw_name+".png"; // adduserDialog->userImage=adduserDialog->userImage.smoothScale(48,48); adduserDialog->userImage.save(filename,"PNG"); } // Should we copy the skeleton homedirectory /etc/skel to the user's homedirectory? accounts->findUser(adduserDialog->loginLineEdit->text()); if(adduserDialog->skelCheckBox->isChecked()) { QString command_cp; QString command_chown; command_cp.sprintf("cp -a /etc/skel/* %s/",accounts->pw_dir.latin1()); system(command_cp); command_cp.sprintf("cp -a /etc/skel/.[!.]* %s/",accounts->pw_dir.latin1()); // Bug in busybox, ".*" includes parent directory, does this work as a workaround? system(command_cp); command_chown.sprintf("chown -R %d:%d %s",accounts->pw_uid,accounts->pw_gid,accounts->pw_dir.latin1()); system(command_chown); } return true; } /** * Deletes the user account. * * @param username User to be deleted. * * @return <code>true</code> if the user was successfully deleted, otherwise <code>false</code>. * */ bool UserDialog::delUser(const char *username) { if((accounts->findUser(username))) { // Does that user exist? if(!(accounts->delUser(username))) { // Delete the user. QMessageBox::information(0,"Ooops!","Something went wrong\nUnable to delete user: "+QString(username)+"."); } } else { QMessageBox::information(0,"Invalid Username","That username ("+QString(username)+")does not exist."); return false; } return true; } /** * This displays a confirmation dialog wether a user should be deleted or not. * (And also deletes the account) * * @param username User to be deleted. * * @return <code>true</code> if the user was successfully deleted, otherwise <code>false</code>. * */ bool UserDialog::editUser(const char *username) { int invalid_group=0; // viewmode is a workaround for a bug in qte-2.3.4 that gives bus error on manipulating edituserDialog's widgets here. UserDialog *edituserDialog=new UserDialog(VIEWMODE_EDIT); // Create Dialog edituserDialog->setCaption(tr("Edit User")); accounts->findUser(username); // Locate user in database and fill variables in 'accounts' object. if(!(accounts->findGroup(accounts->pw_gid))) { // Locate the user's primary group, and fill group variables in 'accounts' object. invalid_group=1; } // Fill widgets with userinfo. edituserDialog->loginLineEdit->setText(accounts->pw_name); edituserDialog->uidLineEdit->setText(QString::number(accounts->pw_uid)); edituserDialog->gecosLineEdit->setText(accounts->pw_gecos); // Set password to '........', we will later check if this still is the contents, if not, the password has been changed. edituserDialog->passwordLineEdit->setText("........"); // If this user is not using /bin/sh,/bin/ash or /bin/false as shell, add that entry to the shell-combobox. if(accounts->pw_shell!="/bin/sh" && accounts->pw_shell!="/bin/ash" && accounts->pw_shell!="/bin/false") { edituserDialog->shellComboBox->insertItem(accounts->pw_shell,0); edituserDialog->shellComboBox->setCurrentItem(0); } // Select the primary group for this user. for(int i=0;i<edituserDialog->groupComboBox->count();++i) { if(accounts->gr_name==edituserDialog->groupComboBox->text(i)) { edituserDialog->groupComboBox->setCurrentItem(i); break; } } if(invalid_group) { edituserDialog->groupComboBox->insertItem("<Undefined group>",0); edituserDialog->groupComboBox->setCurrentItem(0); } // Select the groups in the listview, to which the user belongs. QCheckListItem *temp; // BAH!!! QRegExp in qt2 sucks... or maybe I do... can't figure out how to check for EITHER end of input ($) OR a comma, so here we do two different QRegExps instead. QRegExp userRegExp(QString("[:,]%1$").arg(username)); // The end of line variant. QStringList tempList=accounts->groupStringList.grep(userRegExp); // Find all entries in the group database, that the user is a member of. for(QStringList::Iterator it=tempList.begin(); it!=tempList.end(); ++it) { // Iterate over all of them. owarn << *it << oendl; QListViewItemIterator lvit( edituserDialog->groupsListView ); // Compare to all groups. for ( ; lvit.current(); ++lvit ) { if(lvit.current()->text(0)==(*it).left((*it).find(":"))) { temp=(QCheckListItem*)lvit.current(); temp->setOn(true); // If we find a line with that groupname, select it.; } } } userRegExp=QRegExp(QString("[:,]%1,").arg(username)); // And the other one. (not end of line.) tempList=accounts->groupStringList.grep(userRegExp); // Find all entries in the group database, that the user is a member of. for(QStringList::Iterator it=tempList.begin(); it!=tempList.end(); ++it) { // Iterate over all of them. owarn << *it << oendl; QListViewItemIterator lvit( edituserDialog->groupsListView ); // Compare to all groups. for ( ; lvit.current(); ++lvit ) { if(lvit.current()->text(0)==(*it).left((*it).find(":"))) { temp=(QCheckListItem*)lvit.current(); temp->setOn(true); // If we find a line with that groupname, select it.; } } } if(!(edituserDialog->exec())) return false; // SHOW THE DIALOG! accounts->findUser(username); // Fill user variables in 'acccounts' object. accounts->pw_name=edituserDialog->loginLineEdit->text(); // Has the password been changed ? Make a new "crypt":ed password. if(edituserDialog->passwordLineEdit->text()!="........") accounts->pw_passwd=crypt(edituserDialog->passwordLineEdit->text(), accounts->crypt_make_salt()); // Set all variables in accounts object, that will be used when calling 'updateUser()' accounts->pw_uid=edituserDialog->uidLineEdit->text().toInt(); if(accounts->findGroup(edituserDialog->groupComboBox->currentText())) { // Fill all group variables in 'accounts' object. accounts->pw_gid=accounts->gr_gid; // Only do this if the group is a valid group (ie. "<Undefined group>"), otherwise keep the old group. } accounts->pw_gecos=edituserDialog->gecosLineEdit->text(); accounts->pw_shell=edituserDialog->shellComboBox->currentText(); // Update userinfo, using the information stored in the user variables stored in the accounts object. accounts->updateUser(username); // Remove user from all groups he/she is a member of. (could be done in a better way I guess, this was simple though.) for(QStringList::Iterator it=tempList.begin(); it!=tempList.end(); ++it) { accounts->delGroupMember((*it).left((*it).find(":")),username); } // Add User to additional groups that he/she is a member of. QListViewItemIterator it( edituserDialog->groupsListView ); for ( ; it.current(); ++it ) { temp=(QCheckListItem*)it.current(); if ( temp->isOn() ) accounts->addGroupMember(it.current()->text(0),edituserDialog->loginLineEdit->text()); } // Copy image to pics/users/ if(!(edituserDialog->userImage.isNull())) { QDir d; if(!(d.exists(QPEApplication::qpeDir()+"pics/users"))) { d.mkdir(QPEApplication::qpeDir()+"pics/users"); } QString filename=QPEApplication::qpeDir()+"pics/users/"+accounts->pw_name+".png"; // edituserDialog->userImage=edituserDialog->userImage.smoothScale(48,48); edituserDialog->userImage.save(filename,"PNG"); } return true; } /** * "OK" has been clicked. Verify some information before closing the dialog. * */ void UserDialog::accept() { // Add checking... valid username? username taken? if(loginLineEdit->text().isEmpty()) { QMessageBox::information(0,"Empty Login","Please enter a login."); return; } QDialog::accept(); } /** * This slot is called when the usericon is clicked, this loads (should) the iconselector. * */ void UserDialog::clickedPicture() { QString filename=OFileDialog::getOpenFileName(OFileSelector::EXTENDED, QString::null); if(!(filename.isEmpty())) { userImage.reset(); if(!(userImage.load(filename))) { QMessageBox::information(0,"Sorry!","That icon could not be loaded.\nLoading failed on: "+filename); } else { // userImage=userImage.smoothScale(48,48); QPixmap *picture; picture=(QPixmap *)picturePushButton->pixmap(); picture->convertFromImage(userImage,0); picturePushButton->update(); } } } |