diff --git a/lib/BlockArray.cpp b/lib/BlockArray.cpp index b64f396..1b4696e 100644 --- a/lib/BlockArray.cpp +++ b/lib/BlockArray.cpp @@ -48,8 +48,9 @@ BlockArray::BlockArray() length(0) { // lastmap_index = index = current = size_t(-1); - if (blocksize == 0) + if (blocksize == 0) { blocksize = ((sizeof(Block) / getpagesize()) + 1) * getpagesize(); + } } @@ -59,13 +60,16 @@ BlockArray::~BlockArray() assert(!lastblock); } -size_t BlockArray::append(Block *block) +size_t BlockArray::append(Block * block) { - if (!size) + if (!size) { return size_t(-1); + } ++current; - if (current >= size) current = 0; + if (current >= size) { + current = 0; + } int rc; rc = lseek(ion, current * blocksize, SEEK_SET); @@ -82,7 +86,9 @@ size_t BlockArray::append(Block *block) } length++; - if (length > size) length = size; + if (length > size) { + length = size; + } ++index; @@ -92,38 +98,44 @@ size_t BlockArray::append(Block *block) size_t BlockArray::newBlock() { - if (!size) + if (!size) { return size_t(-1); + } append(lastblock); lastblock = new Block(); return index + 1; } -Block *BlockArray::lastBlock() const +Block * BlockArray::lastBlock() const { return lastblock; } bool BlockArray::has(size_t i) const { - if (i == index + 1) + if (i == index + 1) { return true; + } - if (i > index) + if (i > index) { return false; - if (index - i >= length) + } + if (index - i >= length) { return false; + } return true; } -const Block* BlockArray::at(size_t i) +const Block * BlockArray::at(size_t i) { - if (i == index + 1) + if (i == index + 1) { return lastblock; + } - if (i == lastmap_index) + if (i == lastmap_index) { return lastmap; + } if (i > index) { qDebug() << "BlockArray::at() i > index\n"; @@ -140,9 +152,9 @@ const Block* BlockArray::at(size_t i) assert(j < size); unmap(); - Block *block = (Block*)mmap(0, blocksize, PROT_READ, MAP_PRIVATE, ion, j * blocksize); + Block * block = (Block *)mmap(0, blocksize, PROT_READ, MAP_PRIVATE, ion, j * blocksize); - if (block == (Block*)-1) { + if (block == (Block *)-1) { perror("mmap"); return 0; } @@ -156,8 +168,10 @@ const Block* BlockArray::at(size_t i) void BlockArray::unmap() { if (lastmap) { - int res = munmap((char*)lastmap, blocksize); - if (res < 0) perror("munmap"); + int res = munmap((char *)lastmap, blocksize); + if (res < 0) { + perror("munmap"); + } } lastmap = 0; lastmap_index = size_t(-1); @@ -172,22 +186,25 @@ bool BlockArray::setHistorySize(size_t newsize) { // kDebug(1211) << "setHistorySize " << size << " " << newsize; - if (size == newsize) + if (size == newsize) { return false; + } unmap(); if (!newsize) { delete lastblock; lastblock = 0; - if (ion >= 0) close(ion); + if (ion >= 0) { + close(ion); + } ion = -1; current = size_t(-1); return true; } if (!size) { - FILE* tmp = tmpfile(); + FILE * tmp = tmpfile(); if (!tmp) { perror("konsole: cannot open temp file.\n"); } else { @@ -197,8 +214,9 @@ bool BlockArray::setHistorySize(size_t newsize) fclose(tmp); } } - if (ion < 0) + if (ion < 0) { return false; + } assert(!lastblock); @@ -213,46 +231,51 @@ bool BlockArray::setHistorySize(size_t newsize) return false; } else { decreaseBuffer(newsize); - if (ftruncate(ion, length*blocksize) == -1) - perror("ftruncate"); + ftruncate(ion, length*blocksize); size = newsize; return true; } } -void moveBlock(FILE *fion, int cursor, int newpos, char *buffer2) +void moveBlock(FILE * fion, int cursor, int newpos, char * buffer2) { int res = fseek(fion, cursor * blocksize, SEEK_SET); - if (res) + if (res) { perror("fseek"); + } res = fread(buffer2, blocksize, 1, fion); - if (res != 1) + if (res != 1) { perror("fread"); + } res = fseek(fion, newpos * blocksize, SEEK_SET); - if (res) + if (res) { perror("fseek"); + } res = fwrite(buffer2, blocksize, 1, fion); - if (res != 1) + if (res != 1) { perror("fwrite"); + } // printf("moving block %d to %d\n", cursor, newpos); } void BlockArray::decreaseBuffer(size_t newsize) { - if (index < newsize) // still fits in whole + if (index < newsize) { // still fits in whole return; + } int offset = (current - (newsize - 1) + size) % size; - if (!offset) + if (!offset) { return; + } // The Block constructor could do somthing in future... - char *buffer1 = new char[blocksize]; + char * buffer1 = new char[blocksize]; - FILE *fion = fdopen(dup(ion), "w+b"); + FILE * fion = fdopen(dup(ion), "w+b"); if (!fion) { delete [] buffer1; perror("fdopen/dup"); @@ -272,8 +295,9 @@ void BlockArray::decreaseBuffer(size_t newsize) moveBlock(fion, oldpos, cursor, buffer1); if (oldpos < newsize) { cursor = oldpos; - } else + } else { cursor++; + } } current = newsize - 1; @@ -287,16 +311,18 @@ void BlockArray::decreaseBuffer(size_t newsize) void BlockArray::increaseBuffer() { - if (index < size) // not even wrapped once + if (index < size) { // not even wrapped once return; + } int offset = (current + size + 1) % size; - if (!offset) // no moving needed + if (!offset) { // no moving needed return; + } // The Block constructor could do somthing in future... - char *buffer1 = new char[blocksize]; - char *buffer2 = new char[blocksize]; + char * buffer1 = new char[blocksize]; + char * buffer2 = new char[blocksize]; int runs = 1; int bpr = size; // blocks per run @@ -306,7 +332,7 @@ void BlockArray::increaseBuffer() runs = offset; } - FILE *fion = fdopen(dup(ion), "w+b"); + FILE * fion = fdopen(dup(ion), "w+b"); if (!fion) { perror("fdopen/dup"); delete [] buffer1; @@ -319,11 +345,13 @@ void BlockArray::increaseBuffer() // free one block in chain int firstblock = (offset + i) % size; res = fseek(fion, firstblock * blocksize, SEEK_SET); - if (res) + if (res) { perror("fseek"); + } res = fread(buffer1, blocksize, 1, fion); - if (res != 1) + if (res != 1) { perror("fread"); + } int newpos = 0; for (int j = 1, cursor=firstblock; j < bpr; j++) { cursor = (cursor + offset) % size; @@ -331,11 +359,13 @@ void BlockArray::increaseBuffer() moveBlock(fion, cursor, newpos, buffer2); } res = fseek(fion, i * blocksize, SEEK_SET); - if (res) + if (res) { perror("fseek"); + } res = fwrite(buffer1, blocksize, 1, fion); - if (res != 1) + if (res != 1) { perror("fwrite"); + } } current = size - 1; length = size; diff --git a/lib/BlockArray.h b/lib/BlockArray.h index 37c91b9..886c4cc 100644 --- a/lib/BlockArray.h +++ b/lib/BlockArray.h @@ -68,7 +68,7 @@ public: * Note, that the block may be dropped completely * if history is turned off. */ - size_t append(Block *block); + size_t append(Block * block); /** * gets the block at the index. Function may return @@ -78,7 +78,7 @@ public: * maped in memory - and will be invalid on the next * operation on this class. */ - const Block *at(size_t index); + const Block * at(size_t index); /** * reorders blocks as needed. If newsize is null, @@ -90,7 +90,7 @@ public: size_t newBlock(); - Block *lastBlock() const; + Block * lastBlock() const; /** * Convenient function to set the size in KBytes @@ -118,9 +118,9 @@ private: size_t current; size_t index; - Block *lastmap; + Block * lastmap; size_t lastmap_index; - Block *lastblock; + Block * lastblock; int ion; size_t length; diff --git a/lib/Character.h b/lib/Character.h index 4d63185..3f23841 100644 --- a/lib/Character.h +++ b/lib/Character.h @@ -97,27 +97,27 @@ public: * Returns true if this character has a transparent background when * it is drawn with the specified @p palette. */ - bool isTransparent(const ColorEntry* palette) const; + bool isTransparent(const ColorEntry * palette) const; /** * Returns true if this character should always be drawn in bold when * it is drawn with the specified @p palette, independent of whether * or not the character has the RE_BOLD rendition flag. */ - bool isBold(const ColorEntry* base) const; + bool isBold(const ColorEntry * base) const; /** * Compares two characters and returns true if they have the same unicode character value, * rendition and colors. */ - friend bool operator == (const Character& a, const Character& b); + friend bool operator == (const Character & a, const Character & b); /** * Compares two characters and returns true if they have different unicode character values, * renditions or colors. */ - friend bool operator != (const Character& a, const Character& b); + friend bool operator != (const Character & a, const Character & b); }; -inline bool operator == (const Character& a, const Character& b) +inline bool operator == (const Character & a, const Character & b) { return a.character == b.character && a.rendition == b.rendition && @@ -125,7 +125,7 @@ inline bool operator == (const Character& a, const Character& b) a.backgroundColor == b.backgroundColor; } -inline bool operator != (const Character& a, const Character& b) +inline bool operator != (const Character & a, const Character & b) { return a.character != b.character || a.rendition != b.rendition || @@ -133,7 +133,7 @@ inline bool operator != (const Character& a, const Character& b) a.backgroundColor != b.backgroundColor; } -inline bool Character::isTransparent(const ColorEntry* base) const +inline bool Character::isTransparent(const ColorEntry * base) const { return ((backgroundColor._colorSpace == COLOR_SPACE_DEFAULT) && base[backgroundColor._u+0+(backgroundColor._v?BASE_COLORS:0)].transparent) @@ -141,7 +141,7 @@ inline bool Character::isTransparent(const ColorEntry* base) const base[backgroundColor._u+2+(backgroundColor._v?BASE_COLORS:0)].transparent); } -inline bool Character::isBold(const ColorEntry* base) const +inline bool Character::isBold(const ColorEntry * base) const { return ((backgroundColor._colorSpace == COLOR_SPACE_DEFAULT) && base[backgroundColor._u+0+(backgroundColor._v?BASE_COLORS:0)].bold) @@ -176,7 +176,7 @@ public: * @param unicodePoints An array of unicode character points * @param length Length of @p unicodePoints */ - ushort createExtendedChar(ushort* unicodePoints , ushort length); + ushort createExtendedChar(ushort * unicodePoints , ushort length); /** * Looks up and returns a pointer to a sequence of unicode characters * which was added to the table using createExtendedChar(). @@ -187,20 +187,20 @@ public: * * @return A unicode character sequence of size @p length. */ - ushort* lookupExtendedChar(ushort hash , ushort& length) const; + ushort * lookupExtendedChar(ushort hash , ushort & length) const; /** The global ExtendedCharTable instance. */ static ExtendedCharTable instance; private: // calculates the hash key of a sequence of unicode points of size 'length' - ushort extendedCharHash(ushort* unicodePoints , ushort length) const; + ushort extendedCharHash(ushort * unicodePoints , ushort length) const; // tests whether the entry in the table specified by 'hash' matches the // character sequence 'unicodePoints' of size 'length' - bool extendedCharMatch(ushort hash , ushort* unicodePoints , ushort length) const; + bool extendedCharMatch(ushort hash , ushort * unicodePoints , ushort length) const; // internal, maps hash keys to character sequence buffers. The first ushort // in each value is the length of the buffer, followed by the ushorts in the buffer // themselves. - QHash extendedCharTable; + QHash extendedCharTable; }; } diff --git a/lib/CharacterColor.h b/lib/CharacterColor.h index 483c6e0..612745c 100644 --- a/lib/CharacterColor.h +++ b/lib/CharacterColor.h @@ -65,7 +65,7 @@ public: /** * Sets the color, transparency and boldness of this color to those of @p rhs. */ - void operator=(const ColorEntry& rhs) { + void operator=(const ColorEntry & rhs) { color = rhs.color; transparent = rhs.transparent; bold = rhs.bold; @@ -216,7 +216,7 @@ public: * The @p palette is only used if this color is one of the 16 system colors, otherwise * it is ignored. */ - QColor color(const ColorEntry* palette) const; + QColor color(const ColorEntry * palette) const; /** * Compares two colors and returns true if they represent the same color value and @@ -227,7 +227,7 @@ public: * Compares two colors and returns true if they represent different color values * or use different color spaces. */ - friend bool operator != (const CharacterColor& a, const CharacterColor& b); + friend bool operator != (const CharacterColor & a, const CharacterColor & b); private: quint8 _colorSpace; @@ -238,7 +238,7 @@ private: quint8 _w; }; -inline bool operator == (const CharacterColor& a, const CharacterColor& b) +inline bool operator == (const CharacterColor & a, const CharacterColor & b) { return a._colorSpace == b._colorSpace && a._u == b._u && @@ -246,17 +246,21 @@ inline bool operator == (const CharacterColor& a, const CharacterColor& b) a._w == b._w; } -inline bool operator != (const CharacterColor& a, const CharacterColor& b) +inline bool operator != (const CharacterColor & a, const CharacterColor & b) { return !operator==(a,b); } -inline const QColor color256(quint8 u, const ColorEntry* base) +inline const QColor color256(quint8 u, const ColorEntry * base) { // 0.. 16: system colors - if (u < 8) return base[u+2 ].color; + if (u < 8) { + return base[u+2 ].color; + } u -= 8; - if (u < 8) return base[u+2+BASE_COLORS].color; + if (u < 8) { + return base[u+2+BASE_COLORS].color; + } u -= 8; // 16..231: 6x6x6 rgb color cube @@ -270,7 +274,7 @@ inline const QColor color256(quint8 u, const ColorEntry* base) return QColor(gray,gray,gray); } -inline QColor CharacterColor::color(const ColorEntry* base) const +inline QColor CharacterColor::color(const ColorEntry * base) const { switch (_colorSpace) { case COLOR_SPACE_DEFAULT: diff --git a/lib/Emulation.cpp b/lib/Emulation.cpp index 038051d..8981468 100644 --- a/lib/Emulation.cpp +++ b/lib/Emulation.cpp @@ -93,9 +93,9 @@ void Emulation::usesMouseChanged(bool usesMouse) _usesMouse = usesMouse; } -ScreenWindow* Emulation::createWindow() +ScreenWindow * Emulation::createWindow() { - ScreenWindow* window = new ScreenWindow(); + ScreenWindow * window = new ScreenWindow(); window->setScreen(_currentScreen); _windows << window; @@ -112,7 +112,7 @@ ScreenWindow* Emulation::createWindow() Emulation::~Emulation() { - QListIterator windowIter(_windows); + QListIterator windowIter(_windows); while (windowIter.hasNext()) { delete windowIter.next(); @@ -128,13 +128,13 @@ Emulation::~Emulation() void Emulation::setScreen(int n) { - Screen *old = _currentScreen; + Screen * old = _currentScreen; _currentScreen = _screen[n&1]; if (_currentScreen != old) { old->setBusySelecting(false); // tell all windows onto this emulation to switch to the newly active _screen - QListIterator windowIter(_windows); + QListIterator windowIter(_windows); while ( windowIter.hasNext() ) { windowIter.next()->setScreen(_currentScreen); } @@ -145,14 +145,14 @@ void Emulation::clearHistory() { _screen[0]->setScroll( _screen[0]->getScroll() , false ); } -void Emulation::setHistory(const HistoryType& t) +void Emulation::setHistory(const HistoryType & t) { _screen[0]->setScroll(t); showBulk(); } -const HistoryType& Emulation::history() +const HistoryType & Emulation::history() { return _screen[0]->getScroll(); } @@ -170,13 +170,14 @@ void Emulation::setCodec(const QTextCodec * qtc) void Emulation::setCodec(EmulationCodec codec) { - if ( codec == Utf8Codec ) + if ( codec == Utf8Codec ) { setCodec( QTextCodec::codecForName("utf8") ); - else if ( codec == LocaleCodec ) + } else if ( codec == LocaleCodec ) { setCodec( QTextCodec::codecForLocale() ); + } } -void Emulation::setKeyBindings(const QString& name) +void Emulation::setKeyBindings(const QString & name) { _keyTranslator = KeyboardTranslatorManager::instance()->findTranslator(name); } @@ -235,11 +236,12 @@ void Emulation::receiveChar(int c) /*! */ -void Emulation::sendKeyEvent( QKeyEvent* ev ) +void Emulation::sendKeyEvent( QKeyEvent * ev ) { emit stateSet(NOTIFYNORMAL); - if (!ev->text().isEmpty()) { // A block of text + if (!ev->text().isEmpty()) { + // A block of text // Note that the text is proper unicode. // We should do a conversion here, but since this // routine will never be used, we simply emit plain ascii. @@ -248,7 +250,7 @@ void Emulation::sendKeyEvent( QKeyEvent* ev ) } } -void Emulation::sendString(const char*,int) +void Emulation::sendString(const char *,int) { // default implementation does nothing } @@ -265,7 +267,7 @@ void Emulation::sendMouseEvent(int /*buttons*/, int /*column*/, int /*row*/, int TODO: Character composition from the old code. See #96536 */ -void Emulation::receiveData(const char* text, int length) +void Emulation::receiveData(const char * text, int length) { emit stateSet(NOTIFYACTIVITY); @@ -283,17 +285,18 @@ void Emulation::receiveData(const char* text, int length) //this check into the above for loop? for (int i=0; i 3) && (strncmp(text+i+1, "B00", 3) == 0)) + if ((length-i-1 > 3) && (strncmp(text+i+1, "B00", 3) == 0)) { emit zmodemDetected(); + } } } } //OLDER VERSION //This version of onRcvBlock was commented out because -// a) It decoded incoming characters one-by-one, which is slow in the current version of Qt (4.2 tech preview) -// b) It messed up decoding of non-ASCII characters, with the result that (for example) chinese characters -// were not printed properly. +// a) It decoded incoming characters one-by-one, which is slow in the current version of Qt (4.2 tech preview) +// b) It messed up decoding of non-ASCII characters, with the result that (for example) chinese characters +// were not printed properly. // //There is something about stopping the _decoder if "we get a control code halfway a multi-byte sequence" (see below) //which hasn't been ported into the newer function (above). Hopefully someone who understands this better @@ -333,7 +336,7 @@ void Emulation::receiveData(const char* text, int length) if (s[i] == '\030') { if ((len-i-1 > 3) && (strncmp(s+i+1, "B00", 3) == 0)) - emit zmodemDetected(); + emit zmodemDetected(); } } }*/ @@ -343,46 +346,57 @@ void Emulation::receiveData(const char* text, int length) #if 0 void Emulation::onSelectionBegin(const int x, const int y, const bool columnmode) { - if (!connected) return; + if (!connected) { + return; + } _currentScreen->setSelectionStart( x,y,columnmode); showBulk(); } void Emulation::onSelectionExtend(const int x, const int y) { - if (!connected) return; + if (!connected) { + return; + } _currentScreen->setSelectionEnd(x,y); showBulk(); } void Emulation::setSelection(const bool preserve_line_breaks) { - if (!connected) return; + if (!connected) { + return; + } QString t = _currentScreen->selectedText(preserve_line_breaks); if (!t.isNull()) { - QListIterator< TerminalDisplay* > viewIter(_views); + QListIterator< TerminalDisplay * > viewIter(_views); - while (viewIter.hasNext()) + while (viewIter.hasNext()) { viewIter.next()->setSelection(t); + } } } -void Emulation::testIsSelected(const int x, const int y, bool &selected) +void Emulation::testIsSelected(const int x, const int y, bool & selected) { - if (!connected) return; + if (!connected) { + return; + } selected=_currentScreen->isSelected(x,y); } void Emulation::clearSelection() { - if (!connected) return; + if (!connected) { + return; + } _currentScreen->clearSelection(); showBulk(); } #endif -void Emulation::writeToStream( TerminalCharacterDecoder* _decoder , +void Emulation::writeToStream( TerminalCharacterDecoder * _decoder , int startLine , int endLine) { @@ -447,7 +461,7 @@ QSize Emulation::imageSize() return QSize(_currentScreen->getColumns(), _currentScreen->getLines()); } -ushort ExtendedCharTable::extendedCharHash(ushort* unicodePoints , ushort length) const +ushort ExtendedCharTable::extendedCharHash(ushort * unicodePoints , ushort length) const { ushort hash = 0; for ( ushort i = 0 ; i < length ; i++ ) { @@ -455,23 +469,25 @@ ushort ExtendedCharTable::extendedCharHash(ushort* unicodePoints , ushort length } return hash; } -bool ExtendedCharTable::extendedCharMatch(ushort hash , ushort* unicodePoints , ushort length) const +bool ExtendedCharTable::extendedCharMatch(ushort hash , ushort * unicodePoints , ushort length) const { - ushort* entry = extendedCharTable[hash]; + ushort * entry = extendedCharTable[hash]; // compare given length with stored sequence length ( given as the first ushort in the // stored buffer ) - if ( entry == 0 || entry[0] != length ) + if ( entry == 0 || entry[0] != length ) { return false; + } // if the lengths match, each character must be checked. the stored buffer starts at // entry[1] for ( int i = 0 ; i < length ; i++ ) { - if ( entry[i+1] != unicodePoints[i] ) + if ( entry[i+1] != unicodePoints[i] ) { return false; + } } return true; } -ushort ExtendedCharTable::createExtendedChar(ushort* unicodePoints , ushort length) +ushort ExtendedCharTable::createExtendedChar(ushort * unicodePoints , ushort length) { // look for this sequence of points in the table ushort hash = extendedCharHash(unicodePoints,length); @@ -492,22 +508,23 @@ ushort ExtendedCharTable::createExtendedChar(ushort* unicodePoints , ushort leng // add the new sequence to the table and // return that index - ushort* buffer = new ushort[length+1]; + ushort * buffer = new ushort[length+1]; buffer[0] = length; - for ( int i = 0 ; i < length ; i++ ) + for ( int i = 0 ; i < length ; i++ ) { buffer[i+1] = unicodePoints[i]; + } extendedCharTable.insert(hash,buffer); return hash; } -ushort* ExtendedCharTable::lookupExtendedChar(ushort hash , ushort& length) const +ushort * ExtendedCharTable::lookupExtendedChar(ushort hash , ushort & length) const { // lookup index in table and if found, set the length // argument and return a pointer to the character sequence - ushort* buffer = extendedCharTable[hash]; + ushort * buffer = extendedCharTable[hash]; if ( buffer ) { length = buffer[0]; return buffer+1; @@ -523,7 +540,7 @@ ExtendedCharTable::ExtendedCharTable() ExtendedCharTable::~ExtendedCharTable() { // free all allocated character buffers - QHashIterator iter(extendedCharTable); + QHashIterator iter(extendedCharTable); while ( iter.hasNext() ) { iter.next(); delete[] iter.value(); diff --git a/lib/Emulation.h b/lib/Emulation.h index 9cb6bb4..6b492ca 100644 --- a/lib/Emulation.h +++ b/lib/Emulation.h @@ -133,7 +133,7 @@ public: * of the window are then rendered by views which are set to use this window using the * TerminalDisplay::setScreenWindow() method. */ - ScreenWindow* createWindow(); + ScreenWindow * createWindow(); /** Returns the size of the screen image which the emulation produces */ QSize imageSize(); @@ -152,9 +152,9 @@ public: * The number of lines which are kept and the storage location depend on the * type of store. */ - void setHistory(const HistoryType&); + void setHistory(const HistoryType &); /** Returns the history store used by this emulation. See setHistory() */ - const HistoryType& history(); + const HistoryType & history(); /** Clears the history scroll. */ void clearHistory(); @@ -168,15 +168,15 @@ public: * used decoder. * @param startLine The first */ - virtual void writeToStream(TerminalCharacterDecoder* decoder,int startLine,int endLine); + virtual void writeToStream(TerminalCharacterDecoder * decoder,int startLine,int endLine); /** Returns the codec used to decode incoming characters. See setCodec() */ - const QTextCodec* codec() { + const QTextCodec * codec() { return _codec; } /** Sets the codec used to decode incoming characters. */ - void setCodec(const QTextCodec*); + void setCodec(const QTextCodec *); /** * Convenience method. @@ -197,7 +197,7 @@ public: * ( received through sendKeyEvent() ) into character * streams to send to the terminal. */ - void setKeyBindings(const QString& name); + void setKeyBindings(const QString & name); /** * Returns the name of the emulation's current key bindings. * See setKeyBindings() @@ -230,13 +230,13 @@ public slots: * Interprets a sequence of characters and sends the result to the terminal. * This is equivalent to calling sendKeyEvent() for each character in @p text in succession. */ - virtual void sendText(const QString& text) = 0; + virtual void sendText(const QString & text) = 0; /** * Interprets a key press event and emits the sendData() signal with * the resulting character stream. */ - virtual void sendKeyEvent(QKeyEvent*); + virtual void sendKeyEvent(QKeyEvent *); /** * Converts information about a mouse event into an xterm-compatible escape @@ -251,7 +251,7 @@ public slots: * @param length Length of @p string or if set to a negative value, @p string will * be treated as a null-terminated string and its length will be determined automatically. */ - virtual void sendString(const char* string, int length = -1) = 0; + virtual void sendString(const char * string, int length = -1) = 0; /** * Processes an incoming stream of characters. receiveData() decodes the incoming @@ -265,7 +265,7 @@ public slots: * @param buffer A string of characters received from the terminal program. * @param len The length of @p buffer */ - void receiveData(const char* buffer,int len); + void receiveData(const char * buffer,int len); signals: @@ -276,7 +276,7 @@ signals: * @param data The buffer of data ready to be sent * @paran len The length of @p data in bytes */ - void sendData(const char* data,int len); + void sendData(const char * data,int len); /** * Requests that sending of input to the emulation @@ -374,7 +374,7 @@ signals: * @param newTitle Specifies the new title */ - void titleChanged(int title,const QString& newTitle); + void titleChanged(int title,const QString & newTitle); /** * Emitted when the program running in the terminal changes the @@ -393,7 +393,7 @@ signals: * @param text A string expected to contain a series of key and value pairs in * the form: name=value;name2=value2 ... */ - void profileChangeCommandReceived(const QString& text); + void profileChangeCommandReceived(const QString & text); protected: virtual void setMode (int mode) = 0; @@ -421,12 +421,12 @@ protected: void setCodec(EmulationCodec codec); // codec number, 0 = locale, 1=utf8 - QList _windows; + QList _windows; - Screen* _currentScreen; // pointer to the screen which is currently active, + Screen * _currentScreen; // pointer to the screen which is currently active, // this is one of the elements in the screen[] array - Screen* _screen[2]; // 0 = primary screen ( used by most programs, including the shell + Screen * _screen[2]; // 0 = primary screen ( used by most programs, including the shell // scrollbars are enabled in this mode ) // 1 = alternate ( used by vi , emacs etc. // scrollbars are not enabled in this mode ) @@ -434,10 +434,10 @@ protected: //decodes an incoming C-style character stream into a unicode QString using //the current text codec. (this allows for rendering of non-ASCII characters in text files etc.) - const QTextCodec* _codec; - QTextDecoder* _decoder; + const QTextCodec * _codec; + QTextDecoder * _decoder; - const KeyboardTranslator* _keyTranslator; // the keyboard layout + const KeyboardTranslator * _keyTranslator; // the keyboard layout protected slots: /** diff --git a/lib/Filter.cpp b/lib/Filter.cpp index 90419e0..f0d73ba 100644 --- a/lib/Filter.cpp +++ b/lib/Filter.cpp @@ -45,55 +45,58 @@ using namespace Konsole; FilterChain::~FilterChain() { - QMutableListIterator iter(*this); + QMutableListIterator iter(*this); while ( iter.hasNext() ) { - Filter* filter = iter.next(); + Filter * filter = iter.next(); iter.remove(); delete filter; } } -void FilterChain::addFilter(Filter* filter) +void FilterChain::addFilter(Filter * filter) { append(filter); } -void FilterChain::removeFilter(Filter* filter) +void FilterChain::removeFilter(Filter * filter) { removeAll(filter); } -bool FilterChain::containsFilter(Filter* filter) +bool FilterChain::containsFilter(Filter * filter) { return contains(filter); } void FilterChain::reset() { - QListIterator iter(*this); - while (iter.hasNext()) + QListIterator iter(*this); + while (iter.hasNext()) { iter.next()->reset(); + } } -void FilterChain::setBuffer(const QString* buffer , const QList* linePositions) +void FilterChain::setBuffer(const QString * buffer , const QList* linePositions) { - QListIterator iter(*this); - while (iter.hasNext()) + QListIterator iter(*this); + while (iter.hasNext()) { iter.next()->setBuffer(buffer,linePositions); + } } void FilterChain::process() { - QListIterator iter(*this); - while (iter.hasNext()) + QListIterator iter(*this); + while (iter.hasNext()) { iter.next()->process(); + } } void FilterChain::clear() { - QList::clear(); + QList::clear(); } -Filter::HotSpot* FilterChain::hotSpotAt(int line , int column) const +Filter::HotSpot * FilterChain::hotSpotAt(int line , int column) const { - QListIterator iter(*this); + QListIterator iter(*this); while (iter.hasNext()) { - Filter* filter = iter.next(); - Filter::HotSpot* spot = filter->hotSpotAt(line,column); + Filter * filter = iter.next(); + Filter::HotSpot * spot = filter->hotSpotAt(line,column); if ( spot != 0 ) { return spot; } @@ -102,12 +105,12 @@ Filter::HotSpot* FilterChain::hotSpotAt(int line , int column) const return 0; } -QList FilterChain::hotSpots() const +QList FilterChain::hotSpots() const { - QList list; - QListIterator iter(*this); + QList list; + QListIterator iter(*this); while (iter.hasNext()) { - Filter* filter = iter.next(); + Filter * filter = iter.next(); list << filter->hotSpots(); } return list; @@ -126,11 +129,12 @@ TerminalImageFilterChain::~TerminalImageFilterChain() delete _linePositions; } -void TerminalImageFilterChain::setImage(const Character* const image , int lines , int columns, const QVector& lineProperties) +void TerminalImageFilterChain::setImage(const Character * const image , int lines , int columns, const QVector& lineProperties) { //qDebug("%s %d", __FILE__, __LINE__); - if (empty()) + if (empty()) { return; + } //qDebug("%s %d", __FILE__, __LINE__); // reset all filters and hotspots @@ -142,7 +146,7 @@ void TerminalImageFilterChain::setImage(const Character* const image , int lines //qDebug("%s %d", __FILE__, __LINE__); // setup new shared buffers for the filters to process on - QString* newBuffer = new QString(); + QString * newBuffer = new QString(); QList* newLinePositions = new QList(); setBuffer( newBuffer , newLinePositions ); @@ -170,8 +174,9 @@ void TerminalImageFilterChain::setImage(const Character* const image , int lines // TODO - Use the "line wrapped" attribute associated with lines in a // terminal image to avoid adding this imaginary character for wrapped // lines - if ( !(lineProperties.value(i,LINE_DEFAULT) & LINE_WRAPPED) ) + if ( !(lineProperties.value(i,LINE_DEFAULT) & LINE_WRAPPED) ) { lineStream << QChar('\n'); + } } decoder.end(); // qDebug("%s %d", __FILE__, __LINE__); @@ -185,7 +190,7 @@ Filter::Filter() : Filter::~Filter() { - QListIterator iter(_hotspotList); + QListIterator iter(_hotspotList); while (iter.hasNext()) { delete iter.next(); } @@ -196,13 +201,13 @@ void Filter::reset() _hotspotList.clear(); } -void Filter::setBuffer(const QString* buffer , const QList* linePositions) +void Filter::setBuffer(const QString * buffer , const QList* linePositions) { _buffer = buffer; _linePositions = linePositions; } -void Filter::getLineColumn(int position , int& startLine , int& startColumn) +void Filter::getLineColumn(int position , int & startLine , int & startColumn) { Q_ASSERT( _linePositions ); Q_ASSERT( _buffer ); @@ -236,14 +241,14 @@ void Filter::getLineColumn(int position , int& startLine , int& startColumn) _buffer.append(text); }*/ -const QString* Filter::buffer() +const QString * Filter::buffer() { return _buffer; } Filter::HotSpot::~HotSpot() { } -void Filter::addHotSpot(HotSpot* spot) +void Filter::addHotSpot(HotSpot * spot) { _hotspotList << spot; @@ -251,26 +256,28 @@ void Filter::addHotSpot(HotSpot* spot) _hotspots.insert(line,spot); } } -QList Filter::hotSpots() const +QList Filter::hotSpots() const { return _hotspotList; } -QList Filter::hotSpotsAtLine(int line) const +QList Filter::hotSpotsAtLine(int line) const { return _hotspots.values(line); } -Filter::HotSpot* Filter::hotSpotAt(int line , int column) const +Filter::HotSpot * Filter::hotSpotAt(int line , int column) const { - QListIterator spotIter(_hotspots.values(line)); + QListIterator spotIter(_hotspots.values(line)); while (spotIter.hasNext()) { - HotSpot* spot = spotIter.next(); + HotSpot * spot = spotIter.next(); - if ( spot->startLine() == line && spot->startColumn() > column ) + if ( spot->startLine() == line && spot->startColumn() > column ) { continue; - if ( spot->endLine() == line && spot->endColumn() < column ) + } + if ( spot->endLine() == line && spot->endColumn() < column ) { continue; + } return spot; } @@ -290,9 +297,9 @@ QString Filter::HotSpot::tooltip() const { return QString(); } -QList Filter::HotSpot::actions() +QList Filter::HotSpot::actions() { - return QList(); + return QList(); } int Filter::HotSpot::startLine() const { @@ -329,11 +336,11 @@ RegExpFilter::HotSpot::HotSpot(int startLine,int startColumn,int endLine,int end setType(Marker); } -void RegExpFilter::HotSpot::activate(QObject*) +void RegExpFilter::HotSpot::activate(QObject *) { } -void RegExpFilter::HotSpot::setCapturedTexts(const QStringList& texts) +void RegExpFilter::HotSpot::setCapturedTexts(const QStringList & texts) { _capturedTexts = texts; } @@ -342,7 +349,7 @@ QStringList RegExpFilter::HotSpot::capturedTexts() const return _capturedTexts; } -void RegExpFilter::setRegExp(const QRegExp& regExp) +void RegExpFilter::setRegExp(const QRegExp & regExp) { _searchText = regExp; } @@ -357,15 +364,16 @@ QRegExp RegExpFilter::regExp() const void RegExpFilter::process() { int pos = 0; - const QString* text = buffer(); + const QString * text = buffer(); Q_ASSERT( text ); // ignore any regular expressions which match an empty string. // otherwise the while loop below will run indefinitely static const QString emptyString(""); - if ( _searchText.exactMatch(emptyString) ) + if ( _searchText.exactMatch(emptyString) ) { return; + } while (pos >= 0) { pos = _searchText.indexIn(*text,pos); @@ -386,8 +394,8 @@ void RegExpFilter::process() //kDebug() << "start " << startLine << " / " << startColumn; //kDebug() << "end " << endLine << " / " << endColumn; - RegExpFilter::HotSpot* spot = newHotSpot(startLine,startColumn, - endLine,endColumn); + RegExpFilter::HotSpot * spot = newHotSpot(startLine,startColumn, + endLine,endColumn); spot->setCapturedTexts(_searchText.capturedTexts()); addHotSpot( spot ); @@ -399,13 +407,13 @@ void RegExpFilter::process() } } -RegExpFilter::HotSpot* RegExpFilter::newHotSpot(int startLine,int startColumn, +RegExpFilter::HotSpot * RegExpFilter::newHotSpot(int startLine,int startColumn, int endLine,int endColumn) { return new RegExpFilter::HotSpot(startLine,startColumn, endLine,endColumn); } -RegExpFilter::HotSpot* UrlFilter::newHotSpot(int startLine,int startColumn,int endLine, +RegExpFilter::HotSpot * UrlFilter::newHotSpot(int startLine,int startColumn,int endLine, int endColumn) { return new UrlFilter::HotSpot(startLine,startColumn, @@ -423,32 +431,34 @@ QString UrlFilter::HotSpot::tooltip() const const UrlType kind = urlType(); - if ( kind == StandardUrl ) + if ( kind == StandardUrl ) { return QString(); - else if ( kind == Email ) + } else if ( kind == Email ) { return QString(); - else + } else { return QString(); + } } UrlFilter::HotSpot::UrlType UrlFilter::HotSpot::urlType() const { QString url = capturedTexts().first(); - if ( FullUrlRegExp.exactMatch(url) ) + if ( FullUrlRegExp.exactMatch(url) ) { return StandardUrl; - else if ( EmailAddressRegExp.exactMatch(url) ) + } else if ( EmailAddressRegExp.exactMatch(url) ) { return Email; - else + } else { return Unknown; + } } -void UrlFilter::HotSpot::activate(QObject* object) +void UrlFilter::HotSpot::activate(QObject * object) { QString url = capturedTexts().first(); const UrlType kind = urlType(); - const QString& actionName = object ? object->objectName() : QString(); + const QString & actionName = object ? object->objectName() : QString(); if ( actionName == "copy-action" ) { //kDebug() << "Copying url to clipboard:" << url; @@ -501,14 +511,14 @@ void FilterObject::activated() { _filter->activate(sender()); } -QList UrlFilter::HotSpot::actions() +QList UrlFilter::HotSpot::actions() { - QList list; + QList list; const UrlType kind = urlType(); - QAction* openAction = new QAction(_urlObject); - QAction* copyAction = new QAction(_urlObject);; + QAction * openAction = new QAction(_urlObject); + QAction * copyAction = new QAction(_urlObject);; Q_ASSERT( kind == StandardUrl || kind == Email ); diff --git a/lib/Filter.h b/lib/Filter.h index f15f23f..38e2c47 100644 --- a/lib/Filter.h +++ b/lib/Filter.h @@ -109,12 +109,12 @@ public: * one of the objects from the actions() list. In which case the associated * action should be performed. */ - virtual void activate(QObject* object = 0) = 0; + virtual void activate(QObject * object = 0) = 0; /** * Returns a list of actions associated with the hotspot which can be used in a * menu or toolbar */ - virtual QList actions(); + virtual QList actions(); /** * Returns the text of a tooltip to be shown when the mouse moves over the hotspot, or @@ -154,33 +154,33 @@ public: //void addLine(const QString& string); /** Returns the hotspot which covers the given @p line and @p column, or 0 if no hotspot covers that area */ - HotSpot* hotSpotAt(int line , int column) const; + HotSpot * hotSpotAt(int line , int column) const; /** Returns the list of hotspots identified by the filter */ - QList hotSpots() const; + QList hotSpots() const; /** Returns the list of hotspots identified by the filter which occur on a given line */ - QList hotSpotsAtLine(int line) const; + QList hotSpotsAtLine(int line) const; /** * TODO: Document me */ - void setBuffer(const QString* buffer , const QList* linePositions); + void setBuffer(const QString * buffer , const QList* linePositions); protected: /** Adds a new hotspot to the list */ - void addHotSpot(HotSpot*); + void addHotSpot(HotSpot *); /** Returns the internal buffer */ - const QString* buffer(); + const QString * buffer(); /** Converts a character position within buffer() to a line and column */ - void getLineColumn(int position , int& startLine , int& startColumn); + void getLineColumn(int position , int & startLine , int & startColumn); private: - QMultiHash _hotspots; - QList _hotspotList; + QMultiHash _hotspots; + QList _hotspotList; const QList* _linePositions; - const QString* _buffer; + const QString * _buffer; }; /** @@ -201,10 +201,10 @@ public: { public: HotSpot(int startLine, int startColumn, int endLine , int endColumn); - virtual void activate(QObject* object = 0); + virtual void activate(QObject * object = 0); /** Sets the captured texts associated with this hotspot */ - void setCapturedTexts(const QStringList& texts); + void setCapturedTexts(const QStringList & texts); /** Returns the texts found by the filter when matching the filter's regular expression */ QStringList capturedTexts() const; private: @@ -220,7 +220,7 @@ public: * Regular expressions which match the empty string are treated as not matching * anything. */ - void setRegExp(const QRegExp& text); + void setRegExp(const QRegExp & text); /** Returns the regular expression which the filter searches for in blocks of text */ QRegExp regExp() const; @@ -237,7 +237,7 @@ protected: * Called when a match for the regular expression is encountered. Subclasses should reimplement this * to return custom hotspot types */ - virtual RegExpFilter::HotSpot* newHotSpot(int startLine,int startColumn, + virtual RegExpFilter::HotSpot * newHotSpot(int startLine,int startColumn, int endLine,int endColumn); private: @@ -260,13 +260,13 @@ public: HotSpot(int startLine,int startColumn,int endLine,int endColumn); virtual ~HotSpot(); - virtual QList actions(); + virtual QList actions(); /** * Open a web browser at the current URL. The url itself can be determined using * the capturedTexts() method. */ - virtual void activate(QObject* object = 0); + virtual void activate(QObject * object = 0); virtual QString tooltip() const; private: @@ -277,13 +277,13 @@ public: }; UrlType urlType() const; - FilterObject* _urlObject; + FilterObject * _urlObject; }; UrlFilter(); protected: - virtual RegExpFilter::HotSpot* newHotSpot(int,int,int,int); + virtual RegExpFilter::HotSpot * newHotSpot(int,int,int,int); private: @@ -298,11 +298,11 @@ class FilterObject : public QObject { Q_OBJECT public: - FilterObject(Filter::HotSpot* filter) : _filter(filter) {} + FilterObject(Filter::HotSpot * filter) : _filter(filter) {} private slots: void activated(); private: - Filter::HotSpot* _filter; + Filter::HotSpot * _filter; }; /** @@ -322,17 +322,17 @@ private: * The hotSpots() and hotSpotsAtLine() method return all of the hotspots in the text and on * a given line respectively. */ -class FilterChain : protected QList +class FilterChain : protected QList { public: virtual ~FilterChain(); /** Adds a new filter to the chain. The chain will delete this filter when it is destroyed */ - void addFilter(Filter* filter); + void addFilter(Filter * filter); /** Removes a filter from the chain. The chain will no longer delete the filter when destroyed */ - void removeFilter(Filter* filter); + void removeFilter(Filter * filter); /** Returns true if the chain contains @p filter */ - bool containsFilter(Filter* filter); + bool containsFilter(Filter * filter); /** Removes all filters from the chain */ void clear(); @@ -344,12 +344,12 @@ public: void process(); /** Sets the buffer for each filter in the chain to process. */ - void setBuffer(const QString* buffer , const QList* linePositions); + void setBuffer(const QString * buffer , const QList* linePositions); /** Returns the first hotspot which occurs at @p line, @p column or 0 if no hotspot was found */ - Filter::HotSpot* hotSpotAt(int line , int column) const; + Filter::HotSpot * hotSpotAt(int line , int column) const; /** Returns a list of all the hotspots in all the chain's filters */ - QList hotSpots() const; + QList hotSpots() const; /** Returns a list of all hotspots at the given line in all the chain's filters */ QList hotSpotsAtLine(int line) const; @@ -369,11 +369,11 @@ public: * @param lines The number of lines in the terminal image * @param columns The number of columns in the terminal image */ - void setImage(const Character* const image , int lines , int columns, + void setImage(const Character * const image , int lines , int columns, const QVector& lineProperties); private: - QString* _buffer; + QString * _buffer; QList* _linePositions; }; diff --git a/lib/History.cpp b/lib/History.cpp index f6c34fd..0945927 100644 --- a/lib/History.cpp +++ b/lib/History.cpp @@ -96,8 +96,9 @@ HistoryFile::HistoryFile() HistoryFile::~HistoryFile() { - if (fileMap) + if (fileMap) { unmap(); + } } //TODO: Mapping the entire file in will cause problems if the history file becomes exceedingly large, @@ -107,7 +108,7 @@ void HistoryFile::map() { assert( fileMap == 0 ); - fileMap = (char*)mmap( 0 , length , PROT_READ , MAP_PRIVATE , ion , 0 ); + fileMap = (char *)mmap( 0 , length , PROT_READ , MAP_PRIVATE , ion , 0 ); //if mmap'ing fails, fall back to the read-lseek combination if ( fileMap == MAP_FAILED ) { @@ -130,10 +131,11 @@ bool HistoryFile::isMapped() return (fileMap != 0); } -void HistoryFile::add(const unsigned char* bytes, int len) +void HistoryFile::add(const unsigned char * bytes, int len) { - if ( fileMap ) + if ( fileMap ) { unmap(); + } readWriteBalance++; @@ -152,24 +154,27 @@ void HistoryFile::add(const unsigned char* bytes, int len) length += rc; } -void HistoryFile::get(unsigned char* bytes, int len, int loc) +void HistoryFile::get(unsigned char * bytes, int len, int loc) { //count number of get() calls vs. number of add() calls. //If there are many more get() calls compared with add() //calls (decided by using MAP_THRESHOLD) then mmap the log //file to improve performance. readWriteBalance--; - if ( !fileMap && readWriteBalance < MAP_THRESHOLD ) + if ( !fileMap && readWriteBalance < MAP_THRESHOLD ) { map(); + } if ( fileMap ) { - for (int i=0; i length) + if (loc < 0 || len < 0 || loc + len > length) { fprintf(stderr,"getHist(...,%d,%d): invalid args.\n",len,loc); + } rc = lseek(ion,loc,SEEK_SET); if (rc < 0) { perror("HistoryFile::get.seek"); @@ -192,7 +197,7 @@ int HistoryFile::len() // History Scroll abstract base class ////////////////////////////////////// -HistoryScroll::HistoryScroll(HistoryType* t) +HistoryScroll::HistoryScroll(HistoryType * t) : m_histType(t) { } @@ -220,7 +225,7 @@ bool HistoryScroll::hasScroll() at 0 in cells. */ -HistoryScrollFile::HistoryScrollFile(const QString &logFileName) +HistoryScrollFile::HistoryScrollFile(const QString & logFileName) : HistoryScroll(new HistoryTypeFile(logFileName)), m_logFileName(logFileName) { @@ -244,7 +249,7 @@ bool HistoryScrollFile::isWrappedLine(int lineno) { if (lineno>=0 && lineno <= getLines()) { unsigned char flag; - lineflags.get((unsigned char*)&flag,sizeof(unsigned char),(lineno)*sizeof(unsigned char)); + lineflags.get((unsigned char *)&flag,sizeof(unsigned char),(lineno)*sizeof(unsigned char)); return flag; } return false; @@ -252,14 +257,17 @@ bool HistoryScrollFile::isWrappedLine(int lineno) int HistoryScrollFile::startOfLine(int lineno) { - if (lineno <= 0) return 0; + if (lineno <= 0) { + return 0; + } if (lineno <= getLines()) { - if (!index.isMapped()) + if (!index.isMapped()) { index.map(); + } int res; - index.get((unsigned char*)&res,sizeof(int),(lineno-1)*sizeof(int)); + index.get((unsigned char *)&res,sizeof(int),(lineno-1)*sizeof(int)); return res; } return cells.len(); @@ -267,23 +275,24 @@ int HistoryScrollFile::startOfLine(int lineno) void HistoryScrollFile::getCells(int lineno, int colno, int count, Character res[]) { - cells.get((unsigned char*)res,count*sizeof(Character),startOfLine(lineno)+colno*sizeof(Character)); + cells.get((unsigned char *)res,count*sizeof(Character),startOfLine(lineno)+colno*sizeof(Character)); } void HistoryScrollFile::addCells(const Character text[], int count) { - cells.add((unsigned char*)text,count*sizeof(Character)); + cells.add((unsigned char *)text,count*sizeof(Character)); } void HistoryScrollFile::addLine(bool previousWrapped) { - if (index.isMapped()) + if (index.isMapped()) { index.unmap(); + } int locn = cells.len(); - index.add((unsigned char*)&locn,sizeof(int)); + index.add((unsigned char *)&locn,sizeof(int)); unsigned char flags = previousWrapped ? 0x01 : 0x00; - lineflags.add((unsigned char*)&flags,sizeof(unsigned char)); + lineflags.add((unsigned char *)&flags,sizeof(unsigned char)); } @@ -306,8 +315,9 @@ HistoryScrollBuffer::~HistoryScrollBuffer() void HistoryScrollBuffer::addCellsVector(const QVector& cells) { _head++; - if ( _usedLines < _maxLineCount ) + if ( _usedLines < _maxLineCount ) { _usedLines++; + } if ( _head >= _maxLineCount ) { _head = 0; @@ -352,13 +362,16 @@ bool HistoryScrollBuffer::isWrappedLine(int lineNumber) if (lineNumber < _usedLines) { //kDebug() << "Line" << lineNumber << "wrapped is" << _wrappedLine[bufferIndex(lineNumber)]; return _wrappedLine[bufferIndex(lineNumber)]; - } else + } else { return false; + } } -void HistoryScrollBuffer::getCells(int lineNumber, int startColumn, int count, Character* buffer) +void HistoryScrollBuffer::getCells(int lineNumber, int startColumn, int count, Character * buffer) { - if ( count == 0 ) return; + if ( count == 0 ) { + return; + } Q_ASSERT( lineNumber < _maxLineCount ); @@ -367,7 +380,7 @@ void HistoryScrollBuffer::getCells(int lineNumber, int startColumn, int count, C return; } - const HistoryLine& line = _historyBuffer[bufferIndex(lineNumber)]; + const HistoryLine & line = _historyBuffer[bufferIndex(lineNumber)]; //kDebug() << "startCol " << startColumn; //kDebug() << "line.size() " << line.size(); @@ -380,8 +393,8 @@ void HistoryScrollBuffer::getCells(int lineNumber, int startColumn, int count, C void HistoryScrollBuffer::setMaxNbLines(unsigned int lineCount) { - HistoryLine* oldBuffer = _historyBuffer; - HistoryLine* newBuffer = new HistoryLine[lineCount]; + HistoryLine * oldBuffer = _historyBuffer; + HistoryLine * newBuffer = new HistoryLine[lineCount]; for ( int i = 0 ; i < qMin(_usedLines,(int)lineCount) ; i++ ) { newBuffer[i] = oldBuffer[bufferIndex(i)]; @@ -473,10 +486,11 @@ int HistoryScrollBlockArray::getLines() int HistoryScrollBlockArray::getLineLen(int lineno) { - if ( m_lineLengths.contains(lineno) ) + if ( m_lineLengths.contains(lineno) ) { return m_lineLengths[lineno]; - else + } else { return 0; + } } bool HistoryScrollBlockArray::isWrappedLine(int /*lineno*/) @@ -487,9 +501,11 @@ bool HistoryScrollBlockArray::isWrappedLine(int /*lineno*/) void HistoryScrollBlockArray::getCells(int lineno, int colno, int count, Character res[]) { - if (!count) return; + if (!count) { + return; + } - const Block *b = m_blockArray.at(lineno); + const Block * b = m_blockArray.at(lineno); if (!b) { memset(res, 0, count * sizeof(Character)); // still better than random data @@ -502,9 +518,11 @@ void HistoryScrollBlockArray::getCells(int lineno, int colno, void HistoryScrollBlockArray::addCells(const Character a[], int count) { - Block *b = m_blockArray.lastBlock(); + Block * b = m_blockArray.lastBlock(); - if (!b) return; + if (!b) { + return; + } // put cells in block's data assert((count * sizeof(Character)) < ENTRIES); @@ -548,7 +566,7 @@ bool HistoryTypeNone::isEnabled() const return false; } -HistoryScroll* HistoryTypeNone::scroll(HistoryScroll *old) const +HistoryScroll * HistoryTypeNone::scroll(HistoryScroll * old) const { delete old; return new HistoryScrollNone(); @@ -576,7 +594,7 @@ int HistoryTypeBlockArray::maximumLineCount() const return m_size; } -HistoryScroll* HistoryTypeBlockArray::scroll(HistoryScroll *old) const +HistoryScroll * HistoryTypeBlockArray::scroll(HistoryScroll * old) const { delete old; return new HistoryScrollBlockArray(m_size); @@ -600,26 +618,27 @@ int HistoryTypeBuffer::maximumLineCount() const return m_nbLines; } -HistoryScroll* HistoryTypeBuffer::scroll(HistoryScroll *old) const +HistoryScroll * HistoryTypeBuffer::scroll(HistoryScroll * old) const { if (old) { - HistoryScrollBuffer *oldBuffer = dynamic_cast(old); + HistoryScrollBuffer * oldBuffer = dynamic_cast(old); if (oldBuffer) { oldBuffer->setMaxNbLines(m_nbLines); return oldBuffer; } - HistoryScroll *newScroll = new HistoryScrollBuffer(m_nbLines); + HistoryScroll * newScroll = new HistoryScrollBuffer(m_nbLines); int lines = old->getLines(); int startLine = 0; - if (lines > (int) m_nbLines) + if (lines > (int) m_nbLines) { startLine = lines - m_nbLines; + } Character line[LINE_SIZE]; for (int i = startLine; i < lines; i++) { int size = old->getLineLen(i); if (size > LINE_SIZE) { - Character *tmp_line = new Character[size]; + Character * tmp_line = new Character[size]; old->getCells(i, 0, size, tmp_line); newScroll->addCells(tmp_line, size); newScroll->addLine(old->isWrappedLine(i)); @@ -638,7 +657,7 @@ HistoryScroll* HistoryTypeBuffer::scroll(HistoryScroll *old) const ////////////////////////////// -HistoryTypeFile::HistoryTypeFile(const QString& fileName) +HistoryTypeFile::HistoryTypeFile(const QString & fileName) : m_fileName(fileName) { } @@ -648,24 +667,25 @@ bool HistoryTypeFile::isEnabled() const return true; } -const QString& HistoryTypeFile::getFileName() const +const QString & HistoryTypeFile::getFileName() const { return m_fileName; } -HistoryScroll* HistoryTypeFile::scroll(HistoryScroll *old) const +HistoryScroll * HistoryTypeFile::scroll(HistoryScroll * old) const { - if (dynamic_cast(old)) - return old; // Unchanged. + if (dynamic_cast(old)) { + return old; // Unchanged. + } - HistoryScroll *newScroll = new HistoryScrollFile(m_fileName); + HistoryScroll * newScroll = new HistoryScrollFile(m_fileName); Character line[LINE_SIZE]; int lines = (old != 0) ? old->getLines() : 0; for (int i = 0; i < lines; i++) { int size = old->getLineLen(i); if (size > LINE_SIZE) { - Character *tmp_line = new Character[size]; + Character * tmp_line = new Character[size]; old->getCells(i, 0, size, tmp_line); newScroll->addCells(tmp_line, size); newScroll->addLine(old->isWrappedLine(i)); diff --git a/lib/History.h b/lib/History.h index bb3c4cd..29ce1d9 100644 --- a/lib/History.h +++ b/lib/History.h @@ -46,8 +46,8 @@ public: HistoryFile(); virtual ~HistoryFile(); - virtual void add(const unsigned char* bytes, int len); - virtual void get(unsigned char* bytes, int len, int loc); + virtual void add(const unsigned char * bytes, int len); + virtual void get(unsigned char * bytes, int len, int loc); virtual int len(); //mmaps the file in read-only mode @@ -64,7 +64,7 @@ private: QTemporaryFile tmpFile; //pointer to start of mmap'ed file data, or 0 if the file is not mmap'ed - char* fileMap; + char * fileMap; //incremented whenver 'add' is called and decremented whenever //'get' is called. @@ -87,7 +87,7 @@ class HistoryType; class HistoryScroll { public: - HistoryScroll(HistoryType*); + HistoryScroll(HistoryType *); virtual ~HistoryScroll(); virtual bool hasScroll(); @@ -120,12 +120,12 @@ public: // is very unsafe, because those references will no longer // be valid if the history scroll is deleted. // - const HistoryType& getType() { + const HistoryType & getType() { return *m_histType; } protected: - HistoryType* m_histType; + HistoryType * m_histType; }; @@ -138,7 +138,7 @@ protected: class HistoryScrollFile : public HistoryScroll { public: - HistoryScrollFile(const QString &logFileName); + HistoryScrollFile(const QString & logFileName); virtual ~HistoryScrollFile(); virtual int getLines(); @@ -188,7 +188,7 @@ public: private: int bufferIndex(int lineNumber); - HistoryLine* _historyBuffer; + HistoryLine * _historyBuffer; QBitArray _wrappedLine; int _maxLineCount; int _usedLines; @@ -287,7 +287,7 @@ public: */ virtual int maximumLineCount() const = 0; - virtual HistoryScroll* scroll(HistoryScroll *) const = 0; + virtual HistoryScroll * scroll(HistoryScroll *) const = 0; }; class HistoryTypeNone : public HistoryType @@ -298,7 +298,7 @@ public: virtual bool isEnabled() const; virtual int maximumLineCount() const; - virtual HistoryScroll* scroll(HistoryScroll *) const; + virtual HistoryScroll * scroll(HistoryScroll *) const; }; class HistoryTypeBlockArray : public HistoryType @@ -309,7 +309,7 @@ public: virtual bool isEnabled() const; virtual int maximumLineCount() const; - virtual HistoryScroll* scroll(HistoryScroll *) const; + virtual HistoryScroll * scroll(HistoryScroll *) const; protected: size_t m_size; @@ -319,13 +319,13 @@ protected: class HistoryTypeFile : public HistoryType { public: - HistoryTypeFile(const QString& fileName=QString()); + HistoryTypeFile(const QString & fileName=QString()); virtual bool isEnabled() const; - virtual const QString& getFileName() const; + virtual const QString & getFileName() const; virtual int maximumLineCount() const; - virtual HistoryScroll* scroll(HistoryScroll *) const; + virtual HistoryScroll * scroll(HistoryScroll *) const; protected: QString m_fileName; @@ -340,7 +340,7 @@ public: virtual bool isEnabled() const; virtual int maximumLineCount() const; - virtual HistoryScroll* scroll(HistoryScroll *) const; + virtual HistoryScroll * scroll(HistoryScroll *) const; protected: unsigned int m_nbLines; diff --git a/lib/KeyboardTranslator.cpp b/lib/KeyboardTranslator.cpp index 6cd0fc2..e6d0dbf 100644 --- a/lib/KeyboardTranslator.cpp +++ b/lib/KeyboardTranslator.cpp @@ -50,7 +50,7 @@ using namespace Konsole; //; //and this is default now translator - default.keytab from original Konsole -const char* KeyboardTranslatorManager::defaultTranslatorText = +const char * KeyboardTranslatorManager::defaultTranslatorText = #include "ExtendedDefaultTranslator.h" ; @@ -62,7 +62,7 @@ KeyboardTranslatorManager::~KeyboardTranslatorManager() { qDeleteAll(_translators.values()); } -QString KeyboardTranslatorManager::findTranslatorPath(const QString& name) +QString KeyboardTranslatorManager::findTranslatorPath(const QString & name) { return QString(KB_LAYOUT_DIR + name + ".keytab"); } @@ -92,10 +92,11 @@ void KeyboardTranslatorManager::findTranslators() _haveLoadedAll = true; } -const KeyboardTranslator* KeyboardTranslatorManager::findTranslator(const QString& name) +const KeyboardTranslator * KeyboardTranslatorManager::findTranslator(const QString & name) { - if ( name.isEmpty() ) + if ( name.isEmpty() ) { return defaultTranslator(); + } //here was smth wrong in original Konsole source findTranslators(); @@ -104,17 +105,18 @@ const KeyboardTranslator* KeyboardTranslatorManager::findTranslator(const QStrin return _translators[name]; } - KeyboardTranslator* translator = loadTranslator(name); + KeyboardTranslator * translator = loadTranslator(name); - if ( translator != 0 ) + if ( translator != 0 ) { _translators[name] = translator; - else if ( !name.isEmpty() ) + } else if ( !name.isEmpty() ) { qWarning() << "Unable to load translator" << name; + } return translator; } -bool KeyboardTranslatorManager::saveTranslator(const KeyboardTranslator* translator) +bool KeyboardTranslatorManager::saveTranslator(const KeyboardTranslator * translator) { const QString path = ".keytab";// = KGlobal::dirs()->saveLocation("data","konsole/")+translator->name() // +".keytab"; @@ -135,8 +137,9 @@ bool KeyboardTranslatorManager::saveTranslator(const KeyboardTranslator* transla writer.writeHeader(translator->description()); QListIterator iter(translator->entries()); - while ( iter.hasNext() ) + while ( iter.hasNext() ) { writer.writeEntry(iter.next()); + } } destination.close(); @@ -144,33 +147,35 @@ bool KeyboardTranslatorManager::saveTranslator(const KeyboardTranslator* transla return true; } -KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(const QString& name) +KeyboardTranslator * KeyboardTranslatorManager::loadTranslator(const QString & name) { - const QString& path = findTranslatorPath(name); + const QString & path = findTranslatorPath(name); QFile source(path); - if (name.isEmpty() || !source.open(QIODevice::ReadOnly | QIODevice::Text)) + if (name.isEmpty() || !source.open(QIODevice::ReadOnly | QIODevice::Text)) { return 0; + } return loadTranslator(&source,name); } -const KeyboardTranslator* KeyboardTranslatorManager::defaultTranslator() +const KeyboardTranslator * KeyboardTranslatorManager::defaultTranslator() { qDebug() << "Loading default translator from text"; QBuffer textBuffer; textBuffer.setData(defaultTranslatorText,strlen(defaultTranslatorText)); - if (!textBuffer.open(QIODevice::ReadOnly)) + if (!textBuffer.open(QIODevice::ReadOnly)) { return 0; + } return loadTranslator(&textBuffer,"fallback"); } -KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(QIODevice* source,const QString& name) +KeyboardTranslator * KeyboardTranslatorManager::loadTranslator(QIODevice * source,const QString & name) { - KeyboardTranslator* translator = new KeyboardTranslator(name); + KeyboardTranslator * translator = new KeyboardTranslator(name); KeyboardTranslatorReader reader(source); translator->setDescription( reader.description() ); @@ -188,7 +193,7 @@ KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(QIODevice* source, } } -KeyboardTranslatorWriter::KeyboardTranslatorWriter(QIODevice* destination) +KeyboardTranslatorWriter::KeyboardTranslatorWriter(QIODevice * destination) : _destination(destination) { Q_ASSERT( destination && destination->isWritable() ); @@ -199,18 +204,19 @@ KeyboardTranslatorWriter::~KeyboardTranslatorWriter() { delete _writer; } -void KeyboardTranslatorWriter::writeHeader( const QString& description ) +void KeyboardTranslatorWriter::writeHeader( const QString & description ) { *_writer << "keyboard \"" << description << '\"' << '\n'; } -void KeyboardTranslatorWriter::writeEntry( const KeyboardTranslator::Entry& entry ) +void KeyboardTranslatorWriter::writeEntry( const KeyboardTranslator::Entry & entry ) { QString result; - if ( entry.command() != KeyboardTranslator::NoCommand ) + if ( entry.command() != KeyboardTranslator::NoCommand ) { result = entry.resultToString(); - else + } else { result = '\"' + entry.resultToString() + '\"'; + } *_writer << "key " << entry.conditionToString() << " : " << result << '\n'; } @@ -235,7 +241,7 @@ void KeyboardTranslatorWriter::writeEntry( const KeyboardTranslator::Entry& entr // already been removed) // -KeyboardTranslatorReader::KeyboardTranslatorReader( QIODevice* source ) +KeyboardTranslatorReader::KeyboardTranslatorReader( QIODevice * source ) : _source(source) , _hasNext(false) { @@ -278,8 +284,9 @@ void KeyboardTranslatorReader::readNext() text = tokens[2].text.toLocal8Bit(); } else if ( tokens[2].type == Token::Command ) { // identify command - if (!parseAsCommand(tokens[2].text,command)) + if (!parseAsCommand(tokens[2].text,command)) { qWarning() << "Command" << tokens[2].text << "not understood."; + } } KeyboardTranslator::Entry newEntry; @@ -302,32 +309,33 @@ void KeyboardTranslatorReader::readNext() _hasNext = false; } -bool KeyboardTranslatorReader::parseAsCommand(const QString& text,KeyboardTranslator::Command& command) +bool KeyboardTranslatorReader::parseAsCommand(const QString & text,KeyboardTranslator::Command & command) { - if ( text.compare("erase",Qt::CaseInsensitive) == 0 ) + if ( text.compare("erase",Qt::CaseInsensitive) == 0 ) { command = KeyboardTranslator::EraseCommand; - else if ( text.compare("scrollpageup",Qt::CaseInsensitive) == 0 ) + } else if ( text.compare("scrollpageup",Qt::CaseInsensitive) == 0 ) { command = KeyboardTranslator::ScrollPageUpCommand; - else if ( text.compare("scrollpagedown",Qt::CaseInsensitive) == 0 ) + } else if ( text.compare("scrollpagedown",Qt::CaseInsensitive) == 0 ) { command = KeyboardTranslator::ScrollPageDownCommand; - else if ( text.compare("scrolllineup",Qt::CaseInsensitive) == 0 ) + } else if ( text.compare("scrolllineup",Qt::CaseInsensitive) == 0 ) { command = KeyboardTranslator::ScrollLineUpCommand; - else if ( text.compare("scrolllinedown",Qt::CaseInsensitive) == 0 ) + } else if ( text.compare("scrolllinedown",Qt::CaseInsensitive) == 0 ) { command = KeyboardTranslator::ScrollLineDownCommand; - else if ( text.compare("scrolllock",Qt::CaseInsensitive) == 0 ) + } else if ( text.compare("scrolllock",Qt::CaseInsensitive) == 0 ) { command = KeyboardTranslator::ScrollLockCommand; - else + } else { return false; + } return true; } -bool KeyboardTranslatorReader::decodeSequence(const QString& text, - int& keyCode, - Qt::KeyboardModifiers& modifiers, - Qt::KeyboardModifiers& modifierMask, - KeyboardTranslator::States& flags, - KeyboardTranslator::States& flagMask) +bool KeyboardTranslatorReader::decodeSequence(const QString & text, + int & keyCode, + Qt::KeyboardModifiers & modifiers, + Qt::KeyboardModifiers & modifierMask, + KeyboardTranslator::States & flags, + KeyboardTranslator::States & flagMask) { bool isWanted = true; bool endOfItem = false; @@ -339,7 +347,7 @@ bool KeyboardTranslatorReader::decodeSequence(const QString& text, KeyboardTranslator::States tempFlagMask = flagMask; for ( int i = 0 ; i < text.count() ; i++ ) { - const QChar& ch = text[i]; + const QChar & ch = text[i]; bool isLastLetter = ( i == text.count()-1 ); endOfItem = true; @@ -356,27 +364,31 @@ bool KeyboardTranslatorReader::decodeSequence(const QString& text, if ( parseAsModifier(buffer,itemModifier) ) { tempModifierMask |= itemModifier; - if ( isWanted ) + if ( isWanted ) { tempModifiers |= itemModifier; + } } else if ( parseAsStateFlag(buffer,itemFlag) ) { tempFlagMask |= itemFlag; - if ( isWanted ) + if ( isWanted ) { tempFlags |= itemFlag; - } else if ( parseAsKeyCode(buffer,itemKeyCode) ) + } + } else if ( parseAsKeyCode(buffer,itemKeyCode) ) { keyCode = itemKeyCode; - else + } else { qDebug() << "Unable to parse key binding item:" << buffer; + } buffer.clear(); } // check if this is a wanted / not-wanted flag and update the // state ready for the next item - if ( ch == '+' ) + if ( ch == '+' ) { isWanted = true; - else if ( ch == '-' ) + } else if ( ch == '-' ) { isWanted = false; + } } modifiers = tempModifiers; @@ -387,41 +399,43 @@ bool KeyboardTranslatorReader::decodeSequence(const QString& text, return true; } -bool KeyboardTranslatorReader::parseAsModifier(const QString& item , Qt::KeyboardModifier& modifier) +bool KeyboardTranslatorReader::parseAsModifier(const QString & item , Qt::KeyboardModifier & modifier) { - if ( item == "shift" ) + if ( item == "shift" ) { modifier = Qt::ShiftModifier; - else if ( item == "ctrl" || item == "control" ) + } else if ( item == "ctrl" || item == "control" ) { modifier = Qt::ControlModifier; - else if ( item == "alt" ) + } else if ( item == "alt" ) { modifier = Qt::AltModifier; - else if ( item == "meta" ) + } else if ( item == "meta" ) { modifier = Qt::MetaModifier; - else if ( item == "keypad" ) + } else if ( item == "keypad" ) { modifier = Qt::KeypadModifier; - else + } else { return false; + } return true; } -bool KeyboardTranslatorReader::parseAsStateFlag(const QString& item , KeyboardTranslator::State& flag) +bool KeyboardTranslatorReader::parseAsStateFlag(const QString & item , KeyboardTranslator::State & flag) { - if ( item == "appcukeys" ) + if ( item == "appcukeys" ) { flag = KeyboardTranslator::CursorKeysState; - else if ( item == "ansi" ) + } else if ( item == "ansi" ) { flag = KeyboardTranslator::AnsiState; - else if ( item == "newline" ) + } else if ( item == "newline" ) { flag = KeyboardTranslator::NewLineState; - else if ( item == "appscreen" ) + } else if ( item == "appscreen" ) { flag = KeyboardTranslator::AlternateScreenState; - else if ( item == "anymod" ) + } else if ( item == "anymod" ) { flag = KeyboardTranslator::AnyModifierState; - else + } else { return false; + } return true; } -bool KeyboardTranslatorReader::parseAsKeyCode(const QString& item , int& keyCode) +bool KeyboardTranslatorReader::parseAsKeyCode(const QString & item , int & keyCode) { QKeySequence sequence = QKeySequence::fromString(item); if ( !sequence.isEmpty() ) { @@ -432,12 +446,13 @@ bool KeyboardTranslatorReader::parseAsKeyCode(const QString& item , int& keyCode } } // additional cases implemented for backwards compatibility with KDE 3 - else if ( item == "prior" ) + else if ( item == "prior" ) { keyCode = Qt::Key_PageUp; - else if ( item == "next" ) + } else if ( item == "next" ) { keyCode = Qt::Key_PageDown; - else + } else { return false; + } return true; } @@ -450,8 +465,8 @@ bool KeyboardTranslatorReader::hasNextEntry() { return _hasNext; } -KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString& condition , - const QString& result ) +KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString & condition , + const QString & result ) { QString entryString("keyboard \"temporary\"\nkey "); entryString.append(condition); @@ -461,10 +476,11 @@ KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString& // otherwise the result will be treated as a string to echo when the key sequence // specified by 'condition' is pressed KeyboardTranslator::Command command; - if (parseAsCommand(result,command)) + if (parseAsCommand(result,command)) { entryString.append(result); - else + } else { entryString.append('\"' + result + '\"'); + } QByteArray array = entryString.toUtf8(); @@ -474,8 +490,9 @@ KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString& buffer.open(QIODevice::ReadOnly); KeyboardTranslatorReader reader(&buffer); - if ( reader.hasNextEntry() ) + if ( reader.hasNextEntry() ) { entry = reader.nextEntry(); + } return entry; } @@ -495,7 +512,7 @@ bool KeyboardTranslatorReader::parseError() { return false; } -QList KeyboardTranslatorReader::tokenize(const QString& line) +QList KeyboardTranslatorReader::tokenize(const QString & line) { QString text = line.simplified(); @@ -559,7 +576,7 @@ KeyboardTranslator::Entry::Entry() { } -bool KeyboardTranslator::Entry::operator==(const Entry& rhs) const +bool KeyboardTranslator::Entry::operator==(const Entry & rhs) const { return _keyCode == rhs._keyCode && _modifiers == rhs._modifiers && @@ -574,30 +591,36 @@ bool KeyboardTranslator::Entry::matches(int keyCode , Qt::KeyboardModifiers modifiers, States state) const { - if ( _keyCode != keyCode ) + if ( _keyCode != keyCode ) { return false; + } - if ( (modifiers & _modifierMask) != (_modifiers & _modifierMask) ) + if ( (modifiers & _modifierMask) != (_modifiers & _modifierMask) ) { return false; + } // if modifiers is non-zero, the 'any modifier' state is implicit - if ( modifiers != 0 ) + if ( modifiers != 0 ) { state |= AnyModifierState; + } - if ( (state & _stateMask) != (_state & _stateMask) ) + if ( (state & _stateMask) != (_state & _stateMask) ) { return false; + } // special handling for the 'Any Modifier' state, which checks for the presence of // any or no modifiers. In this context, the 'keypad' modifier does not count. bool anyModifiersSet = modifiers != 0 && modifiers != Qt::KeypadModifier; if ( _stateMask & KeyboardTranslator::AnyModifierState ) { // test fails if any modifier is required but none are set - if ( (_state & KeyboardTranslator::AnyModifierState) && !anyModifiersSet ) + if ( (_state & KeyboardTranslator::AnyModifierState) && !anyModifiersSet ) { return false; + } // test fails if no modifier is allowed but one or more are set - if ( !(_state & KeyboardTranslator::AnyModifierState) && anyModifiersSet ) + if ( !(_state & KeyboardTranslator::AnyModifierState) && anyModifiersSet ) { return false; + } } return true; @@ -632,8 +655,9 @@ QByteArray KeyboardTranslator::Entry::escapedText(bool expandWildCards,Qt::Keybo default: // any character which is not printable is replaced by an equivalent // \xhh escape sequence (where 'hh' are the corresponding hex digits) - if ( !QChar(ch).isPrint() ) + if ( !QChar(ch).isPrint() ) { replacement = 'x'; + } } if ( replacement == 'x' ) { @@ -647,7 +671,7 @@ QByteArray KeyboardTranslator::Entry::escapedText(bool expandWildCards,Qt::Keybo return result; } -QByteArray KeyboardTranslator::Entry::unescape(const QByteArray& input) const +QByteArray KeyboardTranslator::Entry::unescape(const QByteArray & input) const { QByteArray result(input); @@ -684,10 +708,12 @@ QByteArray KeyboardTranslator::Entry::unescape(const QByteArray& input) const // with the corresponding character value char hexDigits[3] = {0}; - if ( (i < result.count()-2) && isxdigit(result[i+2]) ) + if ( (i < result.count()-2) && isxdigit(result[i+2]) ) { hexDigits[0] = result[i+2]; - if ( (i < result.count()-3) && isxdigit(result[i+3]) ) + } + if ( (i < result.count()-3) && isxdigit(result[i+3]) ) { hexDigits[1] = result[i+3]; + } int charValue = 0; sscanf(hexDigits,"%x",&charValue); @@ -701,72 +727,80 @@ QByteArray KeyboardTranslator::Entry::unescape(const QByteArray& input) const escapedChar = false; } - if ( escapedChar ) + if ( escapedChar ) { result.replace(i,charsToRemove,replacement); + } } } return result; } -void KeyboardTranslator::Entry::insertModifier( QString& item , int modifier ) const +void KeyboardTranslator::Entry::insertModifier( QString & item , int modifier ) const { - if ( !(modifier & _modifierMask) ) + if ( !(modifier & _modifierMask) ) { return; + } - if ( modifier & _modifiers ) + if ( modifier & _modifiers ) { item += '+'; - else + } else { item += '-'; + } - if ( modifier == Qt::ShiftModifier ) + if ( modifier == Qt::ShiftModifier ) { item += "Shift"; - else if ( modifier == Qt::ControlModifier ) + } else if ( modifier == Qt::ControlModifier ) { item += "Ctrl"; - else if ( modifier == Qt::AltModifier ) + } else if ( modifier == Qt::AltModifier ) { item += "Alt"; - else if ( modifier == Qt::MetaModifier ) + } else if ( modifier == Qt::MetaModifier ) { item += "Meta"; - else if ( modifier == Qt::KeypadModifier ) + } else if ( modifier == Qt::KeypadModifier ) { item += "KeyPad"; + } } -void KeyboardTranslator::Entry::insertState( QString& item , int state ) const +void KeyboardTranslator::Entry::insertState( QString & item , int state ) const { - if ( !(state & _stateMask) ) + if ( !(state & _stateMask) ) { return; + } - if ( state & _state ) + if ( state & _state ) { item += '+' ; - else + } else { item += '-' ; + } - if ( state == KeyboardTranslator::AlternateScreenState ) + if ( state == KeyboardTranslator::AlternateScreenState ) { item += "AppScreen"; - else if ( state == KeyboardTranslator::NewLineState ) + } else if ( state == KeyboardTranslator::NewLineState ) { item += "NewLine"; - else if ( state == KeyboardTranslator::AnsiState ) + } else if ( state == KeyboardTranslator::AnsiState ) { item += "Ansi"; - else if ( state == KeyboardTranslator::CursorKeysState ) + } else if ( state == KeyboardTranslator::CursorKeysState ) { item += "AppCuKeys"; - else if ( state == KeyboardTranslator::AnyModifierState ) + } else if ( state == KeyboardTranslator::AnyModifierState ) { item += "AnyMod"; + } } QString KeyboardTranslator::Entry::resultToString(bool expandWildCards,Qt::KeyboardModifiers modifiers) const { - if ( !_text.isEmpty() ) + if ( !_text.isEmpty() ) { return escapedText(expandWildCards,modifiers); - else if ( _command == EraseCommand ) + } else if ( _command == EraseCommand ) { return "Erase"; - else if ( _command == ScrollPageUpCommand ) + } else if ( _command == ScrollPageUpCommand ) { return "ScrollPageUp"; - else if ( _command == ScrollPageDownCommand ) + } else if ( _command == ScrollPageDownCommand ) { return "ScrollPageDown"; - else if ( _command == ScrollLineUpCommand ) + } else if ( _command == ScrollLineUpCommand ) { return "ScrollLineUp"; - else if ( _command == ScrollLineDownCommand ) + } else if ( _command == ScrollLineDownCommand ) { return "ScrollLineDown"; - else if ( _command == ScrollLockCommand ) + } else if ( _command == ScrollLockCommand ) { return "ScrollLock"; + } return QString(); } @@ -790,12 +824,12 @@ QString KeyboardTranslator::Entry::conditionToString() const return result; } -KeyboardTranslator::KeyboardTranslator(const QString& name) +KeyboardTranslator::KeyboardTranslator(const QString & name) : _name(name) { } -void KeyboardTranslator::setDescription(const QString& description) +void KeyboardTranslator::setDescription(const QString & description) { _description = description; } @@ -803,7 +837,7 @@ QString KeyboardTranslator::description() const { return _description; } -void KeyboardTranslator::setName(const QString& name) +void KeyboardTranslator::setName(const QString & name) { _name = name; } @@ -817,18 +851,19 @@ QList KeyboardTranslator::entries() const return _entries.values(); } -void KeyboardTranslator::addEntry(const Entry& entry) +void KeyboardTranslator::addEntry(const Entry & entry) { const int keyCode = entry.keyCode(); _entries.insertMulti(keyCode,entry); } -void KeyboardTranslator::replaceEntry(const Entry& existing , const Entry& replacement) +void KeyboardTranslator::replaceEntry(const Entry & existing , const Entry & replacement) { - if ( !existing.isNull() ) + if ( !existing.isNull() ) { _entries.remove(existing.keyCode()); + } _entries.insertMulti(replacement.keyCode(),replacement); } -void KeyboardTranslator::removeEntry(const Entry& entry) +void KeyboardTranslator::removeEntry(const Entry & entry) { _entries.remove(entry.keyCode()); } @@ -840,9 +875,10 @@ KeyboardTranslator::Entry KeyboardTranslator::findEntry(int keyCode, Qt::Keyboar QListIterator iter(entriesForKey); while (iter.hasNext()) { - const Entry& next = iter.next(); - if ( next.matches(keyCode,modifiers,state) ) + const Entry & next = iter.next(); + if ( next.matches(keyCode,modifiers,state) ) { return next; + } } return Entry(); // entry not found @@ -851,7 +887,7 @@ KeyboardTranslator::Entry KeyboardTranslator::findEntry(int keyCode, Qt::Keyboar } } -void KeyboardTranslatorManager::addTranslator(KeyboardTranslator* translator) +void KeyboardTranslatorManager::addTranslator(KeyboardTranslator * translator) { _translators.insert(translator->name(),translator); @@ -859,7 +895,7 @@ void KeyboardTranslatorManager::addTranslator(KeyboardTranslator* translator) qWarning() << "Unable to save translator" << translator->name() << "to disk."; } -bool KeyboardTranslatorManager::deleteTranslator(const QString& name) +bool KeyboardTranslatorManager::deleteTranslator(const QString & name) { Q_ASSERT( _translators.contains(name) ); @@ -874,7 +910,7 @@ bool KeyboardTranslatorManager::deleteTranslator(const QString& name) } } K_GLOBAL_STATIC( KeyboardTranslatorManager , theKeyboardTranslatorManager ) -KeyboardTranslatorManager* KeyboardTranslatorManager::instance() +KeyboardTranslatorManager * KeyboardTranslatorManager::instance() { return theKeyboardTranslatorManager; } diff --git a/lib/KeyboardTranslator.h b/lib/KeyboardTranslator.h index bbe584b..8437ea5 100644 --- a/lib/KeyboardTranslator.h +++ b/lib/KeyboardTranslator.h @@ -228,7 +228,7 @@ public: Qt::KeyboardModifiers modifiers = Qt::NoModifier) const; /** Sets the character sequence associated with this entry */ - void setText(const QByteArray& text); + void setText(const QByteArray & text); /** * Returns the character sequence associated with this entry, @@ -313,12 +313,12 @@ public: Qt::KeyboardModifiers modifiers , States flags ) const; - bool operator==(const Entry& rhs) const; + bool operator==(const Entry & rhs) const; private: - void insertModifier( QString& item , int modifier ) const; - void insertState( QString& item , int state ) const; - QByteArray unescape(const QByteArray& text) const; + void insertModifier( QString & item , int modifier ) const; + void insertState( QString & item , int state ) const; + QByteArray unescape(const QByteArray & text) const; int _keyCode; Qt::KeyboardModifiers _modifiers; @@ -331,7 +331,7 @@ public: }; /** Constructs a new keyboard translator with the given @p name */ - KeyboardTranslator(const QString& name); + KeyboardTranslator(const QString & name); //KeyboardTranslator(const KeyboardTranslator& other); @@ -339,13 +339,13 @@ public: QString name() const; /** Sets the name of this keyboard translator */ - void setName(const QString& name); + void setName(const QString & name); /** Returns the descriptive name of this keyboard translator */ QString description() const; /** Sets the descriptive name of this keyboard translator */ - void setDescription(const QString& description); + void setDescription(const QString & description); /** * Looks for an entry in this keyboard translator which matches the given @@ -366,18 +366,18 @@ public: * Adds an entry to this keyboard translator's table. Entries can be looked up according * to their key sequence using findEntry() */ - void addEntry(const Entry& entry); + void addEntry(const Entry & entry); /** * Replaces an entry in the translator. If the @p existing entry is null, * then this is equivalent to calling addEntry(@p replacement) */ - void replaceEntry(const Entry& existing , const Entry& replacement); + void replaceEntry(const Entry & existing , const Entry & replacement); /** * Removes an entry from the table. */ - void removeEntry(const Entry& entry); + void removeEntry(const Entry & entry); /** Returns a list of all entries in the translator. */ QList entries() const; @@ -425,7 +425,7 @@ class KeyboardTranslatorReader { public: /** Constructs a new reader which parses the given @p source */ - KeyboardTranslatorReader( QIODevice* source ); + KeyboardTranslatorReader( QIODevice * source ); /** * Returns the description text. @@ -450,8 +450,8 @@ public: * * The condition and result strings are in the same format as in */ - static KeyboardTranslator::Entry createEntry( const QString& condition , - const QString& result ); + static KeyboardTranslator::Entry createEntry( const QString & condition , + const QString & result ); private: struct Token { enum Type { @@ -465,21 +465,21 @@ private: Type type; QString text; }; - QList tokenize(const QString&); + QList tokenize(const QString &); void readNext(); - bool decodeSequence(const QString& , - int& keyCode, - Qt::KeyboardModifiers& modifiers, - Qt::KeyboardModifiers& modifierMask, - KeyboardTranslator::States& state, - KeyboardTranslator::States& stateFlags); + bool decodeSequence(const QString & , + int & keyCode, + Qt::KeyboardModifiers & modifiers, + Qt::KeyboardModifiers & modifierMask, + KeyboardTranslator::States & state, + KeyboardTranslator::States & stateFlags); - static bool parseAsModifier(const QString& item , Qt::KeyboardModifier& modifier); - static bool parseAsStateFlag(const QString& item , KeyboardTranslator::State& state); - static bool parseAsKeyCode(const QString& item , int& keyCode); - static bool parseAsCommand(const QString& text , KeyboardTranslator::Command& command); + static bool parseAsModifier(const QString & item , Qt::KeyboardModifier & modifier); + static bool parseAsStateFlag(const QString & item , KeyboardTranslator::State & state); + static bool parseAsKeyCode(const QString & item , int & keyCode); + static bool parseAsCommand(const QString & text , KeyboardTranslator::Command & command); - QIODevice* _source; + QIODevice * _source; QString _description; KeyboardTranslator::Entry _nextEntry; bool _hasNext; @@ -493,20 +493,20 @@ public: * Constructs a new writer which saves data into @p destination. * The caller is responsible for closing the device when writing is complete. */ - KeyboardTranslatorWriter(QIODevice* destination); + KeyboardTranslatorWriter(QIODevice * destination); ~KeyboardTranslatorWriter(); /** * Writes the header for the keyboard translator. * @param description Description of the keyboard translator. */ - void writeHeader( const QString& description ); + void writeHeader( const QString & description ); /** Writes a translator entry. */ - void writeEntry( const KeyboardTranslator::Entry& entry ); + void writeEntry( const KeyboardTranslator::Entry & entry ); private: - QIODevice* _destination; - QTextStream* _writer; + QIODevice * _destination; + QTextStream * _writer; }; /** @@ -532,17 +532,17 @@ public: * * TODO: More documentation. */ - void addTranslator(KeyboardTranslator* translator); + void addTranslator(KeyboardTranslator * translator); /** * Deletes a translator. Returns true on successful deletion or false otherwise. * * TODO: More documentation */ - bool deleteTranslator(const QString& name); + bool deleteTranslator(const QString & name); /** Returns the default translator for Konsole. */ - const KeyboardTranslator* defaultTranslator(); + const KeyboardTranslator * defaultTranslator(); /** * Returns the keyboard translator with the given name or 0 if no translator @@ -551,7 +551,7 @@ public: * The first time that a translator with a particular name is requested, * the on-disk .keyboard file is loaded and parsed. */ - const KeyboardTranslator* findTranslator(const QString& name); + const KeyboardTranslator * findTranslator(const QString & name); /** * Returns a list of the names of available keyboard translators. * @@ -561,20 +561,20 @@ public: QList allTranslators(); /** Returns the global KeyboardTranslatorManager instance. */ - static KeyboardTranslatorManager* instance(); + static KeyboardTranslatorManager * instance(); private: - static const char* defaultTranslatorText; + static const char * defaultTranslatorText; void findTranslators(); // locate the available translators - KeyboardTranslator* loadTranslator(const QString& name); // loads the translator + KeyboardTranslator * loadTranslator(const QString & name); // loads the translator // with the given name - KeyboardTranslator* loadTranslator(QIODevice* device,const QString& name); + KeyboardTranslator * loadTranslator(QIODevice * device,const QString & name); - bool saveTranslator(const KeyboardTranslator* translator); - QString findTranslatorPath(const QString& name); + bool saveTranslator(const KeyboardTranslator * translator); + QString findTranslatorPath(const QString & name); - QHash _translators; // maps translator-name -> KeyboardTranslator + QHash _translators; // maps translator-name -> KeyboardTranslator // instance bool _haveLoadedAll; }; @@ -620,7 +620,7 @@ inline KeyboardTranslator::Command KeyboardTranslator::Entry::command() const return _command; } -inline void KeyboardTranslator::Entry::setText( const QByteArray& text ) +inline void KeyboardTranslator::Entry::setText( const QByteArray & text ) { _text = unescape(text); } @@ -639,8 +639,9 @@ inline QByteArray KeyboardTranslator::Entry::text(bool expandWildCards,Qt::Keybo modifierValue += oneOrZero(modifiers & Qt::ControlModifier) << 2; for (int i=0; i<_text.length(); i++) { - if (expandedText[i] == '*') + if (expandedText[i] == '*') { expandedText[i] = '0' + modifierValue; + } } } @@ -668,7 +669,7 @@ inline KeyboardTranslator::States KeyboardTranslator::Entry::stateMask() const } Q_DECLARE_METATYPE(Konsole::KeyboardTranslator::Entry) -Q_DECLARE_METATYPE(const Konsole::KeyboardTranslator*) +Q_DECLARE_METATYPE(const Konsole::KeyboardTranslator *) #endif // KEYBOARDTRANSLATOR_H diff --git a/lib/Pty.cpp b/lib/Pty.cpp index 6ddeac8..afa2baf 100644 --- a/lib/Pty.cpp +++ b/lib/Pty.cpp @@ -51,8 +51,9 @@ void Pty::setWindowSize(int lines, int cols) _windowColumns = cols; _windowLines = lines; - if (pty()->masterFd() >= 0) + if (pty()->masterFd() >= 0) { pty()->setWinSize(lines, cols); + } } QSize Pty::windowSize() const { @@ -66,12 +67,14 @@ void Pty::setXonXoff(bool enable) if (pty()->masterFd() >= 0) { struct ::termios ttmode; pty()->tcGetAttr(&ttmode); - if (!enable) + if (!enable) { ttmode.c_iflag &= ~(IXOFF | IXON); - else + } else { ttmode.c_iflag |= (IXOFF | IXON); - if (!pty()->tcSetAttr(&ttmode)) + } + if (!pty()->tcSetAttr(&ttmode)) { qWarning("Unable to set terminal attributes."); + } } } @@ -83,12 +86,14 @@ void Pty::setUtf8Mode(bool enable) if (pty()->masterFd() >= 0) { struct ::termios ttmode; pty()->tcGetAttr(&ttmode); - if (!enable) + if (!enable) { ttmode.c_iflag &= ~IUTF8; - else + } else { ttmode.c_iflag |= IUTF8; - if (!pty()->tcSetAttr(&ttmode)) + } + if (!pty()->tcSetAttr(&ttmode)) { qWarning("Unable to set terminal attributes."); + } } #endif } @@ -104,8 +109,9 @@ void Pty::setErase(char erase) ttmode.c_cc[VERASE] = erase; - if (!pty()->tcSetAttr(&ttmode)) + if (!pty()->tcSetAttr(&ttmode)) { qWarning("Unable to set terminal attributes."); + } } } @@ -121,7 +127,7 @@ char Pty::erase() const return _eraseChar; } -void Pty::addEnvironmentVariables(const QStringList& environment) +void Pty::addEnvironmentVariables(const QStringList & environment) { QListIterator iter(environment); while (iter.hasNext()) { @@ -142,9 +148,9 @@ void Pty::addEnvironmentVariables(const QStringList& environment) } } -int Pty::start(const QString& program, - const QStringList& programArguments, - const QStringList& environment, +int Pty::start(const QString & program, + const QStringList & programArguments, + const QStringList & environment, ulong winid, bool addToUtmp // const QString& dbusService, @@ -158,8 +164,9 @@ int Pty::start(const QString& program, addEnvironmentVariables(environment); QStringListIterator it( programArguments ); - while (it.hasNext()) + while (it.hasNext()) { arguments.append( it.next().toUtf8() ); + } // if ( !dbusService.isEmpty() ) // setEnvironment("KONSOLE_DBUS_SERVICE",dbusService); @@ -179,8 +186,9 @@ int Pty::start(const QString& program, // does not have a translation for // // BR:149300 - if (!environment.contains("LANGUAGE")) + if (!environment.contains("LANGUAGE")) { setEnvironment("LANGUAGE",QString()); + } setUsePty(All, addToUtmp); @@ -188,27 +196,32 @@ int Pty::start(const QString& program, struct ::termios ttmode; pty()->tcGetAttr(&ttmode); - if (!_xonXoff) + if (!_xonXoff) { ttmode.c_iflag &= ~(IXOFF | IXON); - else + } else { ttmode.c_iflag |= (IXOFF | IXON); + } #ifdef IUTF8 // XXX not a reasonable place to check it. - if (!_utf8) + if (!_utf8) { ttmode.c_iflag &= ~IUTF8; - else + } else { ttmode.c_iflag |= IUTF8; + } #endif - if (_eraseChar != 0) + if (_eraseChar != 0) { ttmode.c_cc[VERASE] = _eraseChar; + } - if (!pty()->tcSetAttr(&ttmode)) + if (!pty()->tcSetAttr(&ttmode)) { qWarning("Unable to set terminal attributes."); + } pty()->setWinSize(_windowLines, _windowColumns); - if ( K3Process::start(NotifyOnExit, (Communication) (Stdin | Stdout)) == false ) + if ( K3Process::start(NotifyOnExit, (Communication) (Stdin | Stdout)) == false ) { return -1; + } resume(); // Start... return 0; @@ -219,10 +232,11 @@ void Pty::setWriteable(bool writeable) { struct stat sbuf; stat(pty()->ttyName(), &sbuf); - if (writeable) + if (writeable) { chmod(pty()->ttyName(), sbuf.st_mode | S_IWGRP); - else + } else { chmod(pty()->ttyName(), sbuf.st_mode & ~(S_IWGRP|S_IWOTH)); + } } Pty::Pty() @@ -263,7 +277,7 @@ void Pty::doSendJobs() return; } - SendJob& job = _pendingSendJobs.first(); + SendJob & job = _pendingSendJobs.first(); if (!writeStdin( job.data(), job.length() )) { @@ -273,29 +287,31 @@ void Pty::doSendJobs() _bufferFull = true; } -void Pty::appendSendJob(const char* s, int len) +void Pty::appendSendJob(const char * s, int len) { _pendingSendJobs.append(SendJob(s,len)); } -void Pty::sendData(const char* s, int len) +void Pty::sendData(const char * s, int len) { appendSendJob(s,len); - if (!_bufferFull) + if (!_bufferFull) { doSendJobs(); + } } -void Pty::dataReceived(K3Process *,char *buf, int len) +void Pty::dataReceived(K3Process *,char * buf, int len) { emit receivedData(buf,len); } void Pty::lockPty(bool lock) { - if (lock) + if (lock) { suspend(); - else + } else { resume(); + } } int Pty::foregroundProcessGroup() const diff --git a/lib/Pty.h b/lib/Pty.h index 3b6aecb..6466155 100644 --- a/lib/Pty.h +++ b/lib/Pty.h @@ -88,9 +88,9 @@ public: * @param dbusSession Specifies the value of the KONSOLE_DBUS_SESSION * environment variable in the process's environment. */ - int start( const QString& program, - const QStringList& arguments, - const QStringList& environment, + int start( const QString & program, + const QStringList & arguments, + const QStringList & environment, ulong winid, bool addToUtmp // const QString& dbusService, @@ -164,7 +164,7 @@ public slots: * @param buffer Pointer to the data to send. * @param length Length of @p buffer. */ - void sendData(const char* buffer, int length); + void sendData(const char * buffer, int length); signals: @@ -182,7 +182,7 @@ signals: * @param buffer Pointer to the data received. * @param length Length of @p buffer */ - void receivedData(const char* buffer, int length); + void receivedData(const char * buffer, int length); /** * Emitted when the buffer used to send data to the terminal @@ -196,7 +196,7 @@ private slots: // called when terminal process exits void donePty(); // called when data is received from the terminal process - void dataReceived(K3Process*, char* buffer, int length); + void dataReceived(K3Process *, char * buffer, int length); // sends the first enqueued buffer of data to the // terminal process void doSendJobs(); @@ -207,11 +207,11 @@ private slots: private: // takes a list of key=value pairs and adds them // to the environment for the process - void addEnvironmentVariables(const QStringList& environment); + void addEnvironmentVariables(const QStringList & environment); // enqueues a buffer of data to be sent to the // terminal process - void appendSendJob(const char* buffer, int length); + void appendSendJob(const char * buffer, int length); // a buffer of data in the queue to be sent to the // terminal process @@ -219,11 +219,11 @@ private: { public: SendJob() {} - SendJob(const char* b, int len) : buffer(len) { + SendJob(const char * b, int len) : buffer(len) { memcpy( buffer.data() , b , len ); } - const char* data() const { + const char * data() const { return buffer.constData(); } int length() const { @@ -241,7 +241,7 @@ private: char _eraseChar; bool _xonXoff; bool _utf8; - KPty *_pty; + KPty * _pty; }; } diff --git a/lib/Screen.cpp b/lib/Screen.cpp index d3d43e9..1e3218c 100644 --- a/lib/Screen.cpp +++ b/lib/Screen.cpp @@ -86,8 +86,9 @@ Screen::Screen(int l, int c) lastPos(-1) { lineProperties.resize(lines+1); - for (int i=0; i bmargin ? lines-1 : bmargin; cuX = qMin(columns-1,cuX); // nowrap! cuY = qMin(stop,cuY+n); @@ -161,7 +166,9 @@ void Screen::cursorDown(int n) void Screen::cursorLeft(int n) //=CUB { - if (n == 0) n = 1; // Default + if (n == 0) { + n = 1; // Default + } cuX = qMin(columns-1,cuX); // nowrap! cuX = qMax(0,cuX-n); } @@ -175,15 +182,21 @@ void Screen::cursorLeft(int n) void Screen::cursorRight(int n) //=CUF { - if (n == 0) n = 1; // Default + if (n == 0) { + n = 1; // Default + } cuX = qMin(columns-1,cuX+n); } void Screen::setMargins(int top, int bot) //=STBM { - if (top == 0) top = 1; // Default - if (bot == 0) bot = lines; // Default + if (top == 0) { + top = 1; // Default + } + if (bot == 0) { + bot = lines; // Default + } top = top - 1; // Adjust to internal lineno bot = bot - 1; // Adjust to internal lineno if ( !( 0 <= top && top < bot && bot < lines ) ) { @@ -211,17 +224,19 @@ void Screen::index() { if (cuY == bmargin) { scrollUp(1); - } else if (cuY < lines-1) + } else if (cuY < lines-1) { cuY += 1; + } } void Screen::reverseIndex() //=RI { - if (cuY == tmargin) + if (cuY == tmargin) { scrollDown(tmargin,1); - else if (cuY > 0) + } else if (cuY > 0) { cuY -= 1; + } } /*! @@ -240,7 +255,9 @@ void Screen::NextLine() void Screen::eraseChars(int n) { - if (n == 0) n = 1; // Default + if (n == 0) { + n = 1; // Default + } int p = qMax(0,qMin(cuX+n-1,columns-1)); clearImage(loc(cuX,cuY),loc(p,cuY),' '); } @@ -250,15 +267,18 @@ void Screen::deleteChars(int n) Q_ASSERT( n >= 0 ); // always delete at least one char - if (n == 0) + if (n == 0) { n = 1; + } // if cursor is beyond the end of the line there is nothing to do - if ( cuX >= screenLines[cuY].count() ) + if ( cuX >= screenLines[cuY].count() ) { return; + } - if ( cuX+n >= screenLines[cuY].count() ) + if ( cuX+n >= screenLines[cuY].count() ) { n = screenLines[cuY].count() - 1 - cuX; + } Q_ASSERT( n >= 0 ); Q_ASSERT( cuX+n < screenLines[cuY].count() ); @@ -268,20 +288,26 @@ void Screen::deleteChars(int n) void Screen::insertChars(int n) { - if (n == 0) n = 1; // Default + if (n == 0) { + n = 1; // Default + } - if ( screenLines[cuY].size() < cuX ) + if ( screenLines[cuY].size() < cuX ) { screenLines[cuY].resize(cuX); + } screenLines[cuY].insert(cuX,n,' '); - if ( screenLines[cuY].count() > columns ) + if ( screenLines[cuY].count() > columns ) { screenLines[cuY].resize(columns); + } } void Screen::deleteLines(int n) { - if (n == 0) n = 1; // Default + if (n == 0) { + n = 1; // Default + } scrollUp(cuY,n); } @@ -292,7 +318,9 @@ void Screen::deleteLines(int n) void Screen::insertLines(int n) { - if (n == 0) n = 1; // Default + if (n == 0) { + n = 1; // Default + } scrollDown(cuY,n); } @@ -384,9 +412,12 @@ void Screen::restoreCursor() void Screen::resizeImage(int new_lines, int new_columns) { - if ((new_lines==lines) && (new_columns==columns)) return; + if ((new_lines==lines) && (new_columns==columns)) { + return; + } - if (cuY > new_lines-1) { // attempt to preserve focus and lines + if (cuY > new_lines-1) { + // attempt to preserve focus and lines bmargin = lines-1; //FIXME: margin lost for (int i = 0; i < cuY-(new_lines-1); i++) { addHistLine(); @@ -396,15 +427,18 @@ void Screen::resizeImage(int new_lines, int new_columns) // create new screen lines and copy from old to new - ImageLine* newScreenLines = new ImageLine[new_lines+1]; - for (int i=0; i < qMin(lines-1,new_lines+1) ; i++) + ImageLine * newScreenLines = new ImageLine[new_lines+1]; + for (int i=0; i < qMin(lines-1,new_lines+1) ; i++) { newScreenLines[i]=screenLines[i]; - for (int i=lines; (i > 0) && (i 0) && (i 0) && (i 0) && (i= 0 && count > 0 && startLine + count <= hist->getLines() ); @@ -520,8 +555,9 @@ void Screen::copyFromHistory(Character* dest, int startLine, int count) const hist->getCells(line,0,length,dest + destLineOffset); - for (int column = length; column < columns; column++) + for (int column = length; column < columns; column++) { dest[destLineOffset+column] = defaultChar; + } // invert selected text if (sel_begin !=-1) { @@ -534,7 +570,7 @@ void Screen::copyFromHistory(Character* dest, int startLine, int count) const } } -void Screen::copyFromScreen(Character* dest , int startLine , int count) const +void Screen::copyFromScreen(Character * dest , int startLine , int count) const { Q_ASSERT( startLine >= 0 && count > 0 && startLine + count <= lines ); @@ -549,14 +585,15 @@ void Screen::copyFromScreen(Character* dest , int startLine , int count) const dest[destIndex] = screenLines[srcIndex/columns].value(srcIndex%columns,defaultChar); // invert selected text - if (sel_begin != -1 && isSelected(column,line + hist->getLines())) + if (sel_begin != -1 && isSelected(column,line + hist->getLines())) { reverseRendition(dest[destIndex]); + } } } } -void Screen::getImage( Character* dest, int size, int startLine, int endLine ) const +void Screen::getImage( Character * dest, int size, int startLine, int endLine ) const { Q_ASSERT( startLine >= 0 ); Q_ASSERT( endLine >= startLine && endLine < hist->getLines() + lines ); @@ -564,7 +601,6 @@ void Screen::getImage( Character* dest, int size, int startLine, int endLine ) c const int mergedLines = endLine - startLine + 1; Q_ASSERT( size >= mergedLines * columns ); - Q_UNUSED( size ); const int linesInHistoryBuffer = qBound(0,hist->getLines()-startLine,mergedLines); const int linesInScreenBuffer = mergedLines - linesInHistoryBuffer; @@ -583,14 +619,16 @@ void Screen::getImage( Character* dest, int size, int startLine, int endLine ) c // invert display when in screen mode if (getMode(MODE_Screen)) { - for (int i = 0; i < mergedLines*columns; i++) - reverseRendition(dest[i]); // for reverse display + for (int i = 0; i < mergedLines*columns; i++) { + reverseRendition(dest[i]); // for reverse display + } } // mark the character at the current cursor position int cursorIndex = loc(cuX, cuY + linesInHistoryBuffer); - if (getMode(MODE_Cursor) && cursorIndex < columns*mergedLines) + if (getMode(MODE_Cursor) && cursorIndex < columns*mergedLines) { dest[cursorIndex].rendition |= RE_CURSOR; + } } QVector Screen::getLineProperties( int startLine , int endLine ) const @@ -645,8 +683,9 @@ void Screen::reset(bool clearScreen) setDefaultRendition(); saveCursor(); - if ( clearScreen ) + if ( clearScreen ) { clear(); + } } /*! Clear the entire screen and home the cursor. @@ -664,19 +703,26 @@ void Screen::BackSpace() cuX = qMax(0,cuX-1); // if (BS_CLEARS) image[loc(cuX,cuY)].character = ' '; - if (screenLines[cuY].size() < cuX+1) + if (screenLines[cuY].size() < cuX+1) { screenLines[cuY].resize(cuX+1); + } - if (BS_CLEARS) screenLines[cuY][cuX].character = ' '; + if (BS_CLEARS) { + screenLines[cuY][cuX].character = ' '; + } } void Screen::Tabulate(int n) { // note that TAB is a format effector (does not write ' '); - if (n == 0) n = 1; + if (n == 0) { + n = 1; + } while ((n > 0) && (cuX < columns-1)) { cursorRight(1); - while ((cuX < columns-1) && !tabstops[cuX]) cursorRight(1); + while ((cuX < columns-1) && !tabstops[cuX]) { + cursorRight(1); + } n--; } } @@ -684,22 +730,30 @@ void Screen::Tabulate(int n) void Screen::backTabulate(int n) { // note that TAB is a format effector (does not write ' '); - if (n == 0) n = 1; + if (n == 0) { + n = 1; + } while ((n > 0) && (cuX > 0)) { cursorLeft(1); - while ((cuX > 0) && !tabstops[cuX]) cursorLeft(1); + while ((cuX > 0) && !tabstops[cuX]) { + cursorLeft(1); + } n--; } } void Screen::clearTabStops() { - for (int i = 0; i < columns; i++) tabstops[i] = false; + for (int i = 0; i < columns; i++) { + tabstops[i] = false; + } } void Screen::changeTabStop(bool set) { - if (cuX >= columns) return; + if (cuX >= columns) { + return; + } tabstops[cuX] = set; } @@ -711,7 +765,9 @@ void Screen::initTabStops() // Arrg! The 1st tabstop has to be one longer than the other. // i.e. the kids start counting from 0 instead of 1. // Other programs might behave correctly. Be aware. - for (int i = 0; i < columns; i++) tabstops[i] = (i%8 == 0 && i != 0); + for (int i = 0; i < columns; i++) { + tabstops[i] = (i%8 == 0 && i != 0); + } } /*! @@ -722,7 +778,9 @@ void Screen::initTabStops() void Screen::NewLine() { - if (getMode(MODE_NewLine)) Return(); + if (getMode(MODE_NewLine)) { + Return(); + } index(); } @@ -734,7 +792,9 @@ void Screen::NewLine() void Screen::checkSelection(int from, int to) { - if (sel_begin == -1) return; + if (sel_begin == -1) { + return; + } int scr_TL = loc(0, hist->getLines()); //Clear entire selection if it overlaps region [from, to] if ( (sel_BR > (from+scr_TL) )&&(sel_TL < (to+scr_TL)) ) { @@ -751,15 +811,17 @@ void Screen::ShowCharacter(unsigned short c) int w = konsole_wcwidth(c); - if (w <= 0) + if (w <= 0) { return; + } if (cuX+w > columns) { if (getMode(MODE_Wrap)) { lineProperties[cuY] = (LineProperty)(lineProperties[cuY] | LINE_WRAPPED); NextLine(); - } else + } else { cuX = columns-w; + } } // ensure current line vector has enough elements @@ -772,14 +834,16 @@ void Screen::ShowCharacter(unsigned short c) } } - if (getMode(MODE_Insert)) insertChars(w); + if (getMode(MODE_Insert)) { + insertChars(w); + } lastPos = loc(cuX,cuY); // check if selection is still valid. checkSelection(cuX,cuY); - Character& currentChar = screenLines[cuY][cuX]; + Character & currentChar = screenLines[cuY][cuX]; currentChar.character = c; currentChar.foregroundColor = ef_fg; @@ -791,10 +855,11 @@ void Screen::ShowCharacter(unsigned short c) while (w) { i++; - if ( screenLines[cuY].size() < cuX + i + 1 ) + if ( screenLines[cuY].size() < cuX + i + 1 ) { screenLines[cuY].resize(cuX+i+1); + } - Character& ch = screenLines[cuY][cuX + i]; + Character & ch = screenLines[cuY][cuX + i]; ch.character = 0; ch.foregroundColor = ef_fg; ch.backgroundColor = ef_bg; @@ -841,8 +906,12 @@ void Screen::resetScrolledLines() void Screen::scrollUp(int n) { - if (n == 0) n = 1; // Default - if (tmargin == 0) addHistLine(); // hist.history + if (n == 0) { + n = 1; // Default + } + if (tmargin == 0) { + addHistLine(); // hist.history + } scrollUp(tmargin, n); } @@ -858,7 +927,9 @@ QRect Screen::lastScrolledRegion() const void Screen::scrollUp(int from, int n) { - if (n <= 0 || from + n > bmargin) return; + if (n <= 0 || from + n > bmargin) { + return; + } _scrolledLines -= n; _lastScrolledRegion = QRect(0,tmargin,columns-1,(bmargin-tmargin)); @@ -870,7 +941,9 @@ void Screen::scrollUp(int from, int n) void Screen::scrollDown(int n) { - if (n == 0) n = 1; // Default + if (n == 0) { + n = 1; // Default + } scrollDown(tmargin, n); } @@ -887,9 +960,15 @@ void Screen::scrollDown(int from, int n) _scrolledLines += n; //FIXME: make sure `tmargin', `bmargin', `from', `n' is in bounds. - if (n <= 0) return; - if (from > bmargin) return; - if (from + n > bmargin) n = bmargin - from; + if (n <= 0) { + return; + } + if (from > bmargin) { + return; + } + if (from + n > bmargin) { + n = bmargin - from; + } moveImage(loc(0,from+n),loc(0,from),loc(columns-1,bmargin-n)); clearImage(loc(0,from),loc(columns-1,from+n-1),' '); } @@ -902,14 +981,18 @@ void Screen::setCursorYX(int y, int x) void Screen::setCursorX(int x) { - if (x == 0) x = 1; // Default + if (x == 0) { + x = 1; // Default + } x -= 1; // Adjust cuX = qMax(0,qMin(columns-1, x)); } void Screen::setCursorY(int y) { - if (y == 0) y = 1; // Default + if (y == 0) { + y = 1; // Default + } y -= 1; // Adjust cuY = qMax(0,qMin(lines -1, y + (getMode(MODE_Origin) ? tmargin : 0) )); } @@ -983,12 +1066,14 @@ void Screen::clearImage(int loca, int loce, char c) if ( isDefaultCh && endCol == columns-1 ) { line.resize(startCol); } else { - if (line.size() < endCol + 1) + if (line.size() < endCol + 1) { line.resize(endCol+1); + } - Character* data = line.data(); - for (int i=startCol; i<=endCol; i++) + Character * data = line.data(); + for (int i=startCol; i<=endCol; i++) { data[i]=clearCh; + } } } } @@ -1035,8 +1120,9 @@ void Screen::moveImage(int dest, int sourceBegin, int sourceEnd) if (lastPos != -1) { int diff = dest - sourceBegin; // Scroll by this amount lastPos += diff; - if ((lastPos < 0) || (lastPos >= (lines*columns))) + if ((lastPos < 0) || (lastPos >= (lines*columns))) { lastPos = -1; + } } // Adjust selection to follow scroll. @@ -1049,27 +1135,31 @@ void Screen::moveImage(int dest, int sourceBegin, int sourceEnd) int desta = srca+diff; int deste = srce+diff; - if ((sel_TL >= srca) && (sel_TL <= srce)) + if ((sel_TL >= srca) && (sel_TL <= srce)) { sel_TL += diff; - else if ((sel_TL >= desta) && (sel_TL <= deste)) - sel_BR = -1; // Clear selection (see below) + } else if ((sel_TL >= desta) && (sel_TL <= deste)) { + sel_BR = -1; // Clear selection (see below) + } - if ((sel_BR >= srca) && (sel_BR <= srce)) + if ((sel_BR >= srca) && (sel_BR <= srce)) { sel_BR += diff; - else if ((sel_BR >= desta) && (sel_BR <= deste)) - sel_BR = -1; // Clear selection (see below) + } else if ((sel_BR >= desta) && (sel_BR <= deste)) { + sel_BR = -1; // Clear selection (see below) + } if (sel_BR < 0) { clearSelection(); } else { - if (sel_TL < 0) + if (sel_TL < 0) { sel_TL = 0; + } } - if (beginIsTL) + if (beginIsTL) { sel_begin = sel_TL; - else + } else { sel_begin = sel_BR; + } } } @@ -1142,20 +1232,22 @@ void Screen::setForeColor(int space, int color) { cu_fg = CharacterColor(space, color); - if ( cu_fg.isValid() ) + if ( cu_fg.isValid() ) { effectiveRendition(); - else + } else { setForeColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR); + } } void Screen::setBackColor(int space, int color) { cu_bg = CharacterColor(space, color); - if ( cu_bg.isValid() ) + if ( cu_bg.isValid() ) { effectiveRendition(); - else + } else { setBackColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR); + } } /* ------------------------------------------------------------------------- */ @@ -1171,7 +1263,7 @@ void Screen::clearSelection() sel_begin = -1; } -void Screen::getSelectionStart(int& column , int& line) +void Screen::getSelectionStart(int & column , int & line) { if ( sel_TL != -1 ) { column = sel_TL % columns; @@ -1181,7 +1273,7 @@ void Screen::getSelectionStart(int& column , int& line) line = cuY + getHistLines(); } } -void Screen::getSelectionEnd(int& column , int& line) +void Screen::getSelectionEnd(int & column , int & line) { if ( sel_BR != -1 ) { column = sel_BR % columns; @@ -1197,7 +1289,9 @@ void Screen::setSelectionStart(/*const ScreenCursor& viewCursor ,*/ const int x, sel_begin = loc(x,y); //+histCursor) ; /* FIXME, HACK to correct for x too far to the right... */ - if (x == columns) sel_begin--; + if (x == columns) { + sel_begin--; + } sel_BR = sel_begin; sel_TL = sel_begin; @@ -1207,7 +1301,9 @@ void Screen::setSelectionStart(/*const ScreenCursor& viewCursor ,*/ const int x, void Screen::setSelectionEnd( const int x, const int y) { // kDebug(1211) << "setSelExtentXY(" << x << "," << y << ")"; - if (sel_begin == -1) return; + if (sel_begin == -1) { + return; + } int l = loc(x,y); // + histCursor); if (l < sel_begin) { @@ -1215,7 +1311,9 @@ void Screen::setSelectionEnd( const int x, const int y) sel_BR = sel_begin; } else { /* FIXME, HACK to correct for x too far to the right... */ - if (x == columns) l--; + if (x == columns) { + l--; + } sel_TL = sel_begin; sel_BR = l; @@ -1261,12 +1359,13 @@ bool Screen::isSelectionValid() const return ( sel_TL >= 0 && sel_BR >= 0 ); } -void Screen::writeSelectionToStream(TerminalCharacterDecoder* decoder , +void Screen::writeSelectionToStream(TerminalCharacterDecoder * decoder , bool preserveLineBreaks) { // do nothing if selection is invalid - if ( !isSelectionValid() ) + if ( !isSelectionValid() ) { return; + } int top = sel_TL / columns; int left = sel_TL % columns; @@ -1281,10 +1380,14 @@ void Screen::writeSelectionToStream(TerminalCharacterDecoder* decoder , for (int y=top; y<=bottom; y++) { int start = 0; - if ( y == top || columnmode ) start = left; + if ( y == top || columnmode ) { + start = left; + } int count = -1; - if ( y == bottom || columnmode ) count = right - start + 1; + if ( y == bottom || columnmode ) { + count = right - start + 1; + } const bool appendNewLine = ( y != bottom ); copyLineToStream( y, @@ -1300,7 +1403,7 @@ void Screen::writeSelectionToStream(TerminalCharacterDecoder* decoder , void Screen::copyLineToStream(int line , int start, int count, - TerminalCharacterDecoder* decoder, + TerminalCharacterDecoder * decoder, bool appendNewLine, bool preserveLineBreaks) { @@ -1336,17 +1439,19 @@ void Screen::copyLineToStream(int line , hist->getCells(line,start,count,characterBuffer); - if ( hist->isWrappedLine(line) ) + if ( hist->isWrappedLine(line) ) { currentLineProperties |= LINE_WRAPPED; + } } else { - if ( count == -1 ) + if ( count == -1 ) { count = columns - start; + } assert( count >= 0 ); const int screenLine = line-hist->getLines(); - Character* data = screenLines[screenLine].data(); + Character * data = screenLines[screenLine].data(); int length = screenLines[screenLine].count(); //retrieve line from screen image @@ -1363,10 +1468,11 @@ void Screen::copyLineToStream(int line , //do not decode trailing whitespace characters for (int i=count-1 ; i >= 0; i--) - if (QChar(characterBuffer[i].character).isSpace()) + if (QChar(characterBuffer[i].character).isSpace()) { count--; - else + } else { break; + } // add new line character at end const bool omitLineBreak = (currentLineProperties & LINE_WRAPPED) || @@ -1378,7 +1484,7 @@ void Screen::copyLineToStream(int line , } //decode line and write to text stream - decoder->decodeLine( (Character*) characterBuffer , + decoder->decodeLine( (Character *) characterBuffer , count, currentLineProperties ); } @@ -1397,7 +1503,7 @@ void Screen::copyLineToStream(int line , clearSelection(); }*/ -void Screen::writeToStream(TerminalCharacterDecoder* decoder, int from, int to) +void Screen::writeToStream(TerminalCharacterDecoder * decoder, int from, int to) { sel_begin = loc(0,from); sel_TL = sel_begin; @@ -1431,8 +1537,9 @@ void Screen::addHistLine() // If the history is full, increment the count // of dropped lines - if ( newHistLines == oldHistLines ) + if ( newHistLines == oldHistLines ) { _droppedLines++; + } // Adjust selection for the new point of reference if (newHistLines > oldHistLines) { @@ -1446,23 +1553,27 @@ void Screen::addHistLine() // Scroll selection in history up int top_BR = loc(0, 1+newHistLines); - if (sel_TL < top_BR) + if (sel_TL < top_BR) { sel_TL -= columns; + } - if (sel_BR < top_BR) + if (sel_BR < top_BR) { sel_BR -= columns; + } if (sel_BR < 0) { clearSelection(); } else { - if (sel_TL < 0) + if (sel_TL < 0) { sel_TL = 0; + } } - if (beginIsTL) + if (beginIsTL) { sel_begin = sel_TL; - else + } else { sel_begin = sel_BR; + } } } @@ -1473,14 +1584,14 @@ int Screen::getHistLines() return hist->getLines(); } -void Screen::setScroll(const HistoryType& t , bool copyPreviousScroll) +void Screen::setScroll(const HistoryType & t , bool copyPreviousScroll) { clearSelection(); - if ( copyPreviousScroll ) + if ( copyPreviousScroll ) { hist = t.scroll(hist); - else { - HistoryScroll* oldScroll = hist; + } else { + HistoryScroll * oldScroll = hist; hist = t.scroll(0); delete oldScroll; } @@ -1491,7 +1602,7 @@ bool Screen::hasScroll() return hist->hasScroll(); } -const HistoryType& Screen::getScroll() +const HistoryType & Screen::getScroll() { return hist->getType(); } @@ -1504,8 +1615,9 @@ void Screen::setLineProperty(LineProperty property , bool enable) lineProperties[cuY] = (LineProperty)(lineProperties[cuY] & ~property); } } -void Screen::fillWithDefaultChar(Character* dest, int count) +void Screen::fillWithDefaultChar(Character * dest, int count) { - for (int i=0; igetLines() + lines - 1 + // hist->getLines() + lines - 1 //start - the first column on the line to copy //count - the number of characters on the line to copy //decoder - a decoder which coverts terminal characters (an Character array) into text @@ -557,7 +557,7 @@ private: void copyLineToStream(int line, int start, int count, - TerminalCharacterDecoder* decoder, + TerminalCharacterDecoder * decoder, bool appendNewLine, bool preserveLineBreaks); @@ -579,16 +579,16 @@ private: void initTabStops(); void effectiveRendition(); - void reverseRendition(Character& p) const; + void reverseRendition(Character & p) const; bool isSelectionValid() const; // copies 'count' lines from the screen buffer into 'dest', // starting from 'startLine', where 0 is the first line in the screen buffer - void copyFromScreen(Character* dest, int startLine, int count) const; + void copyFromScreen(Character * dest, int startLine, int count) const; // copies 'count' lines from the history buffer into 'dest', // starting from 'startLine', where 0 is the first line in the history - void copyFromHistory(Character* dest, int startLine, int count) const; + void copyFromHistory(Character * dest, int startLine, int count) const; // screen image ---------------- @@ -596,7 +596,7 @@ private: int columns; typedef QVector ImageLine; // [0..columns] - ImageLine* screenLines; // [lines] + ImageLine * screenLines; // [lines] int _scrolledLines; QRect _lastScrolledRegion; @@ -606,7 +606,7 @@ private: QVarLengthArray lineProperties; // history buffer --------------- - HistoryScroll *hist; + HistoryScroll * hist; // cursor location int cuX; @@ -626,7 +626,7 @@ private: // ---------------------------- - bool* tabstops; + bool * tabstops; // selection ------------------- int sel_begin; // The first location selected. diff --git a/lib/ScreenWindow.cpp b/lib/ScreenWindow.cpp index 44da2d2..5c495f3 100644 --- a/lib/ScreenWindow.cpp +++ b/lib/ScreenWindow.cpp @@ -30,7 +30,7 @@ using namespace Konsole; -ScreenWindow::ScreenWindow(QObject* parent) +ScreenWindow::ScreenWindow(QObject * parent) : QObject(parent) , _windowBuffer(0) , _windowBufferSize(0) @@ -45,19 +45,19 @@ ScreenWindow::~ScreenWindow() { delete[] _windowBuffer; } -void ScreenWindow::setScreen(Screen* screen) +void ScreenWindow::setScreen(Screen * screen) { Q_ASSERT( screen ); _screen = screen; } -Screen* ScreenWindow::screen() const +Screen * ScreenWindow::screen() const { return _screen; } -Character* ScreenWindow::getImage() +Character * ScreenWindow::getImage() { // reallocate internal buffer if the window size has changed int size = windowLines() * windowColumns(); @@ -68,8 +68,9 @@ Character* ScreenWindow::getImage() _bufferNeedsUpdate = true; } - if (!_bufferNeedsUpdate) + if (!_bufferNeedsUpdate) { return _windowBuffer; + } _screen->getImage(_windowBuffer,size, currentLine(),endWindowLine()); @@ -110,8 +111,9 @@ QVector ScreenWindow::getLineProperties() { QVector result = _screen->getLineProperties(currentLine(),endWindowLine()); - if (result.count() != windowLines()) + if (result.count() != windowLines()) { result.resize(windowLines()); + } return result; } @@ -121,12 +123,12 @@ QString ScreenWindow::selectedText( bool preserveLineBreaks ) const return _screen->selectedText( preserveLineBreaks ); } -void ScreenWindow::getSelectionStart( int& column , int& line ) +void ScreenWindow::getSelectionStart( int & column , int & line ) { _screen->getSelectionStart(column,line); line -= currentLine(); } -void ScreenWindow::getSelectionEnd( int& column , int& line ) +void ScreenWindow::getSelectionEnd( int & column , int & line ) { _screen->getSelectionEnd(column,line); line -= currentLine(); @@ -254,10 +256,11 @@ QRect ScreenWindow::scrollRegion() const { bool equalToScreenSize = windowLines() == _screen->getLines(); - if ( atEndOfOutput() && equalToScreenSize ) + if ( atEndOfOutput() && equalToScreenSize ) { return _screen->lastScrolledRegion(); - else + } else { return QRect(0,0,windowColumns(),windowLines()); + } } void ScreenWindow::notifyOutputChanged() diff --git a/lib/ScreenWindow.h b/lib/ScreenWindow.h index f993e13..ab49e5b 100644 --- a/lib/ScreenWindow.h +++ b/lib/ScreenWindow.h @@ -65,13 +65,13 @@ public: * to notify the window when the associated screen has changed and synchronize selection updates * between all views on a session. */ - ScreenWindow(QObject* parent = 0); + ScreenWindow(QObject * parent = 0); virtual ~ScreenWindow(); /** Sets the screen which this window looks onto */ - void setScreen(Screen* screen); + void setScreen(Screen * screen); /** Returns the screen which this window looks onto */ - Screen* screen() const; + Screen * screen() const; /** * Returns the image of characters which are currently visible through this window @@ -80,7 +80,7 @@ public: * The buffer is managed by the ScreenWindow instance and does not need to be * deleted by the caller. */ - Character* getImage(); + Character * getImage(); /** * Returns the line attributes associated with the lines of characters which @@ -128,11 +128,11 @@ public: /** * Retrieves the start of the selection within the window. */ - void getSelectionStart( int& column , int& line ); + void getSelectionStart( int & column , int & line ); /** * Retrieves the end of the selection within the window. */ - void getSelectionEnd( int& column , int& line ); + void getSelectionEnd( int & column , int & line ); /** * Returns true if the character at @p line , @p column is part of the selection. */ @@ -239,8 +239,8 @@ private: int endWindowLine() const; void fillUnusedArea(); - Screen* _screen; // see setScreen() , screen() - Character* _windowBuffer; + Screen * _screen; // see setScreen() , screen() + Character * _windowBuffer; int _windowBufferSize; bool _bufferNeedsUpdate; diff --git a/lib/Session.cpp b/lib/Session.cpp index 771d59d..bafe7f2 100644 --- a/lib/Session.cpp +++ b/lib/Session.cpp @@ -88,8 +88,8 @@ Session::Session() : // SLOT( fireZModemDetected() ) ); connect( _emulation, SIGNAL( changeTabTextColorRequest( int ) ), this, SIGNAL( changeTabTextColorRequest( int ) ) ); - connect( _emulation, SIGNAL(profileChangeCommandReceived(const QString&)), - this, SIGNAL( profileChangeCommandReceived(const QString&)) ); + connect( _emulation, SIGNAL(profileChangeCommandReceived(const QString &)), + this, SIGNAL( profileChangeCommandReceived(const QString &)) ); // TODO // connect( _emulation,SIGNAL(imageSizeChanged(int,int)) , this , // SLOT(onEmulationSizeChange(int,int)) ); @@ -97,10 +97,10 @@ Session::Session() : //connect teletype to emulation backend _shellProcess->setUtf8Mode(_emulation->utf8()); - connect( _shellProcess,SIGNAL(receivedData(const char*,int)),this, - SLOT(onReceiveBlock(const char*,int)) ); - connect( _emulation,SIGNAL(sendData(const char*,int)),_shellProcess, - SLOT(sendData(const char*,int)) ); + connect( _shellProcess,SIGNAL(receivedData(const char *,int)),this, + SLOT(onReceiveBlock(const char *,int)) ); + connect( _emulation,SIGNAL(sendData(const char *,int)),_shellProcess, + SLOT(sendData(const char *,int)) ); connect( _emulation,SIGNAL(lockPtyRequest(bool)),_shellProcess,SLOT(lockPty(bool)) ); connect( _emulation,SIGNAL(useUtf8Request(bool)),_shellProcess,SLOT(setUtf8Mode(bool)) ); @@ -127,15 +127,16 @@ WId Session::windowId() const // top-level window which contains the first view is // returned - if ( _views.count() == 0 ) + if ( _views.count() == 0 ) { return 0; - else { - QWidget* window = _views.first(); + } else { + QWidget * window = _views.first(); Q_ASSERT( window ); - while ( window->parentWidget() != 0 ) + while ( window->parentWidget() != 0 ) { window = window->parentWidget(); + } return window->winId(); } @@ -154,30 +155,30 @@ bool Session::isRunning() const return _shellProcess->isRunning(); } -void Session::setCodec(QTextCodec* codec) +void Session::setCodec(QTextCodec * codec) { emulation()->setCodec(codec); } -void Session::setProgram(const QString& program) +void Session::setProgram(const QString & program) { _program = ShellCommand::expand(program); } -void Session::setInitialWorkingDirectory(const QString& dir) +void Session::setInitialWorkingDirectory(const QString & dir) { _initialWorkingDir = ShellCommand::expand(dir); } -void Session::setArguments(const QStringList& arguments) +void Session::setArguments(const QStringList & arguments) { _arguments = ShellCommand::expand(arguments); } -QList Session::views() const +QList Session::views() const { return _views; } -void Session::addView(TerminalDisplay* widget) +void Session::addView(TerminalDisplay * widget) { Q_ASSERT( !_views.contains(widget) ); @@ -185,12 +186,12 @@ void Session::addView(TerminalDisplay* widget) if ( _emulation != 0 ) { // connect emulation - view signals and slots - connect( widget , SIGNAL(keyPressedSignal(QKeyEvent*)) , _emulation , - SLOT(sendKeyEvent(QKeyEvent*)) ); + connect( widget , SIGNAL(keyPressedSignal(QKeyEvent *)) , _emulation , + SLOT(sendKeyEvent(QKeyEvent *)) ); connect( widget , SIGNAL(mouseSignal(int,int,int,int)) , _emulation , SLOT(sendMouseEvent(int,int,int,int)) ); - connect( widget , SIGNAL(sendStringToEmu(const char*)) , _emulation , - SLOT(sendString(const char*)) ); + connect( widget , SIGNAL(sendStringToEmu(const char *)) , _emulation , + SLOT(sendString(const char *)) ); // allow emulation to notify view when the foreground process // indicates whether or not it is interested in mouse signals @@ -206,23 +207,23 @@ void Session::addView(TerminalDisplay* widget) QObject::connect( widget ,SIGNAL(changedContentSizeSignal(int,int)),this, SLOT(onViewSizeChange(int,int))); - QObject::connect( widget ,SIGNAL(destroyed(QObject*)) , this , - SLOT(viewDestroyed(QObject*)) ); + QObject::connect( widget ,SIGNAL(destroyed(QObject *)) , this , + SLOT(viewDestroyed(QObject *)) ); //slot for close QObject::connect(this, SIGNAL(finished()), widget, SLOT(close())); } -void Session::viewDestroyed(QObject* view) +void Session::viewDestroyed(QObject * view) { - TerminalDisplay* display = (TerminalDisplay*)view; + TerminalDisplay * display = (TerminalDisplay *)view; Q_ASSERT( _views.contains(display) ); removeView(display); } -void Session::removeView(TerminalDisplay* widget) +void Session::removeView(TerminalDisplay * widget) { _views.removeAll(widget); @@ -250,10 +251,12 @@ void Session::removeView(TerminalDisplay* widget) void Session::run() { //check that everything is in place to run the session - if (_program.isEmpty()) + if (_program.isEmpty()) { qDebug() << "Session::run() - program to run not set."; - if (_arguments.isEmpty()) + } + if (_arguments.isEmpty()) { qDebug() << "Session::run() - no command line arguments specified."; + } // Upon a KPty error, there is no description on what that error was... // Check to see if the given program is executable. @@ -261,10 +264,12 @@ void Session::run() // if 'exec' is not specified, fall back to default shell. if that // is not set then fall back to /bin/sh - if ( exec.isEmpty() ) + if ( exec.isEmpty() ) { exec = getenv("SHELL"); - if ( exec.isEmpty() ) + } + if ( exec.isEmpty() ) { exec = "/bin/sh"; + } // if no arguments are specified, fall back to shell QStringList arguments = _arguments.join(QChar(' ')).isEmpty() ? @@ -279,10 +284,11 @@ void Session::run() // QString cwd_save = QDir::currentPath(); QString cwd = QDir::currentPath(); - if (!_initialWorkingDir.isEmpty()) + if (!_initialWorkingDir.isEmpty()) { _shellProcess->setWorkingDirectory(_initialWorkingDir); - else + } else { _shellProcess->setWorkingDirectory(cwd); + } // _shellProcess->setWorkingDirectory(QDir::homePath()); _shellProcess->setXonXoff(_flowControl); @@ -309,7 +315,7 @@ void Session::run() emit started(); } -void Session::setUserTitle( int what, const QString &caption ) +void Session::setUserTitle( int what, const QString & caption ) { //set to true if anything is actually changed (eg. old _nameTitle != new _nameTitle ) bool modified = false; @@ -333,7 +339,7 @@ void Session::setUserTitle( int what, const QString &caption ) QString colorString = caption.section(';',0,0); qDebug() << __FILE__ << __LINE__ << ": setting background colour to " << colorString; QColor backColor = QColor(colorString); - if (backColor.isValid()) {// change color via \033]11;Color\007 + if (backColor.isValid()) { // change color via \033]11;Color\007 if (backColor != _modifiedBackground) { _modifiedBackground = backColor; @@ -374,27 +380,30 @@ void Session::setUserTitle( int what, const QString &caption ) return; } - if ( modified ) + if ( modified ) { emit titleChanged(); + } } QString Session::userTitle() const { return _userTitle; } -void Session::setTabTitleFormat(TabTitleContext context , const QString& format) +void Session::setTabTitleFormat(TabTitleContext context , const QString & format) { - if ( context == LocalTabTitle ) + if ( context == LocalTabTitle ) { _localTabTitleFormat = format; - else if ( context == RemoteTabTitle ) + } else if ( context == RemoteTabTitle ) { _remoteTabTitleFormat = format; + } } QString Session::tabTitleFormat(TabTitleContext context) const { - if ( context == LocalTabTitle ) + if ( context == LocalTabTitle ) { return _localTabTitleFormat; - else if ( context == RemoteTabTitle ) + } else if ( context == RemoteTabTitle ) { return _remoteTabTitleFormat; + } return QString(); } @@ -444,10 +453,12 @@ void Session::activityStateSet(int state) } } - if ( state==NOTIFYACTIVITY && !_monitorActivity ) + if ( state==NOTIFYACTIVITY && !_monitorActivity ) { state = NOTIFYNORMAL; - if ( state==NOTIFYSILENCE && !_monitorSilence ) + } + if ( state==NOTIFYSILENCE && !_monitorSilence ) { state = NOTIFYNORMAL; + } emit stateChanged(state); } @@ -463,7 +474,7 @@ void Session::onEmulationSizeChange(int lines , int columns) void Session::updateTerminalSize() { - QListIterator viewIter(_views); + QListIterator viewIter(_views); int minLines = -1; int minColumns = -1; @@ -476,7 +487,7 @@ void Session::updateTerminalSize() //select largest number of lines and columns that will fit in all visible views while ( viewIter.hasNext() ) { - TerminalDisplay* view = viewIter.next(); + TerminalDisplay * view = viewIter.next(); if ( view->isHidden() == false && view->lines() >= VIEW_LINES_THRESHOLD && view->columns() >= VIEW_COLUMNS_THRESHOLD ) { @@ -528,7 +539,7 @@ void Session::close() } } -void Session::sendText(const QString &text) const +void Session::sendText(const QString & text) const { _emulation->sendText(text); } @@ -540,7 +551,7 @@ Session::~Session() // delete _zmodemProc; } -void Session::setProfileKey(const QString& key) +void Session::setProfileKey(const QString & key) { _profileKey = key; emit profileChanged(key); @@ -560,17 +571,18 @@ void Session::done(int exitStatus) if (!_wantedClose && (exitStatus || _shellProcess->signalled())) { QString message; - if (_shellProcess->normalExit()) + if (_shellProcess->normalExit()) { message.sprintf ("Session '%s' exited with status %d.", _nameTitle.toAscii().data(), exitStatus); - else if (_shellProcess->signalled()) { + } else if (_shellProcess->signalled()) { if (_shellProcess->coreDumped()) { message.sprintf("Session '%s' exited with signal %d and dumped core.", _nameTitle.toAscii().data(), _shellProcess->exitSignal()); } else { message.sprintf("Session '%s' exited with signal %d.", _nameTitle.toAscii().data(), _shellProcess->exitSignal()); } - } else + } else { message.sprintf ("Session '%s' exited unexpectedly.", _nameTitle.toAscii().data()); + } //FIXME: See comments in Session::monitorTimerDone() // KNotification::event("Finished", message , QPixmap(), @@ -580,7 +592,7 @@ void Session::done(int exitStatus) emit finished(); } -Emulation* Session::emulation() const +Emulation * Session::emulation() const { return _emulation; } @@ -595,7 +607,7 @@ QStringList Session::environment() const return _environment; } -void Session::setEnvironment(const QStringList& environment) +void Session::setEnvironment(const QStringList & environment) { _environment = environment; } @@ -605,18 +617,19 @@ int Session::sessionId() const return _sessionId; } -void Session::setKeyBindings(const QString &id) +void Session::setKeyBindings(const QString & id) { _emulation->setKeyBindings(id); } -void Session::setTitle(TitleRole role , const QString& newTitle) +void Session::setTitle(TitleRole role , const QString & newTitle) { if ( title(role) != newTitle ) { - if ( role == NameRole ) + if ( role == NameRole ) { _nameTitle = newTitle; - else if ( role == DisplayedTitleRole ) + } else if ( role == DisplayedTitleRole ) { _displayTitle = newTitle; + } emit titleChanged(); } @@ -624,15 +637,16 @@ void Session::setTitle(TitleRole role , const QString& newTitle) QString Session::title(TitleRole role) const { - if ( role == NameRole ) + if ( role == NameRole ) { return _nameTitle; - else if ( role == DisplayedTitleRole ) + } else if ( role == DisplayedTitleRole ) { return _displayTitle; - else + } else { return QString(); + } } -void Session::setIconName(const QString& iconName) +void Session::setIconName(const QString & iconName) { if ( iconName != _iconName ) { _iconName = iconName; @@ -640,7 +654,7 @@ void Session::setIconName(const QString& iconName) } } -void Session::setIconText(const QString& iconText) +void Session::setIconText(const QString & iconText) { _iconText = iconText; //kDebug(1211)<<"Session setIconText " << _iconText; @@ -656,12 +670,12 @@ QString Session::iconText() const return _iconText; } -void Session::setHistoryType(const HistoryType &hType) +void Session::setHistoryType(const HistoryType & hType) { _emulation->setHistory(hType); } -const HistoryType& Session::historyType() const +const HistoryType & Session::historyType() const { return _emulation->history(); } @@ -702,14 +716,16 @@ void Session::setMonitorActivity(bool _monitor) void Session::setMonitorSilence(bool _monitor) { - if (_monitorSilence==_monitor) + if (_monitorSilence==_monitor) { return; + } _monitorSilence=_monitor; if (_monitorSilence) { _monitorTimer->start(_silenceSeconds*1000); - } else + } else { _monitorTimer->stop(); + } activityStateSet(NOTIFYNORMAL); } @@ -729,13 +745,15 @@ void Session::setAddToUtmp(bool set) void Session::setFlowControlEnabled(bool enabled) { - if (_flowControl == enabled) + if (_flowControl == enabled) { return; + } _flowControl = enabled; - if (_shellProcess) + if (_shellProcess) { _shellProcess->setXonXoff(_flowControl); + } emit flowControlEnabledChanged(enabled); } @@ -856,7 +874,7 @@ void Session::zmodemFinished() } } */ -void Session::onReceiveBlock( const char* buf, int len ) +void Session::onReceiveBlock( const char * buf, int len ) { _emulation->receiveData( buf, len ); emit receivedData( QString::fromLatin1( buf, len ) ); @@ -867,10 +885,11 @@ QSize Session::size() return _emulation->imageSize(); } -void Session::setSize(const QSize& size) +void Session::setSize(const QSize & size) { - if ((size.width() <= 1) || (size.height() <= 1)) + if ((size.width() <= 1) || (size.height() <= 1)) { return; + } emit resizeRequest(size); } @@ -896,32 +915,34 @@ int SessionGroup::masterMode() const { return _masterMode; } -QList SessionGroup::sessions() const +QList SessionGroup::sessions() const { return _sessions.keys(); } -bool SessionGroup::masterStatus(Session* session) const +bool SessionGroup::masterStatus(Session * session) const { return _sessions[session]; } -void SessionGroup::addSession(Session* session) +void SessionGroup::addSession(Session * session) { _sessions.insert(session,false); - QListIterator masterIter(masters()); + QListIterator masterIter(masters()); - while ( masterIter.hasNext() ) + while ( masterIter.hasNext() ) { connectPair(masterIter.next(),session); + } } -void SessionGroup::removeSession(Session* session) +void SessionGroup::removeSession(Session * session) { setMasterStatus(session,false); - QListIterator masterIter(masters()); + QListIterator masterIter(masters()); - while ( masterIter.hasNext() ) + while ( masterIter.hasNext() ) { disconnectPair(masterIter.next(),session); + } _sessions.remove(session); } @@ -932,31 +953,32 @@ void SessionGroup::setMasterMode(int mode) connectAll(false); connectAll(true); } -QList SessionGroup::masters() const +QList SessionGroup::masters() const { return _sessions.keys(true); } void SessionGroup::connectAll(bool connect) { - QListIterator masterIter(masters()); + QListIterator masterIter(masters()); while ( masterIter.hasNext() ) { - Session* master = masterIter.next(); + Session * master = masterIter.next(); - QListIterator otherIter(_sessions.keys()); + QListIterator otherIter(_sessions.keys()); while ( otherIter.hasNext() ) { - Session* other = otherIter.next(); + Session * other = otherIter.next(); if ( other != master ) { - if ( connect ) + if ( connect ) { connectPair(master,other); - else + } else { disconnectPair(master,other); + } } } } } -void SessionGroup::setMasterStatus(Session* session, bool master) +void SessionGroup::setMasterStatus(Session * session, bool master) { bool wasMaster = _sessions[session]; _sessions[session] = master; @@ -966,9 +988,9 @@ void SessionGroup::setMasterStatus(Session* session, bool master) return; } - QListIterator iter(_sessions.keys()); + QListIterator iter(_sessions.keys()); while (iter.hasNext()) { - Session* other = iter.next(); + Session * other = iter.next(); if (other != session) { if (master) { @@ -980,26 +1002,26 @@ void SessionGroup::setMasterStatus(Session* session, bool master) } } -void SessionGroup::connectPair(Session* master , Session* other) +void SessionGroup::connectPair(Session * master , Session * other) { // qDebug() << k_funcinfo; if ( _masterMode & CopyInputToAll ) { qDebug() << "Connection session " << master->nameTitle() << "to" << other->nameTitle(); - connect( master->emulation() , SIGNAL(sendData(const char*,int)) , other->emulation() , - SLOT(sendString(const char*,int)) ); + connect( master->emulation() , SIGNAL(sendData(const char *,int)) , other->emulation() , + SLOT(sendString(const char *,int)) ); } } -void SessionGroup::disconnectPair(Session* master , Session* other) +void SessionGroup::disconnectPair(Session * master , Session * other) { // qDebug() << k_funcinfo; if ( _masterMode & CopyInputToAll ) { qDebug() << "Disconnecting session " << master->nameTitle() << "from" << other->nameTitle(); - disconnect( master->emulation() , SIGNAL(sendData(const char*,int)) , other->emulation() , - SLOT(sendString(const char*,int)) ); + disconnect( master->emulation() , SIGNAL(sendData(const char *,int)) , other->emulation() , + SLOT(sendString(const char *,int)) ); } } diff --git a/lib/Session.h b/lib/Session.h index 161128e..05d962f 100644 --- a/lib/Session.h +++ b/lib/Session.h @@ -90,7 +90,7 @@ public: * @param profileKey A key which can be used to obtain the current * profile settings from the SessionManager */ - void setProfileKey(const QString& profileKey); + void setProfileKey(const QString & profileKey); /** * Returns the profile key associated with this session. * This can be passed to the SessionManager to obtain the current @@ -108,7 +108,7 @@ public: * Views can be removed using removeView(). The session is automatically * closed when the last view is removed. */ - void addView(TerminalDisplay* widget); + void addView(TerminalDisplay * widget); /** * Removes a view from this session. When the last view is removed, * the session will be closed automatically. @@ -116,18 +116,18 @@ public: * @p widget will no longer display output from or send input * to the terminal */ - void removeView(TerminalDisplay* widget); + void removeView(TerminalDisplay * widget); /** * Returns the views connected to this session */ - QList views() const; + QList views() const; /** * Returns the terminal emulation instance being used to encode / decode * characters to / from the process. */ - Emulation* emulation() const; + Emulation * emulation() const; /** * Returns the environment of this session as a list of strings like @@ -139,7 +139,7 @@ public: * @p environment should be a list of strings like * VARIABLE=VALUE */ - void setEnvironment(const QStringList& environment); + void setEnvironment(const QStringList & environment); /** Returns the unique ID for this session. */ int sessionId() const; @@ -172,7 +172,7 @@ public: * followed by a letter. (eg. %d for directory). The dynamic * elements available depend on the @p context */ - void setTabTitleFormat(TabTitleContext context , const QString& format); + void setTabTitleFormat(TabTitleContext context , const QString & format); /** Returns the format used by this session for tab titles. */ QString tabTitleFormat(TabTitleContext context) const; @@ -186,9 +186,9 @@ public: * Sets the command line arguments which the session's program will be passed when * run() is called. */ - void setArguments(const QStringList& arguments); + void setArguments(const QStringList & arguments); /** Sets the program to be executed when run() is called. */ - void setProgram(const QString& program); + void setProgram(const QString & program); /** Returns the session's current working directory. */ QString initialWorkingDirectory() { @@ -199,7 +199,7 @@ public: * Sets the initial working directory for the session when it is run * This has no effect once the session has been started. */ - void setInitialWorkingDirectory( const QString& dir ); + void setInitialWorkingDirectory( const QString & dir ); /** * Sets the type of history store used by this session. @@ -209,11 +209,11 @@ public: * remembered before they are lost and the storage * (in memory, on-disk etc.) used. */ - void setHistoryType(const HistoryType& type); + void setHistoryType(const HistoryType & type); /** * Returns the type of history store used by this session. */ - const HistoryType& historyType() const; + const HistoryType & historyType() const; /** * Clears the history store used by this session. */ @@ -254,7 +254,7 @@ public: * names of available key bindings can be determined using the * KeyboardTranslatorManager class. */ - void setKeyBindings(const QString& id); + void setKeyBindings(const QString & id); /** Returns the name of the key bindings used by this session. */ QString keyBindings() const; @@ -269,7 +269,7 @@ public: }; /** Sets the session's title for the specified @p role to @p title. */ - void setTitle(TitleRole role , const QString& title); + void setTitle(TitleRole role , const QString & title); /** Returns the session's title for the specified @p role. */ QString title(TitleRole role) const; /** Convenience method used to read the name property. Returns title(Session::NameRole). */ @@ -278,12 +278,12 @@ public: } /** Sets the name of the icon associated with this session. */ - void setIconName(const QString& iconName); + void setIconName(const QString & iconName); /** Returns the name of the icon associated with this session. */ QString iconName() const; /** Sets the text of the icon associated with this session. */ - void setIconText(const QString& iconText); + void setIconText(const QString & iconText); /** Returns the text of the icon associated with this session. */ QString iconText() const; @@ -313,7 +313,7 @@ public: /** * Sends @p text to the current foreground terminal program. */ - void sendText(const QString& text) const; + void sendText(const QString & text) const; /** * Returns the process id of the terminal process. @@ -336,10 +336,10 @@ public: * * @param size The size in lines and columns to request. */ - void setSize(const QSize& size); + void setSize(const QSize & size); /** Sets the text codec used by this session's terminal emulation. */ - void setCodec(QTextCodec* codec); + void setCodec(QTextCodec * codec); /** * Sets whether the session has a dark background or not. The session @@ -388,7 +388,7 @@ public slots: * emulation display. For a list of what may be changed see the * Emulation::titleChanged() signal. */ - void setUserTitle( int, const QString &caption ); + void setUserTitle( int, const QString & caption ); signals: @@ -403,13 +403,13 @@ signals: /** * Emitted when output is received from the terminal process. */ - void receivedData( const QString& text ); + void receivedData( const QString & text ); /** Emitted when the session's title has changed. */ void titleChanged(); /** Emitted when the session's profile has changed. */ - void profileChanged(const QString& profile); + void profileChanged(const QString & profile); /** * Emitted when the activity state of this session changes. @@ -420,7 +420,7 @@ signals: void stateChanged(int state); /** Emitted when a bell event occurs in the session. */ - void bellRequest( const QString& message ); + void bellRequest( const QString & message ); /** * Requests that the color the text for any tabs associated with @@ -434,10 +434,10 @@ signals: * Requests that the background color of views on this session * should be changed. */ - void changeBackgroundColorRequest(const QColor&); + void changeBackgroundColorRequest(const QColor &); /** TODO: Document me. */ - void openUrlRequest(const QString& url); + void openUrlRequest(const QString & url); /** TODO: Document me. */ // void zmodemDetected(); @@ -448,7 +448,7 @@ signals: * * @param size The requested window size in terms of lines and columns. */ - void resizeRequest(const QSize& size); + void resizeRequest(const QSize & size); /** * Emitted when a profile change command is received from the terminal. @@ -456,7 +456,7 @@ signals: * @param text The text of the command. This is a string of the form * "PropertyName=Value;PropertyName=Value ..." */ - void profileChangeCommandReceived(const QString& text); + void profileChangeCommandReceived(const QString & text); /** * Emitted when the flow control state changes. @@ -470,7 +470,7 @@ private slots: // void fireZModemDetected(); - void onReceiveBlock( const char* buffer, int len ); + void onReceiveBlock( const char * buffer, int len ); void monitorTimerDone(); void onViewSizeChange(int height, int width); @@ -479,7 +479,7 @@ private slots: void activityStateSet(int); //automatically detach views from sessions when view is destroyed - void viewDestroyed(QObject* view); + void viewDestroyed(QObject * view); // void zmodemReadStatus(); // void zmodemReadAndSendBlock(); @@ -493,10 +493,10 @@ private: int _uniqueIdentifier; - Pty* _shellProcess; - Emulation* _emulation; + Pty * _shellProcess; + Emulation * _emulation; - QList _views; + QList _views; bool _monitorActivity; bool _monitorSilence; @@ -504,7 +504,7 @@ private: bool _masterMode; bool _autoClose; bool _wantedClose; - QTimer* _monitorTimer; + QTimer * _monitorTimer; int _silenceSeconds; @@ -563,12 +563,12 @@ public: ~SessionGroup(); /** Adds a session to the group. */ - void addSession( Session* session ); + void addSession( Session * session ); /** Removes a session from the group. */ - void removeSession( Session* session ); + void removeSession( Session * session ); /** Returns the list of sessions currently in the group. */ - QList sessions() const; + QList sessions() const; /** * Sets whether a particular session is a master within the group. @@ -578,9 +578,9 @@ public: * @param session The session whoose master status should be changed. * @param master True to make this session a master or false otherwise */ - void setMasterStatus( Session* session , bool master ); + void setMasterStatus( Session * session , bool master ); /** Returns the master status of a session. See setMasterStatus() */ - bool masterStatus( Session* session ) const; + bool masterStatus( Session * session ) const; /** * This enum describes the options for propagating certain activity or @@ -608,13 +608,13 @@ public: int masterMode() const; private: - void connectPair(Session* master , Session* other); - void disconnectPair(Session* master , Session* other); + void connectPair(Session * master , Session * other); + void disconnectPair(Session * master , Session * other); void connectAll(bool connect); - QList masters() const; + QList masters() const; // maps sessions to their master status - QHash _sessions; + QHash _sessions; int _masterMode; }; diff --git a/lib/ShellCommand.cpp b/lib/ShellCommand.cpp index ee91ce5..626d8af 100644 --- a/lib/ShellCommand.cpp +++ b/lib/ShellCommand.cpp @@ -30,9 +30,9 @@ using namespace Konsole; // expands environment variables in 'text' // function copied from kdelibs/kio/kio/kurlcompletion.cpp -static bool expandEnv(QString& text); +static bool expandEnv(QString & text); -ShellCommand::ShellCommand(const QString& fullCommand) +ShellCommand::ShellCommand(const QString & fullCommand) { bool inQuotes = false; @@ -44,11 +44,12 @@ ShellCommand::ShellCommand(const QString& fullCommand) const bool isLastChar = ( i == fullCommand.count() - 1 ); const bool isQuote = ( ch == '\'' || ch == '\"' ); - if ( !isLastChar && isQuote ) + if ( !isLastChar && isQuote ) { inQuotes = !inQuotes; - else { - if ( (!ch.isSpace() || inQuotes) && !isQuote ) + } else { + if ( (!ch.isSpace() || inQuotes) && !isQuote ) { builder.append(ch); + } if ( (ch.isSpace() && !inQuotes) || ( i == fullCommand.count()-1 ) ) { _arguments << builder; @@ -57,12 +58,13 @@ ShellCommand::ShellCommand(const QString& fullCommand) } } } -ShellCommand::ShellCommand(const QString& command , const QStringList& arguments) +ShellCommand::ShellCommand(const QString & command , const QStringList & arguments) { _arguments = arguments; - if ( !_arguments.isEmpty() ) + if ( !_arguments.isEmpty() ) { _arguments[0] == command; + } } QString ShellCommand::fullCommand() const { @@ -70,10 +72,11 @@ QString ShellCommand::fullCommand() const } QString ShellCommand::command() const { - if ( !_arguments.isEmpty() ) + if ( !_arguments.isEmpty() ) { return _arguments[0]; - else + } else { return QString(); + } } QStringList ShellCommand::arguments() const { @@ -89,7 +92,7 @@ bool ShellCommand::isAvailable() const Q_ASSERT(0); // not implemented yet return false; } -QStringList ShellCommand::expand(const QStringList& items) +QStringList ShellCommand::expand(const QStringList & items) { QStringList result; @@ -98,7 +101,7 @@ QStringList ShellCommand::expand(const QStringList& items) return result; } -QString ShellCommand::expand(const QString& text) +QString ShellCommand::expand(const QString & text) { QString result = text; expandEnv(result); @@ -111,7 +114,7 @@ QString ShellCommand::expand(const QString& text) * Expand environment variables in text. Escaped '$' characters are ignored. * Return true if any variables were expanded */ -static bool expandEnv( QString &text ) +static bool expandEnv( QString & text ) { // Find all environment variables beginning with '$' // @@ -134,18 +137,20 @@ static bool expandEnv( QString &text ) int pos2 = text.indexOf( QLatin1Char(' '), pos+1 ); int pos_tmp = text.indexOf( QLatin1Char('/'), pos+1 ); - if ( pos2 == -1 || (pos_tmp != -1 && pos_tmp < pos2) ) + if ( pos2 == -1 || (pos_tmp != -1 && pos_tmp < pos2) ) { pos2 = pos_tmp; + } - if ( pos2 == -1 ) + if ( pos2 == -1 ) { pos2 = text.length(); + } // Replace if the variable is terminated by '/' or ' ' // and defined // if ( pos2 >= 0 ) { - int len = pos2 - pos; - QString key = text.mid( pos+1, len-1); + int len = pos2 - pos; + QString key = text.mid( pos+1, len-1); QString value = QString::fromLocal8Bit( ::getenv(key.toLocal8Bit()) ); diff --git a/lib/ShellCommand.h b/lib/ShellCommand.h index 2f30ae0..9211aaa 100644 --- a/lib/ShellCommand.h +++ b/lib/ShellCommand.h @@ -57,11 +57,11 @@ public: * * @param fullCommand The command line to parse. */ - ShellCommand(const QString& fullCommand); + ShellCommand(const QString & fullCommand); /** * Constructs a ShellCommand with the specified @p command and @p arguments. */ - ShellCommand(const QString& command , const QStringList& arguments); + ShellCommand(const QString & command , const QStringList & arguments); /** Returns the command. */ QString command() const; @@ -79,10 +79,10 @@ public: bool isAvailable() const; /** Expands environment variables in @p text .*/ - static QString expand(const QString& text); + static QString expand(const QString & text); /** Expands environment variables in each string in @p list. */ - static QStringList expand(const QStringList& items); + static QStringList expand(const QStringList & items); private: QStringList _arguments; diff --git a/lib/TerminalCharacterDecoder.cpp b/lib/TerminalCharacterDecoder.cpp index 8b70700..8b86661 100644 --- a/lib/TerminalCharacterDecoder.cpp +++ b/lib/TerminalCharacterDecoder.cpp @@ -44,7 +44,7 @@ bool PlainTextDecoder::trailingWhitespace() const { return _includeTrailingWhitespace; } -void PlainTextDecoder::begin(QTextStream* output) +void PlainTextDecoder::begin(QTextStream * output) { _output = output; } @@ -52,7 +52,7 @@ void PlainTextDecoder::end() { _output = 0; } -void PlainTextDecoder::decodeLine(const Character* const characters, int count, LineProperty /*properties*/ +void PlainTextDecoder::decodeLine(const Character * const characters, int count, LineProperty /*properties*/ ) { Q_ASSERT( _output ); @@ -71,10 +71,11 @@ void PlainTextDecoder::decodeLine(const Character* const characters, int count, // line if ( !_includeTrailingWhitespace ) { for (int i = count-1 ; i >= 0 ; i--) { - if ( characters[i].character != ' ' ) + if ( characters[i].character != ' ' ) { break; - else + } else { outputCount--; + } } } @@ -94,7 +95,7 @@ HTMLDecoder::HTMLDecoder() : } -void HTMLDecoder::begin(QTextStream* output) +void HTMLDecoder::begin(QTextStream * output) { _output = output; @@ -121,7 +122,7 @@ void HTMLDecoder::end() } //TODO: Support for LineProperty (mainly double width , double height) -void HTMLDecoder::decodeLine(const Character* const characters, int count, LineProperty /*properties*/ +void HTMLDecoder::decodeLine(const Character * const characters, int count, LineProperty /*properties*/ ) { Q_ASSERT( _output ); @@ -137,8 +138,9 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP if ( characters[i].rendition != _lastRendition || characters[i].foregroundColor != _lastForeColor || characters[i].backgroundColor != _lastBackColor ) { - if ( _innerSpanOpen ) + if ( _innerSpanOpen ) { closeSpan(text); + } _lastRendition = characters[i].rendition; _lastForeColor = characters[i].foregroundColor; @@ -148,12 +150,14 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP QString style; if ( _lastRendition & RE_BOLD || - (_colorTable && characters[i].isBold(_colorTable)) ) + (_colorTable && characters[i].isBold(_colorTable)) ) { style.append("font-weight:bold;"); + } - if ( _lastRendition & RE_UNDERLINE ) + if ( _lastRendition & RE_UNDERLINE ) { style.append("font-decoration:underline;"); + } //colours - a colour table must have been defined first if ( _colorTable ) { @@ -170,21 +174,23 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP } //handle whitespace - if (ch.isSpace()) + if (ch.isSpace()) { spaceCount++; - else + } else { spaceCount = 0; + } //output current character if (spaceCount < 2) { //escape HTML tag characters and just display others as they are - if ( ch == '<' ) + if ( ch == '<' ) { text.append("<"); - else if (ch == '>') + } else if (ch == '>') { text.append(">"); - else + } else { text.append(ch); + } } else { text.append(" "); //HTML truncates multiple spaces, so use a space marker instead } @@ -192,8 +198,9 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP } //close any remaining open inner spans - if ( _innerSpanOpen ) + if ( _innerSpanOpen ) { closeSpan(text); + } //start new line text.append("
"); @@ -201,17 +208,17 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP *_output << text; } -void HTMLDecoder::openSpan(QString& text , const QString& style) +void HTMLDecoder::openSpan(QString & text , const QString & style) { text.append( QString("").arg(style) ); } -void HTMLDecoder::closeSpan(QString& text) +void HTMLDecoder::closeSpan(QString & text) { text.append(""); } -void HTMLDecoder::setColorTable(const ColorEntry* table) +void HTMLDecoder::setColorTable(const ColorEntry * table) { _colorTable = table; } diff --git a/lib/TerminalCharacterDecoder.h b/lib/TerminalCharacterDecoder.h index 79b96ab..bf84c31 100644 --- a/lib/TerminalCharacterDecoder.h +++ b/lib/TerminalCharacterDecoder.h @@ -46,7 +46,7 @@ public: virtual ~TerminalCharacterDecoder() {} /** Begin decoding characters. The resulting text is appended to @p output. */ - virtual void begin(QTextStream* output) = 0; + virtual void begin(QTextStream * output) = 0; /** End decoding. */ virtual void end() = 0; @@ -58,7 +58,7 @@ public: * @param properties Additional properties which affect all characters in the line * @param output The output stream which receives the decoded text */ - virtual void decodeLine(const Character* const characters, + virtual void decodeLine(const Character * const characters, int count, LineProperty properties) = 0; }; @@ -84,16 +84,16 @@ public: */ bool trailingWhitespace() const; - virtual void begin(QTextStream* output); + virtual void begin(QTextStream * output); virtual void end(); - virtual void decodeLine(const Character* const characters, + virtual void decodeLine(const Character * const characters, int count, LineProperty properties); private: - QTextStream* _output; + QTextStream * _output; bool _includeTrailingWhitespace; }; @@ -112,21 +112,21 @@ public: * Sets the colour table which the decoder uses to produce the HTML colour codes in its * output */ - void setColorTable( const ColorEntry* table ); + void setColorTable( const ColorEntry * table ); - virtual void decodeLine(const Character* const characters, + virtual void decodeLine(const Character * const characters, int count, LineProperty properties); - virtual void begin(QTextStream* output); + virtual void begin(QTextStream * output); virtual void end(); private: - void openSpan(QString& text , const QString& style); - void closeSpan(QString& text); + void openSpan(QString & text , const QString & style); + void closeSpan(QString & text); - QTextStream* _output; - const ColorEntry* _colorTable; + QTextStream * _output; + const ColorEntry * _colorTable; bool _innerSpanOpen; quint8 _lastRendition; CharacterColor _lastForeColor; diff --git a/lib/TerminalDisplay.cpp b/lib/TerminalDisplay.cpp index fea68de..f46723a 100644 --- a/lib/TerminalDisplay.cpp +++ b/lib/TerminalDisplay.cpp @@ -81,11 +81,11 @@ bool TerminalDisplay::HAVE_TRANSPARENCY = false; IBMPC (rgb) Black Blue Green Cyan Red Magenta Yellow White */ -ScreenWindow* TerminalDisplay::screenWindow() const +ScreenWindow * TerminalDisplay::screenWindow() const { return _screenWindow; } -void TerminalDisplay::setScreenWindow(ScreenWindow* window) +void TerminalDisplay::setScreenWindow(ScreenWindow * window) { // disconnect existing screen window if any if ( _screenWindow ) { @@ -98,19 +98,21 @@ void TerminalDisplay::setScreenWindow(ScreenWindow* window) //#warning "The order here is not specified - does it matter whether updateImage or updateLineProperties comes first?" connect( _screenWindow , SIGNAL(outputChanged()) , this , SLOT(updateLineProperties()) ); connect( _screenWindow , SIGNAL(outputChanged()) , this , SLOT(updateImage()) ); + connect(_screenWindow, SIGNAL(selectionChanged()), this, SLOT(selectionChanged())); window->setWindowLines(_lines); } } -const ColorEntry* TerminalDisplay::colorTable() const +const ColorEntry * TerminalDisplay::colorTable() const { return _colorTable; } void TerminalDisplay::setColorTable(const ColorEntry table[]) { - for (int i = 0; i < TABLE_COLORS; i++) + for (int i = 0; i < TABLE_COLORS; i++) { _colorTable[i] = table[i]; + } QPalette p = palette(); p.setColor( backgroundRole(), _colorTable[DEFAULT_BACK_COLOR].color ); @@ -144,7 +146,7 @@ static inline bool isLineChar(quint16 c) { return ((c & 0xFF80) == 0x2500); } -static inline bool isLineCharString(const QString& string) +static inline bool isLineCharString(const QString & string) { return (string.length() > 0) && (isLineChar(string.at(0).unicode())); } @@ -152,14 +154,15 @@ static inline bool isLineCharString(const QString& string) // assert for i in [0..31] : vt100extended(vt100_graphics[i]) == i. -unsigned short Konsole::vt100_graphics[32] = { // 0/8 1/9 2/10 3/11 4/12 5/13 6/14 7/15 +unsigned short Konsole::vt100_graphics[32] = { + // 0/8 1/9 2/10 3/11 4/12 5/13 6/14 7/15 0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534, 0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7 }; -void TerminalDisplay::fontChange(const QFont&) +void TerminalDisplay::fontChange(const QFont &) { QFontMetrics fm(font()); _fontHeight = fm.height() + _lineSpacing; @@ -181,8 +184,9 @@ void TerminalDisplay::fontChange(const QFont&) } } - if (_fontWidth < 1) + if (_fontWidth < 1) { _fontWidth=1; + } _fontAscent = fm.ascent(); @@ -191,7 +195,7 @@ void TerminalDisplay::fontChange(const QFont&) update(); } -void TerminalDisplay::setVTFont(const QFont& f) +void TerminalDisplay::setVTFont(const QFont & f) { QFont font = f; @@ -200,8 +204,9 @@ void TerminalDisplay::setVTFont(const QFont& f) if ( metrics.height() < height() && metrics.maxWidth() < width() ) { // hint that text should be drawn without anti-aliasing. // depending on the user's font configuration, this may not be respected - if (!_antialiasText) + if (!_antialiasText) { font.setStyleStrategy( QFont::NoAntialias ); + } // experimental optimization. Konsole assumes that the terminal is using a // mono-spaced font, in which case kerning information should have an effect. @@ -224,7 +229,7 @@ void TerminalDisplay::setFont(const QFont &) /* */ /* ------------------------------------------------------------------------- */ -TerminalDisplay::TerminalDisplay(QWidget *parent) +TerminalDisplay::TerminalDisplay(QWidget * parent) :QWidget(parent) ,_screenWindow(0) ,_allowBell(true) @@ -388,7 +393,7 @@ enum LineEncode { #include "LineFont.h" -static void drawLineChar(QPainter& paint, int x, int y, int w, int h, uchar code) +static void drawLineChar(QPainter & paint, int x, int y, int w, int h, uchar code) { //Calculate cell midpoints, end points. int cx = x + w/2; @@ -399,65 +404,86 @@ static void drawLineChar(QPainter& paint, int x, int y, int w, int h, uchar code quint32 toDraw = LineChars[code]; //Top _lines: - if (toDraw & TopL) + if (toDraw & TopL) { paint.drawLine(cx-1, y, cx-1, cy-2); - if (toDraw & TopC) + } + if (toDraw & TopC) { paint.drawLine(cx, y, cx, cy-2); - if (toDraw & TopR) + } + if (toDraw & TopR) { paint.drawLine(cx+1, y, cx+1, cy-2); + } //Bot _lines: - if (toDraw & BotL) + if (toDraw & BotL) { paint.drawLine(cx-1, cy+2, cx-1, ey); - if (toDraw & BotC) + } + if (toDraw & BotC) { paint.drawLine(cx, cy+2, cx, ey); - if (toDraw & BotR) + } + if (toDraw & BotR) { paint.drawLine(cx+1, cy+2, cx+1, ey); + } //Left _lines: - if (toDraw & LeftT) + if (toDraw & LeftT) { paint.drawLine(x, cy-1, cx-2, cy-1); - if (toDraw & LeftC) + } + if (toDraw & LeftC) { paint.drawLine(x, cy, cx-2, cy); - if (toDraw & LeftB) + } + if (toDraw & LeftB) { paint.drawLine(x, cy+1, cx-2, cy+1); + } //Right _lines: - if (toDraw & RightT) + if (toDraw & RightT) { paint.drawLine(cx+2, cy-1, ex, cy-1); - if (toDraw & RightC) + } + if (toDraw & RightC) { paint.drawLine(cx+2, cy, ex, cy); - if (toDraw & RightB) + } + if (toDraw & RightB) { paint.drawLine(cx+2, cy+1, ex, cy+1); + } //Intersection points. - if (toDraw & Int11) + if (toDraw & Int11) { paint.drawPoint(cx-1, cy-1); - if (toDraw & Int12) + } + if (toDraw & Int12) { paint.drawPoint(cx, cy-1); - if (toDraw & Int13) + } + if (toDraw & Int13) { paint.drawPoint(cx+1, cy-1); + } - if (toDraw & Int21) + if (toDraw & Int21) { paint.drawPoint(cx-1, cy); - if (toDraw & Int22) + } + if (toDraw & Int22) { paint.drawPoint(cx, cy); - if (toDraw & Int23) + } + if (toDraw & Int23) { paint.drawPoint(cx+1, cy); + } - if (toDraw & Int31) + if (toDraw & Int31) { paint.drawPoint(cx-1, cy+1); - if (toDraw & Int32) + } + if (toDraw & Int32) { paint.drawPoint(cx, cy+1); - if (toDraw & Int33) + } + if (toDraw & Int33) { paint.drawPoint(cx+1, cy+1); + } } -void TerminalDisplay::drawLineCharString( QPainter& painter, int x, int y, const QString& str, - const Character* attributes) +void TerminalDisplay::drawLineCharString( QPainter & painter, int x, int y, const QString & str, + const Character * attributes) { - const QPen& currentPen = painter.pen(); + const QPen & currentPen = painter.pen(); if ( attributes->rendition & RE_BOLD ) { QPen boldPen(currentPen); @@ -467,8 +493,9 @@ void TerminalDisplay::drawLineCharString( QPainter& painter, int x, int y, const for (int i=0 ; i < str.length(); i++) { uchar code = str[i].cell(); - if (LineChars[code]) + if (LineChars[code]) { drawLineChar(painter, x + (_fontWidth*i), y, _fontWidth, _fontHeight, code); + } } painter.setPen( currentPen ); @@ -482,16 +509,18 @@ TerminalDisplay::KeyboardCursorShape TerminalDisplay::keyboardCursorShape() cons { return _cursorShape; } -void TerminalDisplay::setKeyboardCursorColor(bool useForegroundColor, const QColor& color) +void TerminalDisplay::setKeyboardCursorColor(bool useForegroundColor, const QColor & color) { - if (useForegroundColor) - _cursorColor = QColor(); // an invalid color means that + if (useForegroundColor) { + _cursorColor = QColor(); // an invalid color means that + } // the foreground color of the // current character should // be used - else + else { _cursorColor = color; + } } QColor TerminalDisplay::keyboardCursorColor() const { @@ -514,7 +543,7 @@ void TerminalDisplay::setOpacity(qreal opacity) _blendColor = color.rgba(); } -void TerminalDisplay::drawBackground(QPainter& painter, const QRect& rect, const QColor& backgroundColor, bool useOpacitySetting ) +void TerminalDisplay::drawBackground(QPainter & painter, const QRect & rect, const QColor & backgroundColor, bool useOpacitySetting ) { // the area of the widget showing the contents of the terminal display is drawn // using the background color from the color scheme set with setColorTable() @@ -545,19 +574,19 @@ void TerminalDisplay::drawBackground(QPainter& painter, const QRect& rect, const painter.fillRect(scrollBarArea,_scrollBar->palette().background()); } -void TerminalDisplay::drawCursor(QPainter& painter, - const QRect& rect, - const QColor& foregroundColor, +void TerminalDisplay::drawCursor(QPainter & painter, + const QRect & rect, + const QColor & foregroundColor, const QColor& /*backgroundColor*/, - bool& invertCharacterColor) + bool & invertCharacterColor) { QRect cursorRect = rect; cursorRect.setHeight(_fontHeight - _lineSpacing - 1); if (!_cursorBlinking) { - if ( _cursorColor.isValid() ) + if ( _cursorColor.isValid() ) { painter.setPen(_cursorColor); - else { + } else { painter.setPen(foregroundColor); } @@ -593,15 +622,16 @@ void TerminalDisplay::drawCursor(QPainter& painter, } } -void TerminalDisplay::drawCharacters(QPainter& painter, - const QRect& rect, - const QString& text, - const Character* style, +void TerminalDisplay::drawCharacters(QPainter & painter, + const QRect & rect, + const QString & text, + const Character * style, bool invertCharacterColor) { // don't draw text which is currently blinking - if ( _blinking && (style->rendition & RE_BLINK) ) + if ( _blinking && (style->rendition & RE_BLINK) ) { return; + } // setup bold and underline bool useBold = style->rendition & RE_BOLD || style->isBold(_colorTable) || font().bold(); @@ -615,7 +645,7 @@ void TerminalDisplay::drawCharacters(QPainter& painter, painter.setFont(font); } - const CharacterColor& textColor = ( invertCharacterColor ? style->backgroundColor : style->foregroundColor ); + const CharacterColor & textColor = ( invertCharacterColor ? style->backgroundColor : style->foregroundColor ); const QColor color = textColor.color(_colorTable); QPen pen = painter.pen(); @@ -636,10 +666,10 @@ void TerminalDisplay::drawCharacters(QPainter& painter, } } -void TerminalDisplay::drawTextFragment(QPainter& painter , - const QRect& rect, - const QString& text, - const Character* style) +void TerminalDisplay::drawTextFragment(QPainter & painter , + const QRect & rect, + const QString & text, + const Character * style) { painter.save(); @@ -648,15 +678,17 @@ void TerminalDisplay::drawTextFragment(QPainter& painter , const QColor backgroundColor = style->backgroundColor.color(_colorTable); // draw background if different from the display's background color - if ( backgroundColor != palette().background().color() ) + if ( backgroundColor != palette().background().color() ) { drawBackground(painter,rect,backgroundColor, false /* do not use transparency */); + } // draw cursor shape if the current character is the cursor // this may alter the foreground and background colors bool invertCharacterColor = false; - if ( style->rendition & RE_CURSOR ) + if ( style->rendition & RE_CURSOR ) { drawCursor(painter,rect,foregroundColor,backgroundColor,invertCharacterColor); + } // draw text drawCharacters(painter,rect,text,style,invertCharacterColor); @@ -705,7 +737,7 @@ void TerminalDisplay::setCursorPos(const int curx, const int cury) // scrolled aligns properly with the character grid - // which has a top left point at (_leftMargin,_topMargin) , // a cell width of _fontWidth and a cell height of _fontHeight). -void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) +void TerminalDisplay::scrollImage(int lines , const QRect & screenWindowRegion) { // if the flow control warning is enabled this will interfere with the // scrolling optimisations and cause artifacts. the simple solution here @@ -725,12 +757,14 @@ void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) || _image == 0 || !region.isValid() || (region.top() + abs(lines)) >= region.bottom() - || this->_lines <= region.height() ) return; + || this->_lines <= region.height() ) { + return; + } QRect scrollRect; - void* firstCharPos = &_image[ region.top() * this->_columns ]; - void* lastCharPos = &_image[ (region.top() + abs(lines)) * this->_columns ]; + void * firstCharPos = &_image[ region.top() * this->_columns ]; + void * lastCharPos = &_image[ (region.top() + abs(lines)) * this->_columns ]; int top = _topMargin + (region.top() * _fontHeight); int linesToMove = region.height() - abs(lines); @@ -744,8 +778,8 @@ void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) //scroll internal image if ( lines > 0 ) { // check that the memory areas that we are going to move are valid - Q_ASSERT( (char*)lastCharPos + bytesToMove < - (char*)(_image + (this->_lines * this->_columns)) ); + Q_ASSERT( (char *)lastCharPos + bytesToMove < + (char *)(_image + (this->_lines * this->_columns)) ); Q_ASSERT( (lines*this->_columns) < _imageSize ); @@ -759,8 +793,8 @@ void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) linesToMove * _fontHeight ); } else { // check that the memory areas that we are going to move are valid - Q_ASSERT( (char*)firstCharPos + bytesToMove < - (char*)(_image + (this->_lines * this->_columns)) ); + Q_ASSERT( (char *)firstCharPos + bytesToMove < + (char *)(_image + (this->_lines * this->_columns)) ); //scroll internal image up memmove( lastCharPos , firstCharPos , bytesToMove ); @@ -795,8 +829,9 @@ QRegion TerminalDisplay::hotSpotRegion() const void TerminalDisplay::processFilters() { - if (!_screenWindow) + if (!_screenWindow) { return; + } QRegion preUpdateHotSpots = hotSpotRegion(); @@ -818,8 +853,9 @@ void TerminalDisplay::processFilters() void TerminalDisplay::updateImage() { - if ( !_screenWindow ) + if ( !_screenWindow ) { return; + } // optimization - scroll the existing image where possible and // avoid expensive text drawing for parts of the image that @@ -828,14 +864,15 @@ void TerminalDisplay::updateImage() _screenWindow->scrollRegion() ); _screenWindow->resetScrollCount(); - Character* const newimg = _screenWindow->getImage(); + Character * const newimg = _screenWindow->getImage(); int lines = _screenWindow->windowLines(); int columns = _screenWindow->windowColumns(); setScroll( _screenWindow->currentLine() , _screenWindow->lineCount() ); - if (!_image) - updateImageSize(); // Create _image + if (!_image) { + updateImageSize(); // Create _image + } Q_ASSERT( this->_usedLines <= this->_lines ); Q_ASSERT( this->_usedColumns <= this->_columns ); @@ -855,8 +892,8 @@ void TerminalDisplay::updateImage() const int linesToUpdate = qMin(this->_lines, qMax(0,lines )); const int columnsToUpdate = qMin(this->_columns,qMax(0,columns)); - QChar *disstrU = new QChar[columnsToUpdate]; - char *dirtyMask = new char[columnsToUpdate+2]; + QChar * disstrU = new QChar[columnsToUpdate]; + char * dirtyMask = new char[columnsToUpdate+2]; QRegion dirtyRegion; // debugging variable, this records the number of lines that are found to @@ -865,8 +902,8 @@ void TerminalDisplay::updateImage() int dirtyLineCount = 0; for (y = 0; y < linesToUpdate; y++) { - const Character* currentLine = &_image[y*this->_columns]; - const Character* const newLine = &newimg[y*columns]; + const Character * currentLine = &_image[y*this->_columns]; + const Character * const newLine = &newimg[y*columns]; bool updateLine = false; @@ -890,21 +927,25 @@ void TerminalDisplay::updateImage() // where characters exceed their cell width. if (dirtyMask[x]) { quint16 c = newLine[x+0].character; - if ( !c ) + if ( !c ) { continue; + } int p = 0; disstrU[p++] = c; //fontMap(c); bool lineDraw = isLineChar(c); bool doubleWidth = (x+1 == columnsToUpdate) ? false : (newLine[x+1].character == 0); cr = newLine[x].rendition; _clipboard = newLine[x].backgroundColor; - if (newLine[x].foregroundColor != cf) cf = newLine[x].foregroundColor; + if (newLine[x].foregroundColor != cf) { + cf = newLine[x].foregroundColor; + } int lln = columnsToUpdate - x; for (len = 1; len < lln; len++) { - const Character& ch = newLine[x+len]; + const Character & ch = newLine[x+len]; - if (!ch.character) - continue; // Skip trailing part of multi-col chars. + if (!ch.character) { + continue; // Skip trailing part of multi-col chars. + } bool nextIsDoubleWidth = (x+len+1 == columnsToUpdate) ? false : (newLine[x+len+1].character == 0); @@ -913,8 +954,9 @@ void TerminalDisplay::updateImage() ch.rendition != cr || !dirtyMask[x+len] || isLineChar(c) != lineDraw || - nextIsDoubleWidth != doubleWidth ) + nextIsDoubleWidth != doubleWidth ) { break; + } disstrU[p++] = c; //fontMap(c); } @@ -922,10 +964,12 @@ void TerminalDisplay::updateImage() QString unistr(disstrU, p); bool saveFixedFont = _fixedFont; - if (lineDraw) + if (lineDraw) { _fixedFont = false; - if (doubleWidth) + } + if (doubleWidth) { _fixedFont = false; + } updateLine = true; @@ -939,8 +983,9 @@ void TerminalDisplay::updateImage() //although both top and bottom halves contain the same characters, only //the top one is actually //drawn. - if (_lineProperties.count() > y) + if (_lineProperties.count() > y) { updateLine |= (_lineProperties[y] & LINE_DOUBLEHEIGHT); + } // if the characters on the line are different in the old and the new _image // then this line must be repainted. @@ -959,7 +1004,7 @@ void TerminalDisplay::updateImage() // replace the line of characters in the old _image with the // current line of the new _image - memcpy((void*)currentLine,(const void*)newLine,columnsToUpdate*sizeof(Character)); + memcpy((void *)currentLine,(const void *)newLine,columnsToUpdate*sizeof(Character)); } // if the new _image is smaller than the previous _image, then ensure that the area @@ -985,7 +1030,9 @@ void TerminalDisplay::updateImage() // update the parts of the display which have changed update(dirtyRegion); - if ( _hasBlinker && !_blinkTimer->isActive()) _blinkTimer->start( BLINK_DELAY ); + if ( _hasBlinker && !_blinkTimer->isActive()) { + _blinkTimer->start( BLINK_DELAY ); + } if (!_hasBlinker && _blinkTimer->isActive()) { _blinkTimer->stop(); _blinking = false; @@ -1029,29 +1076,31 @@ void TerminalDisplay::setBlinkingCursor(bool blink) { _hasBlinkingCursor=blink; - if (blink && !_blinkCursorTimer->isActive()) + if (blink && !_blinkCursorTimer->isActive()) { _blinkCursorTimer->start(BLINK_DELAY); + } if (!blink && _blinkCursorTimer->isActive()) { _blinkCursorTimer->stop(); - if (_cursorBlinking) + if (_cursorBlinking) { blinkCursorEvent(); - else + } else { _cursorBlinking = false; + } } } -void TerminalDisplay::paintEvent( QPaintEvent* pe ) +void TerminalDisplay::paintEvent( QPaintEvent * pe ) { //qDebug("%s %d paintEvent", __FILE__, __LINE__); QPainter paint(this); //qDebug("%s %d paintEvent %d %d", __FILE__, __LINE__, paint.window().top(), paint.window().right()); foreach (QRect rect, (pe->region() & contentsRect()).rects()) { - drawBackground(paint,rect,palette().background().color(), true /* use opacity setting */); + drawBackground(paint,rect,palette().background().color(), true /* use opacity setting */); drawContents(paint, rect); } -// drawBackground(paint,contentsRect(),palette().background().color(), true /* use opacity setting */); +// drawBackground(paint,contentsRect(),palette().background().color(), true /* use opacity setting */); // drawContents(paint, contentsRect()); drawInputMethodPreeditString(paint,preeditRect()); paintFilters(paint); @@ -1061,18 +1110,20 @@ void TerminalDisplay::paintEvent( QPaintEvent* pe ) QPoint TerminalDisplay::cursorPosition() const { - if (_screenWindow) + if (_screenWindow) { return _screenWindow->cursorPosition(); - else + } else { return QPoint(0,0); + } } QRect TerminalDisplay::preeditRect() const { const int preeditLength = string_width(_inputMethodData.preeditString); - if ( preeditLength == 0 ) + if ( preeditLength == 0 ) { return QRect(); + } return QRect(_leftMargin + _fontWidth*cursorPosition().x(), _topMargin + _fontHeight*cursorPosition().y(), @@ -1080,7 +1131,7 @@ QRect TerminalDisplay::preeditRect() const _fontHeight); } -void TerminalDisplay::drawInputMethodPreeditString(QPainter& painter , const QRect& rect) +void TerminalDisplay::drawInputMethodPreeditString(QPainter & painter , const QRect & rect) { if ( _inputMethodData.preeditString.isEmpty() ) { return; @@ -1090,7 +1141,7 @@ void TerminalDisplay::drawInputMethodPreeditString(QPainter& painter , const QRe bool invertColors = false; const QColor background = _colorTable[DEFAULT_BACK_COLOR].color; const QColor foreground = _colorTable[DEFAULT_FORE_COLOR].color; - const Character* style = &_image[loc(cursorPos.x(),cursorPos.y())]; + const Character * style = &_image[loc(cursorPos.x(),cursorPos.y())]; drawBackground(painter,rect,background,true); drawCursor(painter,rect,foreground,background,invertColors); @@ -1099,12 +1150,12 @@ void TerminalDisplay::drawInputMethodPreeditString(QPainter& painter , const QRe _inputMethodData.previousPreeditRect = rect; } -FilterChain* TerminalDisplay::filterChain() const +FilterChain * TerminalDisplay::filterChain() const { return _filterChain; } -void TerminalDisplay::paintFilters(QPainter& painter) +void TerminalDisplay::paintFilters(QPainter & painter) { //qDebug("%s %d paintFilters", __FILE__, __LINE__); @@ -1121,10 +1172,10 @@ void TerminalDisplay::paintFilters(QPainter& painter) // iterate over hotspots identified by the display's currently active filters // and draw appropriate visuals to indicate the presence of the hotspot - QList spots = _filterChain->hotSpots(); - QListIterator iter(spots); + QList spots = _filterChain->hotSpots(); + QListIterator iter(spots); while (iter.hasNext()) { - Filter::HotSpot* spot = iter.next(); + Filter::HotSpot * spot = iter.next(); for ( int line = spot->startLine() ; line <= spot->endLine() ; line++ ) { int startColumn = 0; @@ -1133,17 +1184,20 @@ void TerminalDisplay::paintFilters(QPainter& painter) // display in _columns // ignore whitespace at the end of the lines - while ( QChar(_image[loc(endColumn,line)].character).isSpace() && endColumn > 0 ) + while ( QChar(_image[loc(endColumn,line)].character).isSpace() && endColumn > 0 ) { endColumn--; + } // increment here because the column which we want to set 'endColumn' to // is the first whitespace character at the end of the line endColumn++; - if ( line == spot->startLine() ) + if ( line == spot->startLine() ) { startColumn = spot->startColumn(); - if ( line == spot->endLine() ) + } + if ( line == spot->endLine() ) { endColumn = spot->endColumn(); + } // subtract one pixel from // the right and bottom so that @@ -1181,7 +1235,7 @@ void TerminalDisplay::paintFilters(QPainter& painter) } } } -void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) +void TerminalDisplay::drawContents(QPainter & paint, const QRect & rect) { //qDebug("%s %d drawContents and rect x=%d y=%d w=%d h=%d", __FILE__, __LINE__, rect.x(), rect.y(),rect.width(),rect.height()); @@ -1199,12 +1253,13 @@ void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) int rly = qMin(_usedLines-1, qMax(0, (rect.bottom() - tLy - _topMargin ) / _fontHeight)); const int bufferSize = _usedColumns; - QChar *disstrU = new QChar[bufferSize]; + QChar * disstrU = new QChar[bufferSize]; for (int y = luy; y <= rly; y++) { quint16 c = _image[loc(lux,y)].character; int x = lux; - if (!c && x) - x--; // Search for start of multi-column character + if (!c && x) { + x--; // Search for start of multi-column character + } for (; x <= rlx; x++) { int len = 1; int p = 0; @@ -1213,8 +1268,8 @@ void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) if ( _image[loc(x,y)].rendition & RE_EXTENDED_CHAR ) { // sequence of characters ushort extendedCharLength = 0; - ushort* chars = ExtendedCharTable::instance - .lookupExtendedChar(_image[loc(x,y)].charSequence,extendedCharLength); + ushort * chars = ExtendedCharTable::instance + .lookupExtendedChar(_image[loc(x,y)].charSequence,extendedCharLength); for ( int index = 0 ; index < extendedCharLength ; index++ ) { Q_ASSERT( p < bufferSize ); disstrU[p++] = chars[index]; @@ -1240,20 +1295,25 @@ void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) _image[loc(x+len,y)].rendition == currentRendition && (_image[ qMin(loc(x+len,y)+1,_imageSize) ].character == 0) == doubleWidth && isLineChar( c = _image[loc(x+len,y)].character) == lineDraw) { // Assignment! - if (c) - disstrU[p++] = c; //fontMap(c); - if (doubleWidth) // assert((_image[loc(x+len,y)+1].character == 0)), see above if condition - len++; // Skip trailing part of multi-column character + if (c) { + disstrU[p++] = c; //fontMap(c); + } + if (doubleWidth) { // assert((_image[loc(x+len,y)+1].character == 0)), see above if condition + len++; // Skip trailing part of multi-column character + } len++; } - if ((x+len < _usedColumns) && (!_image[loc(x+len,y)].character)) - len++; // Adjust for trailing part of multi-column character + if ((x+len < _usedColumns) && (!_image[loc(x+len,y)].character)) { + len++; // Adjust for trailing part of multi-column character + } bool save__fixedFont = _fixedFont; - if (lineDraw) + if (lineDraw) { _fixedFont = false; - if (doubleWidth) + } + if (doubleWidth) { _fixedFont = false; + } QString unistr(disstrU,p); if (y < _lineProperties.size()) { @@ -1279,15 +1339,15 @@ void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) //painting does actually start from textArea.topLeft() //(instead of textArea.topLeft() * painter-scale) QMatrix inverted = paint.matrix().inverted(); -// textArea.moveTopLeft( inverted.map(textArea.topLeft()) ); +// textArea.moveTopLeft( inverted.map(textArea.topLeft()) ); textArea.moveCenter( inverted.map(textArea.center()) ); //paint text fragment - drawTextFragment( paint, - textArea, - unistr, - &_image[loc(x,y)] ); //, + drawTextFragment( paint, + textArea, + unistr, + &_image[loc(x,y)] ); //, //0, //!_isPrinting ); @@ -1302,8 +1362,9 @@ void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) //both _lines will have the LINE_DOUBLEHEIGHT attribute. //If the current line has the LINE_DOUBLEHEIGHT attribute, //we can therefore skip the next line - if (_lineProperties[y] & LINE_DOUBLEHEIGHT) + if (_lineProperties[y] & LINE_DOUBLEHEIGHT) { y++; + } } x += len - 1; @@ -1322,7 +1383,7 @@ void TerminalDisplay::blinkEvent() update(); } -QRect TerminalDisplay::imageToWidget(const QRect& imageArea) const +QRect TerminalDisplay::imageToWidget(const QRect & imageArea) const { //qDebug("%s %d imageToWidget", __FILE__, __LINE__); QRect result; @@ -1349,7 +1410,7 @@ void TerminalDisplay::blinkCursorEvent() /* */ /* ------------------------------------------------------------------------- */ -void TerminalDisplay::resizeEvent(QResizeEvent*) +void TerminalDisplay::resizeEvent(QResizeEvent *) { updateImageSize(); } @@ -1363,14 +1424,15 @@ void TerminalDisplay::propagateSize() parentWidget()->setFixedSize(parentWidget()->sizeHint()); return; } - if (_image) + if (_image) { updateImageSize(); + } } void TerminalDisplay::updateImageSize() { //qDebug("%s %d updateImageSize", __FILE__, __LINE__); - Character* oldimg = _image; + Character * oldimg = _image; int oldlin = _lines; int oldcol = _columns; @@ -1383,14 +1445,15 @@ void TerminalDisplay::updateImageSize() if (oldimg) { for (int line = 0; line < lines; line++) { - memcpy((void*)&_image[_columns*line], - (void*)&oldimg[oldcol*line],columns*sizeof(Character)); + memcpy((void *)&_image[_columns*line], + (void *)&oldimg[oldcol*line],columns*sizeof(Character)); } delete[] oldimg; } - if (_screenWindow) + if (_screenWindow) { _screenWindow->setWindowLines(_lines); + } _resizing = (oldlin!=_lines) || (oldcol!=_columns); @@ -1408,11 +1471,11 @@ void TerminalDisplay::updateImageSize() //this allows //TODO: Perhaps it would be better to have separate signals for show and hide instead of using //the same signal as the one for a content size change -void TerminalDisplay::showEvent(QShowEvent*) +void TerminalDisplay::showEvent(QShowEvent *) { emit changedContentSizeSignal(_contentHeight,_contentWidth); } -void TerminalDisplay::hideEvent(QHideEvent*) +void TerminalDisplay::hideEvent(QHideEvent *) { emit changedContentSizeSignal(_contentHeight,_contentWidth); } @@ -1425,8 +1488,9 @@ void TerminalDisplay::hideEvent(QHideEvent*) void TerminalDisplay::scrollBarPositionChanged(int) { - if ( !_screenWindow ) + if ( !_screenWindow ) { return; + } _screenWindow->scrollTo( _scrollBar->value() ); @@ -1468,10 +1532,11 @@ void TerminalDisplay::setScrollBarPosition(ScrollBarPosition position) // return; } - if ( position == NoScrollBar ) + if ( position == NoScrollBar ) { _scrollBar->hide(); - else + } else { _scrollBar->show(); + } _topMargin = _leftMargin = 1; _scrollbarLocation = position; @@ -1480,16 +1545,20 @@ void TerminalDisplay::setScrollBarPosition(ScrollBarPosition position) update(); } -void TerminalDisplay::mousePressEvent(QMouseEvent* ev) +void TerminalDisplay::mousePressEvent(QMouseEvent * ev) { if ( _possibleTripleClick && (ev->button()==Qt::LeftButton) ) { mouseTripleClickEvent(ev); return; } - if ( !contentsRect().contains(ev->pos()) ) return; + if ( !contentsRect().contains(ev->pos()) ) { + return; + } - if ( !_screenWindow ) return; + if ( !_screenWindow ) { + return; + } int charLine; int charColumn; @@ -1534,32 +1603,34 @@ void TerminalDisplay::mousePressEvent(QMouseEvent* ev) } } } else if ( ev->button() == Qt::MidButton ) { - if ( _mouseMarks || (!_mouseMarks && (ev->modifiers() & Qt::ShiftModifier)) ) + if ( _mouseMarks || (!_mouseMarks && (ev->modifiers() & Qt::ShiftModifier)) ) { emitSelection(true,ev->modifiers() & Qt::ControlModifier); - else + } else { emit mouseSignal( 1, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0); + } } else if ( ev->button() == Qt::RightButton ) { if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier)) { emit configureRequest( this, ev->modifiers() & (Qt::ShiftModifier|Qt::ControlModifier), ev->pos() ); - } else + } else { emit mouseSignal( 2, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0); + } } } -QList TerminalDisplay::filterActions(const QPoint& position) +QList TerminalDisplay::filterActions(const QPoint & position) { int charLine, charColumn; getCharacterPosition(position,charLine,charColumn); - Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine,charColumn); + Filter::HotSpot * spot = _filterChain->hotSpotAt(charLine,charColumn); - return spot ? spot->actions() : QList(); + return spot ? spot->actions() : QList(); } -void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) +void TerminalDisplay::mouseMoveEvent(QMouseEvent * ev) { int charLine = 0; int charColumn = 0; @@ -1568,7 +1639,7 @@ void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) // handle filters // change link hot-spot appearance on mouse-over - Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine,charColumn); + Filter::HotSpot * spot = _filterChain->hotSpotAt(charLine,charColumn); if ( spot && spot->type() == Filter::HotSpot::Link) { QRect previousHotspotArea = _mouseOverHotspotArea; _mouseOverHotspotArea.setCoords( qMin(spot->startColumn() , spot->endColumn()) * _fontWidth, @@ -1578,7 +1649,7 @@ void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) // display tooltips when mousing over links // TODO: Extend this to work with filter types other than links - const QString& tooltip = spot->tooltip(); + const QString & tooltip = spot->tooltip(); if ( !tooltip.isEmpty() ) { QToolTip::showText( mapToGlobal(ev->pos()) , tooltip , this , _mouseOverHotspotArea ); } @@ -1591,19 +1662,24 @@ void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) } // for auto-hiding the cursor, we need mouseTracking - if (ev->buttons() == Qt::NoButton ) return; + if (ev->buttons() == Qt::NoButton ) { + return; + } // if the terminal is interested in mouse movements // then emit a mouse movement signal, unless the shift // key is being held down, which overrides this. if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) { int button = 3; - if (ev->buttons() & Qt::LeftButton) + if (ev->buttons() & Qt::LeftButton) { button = 0; - if (ev->buttons() & Qt::MidButton) + } + if (ev->buttons() & Qt::MidButton) { button = 1; - if (ev->buttons() & Qt::RightButton) + } + if (ev->buttons() & Qt::RightButton) { button = 2; + } emit mouseSignal( button, @@ -1634,10 +1710,14 @@ void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) return; } - if (_actSel == 0) return; + if (_actSel == 0) { + return; + } // don't extend selection while pasting - if (ev->buttons() & Qt::MidButton) return; + if (ev->buttons() & Qt::MidButton) { + return; + } extendSelection( ev->pos() ); } @@ -1649,7 +1729,7 @@ void TerminalDisplay::setSelectionEnd() } #endif -void TerminalDisplay::extendSelection(const QPoint& position) +void TerminalDisplay::extendSelection(const QPoint & position) { QPoint pos = position; @@ -1864,10 +1944,11 @@ void TerminalDisplay::extendSelection(const QPoint& position) } } -void TerminalDisplay::mouseReleaseEvent(QMouseEvent* ev) +void TerminalDisplay::mouseReleaseEvent(QMouseEvent * ev) { - if ( !_screenWindow ) + if ( !_screenWindow ) { return; + } int charLine; int charColumn; @@ -1909,41 +1990,50 @@ void TerminalDisplay::mouseReleaseEvent(QMouseEvent* ev) } } -void TerminalDisplay::getCharacterPosition(const QPoint& widgetPoint,int& line,int& column) const +void TerminalDisplay::getCharacterPosition(const QPoint & widgetPoint,int & line,int & column) const { column = (widgetPoint.x() + _fontWidth/2 -contentsRect().left()-_leftMargin) / _fontWidth; line = (widgetPoint.y()-contentsRect().top()-_topMargin) / _fontHeight; - if ( line < 0 ) + if ( line < 0 ) { line = 0; - if ( column < 0 ) + } + if ( column < 0 ) { column = 0; + } - if ( line >= _usedLines ) + if ( line >= _usedLines ) { line = _usedLines-1; + } // the column value returned can be equal to _usedColumns, which // is the position just after the last character displayed in a line. // // this is required so that the user can select characters in the right-most // column (or left-most for right-to-left input) - if ( column > _usedColumns ) + if ( column > _usedColumns ) { column = _usedColumns; + } } void TerminalDisplay::updateLineProperties() { - if ( !_screenWindow ) + if ( !_screenWindow ) { return; + } _lineProperties = _screenWindow->getLineProperties(); } -void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) +void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent * ev) { - if ( ev->button() != Qt::LeftButton) return; - if ( !_screenWindow ) return; + if ( ev->button() != Qt::LeftButton) { + return; + } + if ( !_screenWindow ) { + return; + } int charLine = 0; int charColumn = 0; @@ -1980,9 +2070,9 @@ void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) while ( ((x>0) || (bgnSel.y()>0 && (_lineProperties[bgnSel.y()-1] & LINE_WRAPPED) )) && charClass(_image[i-1].character) == selClass ) { i--; - if (x>0) + if (x>0) { x--; - else { + } else { x=_usedColumns-1; bgnSel.ry()--; } @@ -1997,9 +2087,9 @@ void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) while ( ((x<_usedColumns-1) || (endSel.y()<_usedLines-1 && (_lineProperties[endSel.y()] & LINE_WRAPPED) )) && charClass(_image[i+1].character) == selClass ) { i++; - if (x<_usedColumns-1) + if (x<_usedColumns-1) { x++; - else { + } else { x=0; endSel.ry()++; } @@ -2008,8 +2098,9 @@ void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) endSel.setX(x); // In word selection mode don't select @ (64) if at end of word. - if ( ( QChar( _image[i].character ) == '@' ) && ( ( endSel.x() - bgnSel.x() ) > 0 ) ) + if ( ( QChar( _image[i].character ) == '@' ) && ( ( endSel.x() - bgnSel.x() ) > 0 ) ) { endSel.setX( x - 1 ); + } _actSel = 2; // within selection @@ -2025,14 +2116,15 @@ void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) SLOT(tripleClickTimeout())); } -void TerminalDisplay::wheelEvent( QWheelEvent* ev ) +void TerminalDisplay::wheelEvent( QWheelEvent * ev ) { - if (ev->orientation() != Qt::Vertical) + if (ev->orientation() != Qt::Vertical) { return; + } - if ( _mouseMarks ) + if ( _mouseMarks ) { _scrollBar->event(ev); - else { + } else { int charLine; int charColumn; getCharacterPosition( ev->pos() , charLine , charColumn ); @@ -2049,9 +2141,11 @@ void TerminalDisplay::tripleClickTimeout() _possibleTripleClick=false; } -void TerminalDisplay::mouseTripleClickEvent(QMouseEvent* ev) +void TerminalDisplay::mouseTripleClickEvent(QMouseEvent * ev) { - if ( !_screenWindow ) return; + if ( !_screenWindow ) { + return; + } int charLine; int charColumn; @@ -2066,8 +2160,9 @@ void TerminalDisplay::mouseTripleClickEvent(QMouseEvent* ev) _actSel = 2; // within selection emit isBusySelecting(true); // Keep it steady... - while (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) ) + while (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) ) { _iPntSel.ry()--; + } if (_tripleClickMode == SelectForwardsFromCursor) { // find word boundary start @@ -2080,9 +2175,9 @@ void TerminalDisplay::mouseTripleClickEvent(QMouseEvent* ev) ) && charClass(_image[i-1].character) == selClass ) { i--; - if (x>0) + if (x>0) { x--; - else { + } else { x=_columns-1; _iPntSel.ry()--; } @@ -2095,8 +2190,9 @@ void TerminalDisplay::mouseTripleClickEvent(QMouseEvent* ev) _tripleSelBegin = QPoint( 0, _iPntSel.y() ); } - while (_iPntSel.y()<_lines-1 && (_lineProperties[_iPntSel.y()] & LINE_WRAPPED) ) + while (_iPntSel.y()<_lines-1 && (_lineProperties[_iPntSel.y()] & LINE_WRAPPED) ) { _iPntSel.ry()++; + } _screenWindow->setSelectionEnd( _columns - 1 , _iPntSel.y() ); @@ -2108,8 +2204,9 @@ void TerminalDisplay::mouseTripleClickEvent(QMouseEvent* ev) bool TerminalDisplay::focusNextPrevChild( bool next ) { - if (next) - return false; // This disables changing the active part in konqueror + if (next) { + return false; // This disables changing the active part in konqueror + } // when pressing Tab return QWidget::focusNextPrevChild( next ); } @@ -2118,16 +2215,19 @@ bool TerminalDisplay::focusNextPrevChild( bool next ) int TerminalDisplay::charClass(quint16 ch) const { QChar qch=QChar(ch); - if ( qch.isSpace() ) return ' '; + if ( qch.isSpace() ) { + return ' '; + } - if ( qch.isLetterOrNumber() || _wordCharacters.contains(qch, Qt::CaseInsensitive ) ) + if ( qch.isLetterOrNumber() || _wordCharacters.contains(qch, Qt::CaseInsensitive ) ) { return 'a'; + } // Everything else is weird return 1; } -void TerminalDisplay::setWordCharacters(const QString& wc) +void TerminalDisplay::setWordCharacters(const QString & wc) { _wordCharacters = wc; } @@ -2152,14 +2252,16 @@ bool TerminalDisplay::usesMouse() const void TerminalDisplay::emitSelection(bool useXselection,bool appendReturn) { - if ( !_screenWindow ) + if ( !_screenWindow ) { return; + } // Paste Clipboard by simulating keypress events QString text = QApplication::clipboard()->text(useXselection ? QClipboard::Selection : QClipboard::Clipboard); - if (appendReturn) + if (appendReturn) { text.append("\r"); + } if ( ! text.isEmpty() ) { text.replace("\n", "\r"); QKeyEvent e(QEvent::KeyPress, 0, Qt::NoModifier, text); @@ -2169,15 +2271,16 @@ void TerminalDisplay::emitSelection(bool useXselection,bool appendReturn) } } -void TerminalDisplay::setSelection(const QString& t) +void TerminalDisplay::setSelection(const QString & t) { QApplication::clipboard()->setText(t, QClipboard::Selection); } void TerminalDisplay::copyClipboard() { - if ( !_screenWindow ) + if ( !_screenWindow ) { return; + } QString text = _screenWindow->selectedText(_preserveLineBreaks); QApplication::clipboard()->setText(text); @@ -2205,11 +2308,12 @@ void TerminalDisplay::setFlowControlWarningEnabled( bool enable ) // if the dialog is currently visible and the flow control warning has // been disabled then hide the dialog - if (!enable) + if (!enable) { outputSuspended(false); + } } -void TerminalDisplay::keyPressEvent( QKeyEvent* event ) +void TerminalDisplay::keyPressEvent( QKeyEvent * event ) { //qDebug("%s %d keyPressEvent and key is %d", __FILE__, __LINE__, event->key()); @@ -2265,19 +2369,21 @@ void TerminalDisplay::keyPressEvent( QKeyEvent* event ) if (_hasBlinkingCursor) { _blinkCursorTimer->start(BLINK_DELAY); - if (_cursorBlinking) + if (_cursorBlinking) { blinkCursorEvent(); - else + } else { _cursorBlinking = false; + } } - if ( emitKeyPressSignal ) + if ( emitKeyPressSignal ) { emit keyPressedSignal(event); + } event->accept(); } -void TerminalDisplay::inputMethodEvent( QInputMethodEvent* event ) +void TerminalDisplay::inputMethodEvent( QInputMethodEvent * event ) { QKeyEvent keyEvent(QEvent::KeyPress,0,Qt::NoModifier,event->commitString()); emit keyPressedSignal(&keyEvent); @@ -2315,17 +2421,15 @@ QVariant TerminalDisplay::inputMethodQuery( Qt::InputMethodQuery query ) const case Qt::ImCurrentSelection: return QString(); break; - default: - break; } return QVariant(); } -bool TerminalDisplay::event( QEvent *e ) +bool TerminalDisplay::event( QEvent * e ) { if ( e->type() == QEvent::ShortcutOverride ) { - QKeyEvent* keyEvent = static_cast( e ); + QKeyEvent * keyEvent = static_cast( e ); // a check to see if keyEvent->text() is empty is used // to avoid intercepting the press of the modifier key on its own. @@ -2368,9 +2472,11 @@ void TerminalDisplay::enableBell() _allowBell = true; } -void TerminalDisplay::bell(const QString&) +void TerminalDisplay::bell(const QString &) { - if (_bellMode==NoBell) return; + if (_bellMode==NoBell) { + return; + } //limit the rate at which bells can occur //...mainly for sound effects where rapid bells in sequence @@ -2390,6 +2496,11 @@ void TerminalDisplay::bell(const QString&) } } +void TerminalDisplay::selectionChanged() +{ + emit copyAvailable(_screenWindow->selectedText(false).isEmpty() == false); +} + void TerminalDisplay::swapColorTable() { ColorEntry color = _colorTable[1]; @@ -2513,13 +2624,14 @@ QSize TerminalDisplay::sizeHint() const /* */ /* --------------------------------------------------------------------- */ -void TerminalDisplay::dragEnterEvent(QDragEnterEvent* event) +void TerminalDisplay::dragEnterEvent(QDragEnterEvent * event) { - if (event->mimeData()->hasFormat("text/plain")) + if (event->mimeData()->hasFormat("text/plain")) { event->acceptProposedAction(); + } } -void TerminalDisplay::dropEvent(QDropEvent* event) +void TerminalDisplay::dropEvent(QDropEvent * event) { // KUrl::List urls = KUrl::List::fromMimeData(event->mimeData()); @@ -2560,7 +2672,7 @@ void TerminalDisplay::doDrag() { dragInfo.state = diDragging; dragInfo.dragObject = new QDrag(this); - QMimeData *mimeData = new QMimeData; + QMimeData * mimeData = new QMimeData; mimeData->setText(QApplication::clipboard()->text(QClipboard::Selection)); dragInfo.dragObject->setMimeData(mimeData); dragInfo.dragObject->start(Qt::CopyAction); @@ -2587,7 +2699,7 @@ void TerminalDisplay::outputSuspended(bool suspended) palette.setColor(QPalette::Normal, QPalette::WindowText, QColor(Qt::white)); palette.setColor(QPalette::Normal, QPalette::Window, QColor(Qt::black)); // KColorScheme::adjustForeground(palette,KColorScheme::NeutralText); -// KColorScheme::adjustBackground(palette,KColorScheme::NeutralBackground); +// KColorScheme::adjustBackground(palette,KColorScheme::NeutralBackground); _outputSuspendedLabel->setPalette(palette); _outputSuspendedLabel->setAutoFillBackground(true); _outputSuspendedLabel->setBackgroundRole(QPalette::Base); diff --git a/lib/TerminalDisplay.h b/lib/TerminalDisplay.h index a92532f..e9e5747 100644 --- a/lib/TerminalDisplay.h +++ b/lib/TerminalDisplay.h @@ -71,11 +71,11 @@ class TerminalDisplay : public QWidget public: /** Constructs a new terminal display widget with the specified parent. */ - TerminalDisplay(QWidget *parent=0); + TerminalDisplay(QWidget * parent=0); virtual ~TerminalDisplay(); /** Returns the terminal color palette used by the display. */ - const ColorEntry* colorTable() const; + const ColorEntry * colorTable() const; /** Sets the terminal color palette used by the display. */ void setColorTable(const ColorEntry table[]); /** @@ -128,7 +128,7 @@ public: * To add a new filter to the view, call: * viewWidget->filterChain()->addFilter( filterObject ); */ - FilterChain* filterChain() const; + FilterChain * filterChain() const; /** * Updates the filters in the display's filter chain. This will cause @@ -150,7 +150,7 @@ public: * Returns a list of menu actions created by the filters for the content * at the given @p position. */ - QList filterActions(const QPoint& position); + QList filterActions(const QPoint & position); /** Returns true if the cursor is set to blink or false otherwise. */ bool blinkingCursor() { @@ -167,9 +167,9 @@ public: } /** - * This enum describes the methods for selecting text when - * the user triple-clicks within the display. - */ + * This enum describes the methods for selecting text when + * the user triple-clicks within the display. + */ enum TripleClickMode { /** Select the whole line underneath the cursor. */ SelectWholeLine, @@ -237,7 +237,7 @@ public: * @param color The color to use to draw the cursor. This is only taken into * account if @p useForegroundColor is false. */ - void setKeyboardCursorColor(bool useForegroundColor , const QColor& color); + void setKeyboardCursorColor(bool useForegroundColor , const QColor & color); /** * Returns the color of the keyboard cursor, or an invalid color if the keyboard @@ -297,7 +297,7 @@ public: * @param wc An array of characters which are to be considered parts * of a word ( in addition to letters and numbers ). */ - void setWordCharacters(const QString& wc); + void setWordCharacters(const QString & wc); /** * Returns the characters which are considered part of a word for the * purpose of selecting words in the display with the mouse. @@ -345,7 +345,7 @@ public: NoBell=3 }; - void setSelection(const QString &t); + void setSelection(const QString & t); /** * Reimplemented. Has no effect. Use setVTFont() to change the font @@ -362,7 +362,7 @@ public: * Sets the font used to draw the display. Has no effect if @p font * is larger than the size of the display itself. */ - void setVTFont(const QFont& font); + void setVTFont(const QFont & font); /** * Specified whether anti-aliasing of text in the terminal display @@ -419,9 +419,9 @@ public: * In terms of the model-view paradigm, the ScreenWindow is the model which is rendered * by the TerminalDisplay. */ - void setScreenWindow( ScreenWindow* window ); + void setScreenWindow( ScreenWindow * window ); /** Returns the terminal screen section which is displayed in this widget. See setScreenWindow() */ - ScreenWindow* screenWindow() const; + ScreenWindow * screenWindow() const; static bool HAVE_TRANSPARENCY; @@ -452,19 +452,19 @@ public slots: void pasteSelection(); /** - * Changes whether the flow control warning box should be shown when the flow control - * stop key (Ctrl+S) are pressed. - */ + * Changes whether the flow control warning box should be shown when the flow control + * stop key (Ctrl+S) are pressed. + */ void setFlowControlWarningEnabled(bool enabled); /** - * Causes the widget to display or hide a message informing the user that terminal - * output has been suspended (by using the flow control key combination Ctrl+S) - * - * @param suspended True if terminal output has been suspended and the warning message should - * be shown or false to indicate that terminal output has been resumed and that - * the warning message should disappear. - */ + * Causes the widget to display or hide a message informing the user that terminal + * output has been suspended (by using the flow control key combination Ctrl+S) + * + * @param suspended True if terminal output has been suspended and the warning message should + * be shown or false to indicate that terminal output has been resumed and that + * the warning message should disappear. + */ void outputSuspended(bool suspended); /** @@ -490,14 +490,18 @@ public slots: * Shows a notification that a bell event has occurred in the terminal. * TODO: More documentation here */ - void bell(const QString& message); + void bell(const QString & message); + + void selectionChanged(); signals: + void copyAvailable(bool); + /** * Emitted when the user presses a key whilst the terminal widget has focus. */ - void keyPressedSignal(QKeyEvent *e); + void keyPressedSignal(QKeyEvent * e); /** * Emitted when the user presses the suspend or resume flow control key combinations @@ -524,52 +528,52 @@ signals: * * This can be used to display a context menu. */ - void configureRequest( TerminalDisplay*, int state, const QPoint& position ); + void configureRequest( TerminalDisplay *, int state, const QPoint & position ); void isBusySelecting(bool); - void sendStringToEmu(const char*); + void sendStringToEmu(const char *); protected: virtual bool event( QEvent * ); virtual void paintEvent( QPaintEvent * ); - virtual void showEvent(QShowEvent*); - virtual void hideEvent(QHideEvent*); - virtual void resizeEvent(QResizeEvent*); + virtual void showEvent(QShowEvent *); + virtual void hideEvent(QHideEvent *); + virtual void resizeEvent(QResizeEvent *); - virtual void fontChange(const QFont &font); + virtual void fontChange(const QFont & font); - virtual void keyPressEvent(QKeyEvent* event); - virtual void mouseDoubleClickEvent(QMouseEvent* ev); - virtual void mousePressEvent( QMouseEvent* ); - virtual void mouseReleaseEvent( QMouseEvent* ); - virtual void mouseMoveEvent( QMouseEvent* ); - virtual void extendSelection( const QPoint& pos ); - virtual void wheelEvent( QWheelEvent* ); + virtual void keyPressEvent(QKeyEvent * event); + virtual void mouseDoubleClickEvent(QMouseEvent * ev); + virtual void mousePressEvent( QMouseEvent * ); + virtual void mouseReleaseEvent( QMouseEvent * ); + virtual void mouseMoveEvent( QMouseEvent * ); + virtual void extendSelection( const QPoint & pos ); + virtual void wheelEvent( QWheelEvent * ); virtual bool focusNextPrevChild( bool next ); // drag and drop - virtual void dragEnterEvent(QDragEnterEvent* event); - virtual void dropEvent(QDropEvent* event); + virtual void dragEnterEvent(QDragEnterEvent * event); + virtual void dropEvent(QDropEvent * event); void doDrag(); enum DragState { diNone, diPending, diDragging }; struct _dragInfo { DragState state; QPoint start; - QDrag *dragObject; + QDrag * dragObject; } dragInfo; virtual int charClass(quint16) const; void clearImage(); - void mouseTripleClickEvent(QMouseEvent* ev); + void mouseTripleClickEvent(QMouseEvent * ev); // reimplemented - virtual void inputMethodEvent ( QInputMethodEvent* event ); + virtual void inputMethodEvent ( QInputMethodEvent * event ); virtual QVariant inputMethodQuery( Qt::InputMethodQuery query ) const; protected slots: @@ -594,38 +598,38 @@ private: // divides the part of the display specified by 'rect' into // fragments according to their colors and styles and calls // drawTextFragment() to draw the fragments - void drawContents(QPainter &paint, const QRect &rect); + void drawContents(QPainter & paint, const QRect & rect); // draws a section of text, all the text in this section // has a common color and style - void drawTextFragment(QPainter& painter, const QRect& rect, - const QString& text, const Character* style); + void drawTextFragment(QPainter & painter, const QRect & rect, + const QString & text, const Character * style); // draws the background for a text fragment // if useOpacitySetting is true then the color's alpha value will be set to // the display's transparency (set with setOpacity()), otherwise the background // will be drawn fully opaque - void drawBackground(QPainter& painter, const QRect& rect, const QColor& color, + void drawBackground(QPainter & painter, const QRect & rect, const QColor & color, bool useOpacitySetting); // draws the cursor character - void drawCursor(QPainter& painter, const QRect& rect , const QColor& foregroundColor, - const QColor& backgroundColor , bool& invertColors); + void drawCursor(QPainter & painter, const QRect & rect , const QColor & foregroundColor, + const QColor & backgroundColor , bool & invertColors); // draws the characters or line graphics in a text fragment - void drawCharacters(QPainter& painter, const QRect& rect, const QString& text, - const Character* style, bool invertCharacterColor); + void drawCharacters(QPainter & painter, const QRect & rect, const QString & text, + const Character * style, bool invertCharacterColor); // draws a string of line graphics - void drawLineCharString(QPainter& painter, int x, int y, - const QString& str, const Character* attributes); + void drawLineCharString(QPainter & painter, int x, int y, + const QString & str, const Character * attributes); // draws the preedit string for input methods - void drawInputMethodPreeditString(QPainter& painter , const QRect& rect); + void drawInputMethodPreeditString(QPainter & painter , const QRect & rect); // -- // maps an area in the character image to an area on the widget - QRect imageToWidget(const QRect& imageArea) const; + QRect imageToWidget(const QRect & imageArea) const; // maps a point on the widget to the position ( ie. line and column ) // of the character at that point. - void getCharacterPosition(const QPoint& widgetPoint,int& line,int& column) const; + void getCharacterPosition(const QPoint & widgetPoint,int & line,int & column) const; // the area where the preedit string for input methods will be draw QRect preeditRect() const; @@ -640,14 +644,14 @@ private: // 'region' is the part of the image to scroll - currently only // the top, bottom and height of 'region' are taken into account, // the left and right are ignored. - void scrollImage(int lines , const QRect& region); + void scrollImage(int lines , const QRect & region); void calcGeometry(); void propagateSize(); void updateImageSize(); void makeImage(); - void paintFilters(QPainter& painter); + void paintFilters(QPainter & painter); // returns a region covering all of the areas of the widget which contain // a hotspot @@ -662,7 +666,7 @@ private: bool _allowBell; - QGridLayout* _gridLayout; + QGridLayout * _gridLayout; bool _fixedFont; // has fixed pitch int _fontHeight; // height @@ -685,7 +689,7 @@ private: int _contentHeight; int _contentWidth; - Character* _image; // [lines][columns] + Character * _image; // [lines][columns] // only the area [usedLines][usedColumns] in the image contains valid data int _imageSize; @@ -709,8 +713,8 @@ private: bool _preserveLineBreaks; bool _columnSelectionMode; - QClipboard* _clipboard; - QScrollBar* _scrollBar; + QClipboard * _clipboard; + QScrollBar * _scrollBar; ScrollBarPosition _scrollbarLocation; QString _wordCharacters; int _bellMode; @@ -722,8 +726,8 @@ private: bool _ctrlDrag; // require Ctrl key for drag TripleClickMode _tripleClickMode; bool _isFixedSize; //Columns / lines are locked. - QTimer* _blinkTimer; // active when hasBlinker - QTimer* _blinkCursorTimer; // active when hasBlinkingCursor + QTimer * _blinkTimer; // active when hasBlinker + QTimer * _blinkCursorTimer; // active when hasBlinkingCursor // KMenu* _drop; QString _dropText; @@ -733,14 +737,14 @@ private: // after QApplication::doubleClickInterval() delay - QLabel* _resizeWidget; - QTimer* _resizeTimer; + QLabel * _resizeWidget; + QTimer * _resizeTimer; bool _flowControlWarningEnabled; //widgets related to the warning message that appears when the user presses Ctrl+S to suspend //terminal output - informing them what has happened and how to resume output - QLabel* _outputSuspendedLabel; + QLabel * _outputSuspendedLabel; uint _lineSpacing; @@ -752,7 +756,7 @@ private: // list of filters currently applied to the display. used for links and // search highlight - TerminalImageFilterChain* _filterChain; + TerminalImageFilterChain * _filterChain; QRect _mouseOverHotspotArea; KeyboardCursorShape _cursorShape; diff --git a/lib/Vt102Emulation.cpp b/lib/Vt102Emulation.cpp index 9fbebdc..d467138 100644 --- a/lib/Vt102Emulation.cpp +++ b/lib/Vt102Emulation.cpp @@ -251,16 +251,32 @@ void Vt102Emulation::pushToToken(int cc) void Vt102Emulation::initTokenizer() { int i; - quint8* s; - for (i = 0; i < 256; i++) tbl[ i] = 0; - for (i = 0; i < 32; i++) tbl[ i] |= CTL; - for (i = 32; i < 256; i++) tbl[ i] |= CHR; - for (s = (quint8*)"@ABCDGHILMPSTXZcdfry"; *s; s++) tbl[*s] |= CPN; + quint8 * s; + for (i = 0; i < 256; i++) { + tbl[ i] = 0; + } + for (i = 0; i < 32; i++) { + tbl[ i] |= CTL; + } + for (i = 32; i < 256; i++) { + tbl[ i] |= CHR; + } + for (s = (quint8 *)"@ABCDGHILMPSTXZcdfry"; *s; s++) { + tbl[*s] |= CPN; + } // resize = \e[8;;t - for (s = (quint8*)"t"; *s; s++) tbl[*s] |= CPS; - for (s = (quint8*)"0123456789" ; *s; s++) tbl[*s] |= DIG; - for (s = (quint8*)"()+*%" ; *s; s++) tbl[*s] |= SCS; - for (s = (quint8*)"()+*#[]%" ; *s; s++) tbl[*s] |= GRP; + for (s = (quint8 *)"t"; *s; s++) { + tbl[*s] |= CPS; + } + for (s = (quint8 *)"0123456789" ; *s; s++) { + tbl[*s] |= DIG; + } + for (s = (quint8 *)"()+*%" ; *s; s++) { + tbl[*s] |= SCS; + } + for (s = (quint8 *)"()+*#[]%" ; *s; s++) { + tbl[*s] |= GRP; + } resetToken(); } @@ -300,13 +316,18 @@ void Vt102Emulation::initTokenizer() void Vt102Emulation::receiveChar(int cc) { int i; - if (cc == 127) return; //VT100: ignore. + if (cc == 127) { + return; //VT100: ignore. + } - if (ces( CTL)) { // DEC HACK ALERT! Control Characters are allowed *within* esc sequences in VT100 + if (ces( CTL)) { + // DEC HACK ALERT! Control Characters are allowed *within* esc sequences in VT100 // This means, they do neither a resetToken nor a pushToToken. Some of them, do // of course. Guess this originates from a weakly layered handling of the X-on // X-off protocol, which comes really below this level. - if (cc == CNTL('X') || cc == CNTL('Z') || cc == ESC) resetToken(); //VT100: CAN or SUB + if (cc == CNTL('X') || cc == CNTL('Z') || cc == ESC) { + resetToken(); //VT100: CAN or SUB + } if (cc != ESC) { tau( TY_CTL(cc+'@' ), 0, 0); return; @@ -315,7 +336,7 @@ void Vt102Emulation::receiveChar(int cc) pushToToken(cc); // advance the state - int* s = pbuf; + int * s = pbuf; int p = ppos; if (getMode(MODE_Ansi)) { // decide on proper action @@ -397,12 +418,14 @@ void Vt102Emulation::receiveChar(int cc) if ( epp( )) { tau( TY_CSI_PR(cc,argv[i]), 0, 0); } else if (egt( )) { - tau( TY_CSI_PG(cc ), 0, 0); // spec. case for ESC]>0c or ESC]>c - } else if (cc == 'm' && argc - i >= 4 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 2) { // ESC[ ... 48;2;;; ... m -or- ESC[ ... 38;2;;; ... m + tau( TY_CSI_PG(cc ), 0, 0); // spec. case for ESC]>0c or ESC]>c + } else if (cc == 'm' && argc - i >= 4 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 2) { + // ESC[ ... 48;2;;; ... m -or- ESC[ ... 38;2;;; ... m i += 2; tau( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_RGB, (argv[i] << 16) | (argv[i+1] << 8) | argv[i+2]); i += 2; - } else if (cc == 'm' && argc - i >= 2 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 5) { // ESC[ ... 48;5; ... m -or- ESC[ ... 38;5; ... m + } else if (cc == 'm' && argc - i >= 2 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 5) { + // ESC[ ... 48;5; ... m -or- ESC[ ... 38;5; ... m i += 2; tau( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_256, argv[i]); } else { @@ -410,14 +433,20 @@ void Vt102Emulation::receiveChar(int cc) } resetToken(); } else { // mode VT52 - if (lec(1,0,ESC)) return; + if (lec(1,0,ESC)) { + return; + } if (les(1,0,CHR)) { tau( TY_CHR( ), s[0], 0); resetToken(); return; } - if (lec(2,1,'Y')) return; - if (lec(3,1,'Y')) return; + if (lec(2,1,'Y')) { + return; + } + if (lec(3,1,'Y')) { + return; + } if (p < 4) { tau( TY_VT52(s[1] ), 0, 0); resetToken(); @@ -432,14 +461,17 @@ void Vt102Emulation::receiveChar(int cc) void Vt102Emulation::XtermHack() { int i,arg = 0; - for (i = 2; i < ppos && '0'<=pbuf[i] && pbuf[i]<'9' ; i++) + for (i = 2; i < ppos && '0'<=pbuf[i] && pbuf[i]<'9' ; i++) { arg = 10*arg + (pbuf[i]-'0'); + } if (pbuf[i] != ';') { ReportErrorToken(); return; } - QChar *str = new QChar[ppos-i-2]; - for (int j = 0; j < ppos-i-2; j++) str[j] = pbuf[i+1+j]; + QChar * str = new QChar[ppos-i-2]; + for (int j = 0; j < ppos-i-2; j++) { + str[j] = pbuf[i+1+j]; + } QString unistr(str,ppos-i-2); // arg == 1 doesn't change the title. In XTerm it only changes the icon name @@ -490,9 +522,13 @@ void Vt102Emulation::tau( int token, int p, int q ) printf("%c", (p < 128) ? p : '?'); break; case 1: - if (A == 'J') printf("\r"); - else if (A == 'M') printf("\n"); - else printf("CTL-%c ", (token>>8)&0xff); + if (A == 'J') { + printf("\r"); + } else if (A == 'M') { + printf("\n"); + } else { + printf("CTL-%c ", (token>>8)&0xff); + } break; case 2: printf("ESC-%c ", (token>>8)&0xff); @@ -1332,12 +1368,13 @@ void Vt102Emulation::clearScreenAndSetColumns(int columnCount) /*! */ -void Vt102Emulation::sendString(const char* s , int length) +void Vt102Emulation::sendString(const char * s , int length) { - if ( length >= 0 ) + if ( length >= 0 ) { emit sendData(s,length); - else + } else { emit sendData(s,strlen(s)); + } } // Replies ----------------------------------------------------------------- -- @@ -1369,19 +1406,21 @@ void Vt102Emulation::reportTerminalType() // VT100: ^[[?1;2c // VT101: ^[[?1;0c // VT102: ^[[?6v - if (getMode(MODE_Ansi)) - sendString("\033[?1;2c"); // I'm a VT100 - else - sendString("\033/Z"); // I'm a VT52 + if (getMode(MODE_Ansi)) { + sendString("\033[?1;2c"); // I'm a VT100 + } else { + sendString("\033/Z"); // I'm a VT52 + } } void Vt102Emulation::reportSecondaryAttributes() { // Seconday device attribute response (Request was: ^[[>0c or ^[[>c) - if (getMode(MODE_Ansi)) - sendString("\033[>0;115;0c"); // Why 115? ;) - else - sendString("\033/Z"); // FIXME I don't think VT52 knows about it but kept for + if (getMode(MODE_Ansi)) { + sendString("\033[>0;115;0c"); // Why 115? ;) + } else { + sendString("\033/Z"); // FIXME I don't think VT52 knows about it but kept for + } // konsoles backward compatibility. } @@ -1425,21 +1464,26 @@ void Vt102Emulation::reportAnswerBack() or a general mouse release (3). eventType represents the kind of mouse action that occurred: - 0 = Mouse button press or release - 1 = Mouse drag + 0 = Mouse button press or release + 1 = Mouse drag */ void Vt102Emulation::sendMouseEvent( int cb, int cx, int cy , int eventType ) { char tmp[20]; - if ( cx<1 || cy<1 ) return; + if ( cx<1 || cy<1 ) { + return; + } // normal buttons are passed as 0x20 + button, // mouse wheel (buttons 4,5) as 0x5c + button - if (cb >= 4) cb += 0x3c; + if (cb >= 4) { + cb += 0x3c; + } //Mouse motion handling - if ( (getMode(MODE_Mouse1002) || getMode(MODE_Mouse1003)) && eventType == 1 ) - cb += 0x20; //add 32 to signify motion event + if ( (getMode(MODE_Mouse1002) || getMode(MODE_Mouse1003)) && eventType == 1 ) { + cb += 0x20; //add 32 to signify motion event + } sprintf(tmp,"\033[M%c%c%c",cb+0x20,cx+0x20,cy+0x20); sendString(tmp); @@ -1450,7 +1494,7 @@ void Vt102Emulation::sendMouseEvent( int cb, int cx, int cy , int eventType ) #define encodeMode(M,B) BITS(B,getMode(M)) #define encodeStat(M,B) BITS(B,((ev->modifiers() & (M)) == (M))) -void Vt102Emulation::sendText( const QString& text ) +void Vt102Emulation::sendText( const QString & text ) { if (!text.isEmpty()) { QKeyEvent event(QEvent::KeyPress, @@ -1462,16 +1506,24 @@ void Vt102Emulation::sendText( const QString& text ) } -void Vt102Emulation::sendKeyEvent( QKeyEvent* event ) +void Vt102Emulation::sendKeyEvent( QKeyEvent * event ) { Qt::KeyboardModifiers modifiers = event->modifiers(); KeyboardTranslator::States states = KeyboardTranslator::NoState; // get current states - if ( getMode(MODE_NewLine) ) states |= KeyboardTranslator::NewLineState; - if ( getMode(MODE_Ansi) ) states |= KeyboardTranslator::AnsiState; - if ( getMode(MODE_AppCuKeys)) states |= KeyboardTranslator::CursorKeysState; - if ( getMode(MODE_AppScreen)) states |= KeyboardTranslator::AlternateScreenState; + if ( getMode(MODE_NewLine) ) { + states |= KeyboardTranslator::NewLineState; + } + if ( getMode(MODE_Ansi) ) { + states |= KeyboardTranslator::AnsiState; + } + if ( getMode(MODE_AppCuKeys)) { + states |= KeyboardTranslator::CursorKeysState; + } + if ( getMode(MODE_AppScreen)) { + states |= KeyboardTranslator::AlternateScreenState; + } // lookup key binding if ( _keyTranslator ) { @@ -1496,13 +1548,15 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent* event ) } if ( entry.command() != KeyboardTranslator::NoCommand ) { - if (entry.command() & KeyboardTranslator::EraseCommand) + if (entry.command() & KeyboardTranslator::EraseCommand) { textToSend += getErase(); + } // TODO command handling } else if ( !entry.text().isEmpty() ) { textToSend += _codec->fromUnicode(entry.text(true,modifiers)); - } else + } else { textToSend += _codec->fromUnicode(event->text()); + } sendData( textToSend.constData() , textToSend.length() ); } else { @@ -1548,8 +1602,12 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent* event ) unsigned short Vt102Emulation::applyCharset(unsigned short c) { - if (CHARSET.graphic && 0x5f <= c && c <= 0x7e) return vt100_graphics[c-0x5f]; - if (CHARSET.pound && c == '#' ) return 0xa3; //This mode is obsolete + if (CHARSET.graphic && 0x5f <= c && c <= 0x7e) { + return vt100_graphics[c-0x5f]; + } + if (CHARSET.pound && c == '#' ) { + return 0xa3; //This mode is obsolete + } return c; } @@ -1571,7 +1629,7 @@ void Vt102Emulation::resetCharset(int scrno) _charset[scrno].pound = false; } -void Vt102Emulation::setCharset(int n, int cs) // on both screens. +void Vt102Emulation::setCharset(int n, int cs) // on both screens. { _charset[0].charset[n&3] = cs; useCharset(_charset[0].cu_cs); @@ -1716,10 +1774,11 @@ void Vt102Emulation::saveMode(int m) void Vt102Emulation::restoreMode(int m) { - if (_saveParm.mode[m]) + if (_saveParm.mode[m]) { setMode(m); - else + } else { resetMode(m); + } } bool Vt102Emulation::getMode(int m) @@ -1733,10 +1792,11 @@ char Vt102Emulation::getErase() const Qt::Key_Backspace, 0, 0); - if ( entry.text().count() > 0 ) + if ( entry.text().count() > 0 ) { return entry.text()[0]; - else + } else { return '\b'; + } } /* ------------------------------------------------------------------------- */ @@ -1753,16 +1813,17 @@ char Vt102Emulation::getErase() const \sa ReportErrorToken */ -static void hexdump(int* s, int len) +static void hexdump(int * s, int len) { int i; for (i = 0; i < len; i++) { - if (s[i] == '\\') + if (s[i] == '\\') { printf("\\\\"); - else if ((s[i]) > 32 && s[i] < 127) + } else if ((s[i]) > 32 && s[i] < 127) { printf("%c",s[i]); - else + } else { printf("\\%04x(hex)",s[i]); + } } } diff --git a/lib/Vt102Emulation.h b/lib/Vt102Emulation.h index 5498f03..a70f8b1 100644 --- a/lib/Vt102Emulation.h +++ b/lib/Vt102Emulation.h @@ -94,9 +94,9 @@ public: public slots: // reimplemented - virtual void sendString(const char*,int length = -1); - virtual void sendText(const QString& text); - virtual void sendKeyEvent(QKeyEvent*); + virtual void sendString(const char *,int length = -1); + virtual void sendText(const QString & text); + virtual void sendKeyEvent(QKeyEvent *); virtual void sendMouseEvent( int buttons, int column, int line , int eventType ); protected: @@ -181,7 +181,7 @@ private: //these calls occur when certain escape sequences are seen in the //output from the terminal QHash _pendingTitleUpdates; - QTimer* _titleUpdateTimer; + QTimer * _titleUpdateTimer; }; diff --git a/lib/k3process.cpp b/lib/k3process.cpp index 12b508e..28bcade 100644 --- a/lib/k3process.cpp +++ b/lib/k3process.cpp @@ -88,7 +88,7 @@ public: bool addUtmp : 1; bool useShell : 1; - KPty *pty; + KPty * pty; int priority; @@ -102,7 +102,7 @@ public: // public member functions // ///////////////////////////// -K3Process::K3Process( QObject* parent ) +K3Process::K3Process( QObject * parent ) : QObject( parent ), run_mode(NotifyOnExit), runs(false), @@ -128,13 +128,13 @@ K3Process::K3Process( QObject* parent ) } void -K3Process::setEnvironment(const QString &name, const QString &value) +K3Process::setEnvironment(const QString & name, const QString & value) { d->env.insert(name, value); } void -K3Process::setWorkingDirectory(const QString &dir) +K3Process::setWorkingDirectory(const QString & dir) { d->wd = dir; } @@ -170,11 +170,13 @@ bool K3Process::setPriority(int prio) { if (runs) { - if (setpriority(PRIO_PROCESS, pid_, prio)) + if (setpriority(PRIO_PROCESS, pid_, prio)) { return false; + } } else { - if (prio > 19 || prio < (geteuid() ? getpriority(PRIO_PROCESS, 0) : -20)) + if (prio > 19 || prio < (geteuid() ? getpriority(PRIO_PROCESS, 0) : -20)) { return false; + } } d->priority = prio; return true; @@ -182,8 +184,9 @@ K3Process::setPriority(int prio) K3Process::~K3Process() { - if (run_mode != DontCare) + if (run_mode != DontCare) { kill(SIGKILL); + } detach(); delete d->pty; @@ -203,31 +206,32 @@ void K3Process::detach() } } -void K3Process::setBinaryExecutable(const char *filename) +void K3Process::setBinaryExecutable(const char * filename) { d->executable = filename; } -K3Process &K3Process::operator<<(const QStringList& args) +K3Process & K3Process::operator<<(const QStringList & args) { QStringList::ConstIterator it = args.begin(); - for ( ; it != args.end() ; ++it ) + for ( ; it != args.end() ; ++it ) { arguments.append(QFile::encodeName(*it)); + } return *this; } -K3Process &K3Process::operator<<(const QByteArray& arg) +K3Process & K3Process::operator<<(const QByteArray & arg) { return operator<< (arg.data()); } -K3Process &K3Process::operator<<(const char* arg) +K3Process & K3Process::operator<<(const char * arg) { arguments.append(arg); return *this; } -K3Process &K3Process::operator<<(const QString& arg) +K3Process & K3Process::operator<<(const QString & arg) { arguments.append(QFile::encodeName(arg)); return *this; @@ -250,7 +254,7 @@ bool K3Process::start(RunMode runmode, Communication comm) qDebug() << "Attempted to start a process without arguments" << endl; return false; } - char **arglist; + char ** arglist; QByteArray shellCmd; if (d->useShell) { if (d->shell.isEmpty()) { @@ -270,8 +274,9 @@ bool K3Process::start(RunMode runmode, Communication comm) arglist[3] = 0; } else { arglist = static_cast(malloc( (n + 1) * sizeof(char *))); - for (uint i = 0; i < n; i++) + for (uint i = 0; i < n; i++) { arglist[i] = arguments[i].data(); + } arglist[n] = 0; } @@ -286,12 +291,13 @@ bool K3Process::start(RunMode runmode, Communication comm) // We do this in the parent because if we do it in the child process // gdb gets confused when the application runs from gdb. #ifdef HAVE_INITGROUPS - struct passwd *pw = geteuid() ? 0 : getpwuid(getuid()); + struct passwd * pw = geteuid() ? 0 : getpwuid(getuid()); #endif int fd[2]; - if (pipe(fd)) - fd[0] = fd[1] = -1; // Pipe failed.. continue + if (pipe(fd)) { + fd[0] = fd[1] = -1; // Pipe failed.. continue + } // we don't use vfork() because // - it has unclear semantics and is not standardized @@ -304,47 +310,52 @@ bool K3Process::start(RunMode runmode, Communication comm) // Closing of fd[1] indicates that the execvp() succeeded! fcntl(fd[1], F_SETFD, FD_CLOEXEC); - if (!commSetupDoneC()) + if (!commSetupDoneC()) { qDebug() << "Could not finish comm setup in child!" << endl; + } // reset all signal handlers struct sigaction act; sigemptyset(&act.sa_mask); act.sa_handler = SIG_DFL; act.sa_flags = 0; - for (int sig = 1; sig < NSIG; sig++) + for (int sig = 1; sig < NSIG; sig++) { sigaction(sig, &act, 0L); + } - if (d->priority) + if (d->priority) { setpriority(PRIO_PROCESS, 0, d->priority); + } if (!runPrivileged()) { setgid(getgid()); #ifdef HAVE_INITGROUPS - if (pw) + if (pw) { initgroups(pw->pw_name, pw->pw_gid); + } #endif - if (geteuid() != getuid()) + if (geteuid() != getuid()) { setuid(getuid()); - if (geteuid() != getuid()) + } + if (geteuid() != getuid()) { _exit(1); + } } setupEnvironment(); - if (runmode == DontCare || runmode == OwnGroup) + if (runmode == DontCare || runmode == OwnGroup) { setsid(); + } - const char *executable = arglist[0]; - if (!d->executable.isEmpty()) + const char * executable = arglist[0]; + if (!d->executable.isEmpty()) { executable = d->executable.data(); + } execvp(executable, arglist); char resultByte = 1; - ssize_t result = write(fd[1], &resultByte, 1); - if (result<0) { - qDebug() << "Write failed with the error code " << result << endl; - } + write(fd[1], &resultByte, 1); _exit(-1); } else if (pid_ == -1) { // forking failed @@ -357,8 +368,9 @@ bool K3Process::start(RunMode runmode, Communication comm) // the parent continues here free(arglist); - if (!commSetupDoneP()) + if (!commSetupDoneP()) { qDebug() << "Could not finish comm setup in parent!" << endl; + } // Check whether client could be started. close(fd[1]); @@ -374,8 +386,9 @@ bool K3Process::start(RunMode runmode, Communication comm) return false; } if (n == -1) { - if (errno == EINTR) - continue; // Ignore + if (errno == EINTR) { + continue; // Ignore + } } break; // success } @@ -419,8 +432,9 @@ bool K3Process::start(RunMode runmode, Communication comm) bool K3Process::kill(int signo) { - if (runs && pid_ > 0 && !::kill(run_mode == OwnGroup ? -pid_ : pid_, signo)) + if (runs && pid_ > 0 && !::kill(run_mode == OwnGroup ? -pid_ : pid_, signo)) { return true; + } return false; } @@ -452,16 +466,17 @@ pid_t K3Process::pid() const bool K3Process::wait(int timeout) { - if (!runs) + if (!runs) { return true; + } #ifndef __linux__ struct timeval etv; #endif struct timeval tv, *tvp; - if (timeout < 0) + if (timeout < 0) { tvp = 0; - else { + } else { #ifndef __linux__ gettimeofday(&etv, 0); etv.tv_sec += timeout; @@ -482,15 +497,17 @@ bool K3Process::wait(int timeout) if (tvp) { gettimeofday(&tv, 0); timersub(&etv, &tv, &tv); - if (tv.tv_sec < 0) + if (tv.tv_sec < 0) { tv.tv_sec = tv.tv_usec = 0; + } } #endif switch ( select( fd+1, &fds, 0, 0, tvp ) ) { case -1: - if ( errno == EINTR ) + if ( errno == EINTR ) { break; + } // fall through; should happen if tvp->tv_sec < 0 case 0: K3ProcessController::instance()->rescheduleCheck(); @@ -543,36 +560,41 @@ int K3Process::exitSignal() const } -bool K3Process::writeStdin(const char *buffer, int buflen) +bool K3Process::writeStdin(const char * buffer, int buflen) { // if there is still data pending, writing new data // to stdout is not allowed (since it could also confuse // kprocess ...) - if (input_data != 0) + if (input_data != 0) { return false; + } if (communication & Stdin) { input_data = buffer; input_sent = 0; input_total = buflen; innot->setEnabled(true); - if (input_total) + if (input_total) { slotSendData(0); + } return true; - } else + } else { return false; + } } void K3Process::suspend() { - if (outnot) + if (outnot) { outnot->setEnabled(false); + } } void K3Process::resume() { - if (outnot) + if (outnot) { outnot->setEnabled(true); + } } bool K3Process::closeStdin() @@ -581,12 +603,14 @@ bool K3Process::closeStdin() communication = communication & ~Stdin; delete innot; innot = 0; - if (!(d->usePty & Stdin)) + if (!(d->usePty & Stdin)) { close(in[1]); + } in[1] = -1; return true; - } else + } else { return false; + } } bool K3Process::closeStdout() @@ -595,12 +619,14 @@ bool K3Process::closeStdout() communication = communication & ~Stdout; delete outnot; outnot = 0; - if (!(d->usePty & Stdout)) + if (!(d->usePty & Stdout)) { close(out[0]); + } out[0] = -1; return true; - } else + } else { return false; + } } bool K3Process::closeStderr() @@ -609,23 +635,27 @@ bool K3Process::closeStderr() communication = communication & ~Stderr; delete errnot; errnot = 0; - if (!(d->usePty & Stderr)) + if (!(d->usePty & Stderr)) { close(err[0]); + } err[0] = -1; return true; - } else + } else { return false; + } } bool K3Process::closePty() { if (d->pty && d->pty->masterFd() >= 0) { - if (d->addUtmp) + if (d->addUtmp) { d->pty->logout(); + } d->pty->close(); return true; - } else + } else { return false; + } } void K3Process::closeAll() @@ -644,15 +674,17 @@ void K3Process::closeAll() void K3Process::slotChildOutput(int fdno) { - if (!childOutput(fdno)) + if (!childOutput(fdno)) { closeStdout(); + } } void K3Process::slotChildError(int fdno) { - if (!childError(fdno)) + if (!childError(fdno)) { closeStderr(); + } } @@ -673,26 +705,26 @@ void K3Process::slotSendData(int) } } -void K3Process::setUseShell(bool useShell, const char *shell) +void K3Process::setUseShell(bool useShell, const char * shell) { d->useShell = useShell; - if (shell && *shell) + if (shell && *shell) { d->shell = shell; - else + } else // #ifdef NON_FREE // ... as they ship non-POSIX /bin/sh #if !defined(__linux__) && !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && !defined(__GNU__) && !defined(__DragonFly__) // Solaris POSIX ... - if (!access( "/usr/xpg4/bin/sh", X_OK )) + if (!access( "/usr/xpg4/bin/sh", X_OK )) { d->shell = "/usr/xpg4/bin/sh"; - else + } else // ... which links here anyway - if (!access( "/bin/ksh", X_OK )) + if (!access( "/bin/ksh", X_OK )) { d->shell = "/bin/ksh"; - else + } else // dunno, maybe superfluous? - if (!access( "/usr/ucb/sh", X_OK )) + if (!access( "/usr/ucb/sh", X_OK )) { d->shell = "/usr/ucb/sh"; - else + } else #endif d->shell = "/bin/sh"; } @@ -702,20 +734,21 @@ void K3Process::setUsePty(Communication usePty, bool addUtmp) d->usePty = usePty; d->addUtmp = addUtmp; if (usePty) { - if (!d->pty) + if (!d->pty) { d->pty = new KPty; + } } else { delete d->pty; d->pty = 0; } } -KPty *K3Process::pty() const +KPty * K3Process::pty() const { return d->pty; } -QString K3Process::quote(const QString &arg) +QString K3Process::quote(const QString & arg) { QChar q('\''); return QString(arg).replace(q, "'\\''").prepend(q).append(q); @@ -736,8 +769,9 @@ void K3Process::processHasExited(int state) commClose(); // cleanup communication sockets - if (run_mode != DontCare) + if (run_mode != DontCare) { emit processExited(this); + } } @@ -787,37 +821,44 @@ int K3Process::setupCommunication(Communication comm) qWarning() << "Invalid usePty/communication combination (" << d->usePty << "/" << comm << ")" << endl; return 0; } - if (!d->pty->open()) + if (!d->pty->open()) { return 0; + } int rcomm = comm & d->usePty; int mfd = d->pty->masterFd(); - if (rcomm & Stdin) + if (rcomm & Stdin) { in[1] = mfd; - if (rcomm & Stdout) + } + if (rcomm & Stdout) { out[0] = mfd; - if (rcomm & Stderr) + } + if (rcomm & Stderr) { err[0] = mfd; + } } communication = comm; comm = comm & ~d->usePty; if (comm & Stdin) { - if (socketpair(AF_UNIX, SOCK_STREAM, 0, in)) + if (socketpair(AF_UNIX, SOCK_STREAM, 0, in)) { goto fail0; + } fcntl(in[0], F_SETFD, FD_CLOEXEC); fcntl(in[1], F_SETFD, FD_CLOEXEC); } if (comm & Stdout) { - if (socketpair(AF_UNIX, SOCK_STREAM, 0, out)) + if (socketpair(AF_UNIX, SOCK_STREAM, 0, out)) { goto fail1; + } fcntl(out[0], F_SETFD, FD_CLOEXEC); fcntl(out[1], F_SETFD, FD_CLOEXEC); } if (comm & Stderr) { - if (socketpair(AF_UNIX, SOCK_STREAM, 0, err)) + if (socketpair(AF_UNIX, SOCK_STREAM, 0, err)) { goto fail2; + } fcntl(err[0], F_SETFD, FD_CLOEXEC); fcntl(err[1], F_SETFD, FD_CLOEXEC); } @@ -844,17 +885,21 @@ fail0: int K3Process::commSetupDoneP() { int rcomm = communication & ~d->usePty; - if (rcomm & Stdin) + if (rcomm & Stdin) { close(in[0]); - if (rcomm & Stdout) + } + if (rcomm & Stdout) { close(out[1]); - if (rcomm & Stderr) + } + if (rcomm & Stderr) { close(err[1]); + } in[0] = out[1] = err[1] = -1; // Don't create socket notifiers if no interactive comm is to be expected - if (run_mode != NotifyOnExit && run_mode != OwnGroup) + if (run_mode != NotifyOnExit && run_mode != OwnGroup) { return 1; + } if (communication & Stdin) { fcntl(in[1], F_SETFL, O_NONBLOCK | fcntl(in[1], F_GETFL)); @@ -870,8 +915,9 @@ int K3Process::commSetupDoneP() Q_CHECK_PTR(outnot); QObject::connect(outnot, SIGNAL(activated(int)), this, SLOT(slotChildOutput(int))); - if (communication & NoRead) + if (communication & NoRead) { suspend(); + } } if (communication & Stderr) { @@ -890,33 +936,46 @@ int K3Process::commSetupDoneC() { int ok = 1; if (d->usePty & Stdin) { - if (dup2(d->pty->slaveFd(), STDIN_FILENO) < 0) ok = 0; + if (dup2(d->pty->slaveFd(), STDIN_FILENO) < 0) { + ok = 0; + } } else if (communication & Stdin) { - if (dup2(in[0], STDIN_FILENO) < 0) ok = 0; + if (dup2(in[0], STDIN_FILENO) < 0) { + ok = 0; + } } else { int null_fd = open( "/dev/null", O_RDONLY ); - if (dup2( null_fd, STDIN_FILENO ) < 0) ok = 0; + if (dup2( null_fd, STDIN_FILENO ) < 0) { + ok = 0; + } close( null_fd ); } struct linger so; memset(&so, 0, sizeof(so)); if (d->usePty & Stdout) { - if (dup2(d->pty->slaveFd(), STDOUT_FILENO) < 0) ok = 0; + if (dup2(d->pty->slaveFd(), STDOUT_FILENO) < 0) { + ok = 0; + } } else if (communication & Stdout) { if (dup2(out[1], STDOUT_FILENO) < 0 || - setsockopt(out[1], SOL_SOCKET, SO_LINGER, (char *)&so, sizeof(so))) + setsockopt(out[1], SOL_SOCKET, SO_LINGER, (char *)&so, sizeof(so))) { ok = 0; + } if (communication & MergedStderr) { - if (dup2(out[1], STDERR_FILENO) < 0) + if (dup2(out[1], STDERR_FILENO) < 0) { ok = 0; + } } } if (d->usePty & Stderr) { - if (dup2(d->pty->slaveFd(), STDERR_FILENO) < 0) ok = 0; + if (dup2(d->pty->slaveFd(), STDERR_FILENO) < 0) { + ok = 0; + } } else if (communication & Stderr) { if (dup2(err[1], STDERR_FILENO) < 0 || - setsockopt(err[1], SOL_SOCKET, SO_LINGER, (char *)&so, sizeof(so))) + setsockopt(err[1], SOL_SOCKET, SO_LINGER, (char *)&so, sizeof(so))) { ok = 0; + } } // don't even think about closing all open fds here or anywhere else @@ -924,8 +983,9 @@ int K3Process::commSetupDoneC() // PTY stuff // if (d->usePty) { d->pty->setCTty(); - if (d->addUtmp) + if (d->addUtmp) { d->pty->login(getenv("USER"), getenv("DISPLAY")); + } } return ok; @@ -956,13 +1016,15 @@ void K3Process::commClose() } if (communication & Stderr) { FD_SET(err[0], &rfds); - if (err[0] > max_fd) + if (err[0] > max_fd) { max_fd = err[0]; + } } if (runs) { FD_SET(notfd, &rfds); - if (notfd > max_fd) + if (notfd > max_fd) { max_fd = notfd; + } // If the process is still running we block until we // receive data or the process exits. p_timeout = 0; // no timeout @@ -975,17 +1037,21 @@ void K3Process::commClose() int fds_ready = select(max_fd+1, &rfds, 0, 0, p_timeout); if (fds_ready < 0) { - if (errno == EINTR) + if (errno == EINTR) { continue; + } break; - } else if (!fds_ready) + } else if (!fds_ready) { break; + } - if ((communication & Stdout) && FD_ISSET(out[0], &rfds)) + if ((communication & Stdout) && FD_ISSET(out[0], &rfds)) { slotChildOutput(out[0]); + } - if ((communication & Stderr) && FD_ISSET(err[0], &rfds)) + if ((communication & Stderr) && FD_ISSET(err[0], &rfds)) { slotChildError(err[0]); + } if (runs && FD_ISSET(notfd, &rfds)) { runs = false; // hack: signal potential exit @@ -1006,7 +1072,7 @@ void K3Process::commClose() // CC: Class K3ShellProcess /////////////////////////// -K3ShellProcess::K3ShellProcess(const char *shellname): +K3ShellProcess::K3ShellProcess(const char * shellname): K3Process(), d(0) { setUseShell( true, shellname ? shellname : getenv("SHELL") ); @@ -1016,7 +1082,7 @@ K3ShellProcess::~K3ShellProcess() { } -QString K3ShellProcess::quote(const QString &arg) +QString K3ShellProcess::quote(const QString & arg) { return K3Process::quote(arg); } diff --git a/lib/k3process.h b/lib/k3process.h index 1d0fc72..36c796f 100644 --- a/lib/k3process.h +++ b/lib/k3process.h @@ -186,7 +186,7 @@ public: /** * Constructor */ - explicit K3Process( QObject* parent=0L ); + explicit K3Process( QObject * parent=0L ); /** *Destructor: @@ -211,17 +211,17 @@ public: * @param arg the argument to add * @return a reference to this K3Process **/ - K3Process &operator<<(const QString& arg); + K3Process & operator<<(const QString & arg); /** * Similar to previous method, takes a char *, supposed to be in locale 8 bit already. */ - K3Process &operator<<(const char * arg); + K3Process & operator<<(const char * arg); /** * Similar to previous method, takes a QByteArray, supposed to be in locale 8 bit already. * @param arg the argument to add * @return a reference to this K3Process */ - K3Process &operator<<(const QByteArray & arg); + K3Process & operator<<(const QByteArray & arg); /** * Sets the executable and the command line argument list for this process, @@ -229,7 +229,7 @@ public: * @param args the arguments to add * @return a reference to this K3Process **/ - K3Process &operator<<(const QStringList& args); + K3Process & operator<<(const QStringList & args); /** * Clear a command line argument list that has been set by using @@ -353,7 +353,7 @@ public: int exitSignal() const; /** - * Transmit data to the child process' stdin. + * Transmit data to the child process' stdin. * * This function may return false in the following cases: * @@ -382,7 +382,7 @@ public: * @param buflen the length of the buffer * @return false if an error has occurred **/ - bool writeStdin(const char *buffer, int buflen); + bool writeStdin(const char * buffer, int buflen); /** * Shuts down the Stdin communication link. If no pty is used, this @@ -460,7 +460,7 @@ public: * @param name the name of the environment variable * @param value the new value for the environment variable */ - void setEnvironment(const QString &name, const QString &value); + void setEnvironment(const QString & name, const QString & value); /** * Changes the current working directory (CWD) of the process @@ -468,7 +468,7 @@ public: * This function must be called before starting the process. * @param dir the new directory */ - void setWorkingDirectory(const QString &dir); + void setWorkingDirectory(const QString & dir); /** * Specify whether to start the command via a shell or directly. @@ -485,7 +485,7 @@ public: * default shell, but note that doing so is usually a bad idea * for shell compatibility reasons. */ - void setUseShell(bool useShell, const char *shell = 0); + void setUseShell(bool useShell, const char * shell = 0); /** * This function can be used to quote an argument string such that @@ -495,7 +495,7 @@ public: * @param arg the argument to quote * @return the quoted argument */ - static QString quote(const QString &arg); + static QString quote(const QString & arg); /** * Detaches K3Process from child process. All communication is closed. @@ -524,7 +524,7 @@ public: * The pty is open only while the process is running. * @return a pointer to the pty object */ - KPty *pty() const; + KPty * pty() const; /** * More or less intuitive constants for use with setPriority(). @@ -547,7 +547,7 @@ Q_SIGNALS: * start() ) or the Block mode. * @param proc a pointer to the process that has exited **/ - void processExited(K3Process *proc); + void processExited(K3Process * proc); /** @@ -568,7 +568,7 @@ Q_SIGNALS: * QString myBuf = QLatin1String(buffer, buflen); * \endcode **/ - void receivedStdout(K3Process *proc, char *buffer, int buflen); + void receivedStdout(K3Process * proc, char * buffer, int buflen); /** * Emitted when output from the child process has @@ -588,7 +588,7 @@ Q_SIGNALS: * @param len the number of bytes that have been read from @p fd must * be written here **/ - void receivedStdout(int fd, int &len); // KDE4: change, broken API + void receivedStdout(int fd, int & len); // KDE4: change, broken API /** @@ -605,7 +605,7 @@ Q_SIGNALS: * @param buffer The data received. * @param buflen The number of bytes that are available. **/ - void receivedStderr(K3Process *proc, char *buffer, int buflen); + void receivedStderr(K3Process * proc, char * buffer, int buflen); /** * Emitted after all the data that has been @@ -613,7 +613,7 @@ Q_SIGNALS: * written to the child process. * @param proc a pointer to the process **/ - void wroteStdin(K3Process *proc); + void wroteStdin(K3Process * proc); protected Q_SLOTS: @@ -638,7 +638,7 @@ protected Q_SLOTS: * available, this function must disable the QSocketNotifier innot. * @param dummy ignore this argument */ - void slotSendData(int dummy); // KDE 4: remove dummy + void slotSendData(int dummy); // KDE 4: remove dummy protected: @@ -776,7 +776,7 @@ protected: * Normally the the first argument is the executable but you can * override that with this function. */ - void setBinaryExecutable(const char *filename); + void setBinaryExecutable(const char * filename); /** * The socket descriptors for stdout. @@ -794,15 +794,15 @@ protected: /** * The socket notifier for in[1]. */ - QSocketNotifier *innot; + QSocketNotifier * innot; /** * The socket notifier for out[0]. */ - QSocketNotifier *outnot; + QSocketNotifier * outnot; /** * The socket notifier for err[0]. */ - QSocketNotifier *errnot; + QSocketNotifier * errnot; /** * Lists the communication links that are activated for the child @@ -827,7 +827,7 @@ protected: /** * The buffer holding the data that has to be sent to the child */ - const char *input_data; + const char * input_data; /** * The number of bytes already transmitted */ @@ -844,7 +844,7 @@ protected: friend class K3ProcessController; private: - K3ProcessPrivate* const d; + K3ProcessPrivate * const d; }; Q_DECLARE_OPERATORS_FOR_FLAGS(K3Process::Communication) @@ -857,7 +857,7 @@ class K3ShellProcessPrivate; * Use K3Process and K3Process::setUseShell(true) instead. * * @short A class derived from K3Process to start child -* processes through a shell. +* processes through a shell. * @author Christian Czezatke */ class K3ShellProcess : public K3Process @@ -871,7 +871,7 @@ public: * * If no shellname is specified, the user's default shell is used. */ - explicit K3ShellProcess(const char *shellname=0); + explicit K3ShellProcess(const char * shellname=0); /** * Destructor. @@ -881,10 +881,10 @@ public: virtual bool start(RunMode runmode = NotifyOnExit, Communication comm = NoCommunication); - static QString quote(const QString &arg); + static QString quote(const QString & arg); private: - K3ShellProcessPrivate* const d; + K3ShellProcessPrivate * const d; }; diff --git a/lib/k3processcontroller.cpp b/lib/k3processcontroller.cpp index d04586c..5f69db4 100644 --- a/lib/k3processcontroller.cpp +++ b/lib/k3processcontroller.cpp @@ -50,16 +50,16 @@ public: int fd[2]; bool needcheck; - QSocketNotifier *notifier; - QList kProcessList; + QSocketNotifier * notifier; + QList kProcessList; QList unixProcessList; static struct sigaction oldChildHandlerData; static bool handlerSet; static int refCount; - static K3ProcessController* instance; + static K3ProcessController * instance; }; -K3ProcessController *K3ProcessController::Private::instance = 0; +K3ProcessController * K3ProcessController::Private::instance = 0; int K3ProcessController::Private::refCount = 0; void K3ProcessController::ref() @@ -81,7 +81,7 @@ void K3ProcessController::deref() } } -K3ProcessController* K3ProcessController::instance() +K3ProcessController * K3ProcessController::instance() { /* * there were no safety guards in previous revisions, is that ok? @@ -139,8 +139,9 @@ bool K3ProcessController::Private::handlerSet = false; void K3ProcessController::setupHandlers() { - if ( Private::handlerSet ) + if ( Private::handlerSet ) { return; + } Private::handlerSet = true; #ifdef Q_OS_UNIX @@ -170,8 +171,9 @@ void K3ProcessController::setupHandlers() void K3ProcessController::resetHandlers() { - if ( !Private::handlerSet ) + if ( !Private::handlerSet ) { return; + } Private::handlerSet = false; #ifdef Q_OS_UNIX @@ -227,8 +229,9 @@ int K3ProcessController::notifierFd() const void K3ProcessController::unscheduleCheck() { char dummy[16]; // somewhat bigger - just in case several have queued up - if ( ::read( d->fd[0], dummy, sizeof(dummy) ) > 0 ) + if ( ::read( d->fd[0], dummy, sizeof(dummy) ) > 0 ) { d->needcheck = true; + } } void @@ -255,15 +258,16 @@ void K3ProcessController::slotDoHousekeeping() int status; again: - QList::iterator it( d->kProcessList.begin() ); - QList::iterator eit( d->kProcessList.end() ); + QList::iterator it( d->kProcessList.begin() ); + QList::iterator eit( d->kProcessList.end() ); while ( it != eit ) { - K3Process *prc = *it; + K3Process * prc = *it; if ( prc->runs && waitpid( prc->pid_, &status, WNOHANG ) > 0 ) { prc->processHasExited( status ); // the callback can nuke the whole process list and even 'this' - if (!instance()) + if (!instance()) { return; + } goto again; } ++it; @@ -274,8 +278,9 @@ again: if ( waitpid( *uit, 0, WNOHANG ) > 0 ) { uit = d->unixProcessList.erase( uit ); deref(); // counterpart to addProcess, can invalidate 'this' - } else + } else { ++uit; + } } } @@ -284,9 +289,9 @@ bool K3ProcessController::waitForProcessExit( int timeout ) #ifdef Q_OS_UNIX for (;;) { struct timeval tv, *tvp; - if (timeout < 0) + if (timeout < 0) { tvp = 0; - else { + } else { tv.tv_sec = timeout; tv.tv_usec = 0; tvp = &tv; @@ -298,8 +303,9 @@ bool K3ProcessController::waitForProcessExit( int timeout ) switch ( select( d->fd[0]+1, &fds, 0, 0, tvp ) ) { case -1: - if ( errno == EINTR ) + if ( errno == EINTR ) { continue; + } // fall through; should never happen case 0: return false; @@ -314,12 +320,12 @@ bool K3ProcessController::waitForProcessExit( int timeout ) #endif } -void K3ProcessController::addKProcess( K3Process* p ) +void K3ProcessController::addKProcess( K3Process * p ) { d->kProcessList.append( p ); } -void K3ProcessController::removeKProcess( K3Process* p ) +void K3ProcessController::removeKProcess( K3Process * p ) { d->kProcessList.removeAll( p ); } diff --git a/lib/k3processcontroller.h b/lib/k3processcontroller.h index 7a76f72..f4d467c 100644 --- a/lib/k3processcontroller.h +++ b/lib/k3processcontroller.h @@ -57,7 +57,7 @@ public: * Only a single instance of this class is allowed at a time. * This method provides access to that instance. */ - static K3ProcessController *instance(); + static K3ProcessController * instance(); /** * Automatically called upon SIGCHLD. Never call it directly. @@ -102,11 +102,11 @@ public: /** * @internal */ - void addKProcess( K3Process* ); + void addKProcess( K3Process * ); /** * @internal */ - void removeKProcess( K3Process* ); + void removeKProcess( K3Process * ); /** * @internal */ @@ -126,8 +126,8 @@ private: ~K3ProcessController(); // Disallow assignment and copy-construction - K3ProcessController( const K3ProcessController& ); - K3ProcessController& operator= ( const K3ProcessController& ); + K3ProcessController( const K3ProcessController & ); + K3ProcessController & operator= ( const K3ProcessController & ); class Private; Private * const d; diff --git a/lib/konsole_wcwidth.cpp b/lib/konsole_wcwidth.cpp index af83eb2..1996751 100644 --- a/lib/konsole_wcwidth.cpp +++ b/lib/konsole_wcwidth.cpp @@ -15,21 +15,23 @@ struct interval { }; /* auxiliary function for binary search in interval table */ -static int bisearch(quint16 ucs, const struct interval *table, int max) +static int bisearch(quint16 ucs, const struct interval * table, int max) { int min = 0; int mid; - if (ucs < table[0].first || ucs > table[max].last) + if (ucs < table[0].first || ucs > table[max].last) { return 0; + } while (max >= min) { mid = (min + max) / 2; - if (ucs > table[mid].last) + if (ucs > table[mid].last) { min = mid + 1; - else if (ucs < table[mid].first) + } else if (ucs < table[mid].first) { max = mid - 1; - else + } else { return 1; + } } return 0; @@ -107,15 +109,18 @@ int konsole_wcwidth(quint16 ucs) }; /* test for 8-bit control characters */ - if (ucs == 0) + if (ucs == 0) { return 0; - if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0)) + } + if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0)) { return -1; + } /* binary search in table of non-spacing characters */ if (bisearch(ucs, combining, - sizeof(combining) / sizeof(struct interval) - 1)) + sizeof(combining) / sizeof(struct interval) - 1)) { return 0; + } /* if we arrive here, ucs is not a combining or C0/C1 control character */ @@ -200,18 +205,20 @@ int konsole_wcwidth_cjk(quint16 ucs) /* binary search in table of non-spacing characters */ if (bisearch(ucs, ambiguous, - sizeof(ambiguous) / sizeof(struct interval) - 1)) + sizeof(ambiguous) / sizeof(struct interval) - 1)) { return 2; + } return konsole_wcwidth(ucs); } #endif // single byte char: +1, multi byte char: +2 -int string_width( const QString &txt ) +int string_width( const QString & txt ) { int w = 0; - for ( int i = 0; i < txt.length(); ++i ) + for ( int i = 0; i < txt.length(); ++i ) { w += konsole_wcwidth( txt[ i ].unicode() ); + } return w; } diff --git a/lib/konsole_wcwidth.h b/lib/konsole_wcwidth.h index 6f4e46a..6fad21b 100644 --- a/lib/konsole_wcwidth.h +++ b/lib/konsole_wcwidth.h @@ -7,8 +7,8 @@ */ -#ifndef _KONSOLE_WCWIDTH_H_ -#define _KONSOLE_WCWIDTH_H_ +#ifndef _KONSOLE_WCWIDTH_H_ +#define _KONSOLE_WCWIDTH_H_ // Qt #include @@ -19,6 +19,6 @@ int konsole_wcwidth(quint16 ucs); int konsole_wcwidth_cjk(Q_UINT16 ucs); #endif -int string_width( const QString &txt ); +int string_width( const QString & txt ); #endif diff --git a/lib/kpty.cpp b/lib/kpty.cpp index eef0665..394df81 100644 --- a/lib/kpty.cpp +++ b/lib/kpty.cpp @@ -105,7 +105,7 @@ extern "C" { #endif #ifdef HAVE_SYS_STROPTS_H -# include // Defines I_PUSH +# include // Defines I_PUSH # define _NEW_TTY_CTRL #endif @@ -130,7 +130,7 @@ extern "C" { #endif //#include -//#include // findExe +//#include // findExe #include @@ -244,14 +244,14 @@ bool KPty::open() #else int ptyno; if (!ioctl(d->masterFd, TIOCGPTN, &ptyno)) { - char buf[32]; - sprintf(buf, "/dev/pts/%d", ptyno); - d->ttyName = buf; + d->ttyName = QByteArray("/dev/pts/") + QByteArray::number(ptyno); #endif #ifdef HAVE_GRANTPT - if (!grantpt(d->masterFd)) + if (!grantpt(d->masterFd)) { goto grantedpt; + } #else + goto gotpty; #endif } @@ -261,8 +261,8 @@ bool KPty::open() #endif // HAVE_PTSNAME || TIOCGPTN // Linux device names, FIXME: Trouble on other systems? - for (const char* s3 = "pqrstuvwxyzabcde"; *s3; s3++) { - for (const char* s4 = "0123456789abcdef"; *s4; s4++) { + for (const char * s3 = "pqrstuvwxyzabcde"; *s3; s3++) { + for (const char * s4 = "0123456789abcdef"; *s4; s4++) { ptyName = QString().sprintf("/dev/pty%c%c", *s3, *s4).toAscii(); d->ttyName = QString().sprintf("/dev/tty%c%c", *s3, *s4).toAscii(); @@ -282,9 +282,10 @@ bool KPty::open() #endif /* Q_OS_SOLARIS */ if (!access(d->ttyName.data(),R_OK|W_OK)) { // checks availability based on permission bits if (!geteuid()) { - struct group* p = getgrnam(TTY_GROUP); - if (!p) + struct group * p = getgrnam(TTY_GROUP); + if (!p) { p = getgrnam("wheel"); + } gid_t gid = p ? p->gr_gid : getgid (); if (!chown(d->ttyName.data(), getuid(), gid)) { @@ -304,10 +305,11 @@ bool KPty::open() gotpty: struct stat st; - if (stat(d->ttyName.data(), &st)) + if (stat(d->ttyName.data(), &st)) { return false; // this just cannot happen ... *cough* Yeah right, I just - // had it happen when pty #349 was allocated. I guess - // there was some sort of leak? I only had a few open. + // had it happen when pty #349 was allocated. I guess + // there was some sort of leak? I only had a few open. + } if (((st.st_uid != getuid()) || (st.st_mode & (S_IRGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH))) && !d->chownpty(true)) { @@ -316,7 +318,7 @@ gotpty: << "\nThis means the communication can be eavesdropped." << endl; } -#if defined(HAVE_GRANTPT) || defined(HAVE__GETPTY) +#if defined (HAVE__GETPTY) || defined (HAVE_GRANTPT) grantedpt: #endif @@ -357,8 +359,9 @@ void KPty::closeSlave() { Q_D(KPty); - if (d->slaveFd < 0) + if (d->slaveFd < 0) { return; + } ::close(d->slaveFd); d->slaveFd = -1; } @@ -367,17 +370,17 @@ void KPty::close() { Q_D(KPty); - if (d->masterFd < 0) + if (d->masterFd < 0) { return; + } closeSlave(); // don't bother resetting unix98 pty, it will go away after closing master anyway. if (memcmp(d->ttyName.data(), "/dev/pts/", 9)) { if (!geteuid()) { struct stat st; if (!stat(d->ttyName.data(), &st)) { - if (!chown(d->ttyName.data(), 0, st.st_gid == getgid() ? 0 : -1)) { - chmod(d->ttyName.data(), S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH); - } + chown(d->ttyName.data(), 0, st.st_gid == getgid() ? 0 : -1); + chmod(d->ttyName.data(), S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH); } } else { fcntl(d->masterFd, F_SETFD, 0); @@ -415,7 +418,7 @@ void KPty::setCTty() #endif } -void KPty::login(const char *user, const char *remotehost) +void KPty::login(const char * user, const char * remotehost) { #ifdef HAVE_UTEMPTER Q_D(KPty); @@ -431,8 +434,9 @@ void KPty::login(const char *user, const char *remotehost) memset(&l_struct, 0, sizeof(l_struct)); // note: strncpy without terminators _is_ correct here. man 4 utmp - if (user) + if (user) { strncpy(l_struct.ut_name, user, sizeof(l_struct.ut_name)); + } if (remotehost) { strncpy(l_struct.ut_host, remotehost, sizeof(l_struct.ut_host)); @@ -443,9 +447,10 @@ void KPty::login(const char *user, const char *remotehost) # ifndef __GLIBC__ Q_D(KPty); - const char *str_ptr = d->ttyName.data(); - if (!memcmp(str_ptr, "/dev/", 5)) + const char * str_ptr = d->ttyName.data(); + if (!memcmp(str_ptr, "/dev/", 5)) { str_ptr += 5; + } strncpy(l_struct.ut_line, str_ptr, sizeof(l_struct.ut_line)); # ifdef HAVE_STRUCT_UTMP_UT_ID strncpy(l_struct.ut_id, @@ -505,13 +510,15 @@ void KPty::logout() Q_D(KPty); const char *str_ptr = d->ttyName.data(); - if (!memcmp(str_ptr, "/dev/", 5)) + if (!memcmp(str_ptr, "/dev/", 5)) { str_ptr += 5; + } # ifdef __GLIBC__ else { - const char *sl_ptr = strrchr(str_ptr, '/'); - if (sl_ptr) + const char * sl_ptr = strrchr(str_ptr, '/'); + if (sl_ptr) { str_ptr = sl_ptr + 1; + } } # endif # ifdef HAVE_LOGIN @@ -565,14 +572,14 @@ endutent(); // XXX Supposedly, tc[gs]etattr do not work with the master on Solaris. // Please verify. -bool KPty::tcGetAttr(struct ::termios *ttmode) const +bool KPty::tcGetAttr(struct ::termios * ttmode) const { Q_D(const KPty); return _tcgetattr(d->masterFd, ttmode) == 0; } -bool KPty::tcSetAttr(struct ::termios *ttmode) +bool KPty::tcSetAttr(struct ::termios * ttmode) { Q_D(KPty); @@ -593,16 +600,18 @@ bool KPty::setWinSize(int lines, int columns) bool KPty::setEcho(bool echo) { struct ::termios ttmode; - if (!tcGetAttr(&ttmode)) + if (!tcGetAttr(&ttmode)) { return false; - if (!echo) + } + if (!echo) { ttmode.c_lflag &= ~ECHO; - else + } else { ttmode.c_lflag |= ECHO; + } return tcSetAttr(&ttmode); } -const char *KPty::ttyName() const +const char * KPty::ttyName() const { Q_D(const KPty); diff --git a/lib/kpty.h b/lib/kpty.h index 1409add..999ffd6 100644 --- a/lib/kpty.h +++ b/lib/kpty.h @@ -93,7 +93,7 @@ public: * of the client. For local logins from inside an X session it should * be the name of the X display. Otherwise it should be empty. */ - void login(const char *user = 0, const char *remotehost = 0); + void login(const char * user = 0, const char * remotehost = 0); /** * Removes the utmp entry for this tty. @@ -113,7 +113,7 @@ public: * the struct in your class, in your method. * @return @c true on success, false otherwise */ - bool tcGetAttr(struct ::termios *ttmode) const; + bool tcGetAttr(struct ::termios * ttmode) const; /** * Wrapper around tcsetattr(3) with mode TCSANOW. @@ -124,7 +124,7 @@ public: * @return @c true on success, false otherwise. Note that success means * that @em at @em least @em one attribute could be set. */ - bool tcSetAttr(struct ::termios *ttmode); + bool tcSetAttr(struct ::termios * ttmode); /** * Change the logical (screen) size of the pty. @@ -157,7 +157,7 @@ public: * * This function should be called only while the pty is open. */ - const char *ttyName() const; + const char * ttyName() const; /** * @return the file descriptor of the master pty @@ -177,7 +177,7 @@ protected: /** * @internal */ - KPty(KPtyPrivate *d); + KPty(KPtyPrivate * d); /** * @internal diff --git a/lib/qtermwidget.cpp b/lib/qtermwidget.cpp index a6a4260..bc1198e 100644 --- a/lib/qtermwidget.cpp +++ b/lib/qtermwidget.cpp @@ -99,12 +99,50 @@ QTermWidget::QTermWidget(int startnow, QWidget *parent) m_impl->m_terminalDisplay->resize(this->size()); this->setFocusProxy(m_impl->m_terminalDisplay); + connect(m_impl->m_terminalDisplay, SIGNAL(copyAvailable(bool)),this, SLOT(selectionChanged(bool))); +} + +void QTermWidget::selectionChanged(bool textSelected) +{ + emit copyAvailable(textSelected); +} + +int QTermWidget::getShellPID() +{ + return m_impl->m_session->processId(); +} + +void QTermWidget::changeDir(const QString & dir) +{ + /* + this is a very hackish way of trying to determine if the shell is in + the foreground before attempting to change the directory. It may not + be portable to anything other than Linux. + */ + QString strCmd; + strCmd.setNum(getShellPID()); + strCmd.prepend("ps -j "); + strCmd.append(" | tail -1 | awk '{ print $5 }' | grep -q \\+"); + int retval = system(strCmd.toStdString().c_str()); + + if (!retval) { + QString cmd = "cd " + dir + "\n"; + sendText(cmd); + } +} + +QSize QTermWidget::sizeHint() const +{ + QSize size = m_impl->m_terminalDisplay->sizeHint(); + size.rheight() = 150; + return size; } void QTermWidget::startShellProgram() { - if ( m_impl->m_session->isRunning() ) + if ( m_impl->m_session->isRunning() ) { return; + } m_impl->m_session->run(); } diff --git a/lib/qtermwidget.h b/lib/qtermwidget.h index e868d07..974dcb1 100644 --- a/lib/qtermwidget.h +++ b/lib/qtermwidget.h @@ -24,7 +24,7 @@ struct TermWidgetImpl; -enum COLOR_SCHEME { COLOR_SCHEME_WHITE_ON_BLACK = 1, +enum COLOR_SCHEME { COLOR_SCHEME_WHITE_ON_BLACK = 1, COLOR_SCHEME_GREEN_ON_BLACK, COLOR_SCHEME_BLACK_ON_LIGHT_YELLOW }; @@ -46,34 +46,41 @@ public: //Creation of widget QTermWidget(int startnow = 1, //start shell programm immediatelly - QWidget *parent = 0); + QWidget * parent = 0); ~QTermWidget(); + //Initial size + QSize sizeHint() const; + //start shell program if it was not started in constructor void startShellProgram(); + int getShellPID(); + + void changeDir(const QString & dir); + //look-n-feel, if you don`t like defaults - // Terminal font + // Terminal font // Default is application font with family Monospace, size 10 // USE ONLY FIXED-PITCH FONT! // otherwise symbols' position could be incorrect - void setTerminalFont(QFont &font); + void setTerminalFont(QFont & font); //environment - void setEnvironment(const QStringList& environment); + void setEnvironment(const QStringList & environment); - // Shell program, default is /bin/bash - void setShellProgram(const QString &progname); + // Shell program, default is /bin/bash + void setShellProgram(const QString & progname); //working directory - void setWorkingDirectory(const QString& dir); + void setWorkingDirectory(const QString & dir); // Shell program args, default is none - void setArgs(QStringList &args); + void setArgs(QStringList & args); //Text codec, default is UTF-8 - void setTextCodec(QTextCodec *codec); + void setTextCodec(QTextCodec * codec); //Color scheme, default is white on black void setColorScheme(int scheme); @@ -88,7 +95,7 @@ public: void setScrollBarPosition(ScrollBarPosition); // Send some text to terminal - void sendText(QString &text); + void sendText(QString & text); // Sets whether flow control is enabled void setFlowControlEnabled(bool enabled); @@ -111,6 +118,7 @@ public: signals: void finished(); + void copyAvailable(bool); public slots: // Paste clipboard content to terminal @@ -128,10 +136,11 @@ protected: protected slots: void sessionFinished(); + void selectionChanged(bool textSelected); private: void init(); - TermWidgetImpl *m_impl; + TermWidgetImpl * m_impl; }; @@ -140,7 +149,7 @@ private: #ifdef __cplusplus extern "C" #endif -void *createTermWidget(int startnow, void *parent); +void * createTermWidget(int startnow, void * parent); #endif