author | erik <erik> | 2007-01-22 22:56:12 (UTC) |
---|---|---|
committer | erik <erik> | 2007-01-22 22:56:12 (UTC) |
commit | 9b4871054d01a47b4c546952a0948553413840d6 (patch) (side-by-side diff) | |
tree | 4e0248489c2790cf4225a116cfb903b637d4cdf0 | |
parent | f60301bab1f8aa3693089036a3791a01ae6f9db8 (diff) | |
download | opie-9b4871054d01a47b4c546952a0948553413840d6.zip opie-9b4871054d01a47b4c546952a0948553413840d6.tar.gz opie-9b4871054d01a47b4c546952a0948553413840d6.tar.bz2 |
Every file in this commit makes a call to a function which returns a value.
Each file also didn't check the return value.
This commit changes it so that every single non-checked call in these files
is checked.
-rw-r--r-- | core/multimedia/opieplayer/om3u.cpp | 3 | ||||
-rw-r--r-- | libopie2/opiemm/opieexif.cpp | 8 | ||||
-rw-r--r-- | noncore/apps/opie-console/filereceive.cpp | 4 | ||||
-rw-r--r-- | noncore/apps/opie-console/filetransfer.cpp | 4 | ||||
-rw-r--r-- | noncore/apps/opie-console/logger.cpp | 4 | ||||
-rw-r--r-- | noncore/apps/opie-console/mainwindow.cpp | 3 | ||||
-rw-r--r-- | noncore/apps/opie-console/script.cpp | 6 | ||||
-rw-r--r-- | noncore/apps/opie-gutenbrowser/gutenbrowser.cpp | 26 | ||||
-rw-r--r-- | noncore/apps/opie-gutenbrowser/helpwindow.cpp | 64 | ||||
-rw-r--r-- | noncore/graphics/opie-eye/slave/bmp_slave.cpp | 4 | ||||
-rw-r--r-- | noncore/net/ftplib/ftplib.c | 8 | ||||
-rw-r--r-- | noncore/todayplugins/stockticker/stockticker/helpwindow.cpp | 42 | ||||
-rw-r--r-- | noncore/todayplugins/weather/weatherpluginwidget.cpp | 5 | ||||
-rw-r--r-- | noncore/tools/opie-sh/inputdialog.cpp | 20 |
14 files changed, 109 insertions, 92 deletions
diff --git a/core/multimedia/opieplayer/om3u.cpp b/core/multimedia/opieplayer/om3u.cpp index 48aa47e..68ea015 100644 --- a/core/multimedia/opieplayer/om3u.cpp +++ b/core/multimedia/opieplayer/om3u.cpp @@ -1,163 +1,164 @@ /* This file is part of the Opie Project Copyright (C) 2002 L. Potter <ljp@llornkcor.com> =. .=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 "om3u.h" /* OPIE */ #include <opie2/odebug.h> static inline QString fullBaseName ( const QFileInfo &fi ) { QString str = fi. fileName ( ); return str. left ( str. findRev ( '.' )); } //extern PlayListWidget *playList; Om3u::Om3u( const QString &filePath, int mode) : QStringList (){ //odebug << "<<<<<<<new m3u "+filePath << oendl; f.setName(filePath); - f.open(mode); + if ( !f.open(mode) ) + owarn << "Failed to open file " << f.name() << oendl; } Om3u::~Om3u(){} void Om3u::readM3u() { // odebug << "<<<<<<reading m3u "+f.name() << oendl; QTextStream t(&f); t.setEncoding(QTextStream::UnicodeUTF8); QString s; while ( !t.atEnd() ) { s=t.readLine(); // odebug << s << oendl; if( s.find( "#", 0, TRUE) == -1 ) { if( s.left(2) == "E:" || s.left(2) == "P:" ) { s = s.right( s.length() -2 ); QFileInfo f( s ); QString name = fullBaseName ( f ); name = name.right( name.length() - name.findRev( "\\", -1, TRUE ) -1 ); s=s.replace( QRegExp( "\\" ), "/" ); append(s); // odebug << s << oendl; } else { // is url s.replace( QRegExp( "%20" )," " ); QString name; // if( name.left( 4 ) == "http" ) { // name = s.right( s.length() - 7 ); // } else { name = s; // } append(name); // odebug << name << oendl; } } } } void Om3u::readPls() { //it's a pls file QTextStream t( &f ); t.setEncoding(QTextStream::UnicodeUTF8); QString s; while ( !t.atEnd() ) { s = t.readLine(); if( s.left(4) == "File" ) { s = s.right( s.length() - 6 ); s.replace( QRegExp( "%20" )," "); // odebug << "adding " + s + " to playlist" << oendl; // numberofentries=2 // File1=http // Title // Length // Version // File2=http s = s.replace( QRegExp( "\\" ), "/" ); QFileInfo f( s ); QString name = fullBaseName ( f ); if( name.left( 4 ) == "http" ) { name = s.right( s.length() - 7); } else { name = s; } name = name.right( name.length() - name.findRev( "\\", -1, TRUE) - 1 ); if( s.at( s.length() - 4) == '.') // if this is probably a file append(s); else { //if its a url if( name.right( 1 ).find( '/' ) == -1) { s += "/"; } append(s); } } } } void Om3u::write() { //writes list to m3u file QString list; QTextStream t(&f); t.setEncoding(QTextStream::UnicodeUTF8); if(count()>0) { for ( QStringList::ConstIterator it = begin(); it != end(); ++it ) { // odebug << *it << oendl; t << *it << "\n"; } } // f.close(); } void Om3u::add(const QString &filePath) { //adds to m3u file append(filePath); } void Om3u::remove(const QString &filePath) { //removes from m3u list QString list, currentFile; if(count()>0) { for ( QStringList::ConstIterator it = begin(); it != end(); ++it ) { currentFile=*it; // odebug << *it << oendl; if( filePath != currentFile) list += currentFile+"\n"; } f.writeBlock( list, list.length() ); } } void Om3u::deleteFile(const QString &) {//deletes m3u file f.close(); f.remove(); } void Om3u::close() { //closes m3u file f.close(); } diff --git a/libopie2/opiemm/opieexif.cpp b/libopie2/opiemm/opieexif.cpp index de49937..653216c 100644 --- a/libopie2/opiemm/opieexif.cpp +++ b/libopie2/opiemm/opieexif.cpp @@ -1,1151 +1,1155 @@ #include "opieexif.h" /* OPIE */ #include <opie2/odebug.h> #include <qpe/timestring.h> /* QT */ #include <qobject.h> #include <qimage.h> /** exif.h */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <qstring.h> #include <qfile.h> #include <qimage.h> //static int HaveAll; //-------------------------------------------------------------------------- // Table of Jpeg encoding process names #define M_SOF0 0xC0 // Start Of Frame N #define M_SOF1 0xC1 // N indicates which compression process #define M_SOF2 0xC2 // Only SOF0-SOF2 are now in common use #define M_SOF3 0xC3 #define M_SOF5 0xC5 // NB: codes C4 and CC are NOT SOF markers #define M_SOF6 0xC6 #define M_SOF7 0xC7 #define M_SOF9 0xC9 #define M_SOF10 0xCA #define M_SOF11 0xCB #define M_SOF13 0xCD #define M_SOF14 0xCE #define M_SOF15 0xCF #define M_SOI 0xD8 // Start Of Image (beginning of datastream) #define M_EOI 0xD9 // End Of Image (end of datastream) #define M_SOS 0xDA // Start Of Scan (begins compressed data) #define M_JFIF 0xE0 // Jfif marker #define M_EXIF 0xE1 // Exif marker #define M_COM 0xFE // COMment //-------------------------------------------------------------------------- // Describes format descriptor static int BytesPerFormat[] = {0,1,1,2,4,8,1,1,2,4,8,4,8}; #define NUM_FORMATS 12 #define FMT_BYTE 1 #define FMT_STRING 2 #define FMT_USHORT 3 #define FMT_ULONG 4 #define FMT_URATIONAL 5 #define FMT_SBYTE 6 #define FMT_UNDEFINED 7 #define FMT_SSHORT 8 #define FMT_SLONG 9 #define FMT_SRATIONAL 10 #define FMT_SINGLE 11 #define FMT_DOUBLE 12 //-------------------------------------------------------------------------- // Describes tag values #define TAG_EXIF_OFFSET 0x8769 #define TAG_INTEROP_OFFSET 0xa005 #define TAG_MAKE 0x010F #define TAG_MODEL 0x0110 #define TAG_ORIENTATION 0x0112 #define TAG_EXPOSURETIME 0x829A #define TAG_FNUMBER 0x829D #define TAG_SHUTTERSPEED 0x9201 #define TAG_APERTURE 0x9202 #define TAG_MAXAPERTURE 0x9205 #define TAG_FOCALLENGTH 0x920A #define TAG_DATETIME_ORIGINAL 0x9003 #define TAG_USERCOMMENT 0x9286 #define TAG_SUBJECT_DISTANCE 0x9206 #define TAG_FLASH 0x9209 #define TAG_FOCALPLANEXRES 0xa20E #define TAG_FOCALPLANEUNITS 0xa210 #define TAG_EXIF_IMAGEWIDTH 0xA002 #define TAG_EXIF_IMAGELENGTH 0xA003 // the following is added 05-jan-2001 vcs #define TAG_EXPOSURE_BIAS 0x9204 #define TAG_WHITEBALANCE 0x9208 #define TAG_METERING_MODE 0x9207 #define TAG_EXPOSURE_PROGRAM 0x8822 #define TAG_ISO_EQUIVALENT 0x8827 #define TAG_COMPRESSION_LEVEL 0x9102 #define TAG_THUMBNAIL_OFFSET 0x0201 #define TAG_THUMBNAIL_LENGTH 0x0202 namespace Opie { namespace MM { class FatalError { const char* ex; public: FatalError(const char* s) { ex = s; } void debug_print() const { owarn << "exception: " << ex << "" << oendl; } }; ExifData::TagTable_t ProcessTable[] = { { M_SOF0, "Baseline"}, { M_SOF1, "Extended sequential"}, { M_SOF2, "Progressive"}, { M_SOF3, "Lossless"}, { M_SOF5, "Differential sequential"}, { M_SOF6, "Differential progressive"}, { M_SOF7, "Differential lossless"}, { M_SOF9, "Extended sequential, arithmetic coding"}, { M_SOF10, "Progressive, arithmetic coding"}, { M_SOF11, "Lossless, arithmetic coding"}, { M_SOF13, "Differential sequential, arithmetic coding"}, { M_SOF14, "Differential progressive, arithmetic coding"}, { M_SOF15, "Differential lossless, arithmetic coding"}, { 0, "Unknown"} }; //-------------------------------------------------------------------------- // Parse the marker stream until SOS or EOI is seen; //-------------------------------------------------------------------------- int ExifData::ReadJpegSections (QFile & infile, ReadMode_t ReadMode) { int a; a = infile.getch(); if (a != 0xff || infile.getch() != M_SOI) { SectionsRead = 0; return false; } for(SectionsRead = 0; SectionsRead < MAX_SECTIONS-1; ){ int marker = 0; int got; unsigned int ll,lh; unsigned int itemlen; uchar * Data; for (a=0;a<7;a++){ marker = infile.getch(); if (marker != 0xff) break; if (a >= 6){ owarn << "too many padding bytes" << oendl; return false; } } if (marker == 0xff){ // 0xff is legal padding, but if we get that many, something's wrong. return false; } Sections[SectionsRead].Type = marker; // Read the length of the section. lh = (uchar) infile.getch(); ll = (uchar) infile.getch(); itemlen = (lh << 8) | ll; if (itemlen < 2) { return false;; } Sections[SectionsRead].Size = itemlen; Data = (uchar *)malloc(itemlen+1); // Add 1 to allow sticking a 0 at the end. Sections[SectionsRead].Data = Data; // Store first two pre-read bytes. Data[0] = (uchar)lh; Data[1] = (uchar)ll; got = infile.readBlock((char*)Data+2, itemlen-2); // Read the whole section. if (( unsigned ) got != itemlen-2){ return false; } SectionsRead++; switch(marker){ case M_SOS: // stop before hitting compressed data // If reading entire image is requested, read the rest of the data. if (ReadMode & READ_IMAGE){ unsigned long size; - size = QMAX( 0ul, infile.size()-infile.at() ); + size = infile.size()-infile.at(); Data = (uchar *)malloc(size); if (Data == NULL){ return false; } got = infile.readBlock((char*)Data, size); if (( unsigned ) got != size){ return false; } Sections[SectionsRead].Data = Data; Sections[SectionsRead].Size = size; Sections[SectionsRead].Type = PSEUDO_IMAGE_MARKER; SectionsRead ++; //HaveAll = 1; } return true; case M_EOI: // in case it's a tables-only JPEG stream owarn << "No image in jpeg!" << oendl; return false; case M_COM: // Comment section // pieczy 2002-02-12 // now the User comment goes to UserComment // so we can store a Comment section also in READ_EXIF mode process_COM(Data, itemlen); break; case M_JFIF: // Regular jpegs always have this tag, exif images have the exif // marker instead, althogh ACDsee will write images with both markers. // this program will re-create this marker on absence of exif marker. // hence no need to keep the copy from the file. free(Sections[--SectionsRead].Data); break; case M_EXIF: // Seen files from some 'U-lead' software with Vivitar scanner // that uses marker 31 for non exif stuff. Thus make sure // it says 'Exif' in the section before treating it as exif. if ((ReadMode & READ_EXIF) && memcmp(Data+2, "Exif", 4) == 0){ process_EXIF((uchar *)Data, itemlen); }else{ // Discard this section. free(Sections[--SectionsRead].Data); } break; case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: process_SOFn(Data, marker); default: break; break; } } return true; } //-------------------------------------------------------------------------- // Discard read data. //-------------------------------------------------------------------------- void ExifData::DiscardData(void) { for (int a=0; a < SectionsRead; a++) free(Sections[a].Data); SectionsRead = 0; } //-------------------------------------------------------------------------- // Convert a 16 bit unsigned value from file's native byte order //-------------------------------------------------------------------------- int ExifData::Get16u(void * Short) { if (MotorolaOrder){ return (((uchar *)Short)[0] << 8) | ((uchar *)Short)[1]; }else{ return (((uchar *)Short)[1] << 8) | ((uchar *)Short)[0]; } } //-------------------------------------------------------------------------- // Convert a 32 bit signed value from file's native byte order //-------------------------------------------------------------------------- int ExifData::Get32s(void * Long) { if (MotorolaOrder){ return ((( char *)Long)[0] << 24) | (((uchar *)Long)[1] << 16) | (((uchar *)Long)[2] << 8 ) | (((uchar *)Long)[3] << 0 ); }else{ return ((( char *)Long)[3] << 24) | (((uchar *)Long)[2] << 16) | (((uchar *)Long)[1] << 8 ) | (((uchar *)Long)[0] << 0 ); } } //-------------------------------------------------------------------------- // Convert a 32 bit unsigned value from file's native byte order //-------------------------------------------------------------------------- unsigned ExifData::Get32u(void * Long) { return (unsigned)Get32s(Long) & 0xffffffff; } //-------------------------------------------------------------------------- // Evaluate number, be it int, rational, or float from directory. //-------------------------------------------------------------------------- double ExifData::ConvertAnyFormat(void * ValuePtr, int Format) { double Value; Value = 0; switch(Format){ case FMT_SBYTE: Value = *(signed char *)ValuePtr; break; case FMT_BYTE: Value = *(uchar *)ValuePtr; break; case FMT_USHORT: Value = Get16u(ValuePtr); break; case FMT_ULONG: Value = Get32u(ValuePtr); break; case FMT_URATIONAL: case FMT_SRATIONAL: { int Num,Den; Num = Get32s(ValuePtr); Den = Get32s(4+(char *)ValuePtr); if (Den == 0){ Value = 0; }else{ Value = (double)Num/Den; } break; } case FMT_SSHORT: Value = (signed short)Get16u(ValuePtr); break; case FMT_SLONG: Value = Get32s(ValuePtr); break; // Not sure if this is correct (never seen float used in Exif format) case FMT_SINGLE: Value = (double)*(float *)ValuePtr; break; case FMT_DOUBLE: Value = *(double *)ValuePtr; break; } return Value; } //-------------------------------------------------------------------------- // Process one of the nested EXIF directories. //-------------------------------------------------------------------------- void ExifData::ProcessExifDir(unsigned char * DirStart, unsigned char * OffsetBase, unsigned ExifLength) { int de; int a; int NumDirEntries; unsigned ThumbnailOffset = 0; unsigned ThumbnailSize = 0; NumDirEntries = Get16u(DirStart); #define DIR_ENTRY_ADDR(Start, Entry) (Start+2+12*(Entry)) { unsigned char * DirEnd; DirEnd = DIR_ENTRY_ADDR(DirStart, NumDirEntries); if (DirEnd+4 > (OffsetBase+ExifLength)){ if (DirEnd+2 == OffsetBase+ExifLength || DirEnd == OffsetBase+ExifLength){ // Version 1.3 of jhead would truncate a bit too much. // This also caught later on as well. }else{ // Note: Files that had thumbnails trimmed with jhead 1.3 or earlier // might trigger this. return; } } if (DirEnd < LastExifRefd) LastExifRefd = DirEnd; } for (de=0;de<NumDirEntries;de++){ int Tag, Format, Components; unsigned char * ValuePtr; int ByteCount; char * DirEntry; DirEntry = (char *)DIR_ENTRY_ADDR(DirStart, de); Tag = Get16u(DirEntry); Format = Get16u(DirEntry+2); Components = Get32u(DirEntry+4); if ((Format-1) >= NUM_FORMATS) { // (-1) catches illegal zero case as unsigned underflows to positive large. return; } ByteCount = Components * BytesPerFormat[Format]; if (ByteCount > 4){ unsigned OffsetVal; OffsetVal = Get32u(DirEntry+8); // If its bigger than 4 bytes, the dir entry contains an offset. if (OffsetVal+ByteCount > ExifLength){ // Bogus pointer offset and / or bytecount value //printf("Offset %d bytes %d ExifLen %d\n",OffsetVal, ByteCount, ExifLength); return; } ValuePtr = OffsetBase+OffsetVal; }else{ // 4 bytes or less and value is in the dir entry itself ValuePtr = (unsigned char *)DirEntry+8; } if (LastExifRefd < ValuePtr+ByteCount){ // Keep track of last byte in the exif header that was actually referenced. // That way, we know where the discardable thumbnail data begins. LastExifRefd = ValuePtr+ByteCount; } // Extract useful components of tag switch(Tag){ case TAG_MAKE: ExifData::CameraMake = QString((char*)ValuePtr); break; case TAG_MODEL: ExifData::CameraModel = QString((char*)ValuePtr); break; case TAG_ORIENTATION: Orientation = (int)ConvertAnyFormat(ValuePtr, Format); break; case TAG_DATETIME_ORIGINAL: DateTime = QString((char*)ValuePtr); break; case TAG_USERCOMMENT: // Olympus has this padded with trailing spaces. Remove these first. for (a=ByteCount;;){ a--; if ((ValuePtr)[a] == ' '){ (ValuePtr)[a] = '\0'; }else{ break; } if (a == 0) break; } // Copy the comment if (memcmp(ValuePtr, "ASCII",5) == 0){ for (a=5;a<10;a++){ int c; c = (ValuePtr)[a]; if (c != '\0' && c != ' '){ //strncpy(ImageInfo.Comments, (const char*)(a+ValuePtr), 199); UserComment.sprintf("%s", (const char*)(a+ValuePtr)); break; } } }else{ //strncpy(ImageInfo.Comments, (const char*)ValuePtr, 199); UserComment.sprintf("%s", (const char*)ValuePtr); } break; case TAG_FNUMBER: // Simplest way of expressing aperture, so I trust it the most. // (overwrite previously computd value if there is one) ExifData::ApertureFNumber = (float)ConvertAnyFormat(ValuePtr, Format); break; case TAG_APERTURE: case TAG_MAXAPERTURE: // More relevant info always comes earlier, so only use this field if we don't // have appropriate aperture information yet. if (ExifData::ApertureFNumber == 0){ ExifData::ApertureFNumber = (float)exp(ConvertAnyFormat(ValuePtr, Format)*log(2)*0.5); } break; case TAG_FOCALLENGTH: // Nice digital cameras actually save the focal length as a function // of how farthey are zoomed in. ExifData::FocalLength = (float)ConvertAnyFormat(ValuePtr, Format); break; case TAG_SUBJECT_DISTANCE: // Inidcates the distacne the autofocus camera is focused to. // Tends to be less accurate as distance increases. ExifData::Distance = (float)ConvertAnyFormat(ValuePtr, Format); break; case TAG_EXPOSURETIME: // Simplest way of expressing exposure time, so I trust it most. // (overwrite previously computd value if there is one) ExifData::ExposureTime = (float)ConvertAnyFormat(ValuePtr, Format); break; case TAG_SHUTTERSPEED: // More complicated way of expressing exposure time, so only use // this value if we don't already have it from somewhere else. if (ExifData::ExposureTime == 0){ ExifData::ExposureTime = (float)(1/exp(ConvertAnyFormat(ValuePtr, Format)*log(2))); } break; case TAG_FLASH: if (ConvertAnyFormat(ValuePtr, Format)){ ExifData::FlashUsed = 1; } break; case TAG_EXIF_IMAGELENGTH: ExifImageLength = (int)ConvertAnyFormat(ValuePtr, Format); break; case TAG_EXIF_IMAGEWIDTH: ExifImageWidth = (int)ConvertAnyFormat(ValuePtr, Format); break; case TAG_FOCALPLANEXRES: FocalplaneXRes = ConvertAnyFormat(ValuePtr, Format); break; case TAG_FOCALPLANEUNITS: switch((int)ConvertAnyFormat(ValuePtr, Format)){ case 1: FocalplaneUnits = 25.4; break; // inch case 2: // According to the information I was using, 2 means meters. // But looking at the Cannon powershot's files, inches is the only // sensible value. FocalplaneUnits = 25.4; break; case 3: FocalplaneUnits = 10; break; // centimeter case 4: FocalplaneUnits = 1; break; // milimeter case 5: FocalplaneUnits = .001; break; // micrometer } break; // Remaining cases contributed by: Volker C. Schoech (schoech@gmx.de) case TAG_EXPOSURE_BIAS: ExifData::ExposureBias = (float)ConvertAnyFormat(ValuePtr, Format); break; case TAG_WHITEBALANCE: ExifData::Whitebalance = (int)ConvertAnyFormat(ValuePtr, Format); break; case TAG_METERING_MODE: ExifData::MeteringMode = (int)ConvertAnyFormat(ValuePtr, Format); break; case TAG_EXPOSURE_PROGRAM: ExifData::ExposureProgram = (int)ConvertAnyFormat(ValuePtr, Format); break; case TAG_ISO_EQUIVALENT: ExifData::ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format); if ( ExifData::ISOequivalent < 50 ) ExifData::ISOequivalent *= 200; break; case TAG_COMPRESSION_LEVEL: ExifData::CompressionLevel = (int)ConvertAnyFormat(ValuePtr, Format); break; case TAG_THUMBNAIL_OFFSET: ThumbnailOffset = (unsigned)ConvertAnyFormat(ValuePtr, Format); break; case TAG_THUMBNAIL_LENGTH: ThumbnailSize = (unsigned)ConvertAnyFormat(ValuePtr, Format); break; } if (Tag == TAG_EXIF_OFFSET || Tag == TAG_INTEROP_OFFSET){ unsigned char * SubdirStart; SubdirStart = OffsetBase + Get32u(ValuePtr); if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength){ return; } ProcessExifDir(SubdirStart, OffsetBase, ExifLength); continue; } } { // In addition to linking to subdirectories via exif tags, // there's also a potential link to another directory at the end of each // directory. this has got to be the result of a comitee! unsigned char * SubdirStart; unsigned Offset; if (DIR_ENTRY_ADDR(DirStart, NumDirEntries) + 4 <= OffsetBase+ExifLength){ Offset = Get32u(DIR_ENTRY_ADDR(DirStart, NumDirEntries)); // There is at least one jpeg from an HP camera having an Offset of almost MAXUINT. // Adding OffsetBase to it produces an overflow, so compare with ExifLength here. // See http://bugs.kde.org/show_bug.cgi?id=54542 if (Offset && Offset < ExifLength){ SubdirStart = OffsetBase + Offset; if (SubdirStart > OffsetBase+ExifLength){ if (SubdirStart < OffsetBase+ExifLength+20){ // Jhead 1.3 or earlier would crop the whole directory! // As Jhead produces this form of format incorrectness, // I'll just let it pass silently owarn << "Thumbnail removed with Jhead 1.3 or earlier" << oendl; }else{ return; } }else{ if (SubdirStart <= OffsetBase+ExifLength){ ProcessExifDir(SubdirStart, OffsetBase, ExifLength); } } } }else{ // The exif header ends before the last next directory pointer. } } if (ThumbnailSize && ThumbnailOffset){ if (ThumbnailSize + ThumbnailOffset <= ExifLength){ // The thumbnail pointer appears to be valid. Store it. Thumbnail.loadFromData(OffsetBase + ThumbnailOffset, ThumbnailSize, "JPEG"); } } } //-------------------------------------------------------------------------- // Process a COM marker. We want to leave the bytes unchanged. The // progam that displays this text may decide to remove blanks, convert // newlines, or otherwise modify the text. In particular we want to be // safe for passing utf-8 text. //-------------------------------------------------------------------------- void ExifData::process_COM (const uchar * Data, int length) { QChar ch; int a; for (a=2;a<length;a++){ ch = Data[a]; if (ch == '\000') continue; // Remove nulls Comment.append(ch); } } //-------------------------------------------------------------------------- // Process a SOFn marker. This is useful for the image dimensions //-------------------------------------------------------------------------- void ExifData::process_SOFn (const uchar * Data, int marker) { int data_precision, num_components; data_precision = Data[2]; ExifData::Height = Get16m(Data+3); ExifData::Width = Get16m(Data+5); num_components = Data[7]; if (num_components == 3){ ExifData::IsColor = 1; }else{ ExifData::IsColor = 0; } ExifData::Process = marker; } //-------------------------------------------------------------------------- // Get 16 bits motorola order (always) for jpeg header stuff. //-------------------------------------------------------------------------- int ExifData::Get16m(const void * Short) { return (((uchar *)Short)[0] << 8) | ((uchar *)Short)[1]; } //-------------------------------------------------------------------------- // Process a EXIF marker // Describes all the drivel that most digital cameras include... //-------------------------------------------------------------------------- void ExifData::process_EXIF(unsigned char * CharBuf, unsigned int length) { ExifData::FlashUsed = 0; // If it s from a digicam, and it used flash, it says so. FocalplaneXRes = 0; FocalplaneUnits = 0; ExifImageWidth = 0; ExifImageLength = 0; { // Check the EXIF header component static const uchar ExifHeader[] = "Exif\0\0"; if (memcmp(CharBuf+2, ExifHeader,6)){ return; } } if (memcmp(CharBuf+8,"II",2) == 0){ // printf("Exif section in Intel order\n"); MotorolaOrder = 0; }else{ if (memcmp(CharBuf+8,"MM",2) == 0){ // printf("Exif section in Motorola order\n"); MotorolaOrder = 1; }else{ return; } } // Check the next two values for correctness. if (Get16u(CharBuf+10) != 0x2a || Get32u(CharBuf+12) != 0x08){ return; } LastExifRefd = CharBuf; // First directory starts 16 bytes in. Offsets start at 8 bytes in. ProcessExifDir(CharBuf+16, CharBuf+8, length-6); // This is how far the interesting (non thumbnail) part of the exif went. ExifSettingsLength = LastExifRefd - CharBuf; // Compute the CCD width, in milimeters. if (FocalplaneXRes != 0){ ExifData::CCDWidth = (float)(ExifImageWidth * FocalplaneUnits / FocalplaneXRes); } } //-------------------------------------------------------------------------- // Convert exif time to Unix time structure //-------------------------------------------------------------------------- int ExifData::Exif2tm(struct ::tm * timeptr, char * ExifTime) { int a; timeptr->tm_wday = -1; // Check for format: YYYY:MM:DD HH:MM:SS format. a = sscanf(ExifTime, "%d:%d:%d %d:%d:%d", &timeptr->tm_year, &timeptr->tm_mon, &timeptr->tm_mday, &timeptr->tm_hour, &timeptr->tm_min, &timeptr->tm_sec); if (a == 6){ timeptr->tm_isdst = -1; timeptr->tm_mon -= 1; // Adjust for unix zero-based months timeptr->tm_year -= 1900; // Adjust for year starting at 1900 return true; // worked. } return false; // Wasn't in Exif date format. } //-------------------------------------------------------------------------- // Contructor for initialising //-------------------------------------------------------------------------- ExifData::ExifData() { ExifData::Whitebalance = -1; ExifData::MeteringMode = -1; ExifData::FlashUsed = -1; Orientation = 0; Height = 0; Width = 0; IsColor = 0; Process = 0; FocalLength = 0; ExposureTime = 0; ApertureFNumber = 0; Distance = 0; CCDWidth = 0; ExposureBias = 0; ExposureProgram = 0; ISOequivalent = 0; CompressionLevel = 0; MotorolaOrder = 0; } ExifData::~ExifData() { } //-------------------------------------------------------------------------- // process a EXIF jpeg file //-------------------------------------------------------------------------- bool ExifData::scan(const QString & path) { int ret; QFile f(path); - f.open(IO_ReadOnly); + if ( !f.open(IO_ReadOnly) ) { + owarn << "Unable to open file " << f.name() << " readonly" << oendl; + DiscardData(); + return false; + } // Scan the JPEG headers. ret = ReadJpegSections(f, READ_EXIF); if (ret == false){ owarn << "Not JPEG file!" << oendl; DiscardData(); f.close(); return false; } f.close(); DiscardData(); //now make the strings clean, // for exmaple my Casio is a "QV-4000 " CameraMake = CameraMake.stripWhiteSpace(); CameraModel = CameraModel.stripWhiteSpace(); UserComment = UserComment.stripWhiteSpace(); Comment = Comment.stripWhiteSpace(); return true; } //-------------------------------------------------------------------------- // Does the embedded thumbnail match the jpeg image? //-------------------------------------------------------------------------- #ifndef JPEG_TOL #define JPEG_TOL 0.02 #endif bool ExifData::isThumbnailSane() { if (Thumbnail.isNull()) return false; // check whether thumbnail dimensions match the image // not foolproof, but catches some altered images (jpegtran -rotate) if (ExifImageLength != 0 && ExifImageLength != Height) return false; if (ExifImageWidth != 0 && ExifImageWidth != Width) return false; if (Thumbnail.width() == 0 || Thumbnail.height() == 0) return false; if (Height == 0 || Width == 0) return false; double d = (double)Height/Width*Thumbnail.width()/Thumbnail.height(); return (1-JPEG_TOL < d) && (d < 1+JPEG_TOL); } static QImage flip_image( const QImage& img ); static QImage rotate_90( const QImage& img ); static QImage rotate_180( const QImage& ); static QImage rotate_270( const QImage& ); //-------------------------------------------------------------------------- // return a thumbnail that respects the orientation flag // only if it seems sane //-------------------------------------------------------------------------- QImage ExifData::getThumbnail() { if (!isThumbnailSane()) return NULL; if (!Orientation || Orientation == 1) return Thumbnail; // now fix orientation QImage dest = Thumbnail; switch (Orientation) { // notice intentional fallthroughs case 2: dest = flip_image( dest ); break; case 4: dest = flip_image( dest ); case 3: dest =rotate_180( dest ); break; case 5: dest = flip_image( dest ); case 6: dest = rotate_90( dest ); break; case 7: dest = flip_image( dest ); case 8: dest = rotate_270( dest ); break; default: break; // should never happen } return dest; } /* * */ static QImage flip_image( const QImage& img ) { return img.mirror( TRUE, FALSE ); } static QImage dest; static int x, y; static unsigned int *srcData, *destData; // we're not threaded anyway static unsigned char *srcData8, *destData8; // 8 bit is char static unsigned int *srcTable, *destTable; // destination table static QImage rotate_90_8( const QImage &img ) { dest.create(img.height(), img.width(), img.depth()); dest.setNumColors(img.numColors()); srcTable = (unsigned int *)img.colorTable(); destTable = (unsigned int *)dest.colorTable(); for ( x=0; x < img.numColors(); ++x ) destTable[x] = srcTable[x]; for ( y=0; y < img.height(); ++y ){ srcData8 = (unsigned char *)img.scanLine(y); for ( x=0; x < img.width(); ++x ){ destData8 = (unsigned char *)dest.scanLine(x); destData8[img.height()-y-1] = srcData8[x]; } } return dest; } static QImage rotate_90_all( const QImage& img ) { dest.create(img.height(), img.width(), img.depth()); for ( y=0; y < img.height(); ++y ) { srcData = (unsigned int *)img.scanLine(y); for ( x=0; x < img.width(); ++x ) { destData = (unsigned int *)dest.scanLine(x); destData[img.height()-y-1] = srcData[x]; } } return dest; } static QImage rotate_90( const QImage & img ) { if ( img.depth() > 8) return rotate_90_all( img ); else return rotate_90_8( img ); } static QImage rotate_180_all( const QImage& img ) { dest.create(img.width(), img.height(), img.depth()); for ( y=0; y < img.height(); ++y ){ srcData = (unsigned int *)img.scanLine(y); destData = (unsigned int *)dest.scanLine(img.height()-y-1); for ( x=0; x < img.width(); ++x ) destData[img.width()-x-1] = srcData[x]; } return dest; } static QImage rotate_180_8( const QImage& img ) { dest.create(img.width(), img.height(), img.depth()); dest.setNumColors(img.numColors()); srcTable = (unsigned int *)img.colorTable(); destTable = (unsigned int *)dest.colorTable(); for ( x=0; x < img.numColors(); ++x ) destTable[x] = srcTable[x]; for ( y=0; y < img.height(); ++y ){ srcData8 = (unsigned char *)img.scanLine(y); destData8 = (unsigned char *)dest.scanLine(img.height()-y-1); for ( x=0; x < img.width(); ++x ) destData8[img.width()-x-1] = srcData8[x]; } return dest; } static QImage rotate_180( const QImage& img ) { if ( img.depth() > 8 ) return rotate_180_all( img ); else return rotate_180_8( img ); } static QImage rotate_270_8( const QImage& img ) { dest.create(img.height(), img.width(), img.depth()); dest.setNumColors(img.numColors()); srcTable = (unsigned int *)img.colorTable(); destTable = (unsigned int *)dest.colorTable(); for ( x=0; x < img.numColors(); ++x ) destTable[x] = srcTable[x]; for ( y=0; y < img.height(); ++y ){ srcData8 = (unsigned char *)img.scanLine(y); for ( x=0; x < img.width(); ++x ){ destData8 = (unsigned char *)dest.scanLine(img.width()-x-1); destData8[y] = srcData8[x]; } } return dest; } static QImage rotate_270_all( const QImage& img ) { dest.create(img.height(), img.width(), img.depth()); for ( y=0; y < img.height(); ++y ){ srcData = (unsigned int *)img.scanLine(y); for ( x=0; x < img.width(); ++x ){ destData = (unsigned int *)dest.scanLine(img.width()-x-1); destData[y] = srcData[x]; } } return dest; } static QImage rotate_270( const QImage& img ) { if ( img.depth() > 8 ) return rotate_270_all( img ); else return rotate_270_8( img ); } QString ExifData::color_mode_to_string( bool b ) { return b ? QObject::tr( "Colormode: Color\n" ) : QObject::tr( "Colormode: Black and white\n" ); } QString ExifData::compression_to_string( int level ) { QString str; switch( level ) { case 1: str = QObject::tr( "Basic" ); break; case 2: str = QObject::tr( "Normal" ); break; case 4: str = QObject::tr( "Fine" ); break; default: str = QObject::tr( "Unknown" ); } return QObject::tr("Quality: %1\n").arg(str); } QString ExifData::white_balance_string( int i ) { QString balance; switch ( i ) { case 0: balance = QObject::tr( "Unknown" ); break; case 1: balance = QObject::tr( "Daylight" ); break; case 2: balance = QObject::tr( "Fluorescent" ); break; case 3: balance = QObject::tr( "Tungsten" ); break; case 17: balance = QObject::tr( "Standard light A" ); break; case 18: balance = QObject::tr( "Standard light B" ); break; case 19: balance = QObject::tr( "Standard light C" ); break; case 20: balance = QObject::tr( "D55" ); break; case 21: balance = QObject::tr( "D65" ); break; case 22: balance = QObject::tr( "D75" ); break; case 255: balance = QObject::tr( "Other" ); break; default: balance = QObject::tr( "Unknown" ); } return QObject::tr( "White Balance: %1\n" ).arg( balance ); } QString ExifData::metering_mode( int i) { QString meter; switch( i ) { case 0: meter = QObject::tr( "Unknown" ); break; case 1: meter = QObject::tr( "Average" ); break; case 2: meter = QObject::tr( "Center weighted average" ); break; case 3: meter = QObject::tr( "Spot" ); break; case 4: meter = QObject::tr( "MultiSpot" ); break; case 5: meter = QObject::tr( "Pattern" ); break; case 6: meter = QObject::tr( "Partial" ); break; case 255: meter = QObject::tr( "Other" ); break; default: meter = QObject::tr( "Unknown" ); } return QObject::tr( "Metering Mode: %1\n" ).arg( meter ); } QString ExifData::exposure_program( int i ) { QString exp; switch( i ) { case 0: exp = QObject::tr( "Not defined" ); break; case 1: exp = QObject::tr( "Manual" ); break; case 2: exp = QObject::tr( "Normal progam" ); break; case 3: exp = QObject::tr( "Aperture priority" ); break; case 4: exp = QObject::tr( "Shutter priority" ); break; case 5: exp = QObject::tr( "Creative progam\n(biased toward fast shutter speed" ); break; case 6: exp = QObject::tr( "Action progam\n(biased toward fast shutter speed)" ); break; case 7: exp = QObject::tr( "Portrait mode\n(for closeup photos with the background out of focus)" ); break; case 8: exp = QObject::tr( "Landscape mode\n(for landscape photos with the background in focus)" ); break; default: exp = QObject::tr( "Unknown" ); } return QObject::tr( "Exposure Program: %1\n" ).arg( exp ); } } // namespace MM } // namespace OPIE diff --git a/noncore/apps/opie-console/filereceive.cpp b/noncore/apps/opie-console/filereceive.cpp index 452be60..41e6888 100644 --- a/noncore/apps/opie-console/filereceive.cpp +++ b/noncore/apps/opie-console/filereceive.cpp @@ -1,162 +1,164 @@ #include <unistd.h> #include <fcntl.h> #include <signal.h> #include <errno.h> +#include <opie2/odebug.h> #include <qsocketnotifier.h> #include "io_layer.h" #include "procctl.h" #include "filereceive.h" FileReceive::FileReceive( Type t, IOLayer* lay, const QString& dir ) : ReceiveLayer(lay, dir ), m_type( t ) { m_fd = -1; m_not = 0l; m_proc = 0l; } FileReceive::~FileReceive() { } void FileReceive::receive() { receive( currentDir() ); } void FileReceive::receive( const QString& dir ) { m_prog = -1; m_fd = layer()->rawIO(); m_curDir = dir; if (pipe( m_comm ) < 0 ) m_comm[0] = m_comm[1] = 0; if (pipe( m_info ) < 0 ) m_info[0] = m_info[1] = 0; m_pid = fork(); switch( m_pid ) { case -1: //emit error slotExec(); break; /* child */ case 0: { setupChild(); char* typus = NULL; switch(m_type ) { case SZ: break; case SX: typus = "-X"; break; case SY: typus = "--ymodem"; break; } /* we should never return from here */ if( m_type == SX ) // FIXME: file name should be configurable - currently we ensure it // doesn't get overwritten by -E (--rename) execlp("rz", "rz", typus, "--overwrite", QObject::tr("SynchronizedFile").latin1(), NULL ); else execlp("rz", "rz", typus, "--overwrite", NULL ); char resultByte = 1; if (m_info[1] ) ::write(m_info[1], &resultByte, 1 ); _exit( -1 ); break; } default: { if ( m_info[1] ) close( m_info[1] ); if ( m_info[0] ) for (;;) { char resultByte; int len; len = read(m_info[0], &resultByte, 1 ); /* len == 1 start up failed */ if ( len == 1 ) { emit error( StartError, tr("Could not start") ); return; } if ( len == -1 ) if ( (errno == ECHILD ) || (errno == EINTR ) ) continue; // len == 0 or something like this break; } if ( m_info[0] ) close( m_info[0] ); m_not = new QSocketNotifier(m_comm[0], QSocketNotifier::Read ); connect(m_not, SIGNAL(activated(int) ), this, SLOT(slotRead() ) ); if ( pipe(m_term) < 0 ) m_term[0] = m_term[1] = 0; ProcCtl::self()->add(m_pid, m_term[1] ); m_proc = new QSocketNotifier(m_term[0], QSocketNotifier::Read ); connect(m_proc, SIGNAL(activated(int) ), this, SLOT(slotExec() ) ); } break; } } void FileReceive::cancel() { ::kill(m_pid, 9 ); } void FileReceive::setupChild() { changeDir( currentDir() ); /* * we do not want to read from our * information channel */ if (m_info[0] ) close(m_info[0] ); /* * FD_CLOEXEC will close the * fd on successful exec */ if (m_info[1] ) fcntl(m_info[1], F_SETFD, FD_CLOEXEC ); if (m_comm[0] ) close( m_comm[0] ); /* * now set the communication * m_fd STDIN_FILENO * STDOUT_FILENO * STDERR_FILENO */ dup2( m_fd, STDIN_FILENO ); dup2( m_fd, STDOUT_FILENO ); dup2( m_comm[1], STDERR_FILENO ); } void FileReceive::slotRead() { QByteArray ar(4096); int len = read(m_comm[0], ar.data(), 4096 ); for (int i = 0; i < len; i++ ) { // printf("%c", ar[i] ); } ar.resize( len ); QString str( ar ); } void FileReceive::slotExec() { char buf[2]; - ::read(m_term[0], buf, 1 ); + if (::read(m_term[0], buf, 1 ) == -1) + owarn << "read of m_term[0] failed" << oendl; delete m_proc; delete m_not; m_not = m_proc = 0l; close( m_term[0] ); close( m_term[1] ); close( m_comm[0] ); close( m_comm[1] ); layer()->closeRawIO(m_fd); emit received(QString::null); } diff --git a/noncore/apps/opie-console/filetransfer.cpp b/noncore/apps/opie-console/filetransfer.cpp index 7eebc65..6e2d2d5 100644 --- a/noncore/apps/opie-console/filetransfer.cpp +++ b/noncore/apps/opie-console/filetransfer.cpp @@ -1,248 +1,250 @@ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> +#include <opie2/odebug.h> #include <qsocketnotifier.h> #include "procctl.h" #include "filetransfer.h" FileTransfer::FileTransfer( Type t, IOLayer* lay ) : FileTransferLayer( lay ), m_type( t ), m_pid ( 0 ) { signal(SIGPIPE, SIG_IGN ); m_pid = 0; m_not = 0l; m_proc = 0l; } FileTransfer::~FileTransfer() { } /** * now we will send the file. * * we request an fd. The IOLayer should be closed * then we will setup a pipe for progress communication * then we will dup2 the m_fd in the forked process * to do direct IO from and to the fd */ void FileTransfer::sendFile( const QString& file ) { m_prog =-1; m_fd = layer()->rawIO(); // // m_fd = ::open("/dev/ttyS0", O_RDWR); m_file = file; if ( pipe( m_comm ) < 0 ) m_comm[0] = m_comm[1] = 0; if ( pipe( m_info ) < 0 ) m_info[0] = m_info[1] = 0; m_pid = fork(); switch( m_pid ) { case -1: emit error( StartError, tr("Was not able to fork") ); slotExec(); break; case 0:{ setupChild(); /* exec */ char* verbose = "-vv"; char* binray = "-b"; char* typus; switch(m_type ) { default: case SZ: typus = ""; break; case SX: typus = "-X"; break; case SY: typus = "--ymodem"; break; } /* we should never return from here */ execlp("sz", "sz", verbose, binray, file.latin1(), typus, NULL ); /* communication for error!*/ char resultByte =1; if (m_info[1] ) write(m_info[1], &resultByte, 1 ); _exit( -1 ); break; } default:{ if ( m_info[1] ) close( m_info[1] ); if ( m_info[0] ) for (;;) { char resultByte; int len; len = read(m_info[0], &resultByte, 1 ); /* len == 1 start up failed */ if ( len == 1 ) { emit error( StartError, tr("Could not start") ); return; } if ( len == -1 ) if ( (errno == ECHILD ) || (errno == EINTR ) ) continue; // len == 0 or something like this break; } if ( m_info[0] ) close( m_info[0] ); /* replace by QSocketNotifier!!! */ m_not = new QSocketNotifier(m_comm[0], QSocketNotifier::Read ); connect(m_not, SIGNAL(activated(int) ), this, SLOT(slotRead() ) ); if ( pipe(m_term) < 0 ) m_term[0] = m_term[1] = 0; ProcCtl::self()->add(m_pid, m_term[1] ); m_proc = new QSocketNotifier(m_term[0], QSocketNotifier::Read ); connect(m_proc, SIGNAL(activated(int) ), this, SLOT(slotExec() ) ); } break; } } /* * let's call the one with the filename */ void FileTransfer::sendFile( const QFile& file ) { sendFile( file.name() ); } /* * setting up communication * between parent child and ioLayer */ void FileTransfer::setupChild() { /* * we do not want to read from our * information channel */ if (m_info[0] ) close(m_info[0] ); /* * FD_CLOEXEC will close the * fd on successful exec */ if (m_info[1] ) fcntl(m_info[1], F_SETFD, FD_CLOEXEC ); if (m_comm[0] ) close( m_comm[0] ); /* * now set the communication * m_fd STDIN_FILENO * STDOUT_FILENO * STDERR_FILENO */ dup2( m_fd, STDIN_FILENO ); dup2( m_fd, STDOUT_FILENO ); dup2( m_comm[1], STDERR_FILENO ); } /* * read from the stderr of the child * process */ void FileTransfer::slotRead() { QByteArray ar(4096); int len = read(m_comm[0], ar.data(), 4096 ); for (int i = 0; i < len; i++ ) { // printf("%c", ar[i] ); } ar.resize( len ); QString str( ar ); QStringList lis = QStringList::split(' ', str ); /* * Transfer finished.. either complete or incomplete */ if ( lis[0].simplifyWhiteSpace() == "Transfer" ) { return; } /* * do progress reading */ slotProgress( lis ); } /* * find the progress */ void FileTransfer::slotProgress( const QStringList& list ) { if ( m_type != SZ ) return; bool complete = true; int min, sec; int bps; unsigned long sent, total; min = sec = bps = -1; sent = total = 0; // Data looks like this // 0 1 2 3 4 5 // Bytes Sent 65536/11534336 BPS:7784 ETA 24:33 QStringList progi = QStringList::split('/', list[2].simplifyWhiteSpace() ); sent = progi[0].toULong(&complete ); if (!complete ) return; total = progi[1].toULong(&complete ); if (!complete || total == 0) { return; } double pro = (double)sent/total; int prog = pro * 100; // speed progi = QStringList::split(':', list[3].simplifyWhiteSpace() ); bps = progi[1].toInt(); // time progi = QStringList::split(':', list[5].simplifyWhiteSpace() ); min = progi[0].toInt(); sec = progi[1].toInt(); if ( prog > m_prog ) { m_prog = prog; emit progress(m_file, m_prog, bps, -1, min , sec ); } } void FileTransfer::cancel() { if(m_pid > 0) ::kill(m_pid,9 ); } void FileTransfer::slotExec() { char buf[2]; - ::read(m_term[0], buf, 1 ); + if (::read(m_term[0], buf, 1 ) == -1) + owarn << "read of m_term[0] failed" << oendl; delete m_proc; delete m_not; m_proc = m_not = 0l; close( m_term[0] ); close( m_term[1] ); close( m_comm[0] ); close( m_comm[1] ); layer()->closeRawIO( m_fd ); emit sent(); m_pid = 0; } diff --git a/noncore/apps/opie-console/logger.cpp b/noncore/apps/opie-console/logger.cpp index 6620faf..0fdeca0 100644 --- a/noncore/apps/opie-console/logger.cpp +++ b/noncore/apps/opie-console/logger.cpp @@ -1,20 +1,22 @@ #include <qfile.h> #include <qtextstream.h> +#include <opie2/odebug.h> #include "logger.h" Logger::Logger() {} Logger::Logger(const QString fileName) { m_file.setName(fileName); - m_file.open(IO_ReadWrite); + if ( !m_file.open(IO_ReadWrite) ) + owarn << "failed to open " << m_file.name() << oendl; } Logger::~Logger() { m_file.close(); } void Logger::append(QByteArray ar) { m_file.writeBlock(ar); } diff --git a/noncore/apps/opie-console/mainwindow.cpp b/noncore/apps/opie-console/mainwindow.cpp index 18c0434..aba7244 100644 --- a/noncore/apps/opie-console/mainwindow.cpp +++ b/noncore/apps/opie-console/mainwindow.cpp @@ -1,834 +1,835 @@ #include "TEmulation.h" #include "profileeditordialog.h" #include "configdialog.h" #include "default.h" #include "profilemanager.h" #include "mainwindow.h" #include "tabwidget.h" #include "transferdialog.h" #include "function_keyboard.h" #include "emulation_handler.h" #include "script.h" #include "fixit.h" /* OPIE */ #include <opie2/ofiledialog.h> #include <opie2/oresource.h> #include <qpe/filemanager.h> using namespace Opie::Ui; /* QT */ #include <qaction.h> #include <qmenubar.h> #include <qtoolbar.h> #include <qmessagebox.h> #include <qwhatsthis.h> #include <qfileinfo.h> /* STD */ #include <assert.h> #include <opie2/oconfig.h> MainWindow::MainWindow(QWidget *parent, const char *name, WFlags) : QMainWindow(parent, name, WStyle_ContextHelp) { #ifdef FSCKED_DISTRI FixIt fix; fix.fixIt(); #endif setCaption(QObject::tr("Opie Console") ); KeyTrans::loadAll(); for (int i = 0; i < KeyTrans::count(); i++ ) { KeyTrans* s = KeyTrans::find(i ); assert( s ); } m_factory = new MetaFactory(); Default def(m_factory); m_sessions.setAutoDelete( TRUE ); m_curSession = 0; m_manager = new ProfileManager( m_factory ); m_manager->load(); m_scriptsData.setAutoDelete(TRUE); initUI(); populateProfiles(); populateScripts(); } void MainWindow::initUI() { setToolBarsMovable( FALSE ); /* tool bar for the menu */ m_tool = new QToolBar( this ); m_tool->setHorizontalStretchable( TRUE ); m_bar = new QMenuBar( m_tool ); m_console = new QPopupMenu( this ); m_scripts = new QPopupMenu( this ); m_sessionsPop= new QPopupMenu( this ); m_scriptsPop = new QPopupMenu( this ); m_scrollbar = new QPopupMenu( this ); /* add a toolbar for icons */ m_icons = new QToolBar(this); /* * the settings action */ m_setProfiles = new QAction(tr("Configure Profiles"), Opie::Core::OResource::loadPixmap( "SettingsIcon", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0); m_setProfiles->addTo( m_console ); connect( m_setProfiles, SIGNAL(activated() ), this, SLOT(slotConfigure() ) ); m_console->insertSeparator(); /* * new Action for new sessions */ QAction* newCon = new QAction(tr("New Profile"), Opie::Core::OResource::loadPixmap( "new", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0); newCon->addTo( m_console ); connect( newCon, SIGNAL(activated() ), this, SLOT(slotNew() ) ); m_console->insertSeparator(); QAction *saveCon = new QAction( tr("Save Profile" ), Opie::Core::OResource::loadPixmap( "save", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); saveCon->addTo( m_console ); connect( saveCon, SIGNAL(activated() ), this, SLOT(slotSaveSession() ) ); m_console->insertSeparator(); /* * connect action */ m_connect = new QAction( tr("Connect"), Opie::Core::OResource::loadPixmap("console/connected", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); m_connect->addTo( m_console ); connect(m_connect, SIGNAL(activated() ), this, SLOT(slotConnect() ) ); /* * disconnect action */ m_disconnect = new QAction( tr("Disconnect"), Opie::Core::OResource::loadPixmap("console/notconnected", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); m_disconnect->addTo( m_console ); connect(m_disconnect, SIGNAL(activated() ), this, SLOT(slotDisconnect() ) ); m_console->insertSeparator(); #ifndef EAST m_quickLaunch = new QAction( tr("QuickLaunch"), Opie::Core::OResource::loadPixmap("console/konsole_mini", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); m_quickLaunch->addTo( m_icons ); connect( m_quickLaunch, SIGNAL( activated() ), this, SLOT( slotQuickLaunch() ) ); #endif QWhatsThis::add( m_icons, tr( "The shell button launches the \"default\" profile. If there is none default values are taken" ) ); m_transfer = new QAction( tr("Transfer file..."), Opie::Core::OResource::loadPixmap("pass", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); m_transfer->addTo( m_console ); connect(m_transfer, SIGNAL(activated() ), this, SLOT(slotTransfer() ) ); /* * immediate change of line wrap policy */ m_isWrapped = true; m_wrap = new QAction( tr("Line wrap"), Opie::Core::OResource::loadPixmap( "linewrap", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0, true ); m_wrap->addTo( m_console ); m_wrap->setOn( true ); connect( m_wrap, SIGNAL( activated() ), SLOT( slotWrap() ) ); /* * fullscreen */ m_isFullscreen = false; m_fullscreen = new QAction( tr("Full screen"), Opie::Core::OResource::loadPixmap( "fullscreen", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); m_fullscreen->addTo( m_console ); connect( m_fullscreen, SIGNAL( activated() ), this, SLOT( slotFullscreen() ) ); /* * scrollbar */ sm_none = m_scrollbar->insertItem(tr( "None" )); sm_left = m_scrollbar->insertItem(tr( "Left" )); sm_right = m_scrollbar->insertItem(tr( "Right" )); m_console->insertItem(tr("Scrollbar"), m_scrollbar, -1, 0); connect( m_scrollbar, SIGNAL(activated(int)), this, SLOT(slotScrollbarSelected(int))); m_console->insertSeparator(); m_recordLog = new QAction(); m_recordLog->setText( tr("Start log") ); m_recordLog->addTo( m_console ); connect(m_recordLog, SIGNAL(activated() ), this, SLOT( slotSaveLog() ) ); m_recordingLog = false; QAction *a = new QAction(); a->setText( tr("Save history") ); a->addTo( m_console ); connect(a, SIGNAL(activated() ), this, SLOT(slotSaveHistory() ) ); /* * terminate action */ m_terminate = new QAction(); m_terminate->setText( tr("Terminate") ); m_terminate->addTo( m_console ); connect(m_terminate, SIGNAL(activated() ), this, SLOT(slotTerminate() ) ); m_closewindow = new QAction(); m_closewindow->setText( tr("Close Window") ); m_closewindow->addTo( m_console ); connect( m_closewindow, SIGNAL(activated() ), this, SLOT(slotClose() ) ); /* * script actions */ m_runScript_id = m_scripts->insertItem(tr("Run Script"), m_scriptsPop, -1, 0); connect(m_scriptsPop, SIGNAL(activated(int)), this, SLOT(slotRunScript(int))); m_recordScript = new QAction(tr("Record Script"), QString::null, 0, this, 0); m_recordScript->addTo(m_scripts); connect(m_recordScript, SIGNAL(activated()), this, SLOT(slotRecordScript())); m_saveScript = new QAction(tr("Save Script"), QString::null, 0, this, 0); m_saveScript->addTo(m_scripts); connect(m_saveScript, SIGNAL(activated()), this, SLOT(slotSaveScript())); /* * action that open/closes the keyboard */ m_openKeys = new QAction (tr("Open Keyboard..."), Opie::Core::OResource::loadPixmap( "console/keys/keyboard_icon", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0); m_openKeys->setToggleAction(true); connect (m_openKeys, SIGNAL(toggled(bool)), this, SLOT(slotOpenKeb(bool))); /* insert the submenu */ m_console->insertItem(tr("New from Profile"), m_sessionsPop, -1, 0); /* insert the connection menu */ m_bar->insertItem( tr("Connection"), m_console ); /* the scripts menu */ #ifdef EAST Opie::Core::OConfig cfg("opie-console"); cfg.setGroup("10east"); if( !cfg.readEntry("scripthide",0) ) { m_bar->insertItem( tr("Scripts"), m_scripts ); } #endif /* and the keyboard */ m_keyBar = new QToolBar(this); addToolBar( m_keyBar, "Keyboard", QMainWindow::Top, TRUE ); m_keyBar->setHorizontalStretchable( TRUE ); m_keyBar->hide(); m_kb = new FunctionKeyboard(m_keyBar); connect(m_kb, SIGNAL(keyPressed(FKey,ushort,ushort,bool)), this, SLOT(slotKeyReceived(FKey,ushort,ushort,bool))); a = new QAction(tr("Copy"), Opie::Core::OResource::loadPixmap("copy", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); //a->addTo( m_icons ); connect( a, SIGNAL(activated() ), this, SLOT(slotCopy() ) ); QAction *paste = new QAction(tr("Paste"), Opie::Core::OResource::loadPixmap("paste", Opie::Core::OResource::SmallIcon ), QString::null, 0, this, 0 ); connect( paste, SIGNAL(activated() ), this, SLOT(slotPaste() ) ); newCon->addTo( m_icons ); //m_setProfiles->addTo( m_icons ); paste->addTo( m_icons ); m_openKeys->addTo(m_icons); m_fullscreen->addTo( m_icons ); m_connect->setEnabled( false ); m_disconnect->setEnabled( false ); m_terminate->setEnabled( false ); m_transfer->setEnabled( false ); m_scripts->setItemEnabled(m_runScript_id, false); m_recordScript->setEnabled( false ); m_saveScript->setEnabled( false ); m_fullscreen->setEnabled( false ); m_closewindow->setEnabled( false ); m_wrap->setEnabled( false ); /* * connect to the menu activation */ connect( m_sessionsPop, SIGNAL(activated(int) ), this, SLOT(slotProfile(int) ) ); m_consoleWindow = new TabWidget( this, "blah"); connect(m_consoleWindow, SIGNAL(activated(Session*) ), this, SLOT(slotSessionChanged(Session*) ) ); setCentralWidget( m_consoleWindow ); slotQuickLaunch(); } ProfileManager* MainWindow::manager() { return m_manager; } TabWidget* MainWindow::tabWidget() { return m_consoleWindow; } void MainWindow::populateProfiles() { m_sessionsPop->clear(); Profile::ValueList list = manager()->all(); for (Profile::ValueList::Iterator it = list.begin(); it != list.end(); ++it ) { m_sessionsPop->insertItem( (*it).name() ); } } void MainWindow::populateScripts() { m_scriptsPop->clear(); m_scriptsData.clear(); DocLnkSet files(QPEApplication::documentDir(), "text/plain"); QListIterator<DocLnk> dit(files.children()); for (; dit.current(); ++dit) { if (*dit && (*dit)->name().length()>0) { QFileInfo info((*dit)->file()); if (info.extension(false) == "script") { m_scriptsData.append(new DocLnk(**dit)); m_scriptsPop->insertItem((*dit)->name()); } } } } MainWindow::~MainWindow() { delete m_factory; manager()->save(); #ifdef FSCKED_DISTRI FixIt fix; fix.breakIt(); #endif } MetaFactory* MainWindow::factory() { return m_factory; } Session* MainWindow::currentSession() { return m_curSession; } QList<Session> MainWindow::sessions() { return m_sessions; } void MainWindow::slotNew() { ProfileEditorDialog dlg(factory() ); dlg.setCaption( tr("New Connection") ); int ret = QPEApplication::execDialog( &dlg ); if ( ret == QDialog::Accepted ) { create( dlg.profile() ); } } void MainWindow::slotRecordScript() { if (currentSession()) { currentSession()->emulationHandler()->startRecording(); m_saveScript->setEnabled(true); m_recordScript->setEnabled(false); } } void MainWindow::slotSaveScript() { if (currentSession() && currentSession()->emulationHandler()->isRecording()) { QMap<QString, QStringList> map; QStringList text; text << "text/plain"; map.insert(tr("Script"), text ); QString filename = OFileDialog::getSaveFileName(2, QPEApplication::documentDir(), QString::null, map); if (!filename.isEmpty()) { QFileInfo info(filename); if (info.extension(FALSE) != "script") filename += ".script"; DocLnk nf; nf.setType("text/plain"); nf.setFile(filename); nf.setName(info.fileName()); FileManager fm; fm.saveFile(nf, currentSession()->emulationHandler()->script()->script()); currentSession()->emulationHandler()->clearScript(); m_saveScript->setEnabled(false); m_recordScript->setEnabled(true); populateScripts(); } } } void MainWindow::slotRunScript(int id) { if (currentSession()) { int index = m_scriptsPop->indexOf(id); DocLnk *lnk = m_scriptsData.at(index); QString filePath = lnk->file(); Script script(filePath); currentSession()->emulationHandler()->runScript(&script); } } void MainWindow::slotConnect() { if ( currentSession() ) { bool ret = currentSession()->layer()->open(); if(!ret) QMessageBox::warning(currentSession()->widgetStack(), QObject::tr("Failed"), QObject::tr("Connecting failed for this session.")); else { m_connect->setEnabled( false ); m_disconnect->setEnabled( true ); // if it does not support file transfer, disable the menu entry if ( ( m_curSession->layer() )->supports()[1] == 0 ) { m_transfer->setEnabled( false ); } else { m_transfer->setEnabled( true ); } m_recordScript->setEnabled( true ); m_scripts->setItemEnabled(m_runScript_id, true); } } } void MainWindow::slotDisconnect() { if ( currentSession() ) { currentSession()->layer()->close(); m_connect->setEnabled( true ); m_disconnect->setEnabled( false ); m_transfer->setEnabled( false ); m_recordScript->setEnabled( false); m_saveScript->setEnabled( false ); m_scripts->setItemEnabled(m_runScript_id, false); } } void MainWindow::slotTerminate() { if ( currentSession() ) currentSession()->layer()->close(); slotClose(); /* FIXME move to the next session */ } void MainWindow::slotQuickLaunch() { Profile prof = manager()->profile( "default" ); if ( prof.name() == "default" ) { create( prof ); } else { #ifndef EAST Profile newProf = Profile( "default", "console", "default" , 0, 3, 0 ); newProf.setAutoConnect( true ); create( newProf ); slotSaveSession(); #endif } } void MainWindow::slotConfigure() { ConfigDialog conf( manager()->all(), factory() ); int ret = QPEApplication::execDialog( &conf ); if ( QDialog::Accepted == ret ) { manager()->setProfiles( conf.list() ); manager()->save(); populateProfiles(); } } /* * we will remove * this window from the tabwidget * remove it from the list * delete it * and set the currentSession() */ void MainWindow::slotClose() { if (!currentSession() ) return; Session* ses = currentSession(); /* set to NULL to be safe, if its needed slotSessionChanged resets it automatically */ m_curSession = NULL; tabWidget()->remove( /*currentSession()*/ses ); /*it's autodelete */ m_sessions.remove( ses ); if (!currentSession() ) { m_connect->setEnabled( false ); m_disconnect->setEnabled( false ); m_terminate->setEnabled( false ); m_transfer->setEnabled( false ); m_recordScript->setEnabled( false ); m_saveScript->setEnabled( false ); m_scripts->setItemEnabled(m_runScript_id, false); m_fullscreen->setEnabled( false ); m_wrap->setEnabled( false ); m_closewindow->setEnabled( false ); } m_kb->loadDefaults(); } /* * We will get the name * Then the profile * and then we will make a profile */ void MainWindow::slotProfile( int id) { Profile prof = manager()->profile( m_sessionsPop->text( id) ); create( prof ); } void MainWindow::create( const Profile& prof ) { char *homeDir = getenv("HOME"); if ( homeDir ) ::chdir( homeDir ); if(m_curSession) if(m_curSession->transferDialog()) m_curSession->transferDialog()->hide(); Session *ses = manager()->fromProfile( prof, tabWidget() ); if((!ses) || (!ses->layer()) || (!ses->widgetStack())) { QMessageBox::warning(this, QObject::tr("Session failed"), QObject::tr("<qt>Cannot open session: Not all components were found.</qt>")); //if(ses) delete ses; return; } m_sessions.append( ses ); tabWidget()->add( ses ); tabWidget()->repaint(); m_curSession = ses; // dicide if its a local term ( then no connction and no tranfer), maybe make a wrapper method out of it m_connect->setEnabled( true ); m_disconnect->setEnabled( false ); m_terminate->setEnabled( true ); m_fullscreen->setEnabled( true ); m_wrap->setEnabled( true ); m_closewindow->setEnabled( true ); m_transfer->setEnabled( false ); m_recordScript->setEnabled( false ); m_saveScript->setEnabled( false ); m_scripts->setItemEnabled(m_runScript_id, false); // is io_layer wants direct connection, then autoconnect //if ( ( m_curSession->layer() )->supports()[0] == 1 ) { if (prof.autoConnect()) { slotConnect(); } QWidget *w = currentSession()->widget(); if(w) w->setFocus(); if(currentSession()->profile().readNumEntry("Wrap", 80)){ m_isWrapped = true; } else { m_isWrapped = false; } m_kb->load(currentSession()->profile()); } void MainWindow::slotTransfer() { if ( currentSession() ) { Session *mysession = currentSession(); TransferDialog dlg(/*mysession->widgetStack()*/this, this); mysession->setTransferDialog(&dlg); //dlg.reparent(mysession->widgetStack(), QPoint(0, 0)); //dlg.showMaximized(); currentSession()->widgetStack()->addWidget(&dlg, -1); dlg.show(); //dlg.exec(); while(dlg.isRunning()) qApp->processEvents(); mysession->setTransferDialog(0l); } } void MainWindow::slotOpenKeb(bool state) { if (state) m_keyBar->show(); else m_keyBar->hide(); } void MainWindow::slotOpenButtons( bool state ) { if ( state ) { m_buttonBar->show(); } else { m_buttonBar->hide(); } } void MainWindow::slotSessionChanged( Session* ses ) { if(m_curSession) if(m_curSession->transferDialog()) m_curSession->transferDialog()->hide(); if(ses) if(ses->transferDialog()) ses->transferDialog()->show(); if ( ses ) { m_curSession = ses; if ( m_curSession->layer()->isConnected() ) { m_connect->setEnabled( false ); m_disconnect->setEnabled( true ); m_recordScript->setEnabled(!m_curSession->emulationHandler()->isRecording()); m_saveScript->setEnabled(m_curSession->emulationHandler()->isRecording()); m_scripts->setItemEnabled(m_runScript_id, true); } else { m_connect->setEnabled( true ); m_disconnect->setEnabled( false ); m_recordScript->setEnabled( false ); m_saveScript->setEnabled( false ); m_scripts->setItemEnabled(m_runScript_id, false); } if ( ( currentSession()->emulationHandler()->isLogging() ) ) { m_recordLog->setText( tr("Stop log") ); } else { m_recordLog->setText( tr("Start log") ); } if ( ( m_curSession->layer() )->supports()[1] == 0 ) { m_transfer->setEnabled( false ); } else { m_transfer->setEnabled( true ); } QWidget *w = m_curSession->widget(); if(w) w->setFocus(); if(currentSession()->profile().readNumEntry("Wrap", 80)){ m_isWrapped = true; } else { m_isWrapped = false; } m_kb->load(currentSession()->profile()); } } void MainWindow::slotWrap() { if(m_curSession) { EmulationHandler *e = m_curSession->emulationHandler(); if(e) { e->setWrap( m_isWrapped ? 80:0 ); m_isWrapped = !m_isWrapped; } } } void MainWindow::slotFullscreen() { if ( m_isFullscreen ) { ( m_curSession->widgetStack() )->reparent( savedParentFullscreen, 0, QPoint(0,0), true ); ( m_curSession->widgetStack() )->resize( savedParentFullscreen->width(), savedParentFullscreen->height() ); ( m_curSession->emulationHandler() )->cornerButton()->hide(); disconnect( ( m_curSession->emulationHandler() )->cornerButton(), SIGNAL( pressed() ), this, SLOT( slotFullscreen() ) ); } else { savedParentFullscreen = ( m_curSession->widgetStack() )->parentWidget(); ( m_curSession->widgetStack() )->setFrameStyle( QFrame::NoFrame ); ( m_curSession->widgetStack() )->reparent( 0, WStyle_Tool | WStyle_Customize | WStyle_StaysOnTop , QPoint(0,0), false ); ( m_curSession->widgetStack() )->resize( qApp->desktop()->width(), qApp->desktop()->height() ); ( m_curSession->widgetStack() )->setFocus(); ( m_curSession->widgetStack() )->show(); ( ( m_curSession->emulationHandler() )->cornerButton() )->show(); connect( ( m_curSession->emulationHandler() )->cornerButton(), SIGNAL( pressed() ), this, SLOT( slotFullscreen() ) ); } m_isFullscreen = !m_isFullscreen; } void MainWindow::slotScrollbarSelected(int index) { int loc; Config cfg( "Konsole" ); cfg.setGroup("ScrollBar"); if(index == sm_none) { loc = 0; } else if(index == sm_left) { loc = 1; } else if(index == sm_right) { loc = 2; } cfg.writeEntry("Position", loc); if (currentSession()) { currentSession()->emulationHandler()->setScrollbarLocation(loc); } m_scrollbar->setItemChecked(sm_none, index == sm_none); m_scrollbar->setItemChecked(sm_left, index == sm_left); m_scrollbar->setItemChecked(sm_right, index == sm_right); } void MainWindow::slotKeyReceived(FKey k, ushort, ushort, bool pressed) { if ( m_curSession ) { QEvent::Type state; if (pressed) state = QEvent::KeyPress; else state = QEvent::KeyRelease; QKeyEvent ke(state, k.qcode, k.unicode, 0, QString(QChar(k.unicode))); // is this the best way to do this? cant figure out any other way to work QApplication::sendEvent((QObject *)m_curSession->widget(), &ke); ke.ignore(); } } void MainWindow::slotCopy() { if (!currentSession() ) return; currentSession()->emulationHandler()->copy(); } void MainWindow::slotPaste() { if (!currentSession() ) return; currentSession()->emulationHandler()->paste(); } /* * Save the session */ void MainWindow::slotSaveSession() { if (!currentSession() ) { QMessageBox::information(this, tr("Save Connection"), tr("<qt>There is no Connection.</qt>"), 1 ); return; } manager()->add( currentSession()->profile() ); manager()->save(); populateProfiles(); } void MainWindow::slotSaveLog() { if( currentSession()->emulationHandler()->isLogging() ) { DocLnk nf; QString m_logName = currentSession()->emulationHandler()->logFileName(); QFileInfo info(m_logName); nf.setType("text/plain"); nf.setFile(m_logName); nf.setName(info.fileName()); nf.writeLink(); m_recordLog->setText( tr("Start log") ); m_recordingLog = false; currentSession()->emulationHandler()->clearLog(); } else { QMap<QString, QStringList> map; QStringList text; text << "text/plain"; map.insert(tr("Log"), text ); Opie::Core::OConfig cfg("opie-console"); cfg.setGroup("defaults"); QString startDir = cfg.readEntry("defaultlogdir", QPEApplication::documentDir() ); QString m_logName = OFileDialog::getSaveFileName(2, startDir, QString::null, map, 0, startDir); if (m_logName.isEmpty() ) return; m_recordLog->setText( tr("Stop log") ); m_recordingLog = true; currentSession()->emulationHandler()->startLogging(m_logName); } } void MainWindow::slotSaveHistory() { QMap<QString, QStringList> map; QStringList text; text << "text/plain"; map.insert(tr("History"), text ); QString filename = OFileDialog::getSaveFileName(2, QPEApplication::documentDir(), QString::null, map); if (filename.isEmpty() ) return; QFileInfo info(filename); DocLnk nf; nf.setType("text/plain"); nf.setFile(filename); nf.setName(info.fileName()); QFile file(filename); - file.open(IO_WriteOnly ); + if ( !file.open(IO_WriteOnly ) ) return; + QTextStream str(&file ); if ( currentSession() ) currentSession()->emulationHandler()->emulation()->streamHistory(&str); file.close(); nf.writeLink(); } diff --git a/noncore/apps/opie-console/script.cpp b/noncore/apps/opie-console/script.cpp index faea412..8d35776 100644 --- a/noncore/apps/opie-console/script.cpp +++ b/noncore/apps/opie-console/script.cpp @@ -1,29 +1,31 @@ #include <qfile.h> #include "script.h" Script::Script() { } Script::Script(const QString fileName) { QFile file(fileName); - file.open(IO_ReadOnly ); + if ( !file.open(IO_ReadOnly ) ) + return; m_script = file.readAll(); } void Script::saveTo(const QString fileName) const { QFile file(fileName); - file.open(IO_WriteOnly); + if ( !file.open(IO_WriteOnly) ) + return; file.writeBlock(m_script); file.close(); } void Script::append(const QByteArray &data) { int size = m_script.size(); m_script.resize(size + data.size()); memcpy(m_script.data() + size, data.data(), data.size()); } QByteArray Script::script() const { return m_script; } diff --git a/noncore/apps/opie-gutenbrowser/gutenbrowser.cpp b/noncore/apps/opie-gutenbrowser/gutenbrowser.cpp index 733db17..8b02f9f 100644 --- a/noncore/apps/opie-gutenbrowser/gutenbrowser.cpp +++ b/noncore/apps/opie-gutenbrowser/gutenbrowser.cpp @@ -1,2009 +1,2003 @@ /*************************************************************************** gutenbrowser.cpp - description ------------------- begin : Mon Jul 24 22:33:12 MDT 2000 copyright : (C) 2000 -2004 by llornkcor email : ljp@llornkcor.com * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ // http search // http://digital.library.upenn.edu/books/authors.html // http://digital.library.upenn.edu/books/titles.html // ftp://ibiblio.org/pub/docs/books/gutenberg/GUTINDEX.ALL // donate@gutenberg.net #include "editTitle.h" #include "gutenbrowser.h" #include "LibraryDialog.h" //#include "bookmarksdlg.h" #include "optionsDialog.h" #include "helpme.h" #include "NetworkDialog.h" #include "openetext.h" #include "output.h" /* OPIE */ #include <opie2/odebug.h> #include <opie2/oresource.h> #include <qpe/qpeapplication.h> #include <qpe/fontdatabase.h> #include <qpe/config.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/mimetype.h> #include <qpe/applnk.h> /* QT */ #include <qregexp.h> #include <qregion.h> #include <qpaintdevicemetrics.h> #include <qvaluelist.h> #include <qlabel.h> #include <qclipboard.h> #include <qpainter.h> #include <qpalette.h> #include <qobjectlist.h> #include <qfontdialog.h> #include <qtextview.h> #include <qbrush.h> #include <qfile.h> #include <qfontinfo.h> #include <qscrollview.h> #include <qpoint.h> /* STD */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> static const int nfontsizes = 9; static const int fontsize[nfontsizes] = {8,9,10,11,12,13,14,18,24}; #ifdef NOQUICKLAUNCH Gutenbrowser::Gutenbrowser() Gutenbrowser(); #else Gutenbrowser::Gutenbrowser(QWidget *,const char*, WFlags ) #endif : QMainWindow() { // QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; // QCopEnvelope e("QPE/System", "grabKeyboard(QString)" ); // e << ""; // QPEApplication::grabKeyboard(); showMainList=TRUE; working=false; this->setUpdatesEnabled(TRUE); // #ifndef Q_WS_QWS QString msg; msg="You have now entered unto gutenbrowser,\n"; msg+="make your self at home, sit back, relax and read something great.\n"; local_library = (QDir::homeDirPath ()) +"/Applications/gutenbrowser/"; setCaption("Gutenbrowser");// Embedded " VERSION); this->setUpdatesEnabled(TRUE); // bool firstTime=FALSE; topLayout = new QVBoxLayout( this, 0, 0, "topLayout"); menu = new QHBoxLayout(-1,"menu"); buttons2 = new QHBoxLayout(-1,"buttons2"); edits = new QHBoxLayout(-1,"edits"); useSplitter=TRUE; initConfig(); initMenuBar(); initButtonBar(); initStatusBar(); initView(); initSlots(); qDebug("init finished"); QPEApplication::setStylusOperation( mainList->viewport(),QPEApplication::RightOnHold); connect( mainList, SIGNAL( mouseButtonPressed( int, QListBoxItem *, const QPoint &)), this, SLOT( mainListPressed(int, QListBoxItem *, const QPoint &)) ); if( useIcons) toggleButtonIcons( TRUE); else toggleButtonIcons( FALSE); enableButtons(false); Config config("Gutenbrowser"); // populate menubuttonlist config.setGroup("General"); config.setGroup( "Files" ); QString s_numofFiles = config.readEntry("NumberOfFiles", "0" ); int i_numofFiles = s_numofFiles.toInt(); QString tempFileName; for (int i = 0; i <= i_numofFiles; i++) { // tempFileName.setNum(i); config.setGroup( "Files" ); QString ramble = config.readEntry( QString::number(i), "" ); config.setGroup( "Titles" ); QString tempTitle = config.readEntry( ramble, ""); config.setGroup( tempTitle); int index = config.readNumEntry( "LineNumber", -1 ); if( index != -1) { odebug << tempTitle << oendl; if(!tempTitle.isEmpty()) bookmarksMenu->insertItem( tempTitle); } } QString gutenIndex = local_library + "/GUTINDEX.ALL"; qDebug("gutenindex "+gutenIndex ); if( QFile( gutenIndex).exists() ) { indexLib.setName( gutenIndex); } else { QString localLibIndexFile = local_library + "/PGWHOLE.TXT"; // QString localLibIndexFile= local_library + "PGWHOLE.TXT"; newindexLib.setName( localLibIndexFile); } qDebug("attempting new library"); LibraryDlg = new LibraryDialog( this, "Library Index" /*, TRUE */); loadCheck = false; chdir(local_library); if(!showMainList) { Lview->setFocus(); // if(firstTime) // Bookmark(); for (int i=1;i< qApp->argc();i++) { qDebug("Suppose we open somethin"); if(!load(qApp->argv()[i])) return; } } else { fillWithTitles(); mainList->setFocus(); // mainList->setCurrentItem(0); } writeConfig(); QTimer::singleShot( 250, this, SLOT(hideView()) ); } //end init Gutenbrowser::~Gutenbrowser() { // QPEApplication::grabKeyboard(); // QPEApplication::ungrabKeyboard(); odebug << "Exit" << oendl; } /* Google.com search */ void Gutenbrowser::InfoBarClick() { QString text; if( Lview->hasSelectedText()) { Lview->copy(); QClipboard *cb = QApplication::clipboard(); text = cb->text(); } else { // text=title; text=this->caption(); } searchGoogle(text); } /* download http with wget or preferred browser */ void Gutenbrowser::goGetit( const QString &url, bool showMsg) { QString cmd; qApp->processEvents(); QString filename = local_library + "/GUTINDEX.ALL"; // QString filename = old_index; // filename += url.right( url.length() - url.findRev("/",-1,TRUE) -1); Config cfg("Gutenbrowser"); cfg.setGroup("FTPsite"); ftp_host=cfg.readEntry("SiteName", "sailor.gutenberg.org"); ftp_base_dir= cfg.readEntry("base", "/pub/gutenberg"); // Config config("Gutenbrowser"); // config.setGroup( "Browser" ); // QString brow = config.readEntry("Preferred", "Opera"); // //odebug << "Preferred browser is "+brow << oendl; if(!showMsg) { //if we just get the gutenindex.all // QString cmd="wget -O " + gutenindex1 + " http://sailor.gutenberg.org/GUTINDEX.ALL 2>&1"; cmd="wget -O " + filename +" " + url+" 2>&1" ; chdir(local_library); // //odebug << "Issuing the system command: " << cmd << "" << oendl; Output *outDlg; outDlg = new Output( 0, tr("Downloading Gutenberg Index...."),TRUE); outDlg->showMaximized(); outDlg->show(); qApp->processEvents(); FILE *fp; char line[130]; outDlg->OutputEdit->append( tr("Running wget") ); outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); sleep(1); fp = popen( (const char *) cmd, "r"); if ( !fp ) { } else { //odebug << "Issuing the command\n"+cmd << oendl; // system(cmd); while ( fgets( line, sizeof line, fp)) { outDlg->OutputEdit->append(line); outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); } pclose(fp); outDlg->OutputEdit->append("Finished downloading\n"); outDlg->OutputEdit->setCursorPosition(outDlg->OutputEdit->numLines() + 1,0,FALSE); qApp->processEvents(); } outDlg->close(); if(outDlg) delete outDlg; } else { if( brow == "Konq") { cmd = "konqueror "+url+" &"; } if( brow == "Opera") { //for desktop testing cmd = "opera "+url+" &"; } // if( brow == "Opera") { // on Zaurus // cmd = "operagui "+url+" &"; // } if( brow == "Mozilla") { cmd = "mozilla "+url+" &"; } if( brow == "Netscape") { cmd = "netscape "+url+" &"; } if(brow == "wget") { // cmd="wget -q "+url+" &"; QString tempHtml=local_library+"webster.html"; cmd="wget -O "+tempHtml+" -q "+url; } chdir(local_library); // //odebug << "Issuing the sys command: " << cmd << "" << oendl; system(cmd); } } void Gutenbrowser::toggleButtonIcons( bool useEm) { QString pixDir; if(useEm) useEm=TRUE; pixDir=QPEApplication::qpeDir()+"pics/gutenbrowser"; odebug << "Docdir is "+QPEApplication::documentDir() << oendl; if( useIcons && QDir( pixDir).exists() ) { LibraryButton->setPixmap( Opie::Core::OResource::loadPixmap("home", Opie::Core::OResource::SmallIcon ) ); OpenButton->setPixmap( Opie::Core::OResource::loadPixmap("gutenbrowser/openbook", Opie::Core::OResource::SmallIcon )); ForwardButton->setPixmap( Opie::Core::OResource::loadPixmap("forward", Opie::Core::OResource::SmallIcon )); BackButton->setPixmap( Opie::Core::OResource::loadPixmap("back", Opie::Core::OResource::SmallIcon ) ); SearchButton->setPixmap( Opie::Core::OResource::loadPixmap("gutenbrowser/search", Opie::Core::OResource::SmallIcon ) ); lastBmkButton->setPixmap( Opie::Core::OResource::loadPixmap("gutenbrowser/bookmark_folder", Opie::Core::OResource::SmallIcon )); setBookmarkButton->setPixmap( Opie::Core::OResource::loadPixmap("gutenbrowser/bookmark", Opie::Core::OResource::SmallIcon ) ); dictionaryButton->setPixmap( Opie::Core::OResource::loadPixmap("gutenbrowser/spellcheck", Opie::Core::OResource::SmallIcon ) ); InfoBar->setPixmap( Opie::Core::OResource::loadPixmap("gutenbrowser/google", Opie::Core::OResource::SmallIcon )); } } bool Gutenbrowser::queryExit() { int exit=QMessageBox::information(this, "Quit...", "Do your really want to quit?", QMessageBox::Ok, QMessageBox::Cancel); if (exit==1) { writeConfig(); qApp->quit(); } else { }; return (exit==1); } // SLOT IMPLEMENTATION void Gutenbrowser::slotFilePrint() { } void Gutenbrowser::ByeBye() { if (b_queryExit) queryExit(); else { // writeConfig(); qApp->quit(); } } void Gutenbrowser::HelpBtn() { HelpMe* HelpDlg; HelpDlg = new HelpMe( this, "Help Dialog"); HelpDlg->showMaximized(); } void Gutenbrowser::DownloadIndex() { #ifndef Q_WS_QWS { switch( QMessageBox::information( 0, (tr("Download Library Index, or FTP sites?")), (tr("Do you want to download the newest\n" "Project Gutenberg Library Index?\n" "or select an ftp site?\n")), (tr("&Library Index")), (tr("&Ftp Site")), (tr("&Cancel")), 2, 2 ) ) { case 0: // index clicked, downloadLibIndex(); break; case 1: // ftp selected downloadFtpList(); break; case 2: // Cancel break; }; } #endif } // end DownloadIndex void Gutenbrowser::downloadFtpList() { // QString cmd="wget http://www.promo.net/pg/list.html"); //system(cmd); qApp->processEvents(); optionsDialog* optDlg; optDlg = new optionsDialog( this,"Options_Dlg", true); optDlg->getSite(); if(optDlg) delete optDlg; } void Gutenbrowser::downloadLibIndex() { // QString dwmloader = local_library + "pgwhole.zip"; // QString cmd = "lynx -source http://www.gutenberg.net/pgwhole.zip | cat >> " + dwmloader; // system(cmd); // QString outputFile= local_library+ "GUTINDEX.ALL"; // config.setGroup( "FTPsite" ); // ftp server config // ftp_host=config.readEntry("SiteName", ""); // ftp_base_dir= config.readEntry("base", ""); // QString networkUrl= "ftp://"+ftp_host+ftp_base_dir+"/GUTINDEX.ALL"; QDir dir( local_library); dir.cd("", TRUE); goGetit( "http://www.gutenberg.org/dirs/GUTINDEX.ALL", false); // until ghttp works on binaries -qt3 // goGetit( "http://www.gutenberg.net/pgwhole.zip", true); // until ghttp works on binaries -qt3 // NetworkDialog *NetworkDlg; // NetworkDlg = new NetworkDialog( this,"Network Protocol Dialog", TRUE, 0, networkUrl, outputFile ); // if( NetworkDlg->exec() != 0 ) // { // use new, improved, *INSTANT* network-dialog-file-getterer //// QMessageBox::message("Note",""); // } // if(NetworkDlg) // delete NetworkDlg; } void Gutenbrowser::PrintBtn() { } void Gutenbrowser::SearchBtn() { if( loadCheck) { odebug << "loadCheck: we have a loaded doc" << oendl; Search(); } // else // QMessageBox::message("Note","Sorry, can't search. No etext is loaded"); } void Gutenbrowser::ForwardBtn() { if( !ForwardButton->autoRepeat() && !ForwardButton->isDown()) { QString s; QString insertString; int pageSize= Lview->PageSize(); Lview->clear(); for(int fd=0; fd < pageSize - 1;fd++) { f.readLine(s, 256); if(useWrap) s.replace(QRegExp("\n"),""); insertString+=s; Lview->insertLine( s, -1); // odebug << s << oendl; currentLine++; } // Lview->insertAt( insertString,0,0, FALSE); currentFilePos = f.at(); // if( i_pageNum != pages) { // Lview->MultiLine_Ex::pageDown( FALSE); i_pageNum++; pageStopArray.resize(i_pageNum + 1); // int length = Lview->length(); pageStopArray[i_pageNum ] = currentFilePos; odebug << currentFilePos << " current page is number " << i_pageNum << ", pagesize " << pageSize << ", length " << Lview->length() << ", current " << pageStopArray[i_pageNum] << oendl; setStatus(); // Lview->setCursorPosition( 0, 0, FALSE); // } } else { odebug << "bal" << oendl; // if( i_pageNum != pages) { // // int newTop = Lview->Top(); // // if(Lview->lastRow() > i) // Lview->ScrollUp(1); // // i_pageNum++; // setStatus(); // Lview->setCursorPosition( Lview->Top(), 0, FALSE); // } } Lview->setFocus(); odebug << "page number " << i_pageNum << " line number " << currentLine << "" << oendl; } void Gutenbrowser::BackBtn() { if( i_pageNum > 0) { int pageSize= Lview->PageSize(); // int length=Lview->length(); i_pageNum--; currentFilePos = f.at(); odebug << currentFilePos << " move back to " << pageStopArray[i_pageNum - 1 ] << ", current page number " << i_pageNum << ", " << pageSize << ", length " << Lview->length() << oendl; if( i_pageNum < 2) { f.at( 0); } else { if(!f.at( pageStopArray[i_pageNum - 1] )) odebug << "File positioned backward did not work" << oendl; } QString s; // int sizeLine=0; Lview->clear(); // QString insertString; for(int fd = 0; fd < pageSize ;fd++) { // Lview->removeLine( Lview->PageSize() ); f.readLine(s, 256); if(useWrap) s.replace(QRegExp("\n"),""); currentLine++; // insertString+=s; Lview->insertLine( s, -1); } // Lview->insertAt( insertString,0,0, FALSE); if( !BackButton->autoRepeat() && !BackButton->isDown()) { QString topR; QString lastR; QString pageR; // int sizer = Lview->lastRow() - Lview->topRow(); // int i_topRow = Lview->topRow(); if( i_pageNum < 1) i_pageNum = 1; setCaption(QString::number(i_pageNum)); } else { // int newTop = Lview->Top(); // if(Lview->lastRow() > i) Lview->MultiLine_Ex::pageUp( FALSE); // Lview->ScrollDown(1); // i_pageNum--; if( i_pageNum < 1) i_pageNum = 1; setStatus(); // Lview->setCursorPosition( Lview->Top(), 0, FALSE); } } Lview->setFocus(); } void Gutenbrowser::doBeginBtn() { if(loadCheck) { qApp->processEvents(); BeginBtn(); } } // moves text to the very top = 0 void Gutenbrowser::TopBtn() { if(loadCheck) { if( i_pageNum != 0) { odebug << "top" << oendl; qApp->processEvents(); currentLine = 0; i_pageNum = 1; int pageSize = Lview->PageSize() ; Lview->clear(); QString s; f.at(0); for(int fd=0; fd < pageSize ;fd++) { f.readLine(s, 256); if(useWrap) s.replace(QRegExp("\n"),""); Lview->insertLine(s ,-1); currentLine++; } // Lview->setCursorPosition( 0,0, FALSE); i_pageNum=1; setStatus(); } Lview->setFocus(); } } //moves text to the start of the EText void Gutenbrowser::BeginBtn() { i_pageNum = 1; currentLine = 0; QString s_pattern="*END*THE SMALL PRINT"; QString sPattern2 = "*END THE SMALL PRINT"; int pageSize = Lview->PageSize(); Lview->clear(); // int lines = Lview->numLines(); int pos = 0;//, i = 0; int i_topRow = Lview->topRow(); QString LeftText;// = Lview->text(); // int linesPerPage = Lview->lastRow() - Lview->topRow(); // int pages = (( linesPerPage / Lview->editSize() ) ) +1; // int pageN = 0; i_pageNum = 1; int lastPage=1; int lineNo=0; QString s; f.at( 0); while ( !f.atEnd() ) { f.readLine(s, 256); lineNo++; LeftText = s; currentFilePos = f.at(); i_pageNum = lineNo/pageSize; if(lastPage < i_pageNum) { pageStopArray.resize(i_pageNum + 1); pageStopArray[i_pageNum ] = currentFilePos; // odebug << "new page number " << i_pageNum << ", found at " << currentFilePos << "" << oendl; } // lastPage = i_pageNum; if( LeftText.find( s_pattern, 0 , TRUE) != -1 || LeftText.find( sPattern2, 0 , TRUE) != -1 ) { odebug << "<<<<<< FOUND IT!! new page number " << i_pageNum << ", found at " << currentFilePos << "" << oendl; break; } } if(f.atEnd()) //in case we didnt find anything, we need to show something f.at(0); Lview->clear(); for(int fd=0; fd < pageSize - 1;fd++) { f.readLine(s, 256); if(useWrap) s.replace(QRegExp("\n"),""); Lview->insertLine( s, -1); currentLine++; } i_pageNum = lineNo/pageSize; pageStopArray.resize(i_pageNum + 1); // int length = Lview->length(); qApp->processEvents(); if( pos > i_topRow ) { // Lview->setCursorPosition( pos+linesPerPage+2/* - i_topRow+3 */,0, FALSE); } else { // Lview->setCursorPosition( pos+2 , 0, FALSE ); } Lview->deselect(); // AdjustStatus(); Lview->setFocus(); } /* sets the current page and place as a bookmark*/ void Gutenbrowser::setBookmark() { int eexit=QMessageBox::information(this, "Note", "Do you really want to \nset this bookmark?." ,QMessageBox::Yes, QMessageBox::No); if (eexit== 3) { currentFilePos = f.at(); Config cfg("Gutenbrowser"); cfg.setGroup("General"); file_name = cfg.readEntry("Current",""); qApp->processEvents(); odebug << "Setting book mark "+file_name << oendl; cfg.setGroup("Titles"); title = cfg.readEntry(file_name,""); odebug << "title is "+ title << oendl; cfg.setGroup( "Bookmarks" ); cfg.writeEntry("File Name",file_name); cfg.writeEntry("Page Number",QString::number(i_pageNum) ); cfg.writeEntry( "PagePosition", QString::number( pageStopArray[i_pageNum - 1])); cfg.writeEntry("Title", title); int row = Lview->topRow();// Lview->Top(); cfg.writeEntry("LineNumber",QString::number(row) ); cfg.setGroup(title); cfg.writeEntry("File Name",file_name); cfg.writeEntry( "LineNumber", QString::number( row)); cfg.writeEntry( "PagePosition", QString::number( pageStopArray[i_pageNum - 1])); cfg.writeEntry( "Page Number", QString::number( i_pageNum) ); cfg.write(); bookmarksMenu->insertItem( title); } } //end setBookmark /* goes to last set bookmark*/ void Gutenbrowser::Bookmark( int itemId) { // qApp->processEvents(); Config config("Gutenbrowser"); config.setGroup( "Bookmarks" ); odebug << "<<<<<< " << Lview->PageSize() << ", " << Lview->lastRow() - Lview->topRow() << "" << oendl; QString itemString; odebug << "menu item " << itemId << "" << oendl; QString tempTitle; QString s_Bmrkrow; QString s_pageNum; int Bmrkrow=0; int bookmarkPosition = 0; // qApp->processEvents(); config.setGroup( "Bookmarks" ); title = config.readEntry("Title", ""); file_name = config.readEntry("File Name", ""); i_pageNum = config.readNumEntry("Page Number", 0); bookmarkPosition = config.readNumEntry( "PagePosition",0); Bmrkrow = config.readNumEntry("LineNumber",0); if( !file_name.contains("/")) { file_name = local_library + file_name; } // getTitle(file_name); // qApp->processEvents(); // Lview->setFocus(); this->setFocus(); Lview->clear(); if(!load(file_name)) return; int pageSize = Lview->PageSize(); f.at(0); // Lview->clear(); QString s; int lineNo=0; int lastPage=1; while ( !f.atEnd() ) { f.readLine(s, 256); lineNo++; currentFilePos = f.at(); i_pageNum = lineNo/pageSize; if(lastPage < i_pageNum) { pageStopArray.resize(i_pageNum + 1); pageStopArray[i_pageNum ] = currentFilePos; // odebug << "new page number " << i_pageNum << ", found at " << currentFilePos << "" << oendl; } if(currentFilePos == bookmarkPosition) break; } if(f.atEnd()) f.at(0); else f.at( bookmarkPosition); for(int fd=0; fd < pageSize - 1;fd++) { f.readLine(s, 256); lineNo++; if(useWrap) s.replace(QRegExp("\n"),""); Lview->insertLine( s, -1); currentLine++; } i_pageNum = lineNo/pageSize; pageStopArray.resize(i_pageNum + 1); if(showMainList) { showMainList=FALSE; mainList->hide(); Lview->show(); // qApp->processEvents(); } odebug << "bookmark loaded" << oendl; setCaption(title); } bool Gutenbrowser::load( const char *fileName) { // QCopEnvelope ( "QPE/System", "busy()" ); odebug << "Title is already set as "+title << oendl; odebug << "sizeHint " << sizeHint().height() << " pageSize " << Lview->PageSize() << "" << oendl; // pointSize = Lview->fontInfo().pointSize(); // odebug << "sizeHint " << sizeHint().height() << " point size " << pointSize << "" << oendl; if( Lview->PageSize() < 4) { // Lview->setMaximumHeight( sizeHint().height() ); Lview->setMinimumHeight( sizeHint().height() ); pointSize = Lview->fontInfo().pointSize(); odebug << "sizeHint " << sizeHint().height() << " point size " << pointSize << "" << oendl; if(pointSize < 15) Lview->setFixedVisibleLines(19); else Lview->setFixedVisibleLines( ( (sizeHint().height() / pointSize ) * 2) -2); } Config cfg("Gutenbrowser"); cfg.setGroup("General"); cfg.writeEntry("Current",fileName); cfg.write(); currentLine=0; file_name=fileName; QString o_file = fileName; // if (i_pageNum < 1) { i_pageNum = 1; // } odebug << "ready to open "+o_file << oendl; if(f.isOpen()) f.close(); f.setName( o_file); if ( !f.open( IO_ReadOnly)) { QMessageBox::message( (tr("Note")), (tr("File not opened sucessfully.\n" +o_file)) ); return false; } currentFilePos = 0; pageStopArray.resize(3); pageStopArray[0] = currentFilePos; fileHandle = f.handle(); QString insertString; QTextStream t(&f); QString s; for(int fd=0; fd < Lview->PageSize() ;fd++) { s=t.readLine(); // insertString+=s; if(useWrap) s.replace(QRegExp("\n"),""); // s.replace(QRegExp("\r"),""); Lview->insertLine( s,-1); currentLine++; } // int length = Lview->length(); currentFilePos = f.at(); pageStopArray[1] = currentFilePos; odebug << "<<<<<<<<<<<" << currentFilePos << " current page is number " << i_pageNum << ", length " << Lview->length() << ", current " << pageStopArray[i_pageNum] << ", pageSize " << Lview->PageSize() << oendl; Lview->setMaxLines(Lview->PageSize()*2); // odebug << "Gulped " << currentLine << "" << oendl; setCaption(title); Lview->setAutoUpdate( TRUE); // Lview->setCursorPosition(0,0,FALSE); // pages = (int)(( Lview->numLines() / Lview->editSize() ) / 2 ) +1; //odebug << "number of pages " << pages << "" << oendl; loadCheck = true; enableButtons(true); if( donateMenu->count() == 3) { donateMenu->insertItem("Current Title", this, SLOT( InfoBarClick() )); } Lview->setFocus(); // QCopEnvelope("QPE/System", "notBusy()" ); return true; } // end load void Gutenbrowser::Search() { - - // if( searchDlg->isHidden()) - { - odebug << "Starting search dialog" << oendl; - searchDlg = new SearchDialog( this, "Etext Search", true); - searchDlg->setCaption( tr( "Etext Search" )); - // searchDlg->setLabel( "- searches etext"); - connect( searchDlg,SIGNAL( search_signal()),this,SLOT( search_slot())); - connect( searchDlg,SIGNAL( search_done_signal()),this,SLOT( searchdone_slot())); - - QString resultString; - QString string = searchDlg->searchString; - Lview->deselect(); - searchDlg->show(); - searchDlg->result(); - } + odebug << "Starting search dialog" << oendl; + searchDlg = new SearchDialog( this, "Etext Search", true); + searchDlg->setCaption( tr( "Etext Search" )); + connect( searchDlg,SIGNAL( search_signal()),this,SLOT( search_slot())); + connect( searchDlg,SIGNAL( search_done_signal()),this,SLOT( searchdone_slot())); + + QString resultString; + QString string = searchDlg->searchString; + Lview->deselect(); + searchDlg->show(); } void Gutenbrowser::search_slot( ) { int line, col; if (!searchDlg /*&& !loadCheck */) return; Lview->getCursorPosition(&line,&col); QString to_find_string=searchDlg->get_text(); // searchDlg->get_direction();// is true if searching backward if ( last_search != 0 && searchDlg->get_direction() ){ col = col - pattern.length() - 1 ; } again: int result = doSearch( to_find_string , /* searchDlg->case_sensitive()*/ TRUE, searchDlg->forward_search(), line, col); if(result == 0){ if(!searchDlg->get_direction()){ // forward search int query = QMessageBox::information( searchDlg, "Find", "End of document reached.\nContinue from the beginning?", "Yes", "No", "", 0,1); if (query == 0){ line = 0; col = 0; goto again; } } else { //backward search int query = QMessageBox::information( searchDlg, "Find", "End of document reached.\nContinue from the beginning?", "Yes", "No", "", 0,1); if (query == 0){ QString string = Lview->textLine( Lview->numLines() - 1 ); line = Lview->numLines() - 1; lineCheck = line; col = string.length(); last_search = -1; //BACKWARD; goto again; } } } else { //// emit CursorPositionChanged(); textLine } } int Gutenbrowser::doSearch( const QString &s_pattern , bool case_sensitive, bool forward, int line, int col ) { int i, length; int pos = -1; if(forward) { QString string; for(i = line; i < Lview->numLines(); i++) { string = Lview->textLine(i); pos = string.find(s_pattern, i == line ? col : 0, case_sensitive); if( pos != -1) { int top = Lview->Top(); length = s_pattern.length(); if( i > Lview->lastRow() ) { // Lview->setCursorPosition(i,pos,FALSE); for(int l = 0 ; l < length; l++) { Lview->cursorRight(TRUE); } // Lview->setCursorPosition( i , pos + length, TRUE ); int newTop = Lview->Top(); if(Lview->lastRow() > i) Lview->ScrollUp( newTop - top); // AdjustStatus(); } else { // Lview->setCursorPosition(i,pos,FALSE); for(int l = 0 ; l < length; l++) { Lview->cursorRight(TRUE); } // Lview->setCursorPosition( i , pos + length, TRUE ); // AdjustStatus(); } pattern = s_pattern; last_search = 1; //FORWARD; return 1; } } } else { //////////////// searching backwards QString string; for( i = line; i >= 0; i--) { string = Lview->textLine(i); int line_length = string.length(); pos = string.findRev(s_pattern, line == i ? col : line_length , case_sensitive); if (pos != -1) { // int top = Lview->Top(); length = s_pattern.length(); if( i < Lview->Top() ) { Lview->ScrollDown( Lview->PageSize() ); Lview->MultiLine_Ex::pageUp( FALSE ); if( ! (line == i && pos > col ) ) { // Lview->setCursorPosition( i ,pos ,FALSE ); for(int l = 0 ; l < length; l++) { Lview->cursorRight(TRUE); } // Lview->setCursorPosition(i ,pos + length ,TRUE ); // int newTop = Lview->Top(); /* if(useSplitter) Rview->ScrollUp( newTop - top); */ } } else { if( ! (line == i && pos > col ) ) { // Lview->setCursorPosition( i, pos, FALSE ); for( int l = 0 ; l < length; l++) { Lview->cursorRight( TRUE); } // Lview->setCursorPosition( i, pos + length, TRUE ); } pattern = s_pattern; last_search = -1; return 1; } } } } return 0; } void Gutenbrowser::LibraryBtn() { QString newestLibraryFile ="pgwhole.zip"; QString zipFile; // odebug << "Local Library is " << local_library << " " << oendl; zipFile="/usr/bin/unzip"; // odebug << "newestLibraryFile is " << newestLibraryFile << " " << oendl; if( QFile::exists( local_library+newestLibraryFile)) { if( QFile::exists(zipFile) ) { UnZipIt(newestLibraryFile); } else QMessageBox::message( "Note",( tr("Please install unzip")) ); } // LibraryDlg = new LibraryDialog( this, "Library Index"); LibraryDlg->setCaption( tr( "Gutenberg Library")); Config config("Gutenbrowser"); config.setGroup("General"); if(useSplitter) LibraryDlg->useSmallInterface=FALSE; LibraryDlg->showMaximized(); if( LibraryDlg->exec() != 0 ) { listItemNumber = LibraryDlg->DlglistItemNumber; listItemFile = LibraryDlg->DlglistItemFile; listItemYear = LibraryDlg->DlglistItemYear; listItemTitle = LibraryDlg->DlglistItemTitle; file_name = LibraryDlg->File_Name; // odebug << "title is being set as "+title << oendl; title = listItemTitle; // config.setGroup( "Proxy" ); // if( LibraryDlg->checked == 1) { // config.writeEntry("IsChecked", "TRUE"); // } else { // config.writeEntry("IsChecked", "FALSE"); // } // config.write(); // config.read(); if ( listItemNumber.isNull()) { } else { i_pageNum = 1; if( file_name !="Error" && file_name.length() >2 && !file_name.isEmpty() ) { //replace .zip with txt for opening it. // printf("\nFile name is now\n"); // printf(file_name); // printf("\n"); // if( file_name.find(".zip")) { odebug << "Found zip file\n" << oendl; // QStringList args; // args="unzip"; // args+="-o"; // args+=local_library+file_name; // args+="-d"; // args+=local_library; QString cmd = "/usr/bin/unzip -o " + local_library+file_name + " -d " + local_library; odebug << "Issuing the command "+ cmd << oendl; // unzipProc=new QProcess( this, "unzipProc" ); /// fark that idea! // unzipProc->start(); system(cmd); remove( file_name); } // // // file_name = file_name.left(4)+ ".txt"; if( LibraryDlg) delete LibraryDlg; setTitle(); // QCopEnvelope ( "QPE/System", "busy()" ); if( !load( file_name)) return; } else { printf("Not opening the file.\n"); } } } if(showMainList) { if(!Lview->isHidden()) Lview->hide(); qApp->processEvents(); showMainList=TRUE; if(mainList->isHidden()) mainList->show(); fillWithTitles(); qApp->processEvents(); } else setCentralWidget( Lview); // QPEApplication::grabKeyboard(); // fixKeys(); } void Gutenbrowser::OpenBtn() { QString s_temp; s_temp = status; OpenEtext* OpenDlg; OpenDlg = new OpenEtext(this,"OpenDlg"); OpenDlg->showMaximized(); if( OpenDlg->exec() != 0) { title = OpenDlg->openFileTitle; odebug << "title open as "+title << oendl; file_name = OpenDlg->file; i_pageNum = 1; if( !file_name.isEmpty() || file_name.length() > 2 ) { if(showMainList) { showMainList=FALSE; odebug << "ShowMainList is now false" << oendl; mainList->hide(); Lview->show(); qApp->processEvents(); } Lview->clear(); // QCopEnvelope ( "QPE/System", "busy()" ); if(!load(file_name)) return; } else { odebug << "file_name is empty!" << oendl; if(showMainList) { if(!Lview->isHidden()) Lview->hide(); qApp->processEvents(); if(mainList->isHidden()) mainList->show(); fillWithTitles(); qApp->processEvents(); } } } if( OpenDlg) delete OpenDlg; /* Config config("Gutenbrowser"); config.setGroup( title); file_name = config.readEntry("File Name", ""); i_pageNum = config.readNumEntry("Page Number", -1); int Bmrkrow = config.readNumEntry("LineNumber", -1); if(Bmrkrow > -1) { if( Bmrkrow > Lview->topRow() ) { Lview->setCursorPosition( Bmrkrow ,0, FALSE ); Lview->ScrollUp( Bmrkrow - Lview->topRow() ); // AdjustStatus(); } else if( Bmrkrow < Lview->topRow() ) { Lview->setCursorPosition( Lview->topRow() - Bmrkrow ,0, FALSE ); Lview->ScrollDown( Lview->topRow() - Bmrkrow ); // AdjustStatus(); } } */ // ResizeEdits(); } void Gutenbrowser::ChangeFont() { #ifndef Q_WS_QWS bool ok; weight= Lview->fontInfo().weight(); italic = Lview->fontInfo().italic(); bold=Lview->fontInfo().bold(); pointSize= Lview->fontInfo().pointSize(); fontStr=Lview->fontInfo().family(); if(italic == true) italicStr="TRUE"; else italicStr="FALSE"; QFont currentfont( fontStr, pointSize, weight, italic ); if (ok) { QFontInfo fontInfo(font ); fontStr=fontInfo.family(); pointSize= fontInfo.pointSize(); font.setFontSize(pointSize); pointSizeStr.setNum( pointSize); weight= fontInfo.weight(); weightStr.setNum( weight); italic =fontInfo.italic(); bold=fontInfo.bold(); if(italic == true) italicStr="TRUE"; else italicStr="FALSE"; if(bold == true) boldStr="TRUE"; else boldStr="FALSE"; pointSizeStr.setNum( pointSize); config.setGroup( "Font" ); config.writeEntry("Family", fontStr ); config.writeEntry("Size", pointSizeStr ); config.writeEntry("Weight", weightStr ); config.writeEntry("Italic", italicStr ); config.writeEntry("Bold", boldStr ); // config.write(); Lview->setFont(font); QRect lRect; QRect rRect; lRect = Lview->rect(); if(useSplitter) { } // if(loadCheck) { // ResizeEdits(); // } update(); } #endif } /* performs dictionary look ups on the web */ void Gutenbrowser::LookupBtn() { QString text; if( Lview->hasSelectedText()) { Lview->copy(); } QClipboard *cb = QApplication::clipboard(); text = cb->text(); int eexit=QMessageBox::information(this, "Note","Do you want to lookup\n\""+text+"\"\non websters web dictionary?", QMessageBox::Yes, QMessageBox::No); if (eexit== 3) { // this link for sale!! qApp->processEvents(); goGetit( "http://www.m-w.com/cgi-bin/dictionary?" + text, true); } } void Gutenbrowser::ClearEdit() { Lview->setText(""); loadCheck = false; status = ( tr("Gutenbrowser")); InfoBar->setText( ""); setCaption( tr("Gutenbrowser")); i_pageNum = 0; enableButtons(false); if(!showMainList) { Lview->hide(); showMainList=TRUE; mainList->show(); fillWithTitles(); qApp->processEvents(); } if(donateMenu->idAt(3) != -1) donateMenu->removeItemAt(3); } bool Gutenbrowser::getTitle( const char *file ) { QString s_file; QString filer = file; if( filer.contains(local_library, TRUE)) { QFileInfo f(file); s_file = f.fileName(); } else { s_file = filer; } Config config("Gutenbrowser"); config.setGroup( "Files" ); QString s_numofFiles = config.readEntry("NumberOfFiles", "0" ); int i_numofFiles = s_numofFiles.toInt(); for (int i = 1; i <= i_numofFiles; i++) { QString temp; temp.setNum(i); QString ramble = config.readEntry(temp, "" ); if( strcmp(ramble, s_file) == 0) { config.setGroup( "Titles" ); title = config.readEntry(ramble, ""); // odebug << "(getTitle)title is being set as "+title << oendl; } } return true; } void Gutenbrowser::searchdone_slot() { // if (!searchDlg) // return; // searchDlg->hide(); // Lview->setFocus(); this->setFocus(); last_search = 0; // ResizeEdits(); } /* sets the status message */ bool Gutenbrowser::setStatus() { #ifndef Q_WS_QWS QString s_pages; s_pages.setNum( pages); QString chNum; statusTop = status.left( status.find(" ", TRUE) ); status.append(chNum.setNum( i_pageNum)); status += " / " + s_pages; if(loadCheck) { statusBar->message( status); InfoBar->setText( title); } else { } #else QString msg; msg.sprintf(title+" %d", i_pageNum); setCaption( msg); #endif return true; } void Gutenbrowser::keyReleaseEvent( QKeyEvent *e) { switch ( e->key() ) { case Key_M: // Bookmark(); break; case Key_D: DownloadIndex(); break; case Key_L: LibraryBtn(); break; case Key_O: OpenBtn(); break; case Key_F: ForwardBtn(); break; case Key_B: BackBtn(); break; case Key_P: PrintBtn(); break; case Key_S: SearchBtn(); break; case Key_E: ByeBye(); break; case Key_R: // setBookmark(); break; case Key_T: ChangeFont(); break; case Key_C: ClearEdit(); break; case Key_H: HelpBtn(); break; case Key_K: LookupBtn(); break; case Key_U:// hide menu if(menubar->isHidden() ) menubar->show(); else menubar->hide(); break; case Key_I: hideButtons(); break; ////////////////////////////// Zaurus keys case Key_Home: // BeginBtn(); break; case Key_F9: //activity OpenBtn(); break; case Key_F10: //contacts hideButtons(); break; case Key_F11: //menu if(menubar->isHidden() ) menubar->show(); else menubar->hide(); break; case Key_F12: //home BeginBtn(); break; case Key_F13: //mail LibraryBtn(); break; case Key_Space: if(loadCheck) ForwardBtn(); // else // Bookmark(); break; case Key_Down: if(loadCheck) { // if( !e->isAutoRepeat() ) // AdjustStatus(); // } else { // LibraryBtn(); // ForwardBtn(); } // ForwardButton->setFocus(); // Lview->setFocus(); // if(s_Wrap=="FALSE") // Lview->MultiLine_Ex::ScrollDown( 1); // LibraryBtn(); break; case Key_Up: if(loadCheck) { // if( !e->isAutoRepeat() ) // AdjustStatus(); // } else { // OpenBtn(); // BackBtn(); } // BackButton->setFocus(); // Lview->setFocus(); // if(s_Wrap=="FALSE") // Lview->MultiLine_Ex::ScrollUp( 1); // LibraryBtn(); break; case Key_Right: ForwardButton->setFocus(); ForwardBtn(); // LibraryBtn(); break; case Key_Left: BackBtn(); BackButton->setFocus(); // OpenBtn(); break; case Key_Escape: ByeBye(); break; case Key_PageUp: BackBtn(); break; case Key_PageDown: ForwardBtn(); break; ////////////////////////////// Zaurus keys }; } void Gutenbrowser::keyPressEvent( QKeyEvent *e) { switch ( e->key() ) { // case Key_Next: // ForwardBtn(); // break; // case Key_Prior: // BackBtn(); // break; // case Key_Space: // ForwardBtn(); // break; // case Key_Down: // Lview->MultiLine_Ex::ScrollUp( 1); // if(useSplitter) Rview->MultiLine_Ex::ScrollUp( 1); // break; // case Key_Up: // if( Lview->Top() != 0) { // Lview->MultiLine_Ex::ScrollDown( 1); // if(useSplitter) Rview->MultiLine_Ex::ScrollDown( 1); // } // break; } } void Gutenbrowser::resizeEvent( QResizeEvent *ev) { // odebug << "resize: " << ev->size().width() << "," << ev->size().height() << "\n" << oendl; if( !LibraryDlg->isHidden()) LibraryDlg->resize(ev->size().width(),ev->size().height() ); // if( loadCheck == true) { // ResizeEdits(); // AdjustStatus(); // } } void Gutenbrowser::doOptions() { optionsDialog* optDlg; optDlg = new optionsDialog( this,"Options_Dlg", true); QString Ddir; Config config("Gutenbrowser"); config.setGroup( "General" ); QFont myFont; optDlg->showMaximized(); if( optDlg->exec() !=0) { qApp->processEvents(); brow=optDlg->browserName; toggleButtonIcons( optDlg->useIcon); ftp_host= optDlg->ftp_host; ftp_base_dir= optDlg->ftp_base_dir; brow=optDlg->browserName; Ddir=optDlg->downloadDirEdit->text(); odebug << "writing library config" << oendl; Config config("Gutenbrowser"); config.setGroup("General"); QString dirname= optDlg->downloadDirEdit->text(); if(dirname.right(1)!="/") dirname+="/"; config.writeEntry( "DownloadDirectory",dirname); QDir newDir( optDlg->downloadDirEdit->text()); if( !newDir.exists() ) { int exit=QMessageBox::information(this, "Note", "Ok, to make a new directory\n"+Ddir+" ?", QMessageBox::Ok, QMessageBox::Cancel); if (exit==1) { QString cmd="mkdir -p "; cmd+=Ddir.latin1(); system(cmd); odebug << "Making new dir "+cmd << oendl; if(Ddir.right(1)!="/") { Ddir+="/"; } config.writeEntry("DownloadDirectory",Ddir); } } // if(optDlg->styleChanged) // setStyle( optDlg->styleInt); if(optDlg->b_qExit==TRUE) b_queryExit=TRUE; else b_queryExit=FALSE; if(optDlg->fontDlg-> changedFonts) { odebug << "Setting font" << oendl; myFont=optDlg->fontDlg->selectedFont; Lview->setFont( myFont); } if(optDlg->useWordWrap_CheckBox->isChecked() ) { odebug << "WORD WRAP is set" << oendl; Lview->setWordWrap(QMultiLineEdit::WidgetWidth); useWrap=true; } else { odebug << "Word wrap is NOT set" << oendl; Lview->setWordWrap(QMultiLineEdit::NoWrap); useWrap=false; } } if(showMainList) { if(!Lview->isHidden()) Lview->hide(); qApp->processEvents(); if(mainList->isHidden()) mainList->show(); fillWithTitles(); } else { Lview->show(); showMainList=FALSE; mainList->hide(); } qApp->processEvents(); update(); } bool Gutenbrowser::setTitle() { if( file_name.contains( local_library)) { QFileInfo f( file_name); QString s_file = f.fileName(); file_name = s_file; } int test = 0; Config config("Gutenbrowser"); config.setGroup( "Files" ); QString s_numofFiles = config.readEntry("NumberOfFiles", "0" ); int i_numofFiles = s_numofFiles.toInt(); for (int i = 1; i <= i_numofFiles; i++) { QString temp; temp.setNum(i); QString ramble = config.readEntry(temp, "" ); if( strcmp(ramble, file_name) == 0) { test = 1; } } if (test == 0) { config.writeEntry("NumberOfFiles",i_numofFiles +1 ); QString interger; interger.setNum( i_numofFiles +1); config.writeEntry(interger, file_name); config.setGroup( "Titles" ); config.writeEntry(file_name,listItemTitle); } test = 0; // config.write(); return true; } /*Calls new fangled network dialog */ void Gutenbrowser::OnNetworkDialog( const QString &/*networkUrl*/, const QString &/*output*/) { // odebug << networkUrl << oendl; // odebug << output << oendl; // #ifndef Q_WS_QWS // NetworkDialog *NetworkDlg; // if( networkUrl.length() < 4 ) networkUrl= "http://sailor.gutenberg.org/mirror.sites.html"; // NetworkDlg = new NetworkDialog( this,"Network Protocol Dialog", TRUE, 0, networkUrl, output); // if( NetworkDlg->exec() != 0 ) { // } // if(NetworkDlg) // delete NetworkDlg; // #endif } void Gutenbrowser::donateGutenberg() { int exit=QMessageBox::information(this, "Info", "http://www.gutenberg.org\ndonate@gutenberg.net", QMessageBox::Ok, QMessageBox::Cancel); if (exit==1) { } else { }; } void Gutenbrowser::donateByteMonkie() { } void Gutenbrowser::writeConfig() { // config.read(); // Config config("Gutenbrowser"); // #ifndef Q_WS_QWS // config.setGroup( "Geometry" ); // QString s; // QString globalPosition; // QPoint point; // point=mapToGlobal(QPoint(0,0) ); // int posiX, posiY; // posiX=point.x(); // posiY=point.y(); // globalPosition.sprintf("%i,%i", posiX, posiY); // QRect frameRect; // frameRect = geometry(); // s.sprintf("%i,%i", frameRect.width(), frameRect.height()); // config.writeEntry("Frame", s); // config.writeEntry("Position", globalPosition); // if( useIcons==TRUE) // config.writeEntry("Icons", "TRUE"); // else // config.writeEntry("Icons", "FALSE"); // #endif // #ifndef Q_WS_QWS // QString temp; // temp.setNum(styleI, 10); // config.setGroup( "StyleIze" ); // config.writeEntry( "Style", temp); // #endif // config.setGroup("General"); } void Gutenbrowser::annotations() { // #ifndef Q_WS_QWS // QMessageBox::message("Note","hi annotate"); // lastBmkButton->setDown(FALSE); // #endif } void Gutenbrowser::hideButtons() { if( !buttonsHidden) { buttonsHidden=TRUE; LibraryButton->hide(); SearchButton->hide(); InfoBar->hide(); OpenButton->hide(); BackButton->hide(); ForwardButton->hide(); setBookmarkButton->hide(); lastBmkButton->hide(); dictionaryButton->hide(); if(useSplitter) { ClearButton->hide(); PrintButton->hide(); beginButton->hide(); HelpButton->hide(); FontButton->hide(); ExitButton->hide(); OptionsButton->hide(); DownloadButton->hide(); } } else { buttonsHidden=FALSE; LibraryButton->show(); SearchButton->show(); InfoBar->show(); OpenButton->show(); BackButton->show(); ForwardButton->show(); setBookmarkButton->show(); lastBmkButton->show(); dictionaryButton->show(); if(useSplitter) { ClearButton->show(); PrintButton->show(); beginButton->show(); HelpButton->show(); FontButton->show(); ExitButton->show(); OptionsButton->show(); DownloadButton->show(); } } } void Gutenbrowser::focusInEvent( QFocusEvent* ) { } void Gutenbrowser::focusOutEvent( QFocusEvent* ) { } void Gutenbrowser::cleanUp( ) { writeConfig(); QPEApplication::grabKeyboard(); QPEApplication::ungrabKeyboard(); // odebug << "Cleanup" << oendl; if(f.isOpen()) f.close(); } void Gutenbrowser::fixKeys() { odebug << "Attempting to fix keys" << oendl; } void Gutenbrowser::enableButtons(bool b) { BackButton->setEnabled(b); ForwardButton->setEnabled(b); SearchButton->setEnabled(b); setBookmarkButton->setEnabled(b); dictionaryButton->setEnabled(b); InfoBar->setEnabled(b); editMenu->setItemEnabled( -5, b); editMenu->setItemEnabled( -6, b); editMenu->setItemEnabled( -7, b); editMenu->setItemEnabled( -8, b); } void Gutenbrowser::fillWithTitles() { Config config("Gutenbrowser"); config.setGroup( "Files" ); int i_numofFiles = config.readNumEntry("NumberOfFiles", 0); mainList->clear(); QString temp; for (int i = 1; i <= i_numofFiles; i++) { temp.setNum(i); config.setGroup( "Files" ); QString ramble = config.readEntry(temp, "" ); config.setGroup( "Titles" ); temp = config.readEntry(ramble, ""); if( !temp.isEmpty()) { mainList->insertItem ( Opie::Core::OResource::loadPixmap("gutenbrowser/gutenbrowser_sm", Opie::Core::OResource::SmallIcon ), temp, -1); } } } void Gutenbrowser::listClickedSlot( QListBoxItem * index) { // if( !working) { // working=true; if(index) { // QCopEnvelope ( "QPE/System", "busy()" ); title = index->text(); showMainList=FALSE; mainList->hide(); Lview->show(); qApp->processEvents(); QString temp; temp.setNum( mainList->currentItem() + 1); // openFileTitle = title; Config config("Gutenbrowser"); config.setGroup( "Files" ); QString file = config.readEntry(temp, ""); odebug << "About to load" << oendl; if( Lview->isVisible()) if(!load(file)) return; config.setGroup( title); file_name = config.readEntry("File Name", ""); i_pageNum = config.readNumEntry("Page Number", 1); int Bmrkrow = config.readNumEntry("LineNumber", -1); if(Bmrkrow > -1) { if( Bmrkrow > Lview->topRow() ) { // Lview->setCursorPosition( Bmrkrow /* - Lview->topRow() */,0, FALSE ); Lview->ScrollUp( Bmrkrow - Lview->topRow() ); // AdjustStatus(); } else if( Bmrkrow < Lview->topRow() ) { // Lview->setCursorPosition( Lview->topRow() - Bmrkrow ,0, FALSE ); Lview->ScrollDown( Lview->topRow() - Bmrkrow ); // AdjustStatus(); } } } } void Gutenbrowser::infoGutenbrowser() { QMessageBox::message("Info","Gutenbrowser was developed by\n" "Lorn Potter\n" "ljp<ljp@llornkcor.com>\n"); } void Gutenbrowser::setDocument(const QString & frozenBoogers) { // this->hide(); qWarning("\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXSET DOCUMENT\n"); if(showMainList) { showMainList=FALSE; if(!mainList->isHidden()) mainList->hide(); if(Lview->isHidden()) Lview->show(); qApp->processEvents(); } DocLnk lnk; lnk = DocLnk(frozenBoogers); qWarning("open "+frozenBoogers); // odebug << lnk.file() << oendl; title=lnk.comment(); if(!load( lnk.file())) return; this->show(); // odebug << title << oendl; // qApp->processEvents(); // repaint(); } void Gutenbrowser::mainListPressed(int mouse, QListBoxItem * , const QPoint & ) { switch (mouse) { case 1: break; case 2: { QPopupMenu m;// = new QPopupMenu( Local_View ); m.insertItem( tr( "Open" ), this, SLOT( menuOpen() )); m.insertSeparator(); m.insertItem( tr( "Search google.com" ), this, SLOT( menuGoogle())); m.insertItem( tr( "Edit Title" ), this, SLOT( menuEditTitle())); // m.insertSeparator(); // m.insertItem( tr( "Delete" ), this, SLOT( remoteDelete() )); m.exec( QCursor::pos() ); } break; }; } void Gutenbrowser::menuOpen() { listClickedSlot( mainList->item( mainList->currentItem())); } void Gutenbrowser::menuGoogle() { searchGoogle( mainList->text(mainList->currentItem())); } void Gutenbrowser::searchGoogle( const QString &tempText) { QString text = tempText; int eexit=QMessageBox::information(this, "Note","Do you want to search for\n"+text+ "\non google.com?",QMessageBox::Yes, QMessageBox::No); if (eexit== 3) { qApp->processEvents(); text.replace( QRegExp("\\s"), "%20"); text.replace( QRegExp("#"), ""); text.replace( QRegExp(","), "%20"); text.replace( QRegExp("'"), "%20"); text.replace( QRegExp("("), ""); text.replace( QRegExp(")"), ""); // text.replace( QRegExp("[0-9]"), ""); QString s_lookup = "http://google.com/search?q="+text+"&num=30&sa=Google+Search"; goGetit( s_lookup, true); } } void Gutenbrowser::menuEditTitle() { int currentItem = mainList->currentItem(); QString title_text = mainList->text( currentItem); //odebug << "Selected "+title_text << oendl; Config config("Gutenbrowser"); config.setGroup( "Files" ); QString s_numofFiles = config.readEntry("NumberOfFiles", "0"); int i_numofFiles = s_numofFiles.toInt(); QString fileNum; for (int i = 1; i <= i_numofFiles+1; i++) { fileNum.setNum(i); config.setGroup( "Files" ); QString s_filename = config.readEntry(fileNum, "" ); config.setGroup( "Titles" ); QString file_title = config.readEntry( s_filename, ""); //odebug << "file_title is "+file_title << oendl; if(title_text == file_title ) { // selFile = s_filename; //odebug << "Edit: "+ file_title << oendl; i=i_numofFiles+1; Edit_Title *titleEdit; titleEdit = new Edit_Title(this,file_title ,TRUE); if(titleEdit->exec() !=0) { //odebug << titleEdit->newTitle << oendl; config.writeEntry( s_filename, titleEdit->newTitle); mainList->removeItem(currentItem); mainList->insertItem ( Opie::Core::OResource::loadPixmap("gutenbrowser/gutenbrowser_sm", Opie::Core::OResource::SmallIcon ), titleEdit->newTitle, currentItem); } } } // getTitles(); mainList->triggerUpdate(true); } bool Gutenbrowser::UnZipIt(const QString &zipFile) { odebug << zipFile << oendl; #ifndef Q_WS_QWS if( QFile::exists( zipFile)) { // TODO findsome other way of dealingwithzip files. bool isPgWhole=false; QString thatFile; if(zipFile.find("pgwhole",0,TRUE)) { isPgWhole=TRUE; thatFile= local_library +"PGWHOLE.TXT"; } // else { // thatFile=zipFile.left(4); // } // odebug << (const char*)local_library.latin1() << oendl; QString cmd; #if defined(_WS_X11_) if( chdir((const char*)local_library.latin1())!=0) odebug << "chdir failed." << oendl; cmd = "gunzip -S .zip " + local_library+zipFile; //cmd = "gunzip -d " + zipFile /*newestLibraryFile */+" -d " + local_library; #endif #ifdef Q_WS_QWS if( chdir((const char*)local_library.latin1())!=0) odebug << "chdir failed." << oendl; cmd = "unzip " + local_library+zipFile; // cmd = "/usr/bin/unzip -o " + local_library+zipFile +" -d /usr/share/doc/gutenbrowser" ;//+ local_library; #endif int exit=QMessageBox::information(this, "Ok to unzip?", "Ok to unnzip\n"+ zipFile+" ?", QMessageBox::Yes, QMessageBox::No); if (exit==QMessageBox::Yes) { #if defined(_WS_X11_)// odebug << "Issuing the command "+cmd << oendl; system( cmd); if( QFile::exists(thatFile)) remove (thatFile); if(isPgWhole) { if( rename("pgwhole","PGWHOLE.TXT") !=0) odebug << "rename failed" << oendl; } else { if( rename(thatFile.left(4),thatFile.left(4)+".txt") !=0) odebug << "rename failed" << oendl; } #endif #ifdef Q_WS_QWS odebug << "Issuing the command "+cmd << oendl; system( cmd); if( QFile::exists(thatFile)) remove(thatFile); if(isPgWhole) { if( rename("pgwhole","PGWHOLE.TXT") !=0) odebug << "rename failed" << oendl; } else { if( rename(thatFile.left(4),thatFile.left(4)+".txt") !=0) odebug << "rename failed" << oendl; } #endif // remove( zipFile); return true; } else if(exit==QMessageBox::No) { // odebug << "unzip" << oendl; return false; } } else QMessageBox::message( "Note",( tr("Please install unzip in your PATH")) ); #endif return false; } diff --git a/noncore/apps/opie-gutenbrowser/helpwindow.cpp b/noncore/apps/opie-gutenbrowser/helpwindow.cpp index 4bdac02..f444a2e 100644 --- a/noncore/apps/opie-gutenbrowser/helpwindow.cpp +++ b/noncore/apps/opie-gutenbrowser/helpwindow.cpp @@ -1,333 +1,331 @@ /**************************************************************************** ** $Id$ ** ** Copyright (C) 1992-2000 Trolltech AS. All rights reserved. ** ** This file is part of an example program for Qt. This example ** program may be used, distributed and modified without limitation. ** copyright : (C) 2000 -2004 by llornkcor email : ljp@llornkcor.com *****************************************************************************/ #include "helpwindow.h" #include <qpe/global.h> #include <qstatusbar.h> #include <qmenubar.h> #include <qtoolbar.h> #include <qtoolbutton.h> #include <qcombobox.h> #ifndef QT_NO_FILEDIALOG #include <qfiledialog.h> #endif #include <ctype.h> HelpWindow::HelpWindow( const QString& home_, const QString&, QWidget* parent, const char *name ) : QMainWindow( parent, name, WDestructiveClose ), pathCombo( 0 ), selectedURL() { QString local_library = Global::applicationFileName("gutenbrowser", QString::null); // readHistory(); // readBookmarks(); browser = new QTextBrowser( this ); QStringList Strlist; Strlist.append( home_); browser->mimeSourceFactory()->setFilePath( Strlist ); browser->setFrameStyle( QFrame::Panel | QFrame::Sunken ); connect(browser,SIGNAL(textChanged()),this,SLOT(textChanged())); setCentralWidget( browser ); if ( !home_.isEmpty() ) //////////////////////////////// browser->setSource( home_ ); //////////////////////////////// connect( browser, SIGNAL( highlighted( const QString&) ), statusBar(), SLOT( message( const QString&)) ); // resize( 640,600 ); #ifdef Q_WS_QWS setGeometry( 0,0,236,280); #else setGeometry( 10,30,520,420 ); // resize(520,420); #endif QPopupMenu* file = new QPopupMenu( this ); // file->insertItem( tr("&New Window"), this, SLOT( newWindow() ), ALT | Key_N ); file->insertItem( tr("&Open File"), this, SLOT( openFile() ), ALT | Key_O ); // file->insertItem( tr("&Print"), this, SLOT( print() ), ALT | Key_P ); file->insertSeparator(); file->insertItem( tr("&Close"), this, SLOT( close() ), ALT | Key_Q ); // file->insertItem( tr("E&xit"), qApp, SLOT( closeAllWindows() ), ALT | Key_X ); // The same three icons are used twice each. ////F FIXME QString pixs=(QDir::homeDirPath ()) +"/Applications/gutenbrowser/pix/"; QIconSet icon_back( QPixmap(pixs+"back.png") ); QIconSet icon_forward( QPixmap(pixs+"forward.png") ); QIconSet icon_home( QPixmap(pixs+"home.png") ); QPopupMenu* go = new QPopupMenu( this ); backwardId = go->insertItem( icon_back, tr("&Backward"), browser, SLOT( backward() ), ALT | Key_Left ); forwardId = go->insertItem( icon_forward, tr("&Forward"), browser, SLOT( forward() ), ALT | Key_Right ); go->insertItem( icon_home, tr("&Home"), browser, SLOT( home() ) ); // QPopupMenu* help = new QPopupMenu( this ); // help->insertItem( tr("&About ..."), this, SLOT( about() ) ); // help->insertItem( tr("About &Qt ..."), this, SLOT( aboutQt() ) ); hist = new QPopupMenu( this ); QStringList::Iterator it = history.begin(); for ( ; it != history.end(); ++it ) mHistory[ hist->insertItem( *it ) ] = *it; connect( hist, SIGNAL( activated( int ) ), this, SLOT( histChosen( int ) ) ); bookm = new QPopupMenu( this ); bookm->insertItem( tr( "Add Bookmark" ), this, SLOT( addBookmark() ) ); bookm->insertSeparator(); QStringList::Iterator it2 = bookmarks.begin(); for ( ; it2 != bookmarks.end(); ++it2 ) mBookmarks[ bookm->insertItem( *it2 ) ] = *it2; connect( bookm, SIGNAL( activated( int ) ), this, SLOT( bookmChosen( int ) ) ); menuBar()->insertItem( tr("&File"), file ); menuBar()->insertItem( tr("&Go"), go ); menuBar()->insertItem( tr( "History" ), hist ); menuBar()->insertItem( tr( "Bookmarks" ), bookm ); // menuBar()->insertSeparator(); // menuBar()->insertItem( tr("&Help"), help ); menuBar()->setItemEnabled( forwardId, FALSE); menuBar()->setItemEnabled( backwardId, FALSE); connect( browser, SIGNAL( backwardAvailable( bool ) ), this, SLOT( setBackwardAvailable( bool ) ) ); connect( browser, SIGNAL( forwardAvailable( bool ) ), this, SLOT( setForwardAvailable( bool ) ) ); QToolBar* toolbar = new QToolBar( this ); addToolBar( toolbar, "Toolbar"); QToolButton* button; button = new QToolButton( icon_back, tr("Backward"), "", browser, SLOT(backward()), toolbar ); connect( browser, SIGNAL( backwardAvailable(bool) ), button, SLOT( setEnabled(bool) ) ); button->setEnabled( FALSE ); button = new QToolButton( icon_forward, tr("Forward"), "", browser, SLOT(forward()), toolbar ); connect( browser, SIGNAL( forwardAvailable(bool) ), button, SLOT( setEnabled(bool) ) ); button->setEnabled( FALSE ); button = new QToolButton( icon_home, tr("Home"), "", browser, SLOT(home()), toolbar ); toolbar->addSeparator(); pathCombo = new QComboBox( TRUE, toolbar ); connect( pathCombo, SIGNAL( activated( const QString & ) ), this, SLOT( pathSelected( const QString & ) ) ); toolbar->setStretchableWidget( pathCombo ); // pathCombo->setMaximumWidth(190); // setRightJustification( TRUE ); // setDockEnabled( Left, FALSE ); // setDockEnabled( Right, FALSE ); pathCombo->insertItem( home_ ); browser->setFocus(); } void HelpWindow::setBackwardAvailable( bool b) { menuBar()->setItemEnabled( backwardId, b); } void HelpWindow::setForwardAvailable( bool b) { menuBar()->setItemEnabled( forwardId, b); } void HelpWindow::textChanged() { if ( browser->documentTitle().isNull() ) { setCaption( "Gutenbrowser - Helpviewer - " + browser->context() ); selectedURL = browser->context(); } else { setCaption( "Gutenbrowser - Helpviewer - " + browser->documentTitle() ) ; selectedURL = browser->documentTitle(); } if ( !selectedURL.isEmpty() && pathCombo ) { bool exists = FALSE; int i; for ( i = 0; i < pathCombo->count(); ++i ) { if ( pathCombo->text( i ) == selectedURL ) { exists = TRUE; break; } } if ( !exists ) { pathCombo->insertItem( selectedURL, 0 ); pathCombo->setCurrentItem( 0 ); mHistory[ hist->insertItem( selectedURL ) ] = selectedURL; } else pathCombo->setCurrentItem( i ); selectedURL = QString::null; } } HelpWindow::~HelpWindow() { history.clear(); QMap<int, QString>::Iterator it = mHistory.begin(); for ( ; it != mHistory.end(); ++it ) - history.append( *it ); + history.append( *it ); QFile f( QDir::currentDirPath() + "/.history" ); - f.open( IO_WriteOnly ); - QDataStream s( &f ); - s << history; - f.close(); + if ( f.open( IO_WriteOnly ) ) { + QDataStream s( &f ); + s << history; + f.close(); + } bookmarks.clear(); QMap<int, QString>::Iterator it2 = mBookmarks.begin(); for ( ; it2 != mBookmarks.end(); ++it2 ) - bookmarks.append( *it2 ); + bookmarks.append( *it2 ); QFile f2( QDir::currentDirPath() + "/.bookmarks" ); - f2.open( IO_WriteOnly ); + if ( !f2.open( IO_WriteOnly ) ) + return; + QDataStream s2( &f2 ); s2 << bookmarks; f2.close(); } -// void HelpWindow::about() -// { -// QMessageBox::about( this, "Gutenbrowser", "<p>Thanks to Trolltech for this</p>" ); -// } - -// void HelpWindow::aboutQt() -// { -// QMessageBox::aboutQt( this, "QBrowser" ); -// } - void HelpWindow::openFile() { #ifndef QT_NO_FILEDIALOG QString fn = QFileDialog::getOpenFileName( QString::null, QString::null, this ); if ( !fn.isEmpty() ) browser->setSource( fn ); #endif } void HelpWindow::newWindow() { ( new HelpWindow(browser->source(), "qbrowser") )->show(); } void HelpWindow::print() { #ifndef QT_NO_PRINTER QPrinter printer; printer.setFullPage(TRUE); if ( printer.setup() ) { QPainter p( &printer ); QPaintDeviceMetrics metrics(p.device()); int dpix = metrics.logicalDpiX(); int dpiy = metrics.logicalDpiY(); const int margin = 72; // pt QRect body(margin*dpix/72, margin*dpiy/72, metrics.width()-margin*dpix/72*2, metrics.height()-margin*dpiy/72*2 ); QFont font("times", 10); QSimpleRichText richText( browser->text(), font, browser->context(), browser->styleSheet(), browser->mimeSourceFactory(), body.height() ); richText.setWidth( &p, body.width() ); QRect view( body ); int page = 1; do { p.setClipRect( body ); richText.draw( &p, body.left(), body.top(), view, colorGroup() ); p.setClipping( FALSE ); view.moveBy( 0, body.height() ); p.translate( 0 , -body.height() ); p.setFont( font ); p.drawText( view.right() - p.fontMetrics().width( QString::number(page) ), view.bottom() + p.fontMetrics().ascent() + 5, QString::number(page) ); if ( view.top() >= richText.height() ) break; printer.newPage(); page++; } while (TRUE); } #endif } void HelpWindow::pathSelected( const QString &_path ) { browser->setSource( _path ); QMap<int, QString>::Iterator it = mHistory.begin(); bool exists = FALSE; for ( ; it != mHistory.end(); ++it ) { if ( *it == _path ) { exists = TRUE; break; } } if ( !exists ) mHistory[ hist->insertItem( _path ) ] = _path; } void HelpWindow::readHistory() { - if ( QFile::exists( QDir::currentDirPath() + "/.history" ) ) { - QFile f( QDir::currentDirPath() + "/.history" ); - f.open( IO_ReadOnly ); - QDataStream s( &f ); - s >> history; - f.close(); - while ( history.count() > 20 ) - history.remove( history.begin() ); - } + if ( !QFile::exists( QDir::currentDirPath() + "/.history" ) ) + return; + + QFile f( QDir::currentDirPath() + "/.history" ); + if ( !f.open( IO_ReadOnly ) ) + return; + + QDataStream s( &f ); + s >> history; + f.close(); + while ( history.count() > 20 ) + history.remove( history.begin() ); } void HelpWindow::readBookmarks() { - if ( QFile::exists( QDir::currentDirPath() + "/.bookmarks" ) ) { - QFile f( QDir::currentDirPath() + "/.bookmarks" ); - f.open( IO_ReadOnly ); - QDataStream s( &f ); - s >> bookmarks; - f.close(); - } + if ( !QFile::exists( QDir::currentDirPath() + "/.bookmarks" ) ) + return; + + QFile f( QDir::currentDirPath() + "/.bookmarks" ); + if ( !f.open( IO_ReadOnly ) ) + return; + QDataStream s( &f ); + s >> bookmarks; + f.close(); } void HelpWindow::histChosen( int i ) { if ( mHistory.contains( i ) ) browser->setSource( mHistory[ i ] ); } void HelpWindow::bookmChosen( int i ) { if ( mBookmarks.contains( i ) ) browser->setSource( mBookmarks[ i ] ); } void HelpWindow::addBookmark() { mBookmarks[ bookm->insertItem( caption() ) ] = caption(); } diff --git a/noncore/graphics/opie-eye/slave/bmp_slave.cpp b/noncore/graphics/opie-eye/slave/bmp_slave.cpp index 2fa825f..0efadac 100644 --- a/noncore/graphics/opie-eye/slave/bmp_slave.cpp +++ b/noncore/graphics/opie-eye/slave/bmp_slave.cpp @@ -1,175 +1,173 @@ #include "bmp_slave.h" #include "thumbnailtool.h" #include <qimage.h> #include <qobject.h> #include <qfile.h> #include <qpixmap.h> #include <qstring.h> PHUNK_VIEW_INTERFACE( "Bmp", BmpSlave ); namespace { struct pBmpHeader { // file header of bmp char type[2]; // must be "BM" otherwise it is no bmp Q_INT32 hSize; Q_INT32 reserved1,reserved2; Q_INT16 Planes; Q_INT16 BitCount; Q_INT32 Size; Q_INT32 Width; Q_INT32 Height; Q_INT32 Compression; Q_INT32 SizeImage; Q_INT32 XPerMeter; Q_INT32 YPerMeter; Q_INT32 ClrUsed; Q_INT32 ClrImportant; }; class BmpHeader { protected: void read_data(); QString _name; QFile _inputfile; pBmpHeader m_Header; static const int OLD = 12; static const int WIN = 40; static const int OS2 = 64; static const int RGB = 0; static const int RLE8 = 1; static const int RLE4 = 2; public: BmpHeader(const QString&fname); virtual ~BmpHeader(); bool isBmp()const{return qstrncmp(m_Header.type,"BM",2)==0;} bool isCompressed()const{return m_Header.Compression != 0;} QSize imageSize(){return QSize(m_Header.Width,m_Header.Height);} QString imageCompression()const; int bitsPixel()const{return m_Header.BitCount;} int Size()const{return m_Header.hSize;} int compressedSize()const{return m_Header.SizeImage;} int ColorsUsed()const{return m_Header.ClrUsed;} int XPix()const{return m_Header.XPerMeter;} int YPix()const{return m_Header.YPerMeter;} }; QString BmpHeader::imageCompression()const { switch (m_Header.Compression) { case RLE8: return "8Bit RLE Encoding"; break; case RLE4: return "4Bit RLE Encoding"; break; case RGB: default: return "No encoding"; } } BmpHeader::BmpHeader(const QString&fname) : _name(fname),_inputfile(_name) { read_data(); } void BmpHeader::read_data() { memset(&m_Header,0,sizeof(pBmpHeader)); - _inputfile.open(IO_Raw|IO_ReadOnly); - if (!_inputfile.isOpen()) { + if (!_inputfile.open(IO_Raw|IO_ReadOnly)) return; - } QDataStream s(&_inputfile); s.setByteOrder( QDataStream::LittleEndian ); s.readRawBytes(m_Header.type,2); if (!isBmp()) { _inputfile.close(); return; } s >> m_Header.hSize; s >> m_Header.reserved1 >> m_Header.reserved2; s >> m_Header.Size; if ( m_Header.Size == BmpHeader::WIN || m_Header.Size == BmpHeader::OS2 ) { s >> m_Header.Width >> m_Header.Height >> m_Header.Planes >> m_Header.BitCount; s >> m_Header.Compression >> m_Header.SizeImage; s >> m_Header.XPerMeter >> m_Header.YPerMeter; s >> m_Header.ClrUsed >> m_Header.ClrImportant; } else { Q_INT16 w, h; s >> w >> h >> m_Header.Planes >> m_Header.BitCount; m_Header.Width = w; m_Header.Height = h; m_Header.Compression = BmpHeader::RGB; m_Header.SizeImage = 0; m_Header.XPerMeter = m_Header.YPerMeter = 0; m_Header.ClrUsed = m_Header.ClrImportant = 0; } _inputfile.close(); } BmpHeader::~BmpHeader() { } } BmpSlave::BmpSlave() : SlaveInterface(QStringList("bmp")) {} BmpSlave::~BmpSlave() { } QString BmpSlave::iconViewName(const QString& str) { QString st; BmpHeader bh(str); if (!bh.isBmp()) { st.append("No bmp file"); return st; } QSize isize = bh.imageSize(); st+=QObject::tr("Dimensions: %1 x %2\n").arg(isize.width()).arg(isize.height()); st+=QObject::tr("Size: %1\n").arg(bh.Size()); st+=QObject::tr("Depth: %1\n").arg(bh.bitsPixel()); return st; } QString BmpSlave::fullImageInfo( const QString& str) { QString st = "<qt>"; BmpHeader bh(str); if (!bh.isBmp()) { st.append("No bmp file"); st.append( "</qt>" ); return st; } QSize isize = bh.imageSize(); st+=QObject::tr("Dimensions: %1 x %2\n").arg(isize.width()).arg(isize.height()); st+=QObject::tr("Size: %1\n").arg(bh.Size()); st+=QObject::tr("Compression: %1\n").arg(bh.imageCompression()); if (bh.isCompressed()) { st+=QObject::tr("Compressed size: %1").arg(bh.compressedSize()); } st+=QObject::tr("Depth: %1\n").arg(bh.bitsPixel()); st+=QObject::tr("used colors: %1\n").arg(bh.ColorsUsed()); st+=QObject::tr("Resolution: %1 x %2\n").arg(bh.XPix()).arg(bh.YPix()); st.append( "</qt>" ); return st; } QPixmap BmpSlave::pixmap(const QString& path, int width, int height ) { static QImage img; img.load( path ); if ( img.isNull() ) { QPixmap pix; return pix; } return ThumbNailTool::scaleImage( img, width,height ); } diff --git a/noncore/net/ftplib/ftplib.c b/noncore/net/ftplib/ftplib.c index 421f855..efcd6f0 100644 --- a/noncore/net/ftplib/ftplib.c +++ b/noncore/net/ftplib/ftplib.c @@ -1,1346 +1,1350 @@ /***************************************************************************/ /* ftplib.c - callable ftp access routines */ /* Copyright (C) 1996-2000 Thomas Pfau, pfau@cnj.digex.net */ /* 73 Catherine Street, South Bound Brook, NJ, 08880 */ /* */ /* This library is free software; you can redistribute it and/or */ /* modify it under the terms of the GNU Library General Public */ /* License as published by the Free Software Foundation; either */ /* version 2 of the License, or (at your option) any later version. */ /* */ /* This library is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */ /* Library General Public License for more details. */ /* */ /* You should have received a copy of the GNU Library General Public */ /* License along with this progam; if not, write to the */ /* Free Software Foundation, Inc., 59 Temple Place - Suite 330, */ /* Boston, MA 02111-1307, USA. */ /* */ /***************************************************************************/ // changes made by Lorn Potter <llornkcor@handhelds.org> // #if defined(__unix__) || defined(__VMS) #include <unistd.h> #endif #if defined(_WIN32) #include <windows.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <ctype.h> #if defined(__unix__) #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <sys/time.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #elif defined(VMS) #include <types.h> #include <socket.h> #include <in.h> #include <netdb.h> #include <inet.h> #elif defined(_WIN32) #include <winsock.h> #endif #define BUILDING_LIBRARY #include "ftplib.h" #if defined(_WIN32) #define SETSOCKOPT_OPTVAL_TYPE (const char *) #else #define SETSOCKOPT_OPTVAL_TYPE (void *) #endif #define FTPLIB_BUFSIZ 8192 #define ACCEPT_TIMEOUT 10 #define FTPLIB_CONTROL 0 #define FTPLIB_READ 1 #define FTPLIB_WRITE 2 #if !defined FTPLIB_DEFMODE #define FTPLIB_DEFMODE FTPLIB_PASSIVE #endif struct NetBuf { char *cput,*cget; int handle; int cavail,cleft; char *buf; int dir; netbuf *ctrl; netbuf *data; int cmode; struct timeval idletime; FtpCallback idlecb; void *idlearg; int xfered; int cbbytes; int xfered1; char response[256]; }; static char *version = "ftplib Release 3.1-1 9/16/00, copyright 1996-2000 Thomas Pfau"; GLOBALDEF int ftplib_debug = 0; #if defined(__unix__) || defined(VMS) #define net_read read #define net_write write #define net_close close #elif defined(_WIN32) #define net_read(x,y,z) recv(x,y,z,0) #define net_write(x,y,z) send(x,y,z,0) #define net_close closesocket #endif #if defined(NEED_MEMCCPY) /* * VAX C does not supply a memccpy routine so I provide my own */ void *memccpy(void *dest, const void *src, int c, size_t n) { int i=0; const unsigned char *ip=src; unsigned char *op=dest; while (i < n) { if ((*op++ = *ip++) == c) break; i++; } if (i == n) return NULL; return op; } #endif #if defined(NEED_STRDUP) /* * strdup - return a malloc'ed copy of a string */ char *strdup(const char *src) { int l = strlen(src) + 1; char *dst = malloc(l); if (dst) strcpy(dst,src); return dst; } #endif /* * socket_wait - wait for socket to receive or flush data * * return 1 if no user callback, otherwise, return value returned by * user callback */ static int socket_wait(netbuf *ctl) { fd_set fd,*rfd = NULL,*wfd = NULL; struct timeval tv; int rv = 0; if ((ctl->dir == FTPLIB_CONTROL) || (ctl->idlecb == NULL)) return 1; if (ctl->dir == FTPLIB_WRITE) wfd = &fd; else rfd = &fd; FD_ZERO(&fd); do { FD_SET(ctl->handle,&fd); tv = ctl->idletime; rv = select(ctl->handle+1, rfd, wfd, NULL, &tv); if (rv == -1) { rv = 0; strncpy(ctl->ctrl->response, strerror(errno), sizeof(ctl->ctrl->response)); break; } else if (rv > 0) { rv = 1; break; } } while ((rv = ctl->idlecb(ctl, ctl->xfered, ctl->idlearg))); return rv; } /* * read a line of text * * return -1 on error or bytecount */ static int readline(char *buf,int max,netbuf *ctl) { int x,retval = 0; char *end,*bp=buf; int eof = 0; if ((ctl->dir != FTPLIB_CONTROL) && (ctl->dir != FTPLIB_READ)) return -1; if (max == 0) return 0; do { if (ctl->cavail > 0) { x = (max >= ctl->cavail) ? ctl->cavail : max-1; end = memccpy(bp,ctl->cget,'\n',x); if (end != NULL) x = end - bp; retval += x; bp += x; *bp = '\0'; max -= x; ctl->cget += x; ctl->cavail -= x; if (end != NULL) { bp -= 2; if (strcmp(bp,"\r\n") == 0) { *bp++ = '\n'; *bp++ = '\0'; --retval; } break; } } if (max == 1) { *buf = '\0'; break; } if (ctl->cput == ctl->cget) { ctl->cput = ctl->cget = ctl->buf; ctl->cavail = 0; ctl->cleft = FTPLIB_BUFSIZ; } if (eof) { if (retval == 0) retval = -1; break; } if (!socket_wait(ctl)) return retval; if ((x = net_read(ctl->handle,ctl->cput,ctl->cleft)) == -1) { perror("read"); retval = -1; break; } if (x == 0) eof = 1; ctl->cleft -= x; ctl->cavail += x; ctl->cput += x; } while (1); return retval; } /* * write lines of text * * return -1 on error or bytecount */ static int writeline(char *buf, int len, netbuf *nData) { int x, nb=0, w; char *ubp = buf, *nbp; char lc=0; if (nData->dir != FTPLIB_WRITE) return -1; nbp = nData->buf; for (x=0; x < len; x++) { if ((*ubp == '\n') && (lc != '\r')) { if (nb == FTPLIB_BUFSIZ) { if (!socket_wait(nData)) return x; w = net_write(nData->handle, nbp, FTPLIB_BUFSIZ); if (w != FTPLIB_BUFSIZ) { printf("net_write(1) returned %d, errno = %d\n", w, errno); return(-1); } nb = 0; } nbp[nb++] = '\r'; } if (nb == FTPLIB_BUFSIZ) { if (!socket_wait(nData)) return x; w = net_write(nData->handle, nbp, FTPLIB_BUFSIZ); if (w != FTPLIB_BUFSIZ) { printf("net_write(2) returned %d, errno = %d\n", w, errno); return(-1); } nb = 0; } nbp[nb++] = lc = *ubp++; } if (nb) { if (!socket_wait(nData)) return x; w = net_write(nData->handle, nbp, nb); if (w != nb) { printf("net_write(3) returned %d, errno = %d\n", w, errno); return(-1); } } return len; } /* * read a response from the server * * return 0 if first char doesn't match * return 1 if first char matches */ static int readresp(char c, netbuf *nControl) { char match[5]; if (readline(nControl->response,256,nControl) == -1) { perror("Control socket read failed"); return 0; } if (ftplib_debug > 1) fprintf(stderr,"%s",nControl->response); if (nControl->response[3] == '-') { strncpy(match,nControl->response,3); match[3] = ' '; match[4] = '\0'; do { if (readline(nControl->response,256,nControl) == -1) { perror("Control socket read failed"); return 0; } if (ftplib_debug > 1) fprintf(stderr,"%s",nControl->response); } while (strncmp(nControl->response,match,4)); } if (nControl->response[0] == c) return 1; return 0; } /* * FtpInit for stupid operating systems that require it (Windows NT) */ GLOBALDEF void FtpInit(void) { #if defined(_WIN32) WORD wVersionRequested; WSADATA wsadata; int err; wVersionRequested = MAKEWORD(1,1); if ((err = WSAStartup(wVersionRequested,&wsadata)) != 0) fprintf(stderr,"Network failed to start: %d\n",err); #endif } /* * FtpLastResponse - return a pointer to the last response received */ GLOBALDEF char *FtpLastResponse(netbuf *nControl) { if ((nControl) && (nControl->dir == FTPLIB_CONTROL)) return nControl->response; return NULL; } /* * FtpConnect - connect to remote server * * return 1 if connected, 0 if not */ GLOBALDEF int FtpConnect(const char *host, netbuf **nControl) { int sControl, stat, flags, oldflags; struct sockaddr_in sin; struct hostent *phe; struct servent *pse; int on=1; netbuf *ctrl; char *lhost; char *pnum; struct timeval tv; fd_set wr; memset(&sin,0,sizeof(sin)); sin.sin_family = AF_INET; lhost = strdup(host); pnum = strchr(lhost,':'); if (pnum == NULL) { #if defined(VMS) sin.sin_port = htons(21); #else if ((pse = getservbyname("ftp","tcp")) == NULL) { perror("getservbyname"); return 0; } sin.sin_port = pse->s_port; #endif } else { *pnum++ = '\0'; if (isdigit(*pnum)) sin.sin_port = htons(atoi(pnum)); else { pse = getservbyname(pnum,"tcp"); sin.sin_port = pse->s_port; } } if ((sin.sin_addr.s_addr = inet_addr(lhost)) == -1) { if ((phe = gethostbyname(lhost)) == NULL) { perror("gethostbyname"); return 0; } memcpy((char *)&sin.sin_addr, phe->h_addr, phe->h_length); } free(lhost); sControl = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (sControl == -1) { perror("socket"); return 0; } if ( setsockopt(sControl,SOL_SOCKET,SO_REUSEADDR, SETSOCKOPT_OPTVAL_TYPE &on, sizeof(on)) == -1) { perror("setsockopt"); net_close(sControl); return 0; } //set nonblocking for connection timeout flags = fcntl( sControl, F_GETFL,0); oldflags=flags; fcntl( sControl, F_SETFL, O_NONBLOCK|flags); stat=connect( sControl, (struct sockaddr *)&sin, sizeof(sin)); if (stat < 0) { if (errno != EWOULDBLOCK && errno != EINPROGRESS) { perror("connect"); net_close(sControl); return 0; } } FD_ZERO(&wr); FD_SET( sControl, &wr); tv.tv_sec = ACCEPT_TIMEOUT; tv.tv_usec = 0; stat = select(sControl+1, 0, &wr, 0, &tv); if (stat < 1) { // time out has expired, // or an error has ocurred perror("timeout"); net_close(sControl); return 0; } printf("connected\n"); //set original flags fcntl( sControl, F_SETFL, oldflags); ctrl = calloc(1,sizeof(netbuf)); if (ctrl == NULL) { perror("calloc"); net_close(sControl); return 0; } ctrl->buf = malloc(FTPLIB_BUFSIZ); if (ctrl->buf == NULL) { perror("calloc"); net_close(sControl); free(ctrl); return 0; } ctrl->handle = sControl; ctrl->dir = FTPLIB_CONTROL; ctrl->ctrl = NULL; ctrl->cmode = FTPLIB_DEFMODE; ctrl->idlecb = NULL; ctrl->idletime.tv_sec = ctrl->idletime.tv_usec = 0; ctrl->idlearg = NULL; ctrl->xfered = 0; ctrl->xfered1 = 0; ctrl->cbbytes = 0; if (readresp('2', ctrl) == 0) { net_close(sControl); free(ctrl->buf); free(ctrl); return 0; } *nControl = ctrl; return 1; } /* * FtpOptions - change connection options * * returns 1 if successful, 0 on error */ GLOBALDEF int FtpOptions(int opt, long val, netbuf *nControl) { int v,rv=0; switch (opt) { case FTPLIB_CONNMODE: v = (int) val; if ((v == FTPLIB_PASSIVE) || (v == FTPLIB_PORT)) { nControl->cmode = v; rv = 1; } break; case FTPLIB_CALLBACK: nControl->idlecb = (FtpCallback) val; rv = 1; break; case FTPLIB_IDLETIME: v = (int) val; rv = 1; nControl->idletime.tv_sec = v / 1000; nControl->idletime.tv_usec = (v % 1000) * 1000; break; case FTPLIB_CALLBACKARG: rv = 1; nControl->idlearg = (void *) val; break; case FTPLIB_CALLBACKBYTES: rv = 1; nControl->cbbytes = (int) val; break; } return rv; } /* * FtpSendCmd - send a command and wait for expected response * * return 1 if proper response received, 0 otherwise */ static int FtpSendCmd(const char *cmd, char expresp, netbuf *nControl) { char buf[256]; if (nControl->dir != FTPLIB_CONTROL) return 0; if (ftplib_debug > 2) fprintf(stderr,"%s\n",cmd); if ((strlen(cmd) + 3) > sizeof(buf)) return 0; sprintf(buf,"%s\r\n",cmd); if (net_write(nControl->handle,buf,strlen(buf)) <= 0) { perror("write"); return 0; } return readresp(expresp, nControl); } /* * FtpLogin - log in to remote server * * return 1 if logged in, 0 otherwise */ GLOBALDEF int FtpLogin(const char *user, const char *pass, netbuf *nControl) { char tempbuf[64]; if (((strlen(user) + 7) > sizeof(tempbuf)) || ((strlen(pass) + 7) > sizeof(tempbuf))) return 0; sprintf(tempbuf,"USER %s",user); if (!FtpSendCmd(tempbuf,'3',nControl)) { if (nControl->response[0] == '2') return 1; return 0; } sprintf(tempbuf,"PASS %s",pass); return FtpSendCmd(tempbuf,'2',nControl); } /* * FtpOpenPort - set up data connection * * return 1 if successful, 0 otherwise */ static int FtpOpenPort(netbuf *nControl, netbuf **nData, int mode, int dir) { int sData; union { struct sockaddr sa; struct sockaddr_in in; } sin; struct linger lng = { 0, 0 }; unsigned int l; int on=1; netbuf *ctrl; char *cp; unsigned int v[6]; char buf[256]; if (nControl->dir != FTPLIB_CONTROL) return -1; if ((dir != FTPLIB_READ) && (dir != FTPLIB_WRITE)) { sprintf(nControl->response, "Invalid direction %d\n", dir); return -1; } if ((mode != FTPLIB_ASCII) && (mode != FTPLIB_IMAGE)) { sprintf(nControl->response, "Invalid mode %c\n", mode); return -1; } l = sizeof(sin); if (nControl->cmode == FTPLIB_PASSIVE) { memset(&sin, 0, l); sin.in.sin_family = AF_INET; if (!FtpSendCmd("PASV",'2',nControl)) return -1; cp = strchr(nControl->response,'('); if (cp == NULL) return -1; cp++; sscanf(cp,"%u,%u,%u,%u,%u,%u",&v[2],&v[3],&v[4],&v[5],&v[0],&v[1]); sin.sa.sa_data[2] = v[2]; sin.sa.sa_data[3] = v[3]; sin.sa.sa_data[4] = v[4]; sin.sa.sa_data[5] = v[5]; sin.sa.sa_data[0] = v[0]; sin.sa.sa_data[1] = v[1]; } else { if (getsockname(nControl->handle, &sin.sa, &l) < 0) { perror("getsockname"); return 0; } } sData = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP); if (sData == -1) { perror("socket"); return -1; } if (setsockopt(sData,SOL_SOCKET,SO_REUSEADDR, SETSOCKOPT_OPTVAL_TYPE &on,sizeof(on)) == -1) { perror("setsockopt"); net_close(sData); return -1; } if (setsockopt(sData,SOL_SOCKET,SO_LINGER, SETSOCKOPT_OPTVAL_TYPE &lng,sizeof(lng)) == -1) { perror("setsockopt"); net_close(sData); return -1; } if (nControl->cmode == FTPLIB_PASSIVE) { if (connect(sData, &sin.sa, sizeof(sin.sa)) == -1) { perror("connect"); net_close(sData); return -1; } } else { sin.in.sin_port = 0; if (bind(sData, &sin.sa, sizeof(sin)) == -1) { perror("bind"); net_close(sData); return 0; } if (listen(sData, 1) < 0) { perror("listen"); net_close(sData); return 0; } if (getsockname(sData, &sin.sa, &l) < 0) return 0; sprintf(buf, "PORT %d,%d,%d,%d,%d,%d", (unsigned char) sin.sa.sa_data[2], (unsigned char) sin.sa.sa_data[3], (unsigned char) sin.sa.sa_data[4], (unsigned char) sin.sa.sa_data[5], (unsigned char) sin.sa.sa_data[0], (unsigned char) sin.sa.sa_data[1]); if (!FtpSendCmd(buf,'2',nControl)) { net_close(sData); return 0; } } ctrl = calloc(1,sizeof(netbuf)); if (ctrl == NULL) { perror("calloc"); net_close(sData); return -1; } if ((mode == 'A') && ((ctrl->buf = malloc(FTPLIB_BUFSIZ)) == NULL)) { perror("calloc"); net_close(sData); free(ctrl); return -1; } ctrl->handle = sData; ctrl->dir = dir; ctrl->idletime = nControl->idletime; ctrl->idlearg = nControl->idlearg; ctrl->xfered = 0; ctrl->xfered1 = 0; ctrl->cbbytes = nControl->cbbytes; if (ctrl->idletime.tv_sec || ctrl->idletime.tv_usec || ctrl->cbbytes) ctrl->idlecb = nControl->idlecb; else ctrl->idlecb = NULL; *nData = ctrl; return 1; } /* * FtpAcceptConnection - accept connection from server * * return 1 if successful, 0 otherwise */ static int FtpAcceptConnection(netbuf *nData, netbuf *nControl) { int sData; struct sockaddr addr; unsigned int l; int i; struct timeval tv; fd_set mask; int rv; FD_ZERO(&mask); FD_SET(nControl->handle, &mask); FD_SET(nData->handle, &mask); tv.tv_usec = 0; tv.tv_sec = ACCEPT_TIMEOUT; printf("<<<<<<<<<<<<<<<<%d\n",ACCEPT_TIMEOUT); i = nControl->handle; if (i < nData->handle) i = nData->handle; i = select(i+1, &mask, NULL, NULL, &tv); if (i == -1) { strncpy(nControl->response, strerror(errno), sizeof(nControl->response)); net_close(nData->handle); nData->handle = 0; rv = 0; } else if (i == 0) { strcpy(nControl->response, "timed out waiting for connection"); net_close(nData->handle); nData->handle = 0; rv = 0; } else { if (FD_ISSET(nData->handle, &mask)) { l = sizeof(addr); sData = accept(nData->handle, &addr, &l); i = errno; net_close(nData->handle); if (sData > 0) { rv = 1; nData->handle = sData; } else { strncpy(nControl->response, strerror(i), sizeof(nControl->response)); nData->handle = 0; rv = 0; } } else if (FD_ISSET(nControl->handle, &mask)) { net_close(nData->handle); nData->handle = 0; readresp('2', nControl); rv = 0; } } return rv; } /* * FtpAccess - return a handle for a data stream * * return 1 if successful, 0 otherwise */ GLOBALDEF int FtpAccess(const char *path, int typ, int mode, netbuf *nControl, netbuf **nData) { char buf[256]; int dir; if ((path == NULL) && ((typ == FTPLIB_FILE_WRITE) || (typ == FTPLIB_FILE_READ))) { sprintf(nControl->response, "Missing path argument for file transfer\n"); return 0; } sprintf(buf, "TYPE %c", mode); if (!FtpSendCmd(buf, '2', nControl)) return 0; switch (typ) { case FTPLIB_DIR: strcpy(buf,"NLST"); dir = FTPLIB_READ; break; case FTPLIB_DIR_VERBOSE: strcpy(buf,"LIST"); dir = FTPLIB_READ; break; case FTPLIB_FILE_READ: strcpy(buf,"RETR"); dir = FTPLIB_READ; break; case FTPLIB_FILE_WRITE: strcpy(buf,"STOR"); dir = FTPLIB_WRITE; break; default: sprintf(nControl->response, "Invalid open type %d\n", typ); return 0; } if (path != NULL) { int i = strlen(buf); buf[i++] = ' '; if ((strlen(path) + i) >= sizeof(buf)) return 0; strcpy(&buf[i],path); } if (FtpOpenPort(nControl, nData, mode, dir) == -1) return 0; if (!FtpSendCmd(buf, '1', nControl)) { FtpClose(*nData); *nData = NULL; return 0; } (*nData)->ctrl = nControl; nControl->data = *nData; if (nControl->cmode == FTPLIB_PORT) { if (!FtpAcceptConnection(*nData,nControl)) { FtpClose(*nData); *nData = NULL; nControl->data = NULL; return 0; } } return 1; } /* * FtpRead - read from a data connection */ GLOBALDEF int FtpRead(void *buf, int max, netbuf *nData) { int i; if (nData->dir != FTPLIB_READ) return 0; if (nData->buf) i = readline(buf, max, nData); else { i = socket_wait(nData); if (i != 1) return 0; i = net_read(nData->handle, buf, max); } if (i == -1) return 0; nData->xfered += i; if (nData->idlecb && nData->cbbytes) { nData->xfered1 += i; if (nData->xfered1 > nData->cbbytes) { if (nData->idlecb(nData, nData->xfered, nData->idlearg) == 0) return 0; nData->xfered1 = 0; } } return i; } /* * FtpWrite - write to a data connection */ GLOBALDEF int FtpWrite(void *buf, int len, netbuf *nData) { int i; if (nData->dir != FTPLIB_WRITE) return 0; if (nData->buf) i = writeline(buf, len, nData); else { - socket_wait(nData); + if (socket_wait(nData) < 0) + fprintf(stderr, "FtpWrite: socket_wait failed with %s\n", nData->ctrl->response); i = net_write(nData->handle, buf, len); } if (i == -1) return 0; nData->xfered += i; if (nData->idlecb && nData->cbbytes) { nData->xfered1 += i; if (nData->xfered1 > nData->cbbytes) { nData->idlecb(nData, nData->xfered, nData->idlearg); nData->xfered1 = 0; } } return i; } /* * FtpClose - close a data connection */ GLOBALDEF int FtpClose(netbuf *nData) { netbuf *ctrl; switch (nData->dir) { case FTPLIB_WRITE: /* potential problem - if buffer flush fails, how to notify user? */ if (nData->buf != NULL) writeline(NULL, 0, nData); case FTPLIB_READ: if (nData->buf) free(nData->buf); shutdown(nData->handle,2); net_close(nData->handle); ctrl = nData->ctrl; free(nData); if (ctrl) { ctrl->data = NULL; return(readresp('2', ctrl)); } return 1; case FTPLIB_CONTROL: if (nData->data) { nData->ctrl = NULL; FtpClose(nData); } net_close(nData->handle); free(nData); return 0; } return 1; } /* * FtpSite - send a SITE command * * return 1 if command successful, 0 otherwise */ GLOBALDEF int FtpSite(const char *cmd, netbuf *nControl) { char buf[256]; if ((strlen(cmd) + 7) > sizeof(buf)) return 0; sprintf(buf,"SITE %s",cmd); if (!FtpSendCmd(buf,'2',nControl)) return 0; return 1; } /* * FtpSysType - send a SYST command * * Fills in the user buffer with the remote system type. If more * information from the response is required, the user can parse * it out of the response buffer returned by FtpLastResponse(). * * return 1 if command successful, 0 otherwise */ GLOBALDEF int FtpSysType(char *buf, int max, netbuf *nControl) { int l = max; char *b = buf; char *s; if (!FtpSendCmd("SYST",'2',nControl)) return 0; s = &nControl->response[4]; while ((--l) && (*s != ' ')) *b++ = *s++; *b++ = '\0'; return 1; } /* * FtpMkdir - create a directory at server * * return 1 if successful, 0 otherwise */ GLOBALDEF int FtpMkdir(const char *path, netbuf *nControl) { char buf[256]; if ((strlen(path) + 6) > sizeof(buf)) return 0; sprintf(buf,"MKD %s",path); if (!FtpSendCmd(buf,'2', nControl)) return 0; return 1; } /* * FtpChdir - change path at remote * * return 1 if successful, 0 otherwise */ GLOBALDEF int FtpChdir(const char *path, netbuf *nControl) { char buf[256]; if ((strlen(path) + 6) > sizeof(buf)) return 0; sprintf(buf,"CWD %s",path); if (!FtpSendCmd(buf,'2',nControl)) return 0; return 1; } /* * FtpCDUp - move to parent directory at remote * * return 1 if successful, 0 otherwise */ GLOBALDEF int FtpCDUp(netbuf *nControl) { if (!FtpSendCmd("CDUP",'2',nControl)) return 0; return 1; } /* * FtpRmdir - remove directory at remote * * return 1 if successful, 0 otherwise */ GLOBALDEF int FtpRmdir(const char *path, netbuf *nControl) { char buf[256]; if ((strlen(path) + 6) > sizeof(buf)) return 0; sprintf(buf,"RMD %s",path); if (!FtpSendCmd(buf,'2',nControl)) return 0; return 1; } /* * FtpPwd - get working directory at remote * * return 1 if successful, 0 otherwise */ GLOBALDEF int FtpPwd(char *path, int max, netbuf *nControl) { int l = max; char *b = path; char *s; if (!FtpSendCmd("PWD",'2',nControl)) return 0; s = strchr(nControl->response, '"'); if (s == NULL) return 0; s++; while ((--l) && (*s) && (*s != '"')) *b++ = *s++; *b++ = '\0'; return 1; } /* * FtpXfer - issue a command and transfer data * * return 1 if successful, 0 otherwise */ static int FtpXfer(const char *localfile, const char *path, netbuf *nControl, int typ, int mode) { int l,c; char *dbuf; FILE *local = NULL; netbuf *nData; int rv=1; if (localfile != NULL) { char ac[4] = "w"; if (typ == FTPLIB_FILE_WRITE) ac[0] = 'r'; if (mode == FTPLIB_IMAGE) ac[1] = 'b'; local = fopen(localfile, ac); if (local == NULL) { strncpy(nControl->response, strerror(errno), sizeof(nControl->response)); return 0; } } if (local == NULL) local = (typ == FTPLIB_FILE_WRITE) ? stdin : stdout; if (!FtpAccess(path, typ, mode, nControl, &nData)) return 0; dbuf = malloc(FTPLIB_BUFSIZ); if (typ == FTPLIB_FILE_WRITE) { while ((l = fread(dbuf, 1, FTPLIB_BUFSIZ, local)) > 0) if ((c = FtpWrite(dbuf, l, nData)) < l) { printf("short write: passed %d, wrote %d\n", l, c); rv = 0; break; } } else { while ((l = FtpRead(dbuf, FTPLIB_BUFSIZ, nData)) > 0) if (fwrite(dbuf, 1, l, local) <= 0) { perror("localfile write"); rv = 0; break; } } free(dbuf); fflush(local); if (localfile != NULL) fclose(local); FtpClose(nData); return rv; } /* * FtpNlst - issue an NLST command and write response to output * * return 1 if successful, 0 otherwise */ GLOBALDEF int FtpNlst(const char *outputfile, const char *path, netbuf *nControl) { return FtpXfer(outputfile, path, nControl, FTPLIB_DIR, FTPLIB_ASCII); } /* * FtpDir - issue a LIST command and write response to output * * return 1 if successful, 0 otherwise */ GLOBALDEF int FtpDir(const char *outputfile, const char *path, netbuf *nControl) { return FtpXfer(outputfile, path, nControl, FTPLIB_DIR_VERBOSE, FTPLIB_ASCII); } /* * FtpSize - determine the size of a remote file * * return 1 if successful, 0 otherwise */ GLOBALDEF int FtpSize(const char *path, int *size, char mode, netbuf *nControl) { char cmd[256]; int resp,sz,rv=1; if ((strlen(path) + 7) > sizeof(cmd)) return 0; sprintf(cmd, "TYPE %c", mode); if (!FtpSendCmd(cmd, '2', nControl)) return 0; sprintf(cmd,"SIZE %s",path); if (!FtpSendCmd(cmd,'2',nControl)) rv = 0; else { if (sscanf(nControl->response, "%d %d", &resp, &sz) == 2) *size = sz; else rv = 0; } return rv; } /* * FtpModDate - determine the modification date of a remote file * * return 1 if successful, 0 otherwise */ GLOBALDEF int FtpModDate(const char *path, char *dt, int max, netbuf *nControl) { char buf[256]; int rv = 1; if ((strlen(path) + 7) > sizeof(buf)) return 0; sprintf(buf,"MDTM %s",path); if (!FtpSendCmd(buf,'2',nControl)) rv = 0; else strncpy(dt, &nControl->response[4], max); return rv; } /* * FtpGet - issue a GET command and write received data to output * * return 1 if successful, 0 otherwise */ GLOBALDEF int FtpGet(const char *outputfile, const char *path, char mode, netbuf *nControl) { return FtpXfer(outputfile, path, nControl, FTPLIB_FILE_READ, mode); } /* * FtpPut - issue a PUT command and send data from input * * return 1 if successful, 0 otherwise */ GLOBALDEF int FtpPut(const char *inputfile, const char *path, char mode, netbuf *nControl) { return FtpXfer(inputfile, path, nControl, FTPLIB_FILE_WRITE, mode); } /* * FtpRename - rename a file at remote * * return 1 if successful, 0 otherwise */ GLOBALDEF int FtpRename(const char *src, const char *dst, netbuf *nControl) { char cmd[256]; if (((strlen(src) + 7) > sizeof(cmd)) || ((strlen(dst) + 7) > sizeof(cmd))) return 0; sprintf(cmd,"RNFR %s",src); if (!FtpSendCmd(cmd,'3',nControl)) return 0; sprintf(cmd,"RNTO %s",dst); if (!FtpSendCmd(cmd,'2',nControl)) return 0; return 1; } /* * FtpDelete - delete a file at remote * * return 1 if successful, 0 otherwise */ GLOBALDEF int FtpDelete(const char *fnm, netbuf *nControl) { char cmd[256]; if ((strlen(fnm) + 7) > sizeof(cmd)) return 0; sprintf(cmd,"DELE %s",fnm); if (!FtpSendCmd(cmd,'2', nControl)) return 0; return 1; } /* * FtpQuit - disconnect from remote * * return 1 if successful, 0 otherwise */ GLOBALDEF void FtpQuit(netbuf *nControl) { if (nControl->dir != FTPLIB_CONTROL) return; - FtpSendCmd("QUIT",'2',nControl); + if (FtpSendCmd("QUIT",'2',nControl) == 1) { + if (ftplib_debug > 2) + fprintf(stderr, "FtpQuit: FtpSendCmd(QUIT) failed\n"); + } net_close(nControl->handle); free(nControl->buf); free(nControl); } diff --git a/noncore/todayplugins/stockticker/stockticker/helpwindow.cpp b/noncore/todayplugins/stockticker/stockticker/helpwindow.cpp index 410d642..2498bf9 100644 --- a/noncore/todayplugins/stockticker/stockticker/helpwindow.cpp +++ b/noncore/todayplugins/stockticker/stockticker/helpwindow.cpp @@ -1,271 +1,275 @@ /**************************************************************************** ** ** Copyright (C) 1992-2000 Trolltech AS. All rights reserved. ** ** This file is part of an example program for Qt. This example ** program may be used, distributed and modified without limitation. ** *****************************************************************************/ #include "helpwindow.h" #include <qstatusbar.h> #include <qmenubar.h> #include <qtoolbar.h> #include <qtoolbutton.h> #include <qcombobox.h> #ifndef QT_NO_FILEDIALOG #include <qfiledialog.h> #endif #include <ctype.h> HelpWindow::HelpWindow( const QString& home_, const QString& _path, QWidget* parent, const char *name ) : QMainWindow( parent, name, WDestructiveClose ), pathCombo( 0 ), selectedURL() { readHistory(); readBookmarks(); browser = new QTextBrowser( this ); QStringList Strlist; Strlist.append( home_); browser->mimeSourceFactory()->setFilePath( Strlist ); browser->setFrameStyle( QFrame::Panel | QFrame::Sunken ); connect( browser, SIGNAL( textChanged() ), this, SLOT( textChanged() ) ); setCentralWidget( browser ); if ( !home_.isEmpty() ) //////////////////////////////// browser->setSource( home_ ); //////////////////////////////// connect( browser, SIGNAL( highlighted(const QString&) ), statusBar(), SLOT( message(const QString&)) ); setGeometry( 0,0,236,280); QPopupMenu* file = new QPopupMenu( this ); // file->insertItem( tr("&New Window"), this, SLOT( newWindow() ), ALT | Key_N ); file->insertItem( tr("&Open File"), this, SLOT( openFile() ), ALT | Key_O ); // file->insertItem( tr("&Print"), this, SLOT( print() ), ALT | Key_P ); file->insertSeparator(); file->insertItem( tr("&Close"), this, SLOT( close() ), ALT | Key_Q ); // file->insertItem( tr("E&xit"), qApp, SLOT( closeAllWindows() ), ALT | Key_X ); // The same three icons are used twice each. ////F FIXME QString pixs=(QDir::homeDirPath ()) +"/Applications/gutenbrowser/pix/"; QIconSet icon_back( QPixmap(pixs+"back.png") ); QIconSet icon_forward( QPixmap(pixs+"forward.png") ); QIconSet icon_home( QPixmap(pixs+"home.png") ); QPopupMenu* go = new QPopupMenu( this ); backwardId = go->insertItem( icon_back, tr("&Backward"), browser, SLOT( backward() ), ALT | Key_Left ); forwardId = go->insertItem( icon_forward, tr("&Forward"), browser, SLOT( forward() ), ALT | Key_Right ); go->insertItem( icon_home, tr("&Home"), browser, SLOT( home() ) ); hist = new QPopupMenu( this ); QStringList::Iterator it = history.begin(); for ( ; it != history.end(); ++it ) mHistory[ hist->insertItem( *it ) ] = *it; connect( hist, SIGNAL( activated(int) ), this, SLOT( histChosen(int) ) ); bookm = new QPopupMenu( this ); bookm->insertItem( tr( "Add Bookmark" ), this, SLOT( addBookmark() ) ); bookm->insertSeparator(); QStringList::Iterator it2 = bookmarks.begin(); for ( ; it2 != bookmarks.end(); ++it2 ) mBookmarks[ bookm->insertItem( *it2 ) ] = *it2; connect( bookm, SIGNAL( activated(int) ), this, SLOT( bookmChosen(int) ) ); menuBar()->insertItem( tr("&File"), file ); menuBar()->insertItem( tr("&Go"), go ); menuBar()->insertItem( tr( "History" ), hist ); menuBar()->insertItem( tr( "Bookmarks" ), bookm ); // menuBar()->insertSeparator(); // menuBar()->insertItem( tr("&Help"), help ); menuBar()->setItemEnabled( forwardId, FALSE); menuBar()->setItemEnabled( backwardId, FALSE); connect( browser, SIGNAL( backwardAvailable(bool) ), this, SLOT( setBackwardAvailable(bool) ) ); connect( browser, SIGNAL( forwardAvailable(bool) ), this, SLOT( setForwardAvailable(bool) ) ); QToolBar* toolbar = new QToolBar( this ); addToolBar( toolbar, "Toolbar"); QToolButton* button; button = new QToolButton( icon_back, tr("Backward"), "", browser, SLOT(backward()), toolbar ); connect( browser, SIGNAL( backwardAvailable(bool) ), button, SLOT( setEnabled(bool) ) ); button->setEnabled( FALSE ); button = new QToolButton( icon_forward, tr("Forward"), "", browser, SLOT(forward()), toolbar ); connect( browser, SIGNAL( forwardAvailable(bool) ), button, SLOT( setEnabled(bool) ) ); button->setEnabled( FALSE ); button = new QToolButton( icon_home, tr("Home"), "", browser, SLOT(home()), toolbar ); toolbar->addSeparator(); pathCombo = new QComboBox( TRUE, toolbar ); connect( pathCombo, SIGNAL( activated(const QString&) ), this, SLOT( pathSelected(const QString&) ) ); toolbar->setStretchableWidget( pathCombo ); // pathCombo->setMaximumWidth(190); // setRightJustification( TRUE ); // setDockEnabled( Left, FALSE ); // setDockEnabled( Right, FALSE ); pathCombo->insertItem( home_ ); browser->setFocus(); } void HelpWindow::setBackwardAvailable( bool b) { menuBar()->setItemEnabled( backwardId, b); } void HelpWindow::setForwardAvailable( bool b) { menuBar()->setItemEnabled( forwardId, b); } void HelpWindow::textChanged() { if ( browser->documentTitle().isNull() ) { setCaption( "Stockticker Lookup - " + browser->context() ); selectedURL = browser->context(); } else { setCaption( "Stockticker Lookup - " + browser->documentTitle() ) ; selectedURL = browser->documentTitle(); } if ( !selectedURL.isEmpty() && pathCombo ) { bool exists = FALSE; int i; for ( i = 0; i < pathCombo->count(); ++i ) { if ( pathCombo->text( i ) == selectedURL ) { exists = TRUE; break; } } if ( !exists ) { pathCombo->insertItem( selectedURL, 0 ); pathCombo->setCurrentItem( 0 ); mHistory[ hist->insertItem( selectedURL ) ] = selectedURL; } else pathCombo->setCurrentItem( i ); selectedURL = QString::null; } } HelpWindow::~HelpWindow() { history.clear(); QMap<int, QString>::Iterator it = mHistory.begin(); for ( ; it != mHistory.end(); ++it ) - history.append( *it ); + history.append( *it ); QFile f( QDir::currentDirPath() + "/.history" ); - f.open( IO_WriteOnly ); - QDataStream s( &f ); - s << history; - f.close(); + if ( f.open( IO_WriteOnly ) ) { + QDataStream s( &f ); + s << history; + f.close(); + } bookmarks.clear(); QMap<int, QString>::Iterator it2 = mBookmarks.begin(); for ( ; it2 != mBookmarks.end(); ++it2 ) - bookmarks.append( *it2 ); + bookmarks.append( *it2 ); QFile f2( QDir::currentDirPath() + "/.bookmarks" ); - f2.open( IO_WriteOnly ); + if ( !f2.open( IO_WriteOnly ) ) + return; QDataStream s2( &f2 ); s2 << bookmarks; f2.close(); } void HelpWindow::openFile() { #ifndef QT_NO_FILEDIALOG QString fn = QFileDialog::getOpenFileName( QString::null, QString::null, this ); if ( !fn.isEmpty() ) browser->setSource( fn ); #endif } void HelpWindow::newWindow() { ( new HelpWindow(browser->source(), "qbrowser") )->show(); } void HelpWindow::pathSelected( const QString &_path ) { browser->setSource( _path ); QMap<int, QString>::Iterator it = mHistory.begin(); bool exists = FALSE; for ( ; it != mHistory.end(); ++it ) { if ( *it == _path ) { exists = TRUE; break; } } if ( !exists ) mHistory[ hist->insertItem( _path ) ] = _path; } void HelpWindow::readHistory() { if ( QFile::exists( QDir::currentDirPath() + "/.history" ) ) { - QFile f( QDir::currentDirPath() + "/.history" ); - f.open( IO_ReadOnly ); - QDataStream s( &f ); - s >> history; - f.close(); - while ( history.count() > 20 ) - history.remove( history.begin() ); + QFile f( QDir::currentDirPath() + "/.history" ); + if ( !f.open( IO_ReadOnly ) ) + return; + QDataStream s( &f ); + s >> history; + f.close(); + while ( history.count() > 20 ) + history.remove( history.begin() ); } } void HelpWindow::readBookmarks() { if ( QFile::exists( QDir::currentDirPath() + "/.bookmarks" ) ) { - QFile f( QDir::currentDirPath() + "/.bookmarks" ); - f.open( IO_ReadOnly ); - QDataStream s( &f ); - s >> bookmarks; - f.close(); + QFile f( QDir::currentDirPath() + "/.bookmarks" ); + if ( !f.open( IO_ReadOnly ) ) + return; + QDataStream s( &f ); + s >> bookmarks; + f.close(); } } void HelpWindow::histChosen( int i ) { if ( mHistory.contains( i ) ) browser->setSource( mHistory[ i ] ); } void HelpWindow::bookmChosen( int i ) { if ( mBookmarks.contains( i ) ) browser->setSource( mBookmarks[ i ] ); } void HelpWindow::addBookmark() { mBookmarks[ bookm->insertItem( caption() ) ] = caption(); } diff --git a/noncore/todayplugins/weather/weatherpluginwidget.cpp b/noncore/todayplugins/weather/weatherpluginwidget.cpp index fe54051..27624c5 100644 --- a/noncore/todayplugins/weather/weatherpluginwidget.cpp +++ b/noncore/todayplugins/weather/weatherpluginwidget.cpp @@ -1,320 +1,321 @@ /* This file is part of the OPIE Project =. .=l. Copyright (c) 2002 Dan Williams <williamsdr@acm.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 <opie2/oprocess.h> #include <opie2/oresource.h> #include <qpe/config.h> #include <qfile.h> #include <qlabel.h> #include <qlayout.h> #include <qpixmap.h> #include <qtextstream.h> #include "weatherpluginwidget.h" using namespace Opie::Core; WeatherPluginWidget::WeatherPluginWidget( QWidget *parent, const char* name ) : QWidget( parent, name ) { QHBoxLayout *layout = new QHBoxLayout( this, 1, 2 ); layout->setAutoAdd( true ); weatherIcon = new QLabel( this ); weatherIcon->setPixmap( Opie::Core::OResource::loadPixmap( "Clock", Opie::Core::OResource::SmallIcon ) ); weatherLabel = new QLabel( tr( "Retreiving current weather information." ), this ); weatherLabel->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ) ); weatherIcon->setFixedSize( weatherLabel->height(), weatherLabel->height() ); startTimer(1000); } WeatherPluginWidget::~WeatherPluginWidget() { QFile file( localFile ); if ( file.exists() ) { file.remove(); } } void WeatherPluginWidget::timerEvent( QTimerEvent *e ) { killTimer( e->timerId() ); retreiveData(); } void WeatherPluginWidget::retreiveData() { Config config( "todayweatherplugin"); config.setGroup( "Config" ); location = config.readEntry( "Location", "" ); useMetric = config.readBoolEntry( "Metric", true ); frequency = config.readNumEntry( "Frequency", 5 ); startTimer( frequency * 60000 ); localFile = "/tmp/"; localFile.append( location ); localFile.append( ".TXT" ); remoteFile = "http://weather.noaa.gov/pub/data/observations/metar/stations/"; remoteFile.append( location ); remoteFile.append( ".TXT" ); QFile file( localFile ); if ( file.exists() ) { file.remove(); } OProcess *proc = new OProcess; *proc << "wget" << "-q" << remoteFile << "-O" << localFile; connect( proc, SIGNAL( processExited(Opie::Core::OProcess*) ), this, SLOT( dataRetrieved(Opie::Core::OProcess*) ) ); - proc->start(); + if ( !proc->start() ) + weatherLabel->setText( tr( "Could not start wget process." ) ); } void WeatherPluginWidget::displayWeather() { weatherData = QString::null; QFile file( localFile ); if ( file.size() > 0 && file.open( IO_ReadOnly ) ) { QTextStream data( &file ); while ( !data.eof() ) { weatherData.append( data.readLine() ); } file.close(); weatherData = weatherData.simplifyWhiteSpace(); QString tmpstr; tmpstr.append( tr( "Temp: " ) ); getTemp( weatherData ); tmpstr.append( dataStr ); tmpstr.append( tr( " Wind: " ) ); getWind( weatherData ); tmpstr.append( dataStr ); tmpstr.append( tr( "\nPres: " ) ); getPressure( weatherData ); tmpstr.append( dataStr ); weatherLabel->setText( tmpstr ); tmpstr = "todayweatherplugin/"; getIcon( weatherData ); tmpstr.append( dataStr ); - weatherIcon->setPixmap( Opie::Core::OResource::loadPixmap( tmpstr, Opie::Core::OResource::SmallIcon ) ); + weatherIcon->setPixmap( Opie::Core::OResource::loadPixmap( tmpstr, Opie::Core::OResource::SmallIcon ) ); } else { weatherLabel->setText( tr( "Current weather data not available." ) ); } } void WeatherPluginWidget::getTemp( const QString &data ) { int value; bool ok; int pos = data.find( QRegExp( "M?[0-9]+/M?[0-9]+" ), 20 ); if ( pos > -1 ) { if ( data.at( pos ) == 'M' ) { value = -1 * data.mid( pos + 1, 2 ).toInt( &ok ); } else { value = data.mid( pos, 2 ).toInt( &ok ); } if ( useMetric ) { dataStr = QString::number( value ); dataStr.append( 'C' ); } else { dataStr = QString::number( ( value * 9 / 5 ) + 32 ); dataStr.append( 'F' ); } } else { dataStr = tr( "n/a" ); } } void WeatherPluginWidget::getWind( const QString &data ) { int value; bool ok; int pos = data.find( QRegExp( "[0-9]*G*[0-9]*KT" ), 20 ); if ( pos > -1 ) { if ( data.mid( pos, 3 ) != "VRB" ) { value = data.mid( pos, 3 ).toInt( &ok ); if ( ( value >= 0 && value < 23 ) || ( value >= 239 && value <= 360 ) ) dataStr = tr("E " ); else if ( value >= 23 && value < 69 ) dataStr = tr( "NE " ); else if ( value >= 69 && value < 113 ) dataStr = tr( "N " ); else if ( value >= 113 && value < 157 ) dataStr = tr( "NW " ); else if ( value >= 157 && value < 203 ) dataStr = tr( "W " ); else if ( value >= 203 && value < 248 ) dataStr = tr( "SW " ); else if ( value >= 248 && value < 294 ) dataStr = tr( "S " ); else if ( value >= 294 && value < 238 ) dataStr = tr( "SE " ); } if ( data.mid( pos + 5, 1) == "G" || data.mid( pos + 5, 1) == "K" ) { value = data.mid( pos + 3, 2 ).toInt( &ok ); } else { value = data.mid( pos + 3, 3 ).toInt( &ok ); } if ( useMetric ) { value = value * 3.6 / 1.94; dataStr.append( QString::number( value ) ); dataStr.append( tr( " KPH" ) ); } else { value = value * 2.24 / 1.94; dataStr.append( QString::number( value ) ); dataStr.append( tr( " MPH" ) ); } } else { dataStr = tr( "n/a" ); } } void WeatherPluginWidget::getPressure( const QString &data ) { float value; bool ok; int pos = data.find( QRegExp( "[AQ][0-9]+" ), 20 ); if ( pos > -1 ) { value = data.mid( pos + 1, 4 ).toFloat( &ok ); if ( useMetric ) { if ( data.mid( pos, 1 ) == "A" ) value *= 33.8639 / 100; dataStr = QString::number( value, 'f', 2 ); dataStr.append( tr( " kPa" ) ); } else { if ( data.mid( pos, 1 ) == "Q" ) value /= 33.8639; else value /= 100; dataStr = QString::number( value, 'f', 2 ); dataStr.append( tr( " Hg" ) ); } } else { dataStr = tr( "n/a" ); } } void WeatherPluginWidget::getIcon(const QString &data ) { dataStr = "psunny"; if ( data.find( "CLR ", 20 ) > -1 || data.find( "SKC ", 20 ) > -1 || data.find( "CAVOK ", 20 ) > -1 ) { dataStr = "sunny"; } else if ( data.find( "SH ", 20 ) > -1 || data.find( "DZ ", 20 ) > -1 || data.find( "RA ", 20 ) > -1 || data.find( "UP ", 20 ) > -1 || data.find( "BR ", 20 ) > -1 ) { dataStr = "shower"; } else if ( data.find( "TS ", 20 ) > -1 ) { dataStr = "tstorm"; } else if ( data.find( "SN ", 20 ) > -1 || data.find( "SG ", 20 ) > -1 ) { dataStr = "snow"; } else if ( data.find( "FZ ", 20 ) > -1 || data.find( "GR ", 20 ) > -1 || data.find( "GS ", 20 ) > -1 || data.find( "PE ", 20 ) > -1 || data.find( "IC ", 20 ) > -1 ) { dataStr = "sleet"; } } void WeatherPluginWidget::dataRetrieved( OProcess *process ) { if ( process->normalExit() ) { displayWeather(); } else { weatherLabel->setText( tr( "Current weather data not available." ) ); } } diff --git a/noncore/tools/opie-sh/inputdialog.cpp b/noncore/tools/opie-sh/inputdialog.cpp index 8046795..1dd8bf7 100644 --- a/noncore/tools/opie-sh/inputdialog.cpp +++ b/noncore/tools/opie-sh/inputdialog.cpp @@ -1,124 +1,128 @@ /* Opie-sh. convinience app to allow you to use qdialogs in scripts (mainly shell scripts) Copyright (C) 2002 Thomas Stephens 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. 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "inputdialog.h" InputDialog::InputDialog(int w, int h, int newtype, QString labelString, QString title, QString filename, bool edit, QWidget *parent, const char *name, bool modal, WFlags f):QDialog(parent, name, modal, f) { type = newtype; QHBoxLayout *layout = new QHBoxLayout(this); layout->addStrut(32); QLabel *label = new QLabel(labelString, this, "label"); setCaption(title); int x, y; layout->addSpacing(5); layout->addWidget(label); layout->addSpacing(5); switch(type) { case 0: lineEdit = new QLineEdit(this, "line edit"); layout->addWidget(lineEdit); break; case 1: comboBox = new QComboBox(edit, this, "combo box"); layout->addWidget(comboBox); if(!filename.isNull()) { QFile file(filename); - file.open(IO_ReadOnly); - QTextStream stream(&file); - QString string = stream.read(); + if (file.open(IO_ReadOnly)) + { + QTextStream stream(&file); + QString string = stream.read(); - comboBox->insertStringList(QStringList::split('\n', string)); + comboBox->insertStringList(QStringList::split('\n', string)); + } } else { QFile file; file.open(IO_ReadOnly, 0); QTextStream stream(&file); QString string = stream.read(); comboBox->insertStringList(QStringList::split('\n', string)); } break; case 2: listBox = new QListBox(this, "list box"); listBox->setSelectionMode(QListBox::Multi); layout->addWidget(listBox); if(!filename.isNull()) { QFile file(filename); - file.open(IO_ReadOnly); - QTextStream stream(&file); - QString string = stream.read(); + if (file.open(IO_ReadOnly)) + { + QTextStream stream(&file); + QString string = stream.read(); - listBox->insertStringList(QStringList::split('\n', string)); + listBox->insertStringList(QStringList::split('\n', string)); + } } else { QFile file; file.open(IO_ReadOnly, 0); QTextStream stream(&file); QString string = stream.read(); listBox->insertStringList(QStringList::split('\n', string)); } break; case 3: lineEdit = new QLineEdit(this, "line edit"); lineEdit->setEchoMode(QLineEdit::Password); layout->addWidget(lineEdit); break; } layout->addSpacing(5); x=(w/2)-(width()/2); y=(h/2)-(height()/2); move(x,y); } QString InputDialog::getString() { switch (type) { case 0: case 3: return ((QLineEdit *)child("line edit"))->text(); break; case 1: return ((QComboBox *)child("combo box"))->currentText(); break; case 2: QString string; int i; for(i = 0; i < listBox->count(); i++) { if(listBox->isSelected(i)) { string+=listBox->text(i)+'\n'; } } if(string[string.length()-1] == '\n') { string.truncate(string.length()-1); } return string; } return QString::null; } |