author | ar <ar> | 2005-01-21 19:56:15 (UTC) |
---|---|---|
committer | ar <ar> | 2005-01-21 19:56:15 (UTC) |
commit | cd51d382be50bc021739395309e23760f1619759 (patch) (side-by-side diff) | |
tree | e76155f772df7faea5fcf38667c6da8c916208db | |
parent | fdc37fbd908472e28735a8f0b01e3e66a43535e0 (diff) | |
download | opie-cd51d382be50bc021739395309e23760f1619759.zip opie-cd51d382be50bc021739395309e23760f1619759.tar.gz opie-cd51d382be50bc021739395309e23760f1619759.tar.bz2 |
- make opie compilable against qte 2.3.10 snapshot
check QT_VERSION against 0x030000 instead of 300
26 files changed, 45 insertions, 45 deletions
diff --git a/core/apps/embeddedkonsole/TEWidget.cpp b/core/apps/embeddedkonsole/TEWidget.cpp index 5171bf1..bee58e7 100644 --- a/core/apps/embeddedkonsole/TEWidget.cpp +++ b/core/apps/embeddedkonsole/TEWidget.cpp @@ -1,1431 +1,1431 @@ /* ------------------------------------------------------------------------ */ /* */ /* [TEWidget.C] Terminal Emulation Widget */ /* */ /* ------------------------------------------------------------------------ */ /* */ /* Copyright (c) 1997,1998 by Lars Doelle <lars.doelle@on-line.de> */ /* */ /* This file is part of Konsole - an X terminal for KDE */ /* */ /* ------------------------------------------------------------------------ */ /* */ /* Ported Konsole to Qt/Embedded */ /* */ /* Copyright (C) 2000 by John Ryland <jryland@trolltech.com> */ /* */ /* -------------------------------------------------------------------------- */ /*! \class TEWidget \brief Visible screen contents This class is responsible to map the `image' of a terminal emulation to the display. All the dependency of the emulation to a specific GUI or toolkit is localized here. Further, this widget has no knowledge about being part of an emulation, it simply work within the terminal emulation framework by exposing size and key events and by being ordered to show a new image. <ul> <li> The internal image has the size of the widget (evtl. rounded up) <li> The external image used in setImage can have any size. <li> (internally) the external image is simply copied to the internal when a setImage happens. During a resizeEvent no painting is done a paintEvent is expected to follow anyway. </ul> \sa TEScreen \sa Emulation */ /* FIXME: - 'image' may also be used uninitialized (it isn't in fact) in resizeEvent - 'font_a' not used in mouse events - add destructor */ /* TODO - evtl. be sensitive to `paletteChange' while using default colors. - set different 'rounding' styles? I.e. have a mode to show clipped chars? */ // #include "config.h" #include "TEWidget.h" #include "session.h" #include <qpe/config.h> #if !(QT_NO_COP) #include <qpe/qcopenvelope_qws.h> #endif #include <qclipboard.h> #ifndef QT_NO_DRAGANDDROP #include <qdragobject.h> #include <qfile.h> #endif #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <ctype.h> #include <sys/stat.h> #include <sys/types.h> #include <signal.h> #include <assert.h> // #include "TEWidget.moc" //#include <kapp.h> //#include <kcursor.h> //#include <kurl.h> //#include <kdebug.h> //#include <klocale.h> #define HERE printf("%s(%d): %s\n",__FILE__,__LINE__,__FUNCTION__) #define HCNT(Name) // { static int cnt = 1; printf("%s(%d): %s %d\n",__FILE__,__LINE__,Name,cnt++); } #define loc(X,Y) ((Y)*columns+(X)) //FIXME: the rim should normally be 1, 0 only when running in full screen mode. #define rimX 0 // left/right rim width #define rimY 0 // top/bottom rim high #define SCRWIDTH 16 // width of the scrollbar #define yMouseScroll 1 // scroll increment used when dragging selection at top/bottom of window. /* ------------------------------------------------------------------------- */ /* */ /* Colors */ /* */ /* ------------------------------------------------------------------------- */ //FIXME: the default color table is in session.C now. // We need a way to get rid of this one, here. static const ColorEntry base_color_table[TABLE_COLORS] = // The following are almost IBM standard color codes, with some slight // gamma correction for the dim colors to compensate for bright X screens. // It contains the 8 ansiterm/xterm colors in 2 intensities. { // Fixme: could add faint colors here, also. // normal ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 1, 0 ), // Dfore, Dback ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0x18), 0, 0 ), // Black, Red ColorEntry(QColor(0x18,0xB2,0x18), 0, 0 ), ColorEntry( QColor(0xB2,0x68,0x18), 0, 0 ), // Green, Yellow ColorEntry(QColor(0x18,0x18,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ), // Blue, Magenta ColorEntry(QColor(0x18,0xB2,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 0, 0 ), // Cyan, White // intensiv ColorEntry(QColor(0x00,0x00,0x00), 0, 1 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 1, 0 ), ColorEntry(QColor(0x68,0x68,0x68), 0, 0 ), ColorEntry( QColor(0xFF,0x54,0x54), 0, 0 ), ColorEntry(QColor(0x54,0xFF,0x54), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0x54), 0, 0 ), ColorEntry(QColor(0x54,0x54,0xFF), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ), ColorEntry(QColor(0x54,0xFF,0xFF), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 0, 0 ) }; /* Note that we use ANSI color order (bgr), while IBMPC color order is (rgb) Code 0 1 2 3 4 5 6 7 ----------- ------- ------- ------- ------- ------- ------- ------- ------- ANSI (bgr) Black Red Green Yellow Blue Magenta Cyan White IBMPC (rgb) Black Blue Green Cyan Red Magenta Yellow White */ QColor TEWidget::getDefaultBackColor() { return color_table[DEFAULT_BACK_COLOR].color; } const ColorEntry* TEWidget::getColorTable() const { return color_table; } const ColorEntry* TEWidget::getdefaultColorTable() const { return base_color_table; } const QPixmap *TEWidget::backgroundPixmap() { static QPixmap *bg = new QPixmap("~/qpim/main/pics/faded_bg.xpm"); const QPixmap *pm = bg; return pm; } void TEWidget::setColorTable(const ColorEntry table[]) { for (int i = 0; i < TABLE_COLORS; i++) color_table[i] = table[i]; const QPixmap* pm = backgroundPixmap(); if (!pm) setBackgroundColor(color_table[DEFAULT_BACK_COLOR].color); update(); } //FIXME: add backgroundPixmapChanged. /* ------------------------------------------------------------------------- */ /* */ /* Font */ /* */ /* ------------------------------------------------------------------------- */ /* The VT100 has 32 special graphical characters. The usual vt100 extended xterm fonts have these at 0x00..0x1f. QT's iso mapping leaves 0x00..0x7f without any changes. But the graphicals come in here as proper unicode characters. We treat non-iso10646 fonts as VT100 extended and do the requiered mapping from unicode to 0x00..0x1f. The remaining translation is then left to the QCodec. */ // assert for i in [0..31] : vt100extended(vt100_graphics[i]) == i. unsigned short 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 }; static QChar vt100extended(QChar c) { switch (c.unicode()) { case 0x25c6 : return 1; case 0x2592 : return 2; case 0x2409 : return 3; case 0x240c : return 4; case 0x240d : return 5; case 0x240a : return 6; case 0x00b0 : return 7; case 0x00b1 : return 8; case 0x2424 : return 9; case 0x240b : return 10; case 0x2518 : return 11; case 0x2510 : return 12; case 0x250c : return 13; case 0x2514 : return 14; case 0x253c : return 15; case 0xf800 : return 16; case 0xf801 : return 17; case 0x2500 : return 18; case 0xf803 : return 19; case 0xf804 : return 20; case 0x251c : return 21; case 0x2524 : return 22; case 0x2534 : return 23; case 0x252c : return 24; case 0x2502 : return 25; case 0x2264 : return 26; case 0x2265 : return 27; case 0x03c0 : return 28; case 0x2260 : return 29; case 0x00a3 : return 30; case 0x00b7 : return 31; } return c; } static QChar identicalMap(QChar c) { return c; } void TEWidget::fontChange(const QFont &) { QFontMetrics fm(font()); font_h = fm.height(); // font_w = fm.maxWidth(); font_w = fm.width("m"); font_a = fm.ascent(); printf("font h=%d max_width=%d width_m=%d assent=%d\n", font_h, fm.maxWidth(), font_w, font_a); //printf("font_h: %d\n",font_h); //printf("font_w: %d\n",font_w); //printf("font_a: %d\n",font_a); //printf("charset: %s\n",QFont::encodingName(font().charSet()).ascii()); //printf("rawname: %s\n",font().rawName().ascii()); fontMap = -#if QT_VERSION < 300 +#if QT_VERSION < 0x030000 strcmp(QFont::encodingName(font().charSet()).ascii(),"iso10646") ? vt100extended : #endif identicalMap; propagateSize(); update(); } void TEWidget::setVTFont(const QFont& f) { QFrame::setFont(f); } QFont TEWidget::getVTFont() { return font(); } void TEWidget::setFont(const QFont &) { // ignore font change request if not coming from konsole itself } /* ------------------------------------------------------------------------- */ /* */ /* Constructor / Destructor */ /* */ /* ------------------------------------------------------------------------- */ TEWidget::TEWidget(QWidget *parent, const char *name) : QFrame(parent,name) { #ifndef QT_NO_CLIPBOARD cb = QApplication::clipboard(); QObject::connect( (QObject*)cb, SIGNAL(dataChanged()), this, SLOT(onClearSelection()) ); #endif scrollbar = new QScrollBar(this); scrollbar->setCursor( arrowCursor ); connect(scrollbar, SIGNAL(valueChanged(int)), this, SLOT(scrollChanged(int))); hScrollbar = new QScrollBar(this); hScrollbar->setCursor( arrowCursor ); hScrollbar->setOrientation(QScrollBar::Horizontal); // hScrollbar->setMaximumHeight(16); connect( hScrollbar, SIGNAL(valueChanged(int)), this, SLOT( hScrollChanged(int))); Config cfg( "Konsole" ); cfg.setGroup("ScrollBar"); switch( cfg.readNumEntry("Position",2)){ case 0: scrollLoc = SCRNONE; break; case 1: scrollLoc = SCRLEFT; break; case 2: scrollLoc = SCRRIGHT; break; }; useHorzScroll=cfg.readBoolEntry("HorzScroll",0); blinkT = new QTimer(this); connect(blinkT, SIGNAL(timeout()), this, SLOT(blinkEvent())); // blinking = FALSE; blinking = TRUE; resizing = FALSE; actSel = 0; image = 0; lines = 1; columns = 1; font_w = 1; font_h = 1; font_a = 1; word_selection_mode = FALSE; hposition = 0; vcolumns = 0; useBeep = true; setMouseMarks(TRUE); setVTFont( QFont("fixed") ); setColorTable(base_color_table); // init color table qApp->installEventFilter( this ); //FIXME: see below // KCursor::setAutoHideCursor( this, true ); // Init DnD //////////////////////////////////////////////////////////////// currentSession = NULL; // setAcceptDrops(true); // attempt // m_drop = new QPopupMenu(this); // m_drop->insertItem( QString("Paste"), 0); // m_drop->insertItem( QString("cd"), 1); // connect(m_drop, SIGNAL(activated(int)), SLOT(drop_menu_activated(int))); // we need focus so that the auto-hide cursor feature works setFocus(); setFocusPolicy( WheelFocus ); } //FIXME: make proper destructor // Here's a start (David) TEWidget::~TEWidget() { qApp->removeEventFilter( this ); if (image) free(image); } /* ------------------------------------------------------------------------- */ /* */ /* Display Operations */ /* */ /* ------------------------------------------------------------------------- */ /*! attributed string draw primitive */ void TEWidget::drawAttrStr(QPainter &paint, QRect rect, QString& str, ca attr, BOOL pm, BOOL clear) { if (pm && color_table[attr.b].transparent) { paint.setBackgroundMode( TransparentMode ); if (clear) erase(rect); } else { if (blinking) paint.fillRect(rect, color_table[attr.b].color); else { paint.setBackgroundMode( OpaqueMode ); paint.setBackgroundColor( color_table[attr.b].color ); } } if (color_table[attr.f].bold) paint.setPen(QColor( 0x8F, 0x00, 0x00 )); else paint.setPen(color_table[attr.f].color); paint.drawText(rect.x(),rect.y()+font_a, str); if (attr.r & RE_UNDERLINE) paint.drawLine(rect.left(), rect.y()+font_a+1, rect.right(),rect.y()+font_a+1 ); } /*! The image can only be set completely. The size of the new image may or may not match the size of the widget. */ void TEWidget::setImage(const ca* const newimg, int lines, int columns) { int y,x,len; const QPixmap* pm = backgroundPixmap(); QPainter paint; setUpdatesEnabled(FALSE); paint.begin( this ); HCNT("setImage"); QPoint tL = contentsRect().topLeft(); int tLx = tL.x(); int tLy = tL.y(); hasBlinker = FALSE; int cf = -1; // undefined int cb = -1; // undefined int cr = -1; // undefined int lins = QMIN(this->lines, QMAX(0,lines )); int cols = QMIN(this->columns,QMAX(0,columns)); QChar *disstrU = new QChar[cols]; for (y = 0; y < lins; y++) { const ca* lcl = &image[y*this->columns]; const ca* const ext = &newimg[y*columns]; if (!resizing) // not while resizing, we're expecting a paintEvent for (x = 0; x < cols; x++) { hasBlinker |= (ext[x].r & RE_BLINK); if (ext[x] != lcl[x]) { cr = ext[x].r; cb = ext[x].b; if (ext[x].f != cf) cf = ext[x].f; int lln = cols - x; disstrU[0] = fontMap(ext[x+0].c); for (len = 1; len < lln; len++) { if (ext[x+len].f != cf || ext[x+len].b != cb || ext[x+len].r != cr || ext[x+len] == lcl[x+len] ) break; disstrU[len] = fontMap(ext[x+len].c); } QString unistr(disstrU,len); drawAttrStr(paint, QRect(blX+tLx+font_w*x,bY+tLy+font_h*y,font_w*len,font_h), unistr, ext[x], pm != NULL, true); x += len - 1; } } // finally, make `image' become `newimg'. memcpy((void*)lcl,(const void*)ext,cols*sizeof(ca)); } drawFrame( &paint ); paint.end(); setUpdatesEnabled(TRUE); if ( hasBlinker && !blinkT->isActive()) blinkT->start(1000); // 1000 ms if (!hasBlinker && blinkT->isActive()) { blinkT->stop(); blinking = FALSE; } delete [] disstrU; } // paint Event //////////////////////////////////////////////////// /*! The difference of this routine vs. the `setImage' is, that the drawing does not include a difference analysis between the old and the new image. Instead, the internal image is used and the painting bound by the PaintEvent box. */ void TEWidget::paintEvent( QPaintEvent* pe ) { //{ static int cnt = 0; printf("paint %d\n",cnt++); } const QPixmap* pm = backgroundPixmap(); QPainter paint; setUpdatesEnabled(FALSE); paint.begin( this ); paint.setBackgroundMode( TransparentMode ); HCNT("paintEvent"); // Note that the actual widget size can be slightly larger // that the image (the size is truncated towards the smaller // number of characters in `resizeEvent'. The paint rectangle // can thus be larger than the image, but less then the size // of one character. QRect rect = pe->rect().intersect(contentsRect()); QPoint tL = contentsRect().topLeft(); int tLx = tL.x(); int tLy = tL.y(); int lux = QMIN(columns-1, QMAX(0,(rect.left() - tLx - blX ) / font_w)); int luy = QMIN(lines-1, QMAX(0,(rect.top() - tLy - bY ) / font_h)); int rlx = QMIN(columns-1, QMAX(0,(rect.right() - tLx - blX ) / font_w)); int rly = QMIN(lines-1, QMAX(0,(rect.bottom() - tLy - bY ) / font_h)); /* printf("paintEvent: %d..%d, %d..%d (%d..%d, %d..%d)\n",lux,rlx,luy,rly, rect.left(), rect.right(), rect.top(), rect.bottom()); */ // if (pm != NULL && color_table[image->b].transparent) // erase(rect); // BL: I have no idea why we need this, and it breaks the refresh. QChar *disstrU = new QChar[columns]; for (int y = luy; y <= rly; y++) for (int x = lux; x <= rlx; x++) { int len = 1; disstrU[0] = fontMap(image[loc(x,y)].c); int cf = image[loc(x,y)].f; int cb = image[loc(x,y)].b; int cr = image[loc(x,y)].r; while (x+len <= rlx && image[loc(x+len,y)].f == cf && image[loc(x+len,y)].b == cb && image[loc(x+len,y)].r == cr ) { disstrU[len] = fontMap(image[loc(x+len,y)].c); len += 1; } QString unistr(disstrU,len); drawAttrStr(paint, QRect(blX+tLx+font_w*x,bY+tLy+font_h*y,font_w*len,font_h), unistr, image[loc(x,y)], pm != NULL, false); x += len - 1; } delete [] disstrU; drawFrame( &paint ); paint.end(); setUpdatesEnabled(TRUE); } void TEWidget::blinkEvent() { blinking = !blinking; repaint(FALSE); } /* ------------------------------------------------------------------------- */ /* */ /* Resizing */ /* */ /* ------------------------------------------------------------------------- */ void TEWidget::resizeEvent(QResizeEvent* ev) { // printf("resize: %d,%d\n",ev->size().width(),ev->size().height()); //printf("approx: %d,%d\n",ev->size().width()/font_w,ev->size().height()/font_h); //printf("leaves: %d,%d\n",ev->size().width()%font_w,ev->size().height()%font_h); //printf("curren: %d,%d\n",width(),height()); HCNT("resizeEvent"); // see comment in `paintEvent' concerning the rounding. //FIXME: could make a routine here; check width(),height() assert(ev->size().width() == width()); assert(ev->size().height() == height()); propagateSize(); } void TEWidget::propagateSize() { ca* oldimg = image; int oldlin = lines; int oldcol = columns; makeImage(); // we copy the old image to reduce flicker int lins = QMIN(oldlin,lines); int cols = QMIN(oldcol,columns); if (oldimg) { for (int lin = 0; lin < lins; lin++) memcpy((void*)&image[columns*lin], (void*)&oldimg[oldcol*lin],cols*sizeof(ca)); free(oldimg); //FIXME: try new,delete } else clearImage(); //NOTE: control flows from the back through the chest right into the eye. // `emu' will call back via `setImage'. resizing = TRUE; emit changedImageSizeSignal(lines, columns); // expose resizeEvent resizing = FALSE; } /* ------------------------------------------------------------------------- */ /* */ /* Scrollbar */ /* */ /* ------------------------------------------------------------------------- */ void TEWidget::scrollChanged(int) { emit changedHistoryCursor(scrollbar->value()); //expose } void TEWidget::hScrollChanged(int loc) { hposition = loc; propagateSize(); update(); // emit changedHorzCursor( hScrollbar->value()); //expose } void TEWidget::setScroll(int cursor, int slines) { disconnect(scrollbar, SIGNAL(valueChanged(int)), this, SLOT(scrollChanged(int))); scrollbar->setRange(0,slines); scrollbar->setSteps(1,lines); scrollbar->setValue(cursor); connect(scrollbar, SIGNAL(valueChanged(int)), this, SLOT(scrollChanged(int))); } void TEWidget::setScrollbarLocation(int loc) { if (scrollLoc == loc) return; // quickly scrollLoc = loc; propagateSize(); update(); } /* ------------------------------------------------------------------------- */ /* */ /* Mouse */ /* */ /* ------------------------------------------------------------------------- */ /*! Three different operations can be performed using the mouse, and the routines in this section serve all of them: 1) The press/release events are exposed to the application 2) Marking (press and move left button) and Pasting (press middle button) 3) The right mouse button is used from the configuration menu NOTE: During the marking process we attempt to keep the cursor within the bounds of the text as being displayed by setting the mouse position whenever the mouse has left the text area. Two reasons to do so: 1) QT does not allow the `grabMouse' to confine-to the TEWidget. Thus a `XGrapPointer' would have to be used instead. 2) Even if so, this would not help too much, since the text area of the TEWidget is normally not identical with it's bounds. The disadvantage of the current handling is, that the mouse can visibly leave the bounds of the widget and is then moved back. Because of the current construction, and the reasons mentioned above, we cannot do better without changing the overall construction. */ /*! */ void TEWidget::mousePressEvent(QMouseEvent* ev) { //printf("press [%d,%d] %d\n",ev->x()/font_w,ev->y()/font_h,ev->button()); if ( !contentsRect().contains(ev->pos()) ) return; QPoint tL = contentsRect().topLeft(); int tLx = tL.x(); int tLy = tL.y(); mouse_down_x = ev->x(); mouse_down_y = ev->y(); //printf("press top left [%d,%d] by=%d\n",tLx,tLy, bY); if ( ev->button() == LeftButton) { QPoint pos = QPoint((ev->x()-tLx-blX)/font_w,(ev->y()-tLy-bY)/font_h); word_selection_mode = (ev->state() & ShiftButton); if ( ev->state() & ControlButton ) preserve_line_breaks = FALSE ; if (mouse_marks || (ev->state() & ShiftButton)) { emit clearSelectionSignal(); iPntSel = pntSel = pos; actSel = 1; // left mouse button pressed but nothing selected yet. grabMouse( /*crossCursor*/ ); // handle with care! } else { emit mouseSignal( 0, pos.x() + 1, pos.y() + 1 ); // left button } } if ( ev->button() == MidButton ) { emitSelection(); } if ( ev->button() == RightButton ) // Configure { emit configureRequest( this, ev->state()&(ShiftButton|ControlButton), ev->x(), ev->y() ); } } void TEWidget::mouseMoveEvent(QMouseEvent* ev) { // for auto-hiding the cursor, we need mouseTracking if (ev->state() == NoButton ) return; if (actSel == 0) return; // don't extend selection while pasting if (ev->state() & MidButton) return; //if ( !contentsRect().contains(ev->pos()) ) return; QPoint tL = contentsRect().topLeft(); int tLx = tL.x(); int tLy = tL.y(); int scroll = scrollbar->value(); // int hScroll = hScrollbar->value(); // we're in the process of moving the mouse with the left button pressed // the mouse cursor will kept catched within the bounds of the text in // this widget. // Adjust position within text area bounds. See FIXME above. QPoint pos = ev->pos(); if ( pos.x() < tLx+blX ) pos.setX( tLx+blX ); if ( pos.x() > tLx+blX+columns*font_w-1 ) pos.setX( tLx+blX+columns*font_w ); if ( pos.y() < tLy+bY ) pos.setY( tLy+bY ); if ( pos.y() > tLy+bY+lines*font_h-1 ) pos.setY( tLy+bY+lines*font_h-1 ); // check if we produce a mouse move event by this if ( pos != ev->pos() ) cursor().setPos(mapToGlobal(pos)); if ( pos.y() == tLy+bY+lines*font_h-1 ) { scrollbar->setValue(scrollbar->value()+yMouseScroll); // scrollforward } if ( pos.y() == tLy+bY ) { scrollbar->setValue(scrollbar->value()-yMouseScroll); // scrollback } QPoint here = QPoint((pos.x()-tLx-blX)/font_w,(pos.y()-tLy-bY)/font_h); QPoint ohere; bool swapping = FALSE; if ( word_selection_mode ) { // Extend to word boundaries int i; int selClass; bool left_not_right = ( here.y() < iPntSel.y() || here.y() == iPntSel.y() && here.x() < iPntSel.x() ); bool old_left_not_right = ( pntSel.y() < iPntSel.y() || pntSel.y() == iPntSel.y() && pntSel.x() < iPntSel.x() ); swapping = left_not_right != old_left_not_right; // Find left (left_not_right ? from here : from start) QPoint left = left_not_right ? here : iPntSel; i = loc(left.x(),left.y()); selClass = charClass(image[i].c); while ( left.x() > 0 && charClass(image[i-1].c) == selClass ) { i--; left.rx()--; } // Find left (left_not_right ? from start : from here) QPoint right = left_not_right ? iPntSel : here; i = loc(right.x(),right.y()); selClass = charClass(image[i].c); while ( right.x() < columns-1 && charClass(image[i+1].c) == selClass ) { i++; right.rx()++; } // Pick which is start (ohere) and which is extension (here) if ( left_not_right ) { here = left; ohere = right; } else { here = right; ohere = left; } } if (here == pntSel && scroll == scrollbar->value()) return; // not moved if ( word_selection_mode ) { if ( actSel < 2 || swapping ) { emit beginSelectionSignal( ohere.x(), ohere.y() ); } } else if ( actSel < 2 ) { emit beginSelectionSignal( pntSel.x(), pntSel.y() ); } actSel = 2; // within selection pntSel = here; emit extendSelectionSignal( here.x(), here.y() ); } void TEWidget::mouseReleaseEvent(QMouseEvent* ev) { //printf("release [%d,%d] %d\n",ev->x()/font_w,ev->y()/font_h,ev->button()); if ( ev->button() == LeftButton) { if (QABS(ev->x() - mouse_down_x) < 3 && QABS(ev->y() - mouse_down_y) < 3 && ev->y() < qApp->desktop()->height()/8) { emit setFullScreen(false); } if ( actSel > 1 ) emit endSelectionSignal(preserve_line_breaks); preserve_line_breaks = TRUE; actSel = 0; //FIXME: emits a release event even if the mouse is // outside the range. The procedure used in `mouseMoveEvent' // applies here, too. QPoint tL = contentsRect().topLeft(); int tLx = tL.x(); int tLy = tL.y(); if (!mouse_marks && !(ev->state() & ShiftButton)) emit mouseSignal( 3, // release (ev->x()-tLx-blX)/font_w + 1, (ev->y()-tLy-bY)/font_h + 1 ); releaseMouse(); } } void TEWidget::mouseDoubleClickEvent(QMouseEvent* ev) { if ( ev->button() != LeftButton) return; QPoint tL = contentsRect().topLeft(); int tLx = tL.x(); int tLy = tL.y(); QPoint pos = QPoint((ev->x()-tLx-blX)/font_w,(ev->y()-tLy-bY)/font_h); // pass on double click as two clicks. if (!mouse_marks && !(ev->state() & ShiftButton)) { emit mouseSignal( 0, pos.x()+1, pos.y()+1 ); // left button emit mouseSignal( 3, pos.x()+1, pos.y()+1 ); // release emit mouseSignal( 0, pos.x()+1, pos.y()+1 ); // left button return; } emit clearSelectionSignal(); QPoint bgnSel = pos; QPoint endSel = QPoint((ev->x()-tLx-blX)/font_w,(ev->y()-tLy-bY)/font_h); int i = loc(bgnSel.x(),bgnSel.y()); iPntSel = bgnSel; word_selection_mode = TRUE; // find word boundaries... int selClass = charClass(image[i].c); { // set the start... int x = bgnSel.x(); while ( x > 0 && charClass(image[i-1].c) == selClass ) { i--; x--; } bgnSel.setX(x); emit beginSelectionSignal( bgnSel.x(), bgnSel.y() ); // set the end... i = loc( endSel.x(), endSel.y() ); x = endSel.x(); while( x < columns-1 && charClass(image[i+1].c) == selClass ) { i++; x++ ; } endSel.setX(x); actSel = 2; // within selection emit extendSelectionSignal( endSel.x(), endSel.y() ); emit endSelectionSignal(preserve_line_breaks); preserve_line_breaks = TRUE; } } void TEWidget::focusInEvent( QFocusEvent * ) { // do nothing, to prevent repainting } void TEWidget::focusOutEvent( QFocusEvent * ) { // do nothing, to prevent repainting } bool TEWidget::focusNextPrevChild( bool next ) { if (next) return false; // This disables changing the active part in konqueror // when pressing Tab return QFrame::focusNextPrevChild( next ); } int TEWidget::charClass(char ch) const { // This might seem like overkill, but imagine if ch was a Unicode // character (Qt 2.0 QChar) - it might then be sensible to separate // the different language ranges, etc. if ( isspace(ch) ) return ' '; static const char *word_characters = ":@-./_~"; if ( isalnum(ch) || strchr(word_characters, ch) ) return 'a'; // Everything else is weird return 1; } void TEWidget::setMouseMarks(bool on) { mouse_marks = on; setCursor( mouse_marks ? ibeamCursor : arrowCursor ); } /* ------------------------------------------------------------------------- */ /* */ /* Clipboard */ /* */ /* ------------------------------------------------------------------------- */ #undef KeyPress void TEWidget::emitSelection() // Paste Clipboard by simulating keypress events { #ifndef QT_NO_CLIPBOARD QString text = QApplication::clipboard()->text(); // odebug << text << oendl; if ( ! text.isNull()) { text.replace(QRegExp("\n"), "\r"); QKeyEvent e(QEvent::KeyPress, 0, -1, 0, text); emit keyPressedSignal(&e); // expose as a big fat keypress event emit clearSelectionSignal(); } #endif } void TEWidget::emitText(QString text) { QKeyEvent e(QEvent::KeyPress, 0, -1, 0, text); emit keyPressedSignal(&e); // expose as a big fat keypress event } void TEWidget::pasteClipboard( ) { emitSelection(); } void TEWidget::setSelection(const QString& t) { #ifndef QT_NO_CLIPBOARD // Disconnect signal while WE set the clipboard QObject *cb = QApplication::clipboard(); QObject::disconnect( cb, SIGNAL(dataChanged()), this, SLOT(onClearSelection()) ); QApplication::clipboard()->setText(t); QObject::connect( cb, SIGNAL(dataChanged()), this, SLOT(onClearSelection()) ); #endif } void TEWidget::onClearSelection() { emit clearSelectionSignal(); } /* ------------------------------------------------------------------------- */ /* */ /* Keyboard */ /* */ /* ------------------------------------------------------------------------- */ //FIXME: an `eventFilter' has been installed instead of a `keyPressEvent' // due to a bug in `QT' or the ignorance of the author to prevent // repaint events being emitted to the screen whenever one leaves // or reenters the screen to/from another application. // // Troll says one needs to change focusInEvent() and focusOutEvent(), // which would also let you have an in-focus cursor and an out-focus // cursor like xterm does. // for the auto-hide cursor feature, I added empty focusInEvent() and // focusOutEvent() so that update() isn't called. // For auto-hide, we need to get keypress-events, but we only get them when // we have focus. void TEWidget::doScroll(int lines) { scrollbar->setValue(scrollbar->value()+lines); } void TEWidget::doHScroll(int lines) { hScrollbar->setValue( hScrollbar->value()+lines); } bool TEWidget::eventFilter( QObject *obj, QEvent *e ) { if ( (e->type() == QEvent::Accel || e->type() == QEvent::AccelAvailable ) && qApp->focusWidget() == this ) { static_cast<QKeyEvent *>( e )->ignore(); return true; } if ( obj != this /* when embedded */ && obj != parent() /* when standalone */ ) return FALSE; // not us if ( e->type() == QEvent::Wheel) { QApplication::sendEvent(scrollbar, e); } #ifdef FAKE_CTRL_AND_ALT static bool control = FALSE; static bool alt = FALSE; // odebug << " Has a keyboard with no CTRL and ALT keys, but we fake it:" << oendl; bool dele=FALSE; if ( e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease ) { QKeyEvent* ke = (QKeyEvent*)e; bool keydown = e->type() == QEvent::KeyPress || ke->isAutoRepeat(); switch (ke->key()) { case Key_F9: // let this be "Control" control = keydown; e = new QKeyEvent(QEvent::KeyPress, Key_Control, 0, ke->state()); dele=TRUE; break; case Key_F13: // let this be "Alt" alt = keydown; e = new QKeyEvent(QEvent::KeyPress, Key_Alt, 0, ke->state()); dele=TRUE; break; default: if ( control ) { int a = toupper(ke->ascii())-64; if ( a >= 0 && a < ' ' ) { e = new QKeyEvent(e->type(), ke->key(), a, ke->state()|ControlButton, QChar(a,0)); dele=TRUE; } } if ( alt ) { e = new QKeyEvent(e->type(), ke->key(), ke->ascii(), ke->state()|AltButton, ke->text()); dele=TRUE; } } } #endif if ( e->type() == QEvent::KeyPress ) { QKeyEvent* ke = (QKeyEvent*)e; actSel=0; // Key stroke implies a screen update, so TEWidget won't // know where the current selection is. // odebug << "key pressed is 0x" << ke->key() << ", ascii is 0x" << ke->ascii() << ", state " << ke->state() << "" << oendl; bool special_function = true; switch(ke->key()) { // case 0x201b: // fn-5 // case Key_F1: // switch sessions (?) // emitText("\\"); // expose (??) // break; case 0x2016: // fn-p case Key_F2: pasteClipboard(); break; case 0x2018: // fn-S case Key_F3: emit changeSession(1); break; case 0x2019: // fn-n emit newSession(); break; case Qt::Key_Tab: if (ke->state() == ControlButton) { emit changeSession(1); } else { special_function = false; } break; #if 0 case Qt::Key_Left: if (vcolumns == 0) { emit changeSession(-1); } else { special_function = false; } break; case Qt::Key_Right: if (vcolumns == 0) { emit changeSession(1); } else { special_function = false; } break; #endif case 0x201b: // fn-5 case Key_F4: emit toggleFullScreen(); break; case 0x200f: // fn-1 magnify minus case Key_F5: emit changeFontSize(-1); break; case 0x2010: // fn-2 magnify plus case Key_F6: emit changeFontSize(1); break; default: special_function = false; } if (special_function) { return true; } // else if( ke->state() == ControlButton && ke->key() == Key_V) { // pasteClipboard(); // } // else if( ke->state() == ControlButton && ke->key() == Key_C) { // pasteClipboard(); // } emit keyPressedSignal(ke); // expose ke->accept(); #ifdef FAKE_CTRL_AND_ALT if ( dele ) delete e; #endif return true; // stop the event } if ( e->type() == QEvent::Enter ) { QObject::disconnect( (QObject*)cb, SIGNAL(dataChanged()), this, SLOT(onClearSelection()) ); } if ( e->type() == QEvent::Leave ) { QObject::connect( (QObject*)cb, SIGNAL(dataChanged()), this, SLOT(onClearSelection()) ); } return QFrame::eventFilter( obj, e ); } /* ------------------------------------------------------------------------- */ /* */ /* Frame */ /* */ /* ------------------------------------------------------------------------- */ void TEWidget::frameChanged() { propagateSize(); update(); } /* ------------------------------------------------------------------------- */ /* */ /* Sound */ /* */ /* ------------------------------------------------------------------------- */ void TEWidget::Bell() { //#ifdef QT_QWS_SL5XXX //# ifndef QT_NO_COP if(useBeep) QCopEnvelope( "QPE/TaskBar", "soundAlarm()" ); //# endif //#else //# ifndef QT_NO_SOUND // QSound::play(Resource::findSound("alarm")); //# endif //#endif // QApplication::beep(); } /* ------------------------------------------------------------------------- */ /* */ /* Auxiluary */ /* */ /* ------------------------------------------------------------------------- */ void TEWidget::clearImage() // initialize the image // for internal use only { for (int y = 0; y < lines; y++) for (int x = 0; x < columns; x++) { image[loc(x,y)].c = 0xff; //' '; image[loc(x,y)].f = 0xff; //DEFAULT_FORE_COLOR; image[loc(x,y)].b = 0xff; //DEFAULT_BACK_COLOR; image[loc(x,y)].r = 0xff; //DEFAULT_RENDITION; } } // Create Image /////////////////////////////////////////////////////// void TEWidget::calcGeometry() { int showhscrollbar = 1; int hwidth = 0; int dcolumns = 0; Config cfg( "Konsole" ); cfg.setGroup("ScrollBar"); useHorzScroll=cfg.readBoolEntry("HorzScroll",0); if(vcolumns == 0) showhscrollbar = 0; if(showhscrollbar == 1) hwidth = QApplication::style().scrollBarExtent().width(); scrollbar->resize(QApplication::style().scrollBarExtent().width(), contentsRect().height() - hwidth); switch(scrollLoc) { case SCRNONE : columns = ( contentsRect().width() - 2 * rimX ) / font_w; dcolumns = columns; if(vcolumns) columns = vcolumns; blX = (contentsRect().width() - (columns*font_w) ) / 2; if(showhscrollbar) blX = -hposition * font_w; brX = blX; scrollbar->hide(); break; case SCRLEFT : columns = ( contentsRect().width() - 2 * rimX - scrollbar->width()) / font_w; dcolumns = columns; if(vcolumns) columns = vcolumns; brX = (contentsRect().width() - (columns*font_w) - scrollbar->width() ) / 2; if(showhscrollbar) brX = -hposition * font_w; blX = brX + scrollbar->width(); scrollbar->move(contentsRect().topLeft()); scrollbar->show(); break; case SCRRIGHT: columns = ( contentsRect().width() - 2 * rimX - scrollbar->width()) / font_w; dcolumns = columns; if(vcolumns) columns = vcolumns; blX = (contentsRect().width() - (columns*font_w) - scrollbar->width() ) / 2; if(showhscrollbar) blX = -hposition * font_w; brX = blX; scrollbar->move(contentsRect().topRight() - QPoint(scrollbar->width()-1,0)); scrollbar->show(); break; } //FIXME: support 'rounding' styles lines = ( contentsRect().height() - 2 * rimY ) / font_h; bY = (contentsRect().height() - (lines *font_h)) / 2; if(showhscrollbar == 1) { hScrollbar->resize(contentsRect().width() - hwidth, hwidth); hScrollbar->setRange(0, vcolumns - dcolumns); QPoint p = contentsRect().bottomLeft(); if(scrollLoc == SCRLEFT) hScrollbar->move(QPoint(p.x()+hwidth, p.y() - hwidth)); else hScrollbar->move(QPoint(p.x(), p.y() - hwidth)); hScrollbar->show(); } else hScrollbar->hide(); if(showhscrollbar == 1) { lines = lines - (hwidth / font_h) - 1; if(lines < 1) lines = 1; } //FIXME: support 'rounding' styles } void TEWidget::makeImage() //FIXME: rename 'calcGeometry? { calcGeometry(); image = (ca*) malloc(lines*columns*sizeof(ca)); clearImage(); } // calculate the needed size QSize TEWidget::calcSize(int cols, int lins) const { int frw = width() - contentsRect().width(); int frh = height() - contentsRect().height(); int scw = (scrollLoc==SCRNONE?0:scrollbar->width()); return QSize( font_w*cols + 2*rimX + frw + scw, font_h*lins + 2*rimY + frh ); } QSize TEWidget::sizeHint() const { return size(); } void TEWidget::styleChange(QStyle &) { propagateSize(); } #ifndef QT_NO_DRAGANDDROP /* --------------------------------------------------------------------- */ /* */ /* Drag & Drop */ /* */ /* --------------------------------------------------------------------- */ void TEWidget::dragEnterEvent(QDragEnterEvent* e) { e->accept(QTextDrag::canDecode(e) || QUriDrag::canDecode(e)); } void TEWidget::dropEvent(QDropEvent* event) { // The current behaviour when url(s) are dropped is // * if there is only ONE url and if it's a LOCAL one, ask for paste or cd // * in all other cases, just paste // (for non-local ones, or for a list of URLs, 'cd' is nonsense) QStrList strlist; int file_count = 0; dropText = ""; bool bPopup = true; if(QUriDrag::decode(event, strlist)) { if (strlist.count()) { for(const char* p = strlist.first(); p; p = strlist.next()) { if(file_count++ > 0) { dropText += " "; bPopup = false; // more than one file, don't popup } /* KURL url(p); if (url.isLocalFile()) { dropText += url.path(); // local URL : remove protocol } else { dropText += url.prettyURL(); bPopup = false; // a non-local file, don't popup } */ } if (bPopup) // m_drop->popup(pos() + event->pos()); m_drop->popup(mapToGlobal(event->pos())); else { if (currentSession) { currentSession->getEmulation()->sendString(dropText.local8Bit()); } // kdDebug() << "Drop:" << dropText.local8Bit() << "\n"; } } } else if(QTextDrag::decode(event, dropText)) { // kdDebug() << "Drop:" << dropText.local8Bit() << "\n"; if (currentSession) { currentSession->getEmulation()->sendString(dropText.local8Bit()); } // Paste it } } #endif void TEWidget::drop_menu_activated(int item) { #ifndef QT_NO_DRAGANDDROP switch (item) { case 0: // paste currentSession->getEmulation()->sendString(dropText.local8Bit()); // KWM::activate((Window)this->winId()); break; case 1: // cd ... currentSession->getEmulation()->sendString("cd "); struct stat statbuf; if ( ::stat( QFile::encodeName( dropText ), &statbuf ) == 0 ) { if ( !S_ISDIR(statbuf.st_mode) ) { /* KURL url; url.setPath( dropText ); dropText = url.directory( true, false ); // remove filename */ } } dropText.replace(QRegExp(" "), "\\ "); // escape spaces currentSession->getEmulation()->sendString(dropText.local8Bit()); currentSession->getEmulation()->sendString("\n"); // KWM::activate((Window)this->winId()); break; } #else Q_UNUSED(item); #endif } void TEWidget::setWrapAt(int columns) { vcolumns = columns; propagateSize(); update(); } diff --git a/core/apps/textedit/textedit.cpp b/core/apps/textedit/textedit.cpp index cabeb20..c7273c5 100644 --- a/core/apps/textedit/textedit.cpp +++ b/core/apps/textedit/textedit.cpp @@ -1,1208 +1,1208 @@ /********************************************************************** // textedit.cpp ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Opie Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** **********************************************************************/ // changes added by L. J. Potter Sun 02-17-2002 21:31:31 #include "textedit.h" #include "filePermissions.h" /* OPIE */ #include <opie2/odebug.h> #include <opie2/ofileselector.h> #include <opie2/ofiledialog.h> #include <opie2/ofontselector.h> #include <qpe/resource.h> #include <qpe/config.h> #include <qpe/qpeapplication.h> /* QT */ #include <qmenubar.h> #include <qtoolbar.h> #include <qtextstream.h> #include <qclipboard.h> #include <qaction.h> #include <qlineedit.h> #include <qmessagebox.h> #include <qlayout.h> #include <qtimer.h> #include <qdir.h> /* STD */ #include <unistd.h> #include <sys/stat.h> #include <stdlib.h> //getenv using namespace Opie::Core; using namespace Opie::Ui; -#if QT_VERSION < 300 +#if QT_VERSION < 0x030000 class QpeEditor : public QMultiLineEdit { public: QpeEditor( QWidget *parent, const char * name = 0 ) : QMultiLineEdit( parent, name ) { clearTableFlags(); setTableFlags( Tbl_vScrollBar | Tbl_autoHScrollBar ); } void find( const QString &txt, bool caseSensitive, bool backwards ); protected: bool markIt; int line1, line2, col1, col2; void mousePressEvent( QMouseEvent * ); void mouseReleaseEvent( QMouseEvent * ); //public slots: /* signals: void notFound(); void searchWrapped(); */ private: }; void QpeEditor::mousePressEvent( QMouseEvent *e ) { switch(e->button()) { case RightButton: { //rediculous workaround for qt popup menu //and the hold right click mechanism this->setSelection( line1, col1, line2, col2); QMultiLineEdit::mousePressEvent( e ); markIt = false; } break; default: { if(!markIt) { int line, col; this->getCursorPosition(&line, &col); line1=line2=line; col1=col2=col; } QMultiLineEdit::mousePressEvent( e ); } break; }; } void QpeEditor::mouseReleaseEvent( QMouseEvent * ) { if(this->hasMarkedText()) { markIt = true; this->getMarkedRegion( &line1, &col1, &line2, & col2 ); } else { markIt = false; } } void QpeEditor::find ( const QString &txt, bool caseSensitive, bool backwards ) { static bool wrap = false; int line, col; if ( wrap ) { if ( !backwards ) line = col = 0; wrap = false; // emit searchWrapped(); } else { getCursorPosition( &line, &col ); } //ignore backwards for now.... if ( !backwards ) { for ( ; ; ) { if ( line >= numLines() ) { wrap = true; //emit notFound(); break; } int findCol = getString( line )->find( txt, col, caseSensitive ); if ( findCol >= 0 ) { setCursorPosition( line, findCol, false ); col = findCol + txt.length(); setCursorPosition( line, col, true ); //found = true; break; } line++; col = 0; } } } #else #error "Must make a QpeEditor that inherits QTextEdit" #endif static const int nfontsizes = 6; static const int fontsize[nfontsizes] = {8,10,12,14,18,24}; TextEdit::TextEdit( QWidget *parent, const char *name, WFlags f ) : QMainWindow( parent, name, f ), bFromDocView( false ) { doc = 0; edited=false; fromSetDocument=false; setToolBarsMovable( false ); connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); channel = new QCopChannel( "QPE/Application/textedit", this ); connect( channel, SIGNAL(received(const QCString&,const QByteArray&)), this, SLOT(receive(const QCString&,const QByteArray&)) ); setIcon( Resource::loadPixmap( "TextEditor" ) ); QToolBar *bar = new QToolBar( this ); bar->setHorizontalStretchable( true ); menu = bar; QMenuBar *mb = new QMenuBar( bar ); QPopupMenu *file = new QPopupMenu( this ); QPopupMenu *edit = new QPopupMenu( this ); QPopupMenu *advancedMenu = new QPopupMenu(this); font = new QPopupMenu( this ); bar = new QToolBar( this ); editBar = bar; QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( fileNew() ) ); // a->addTo( bar ); a->addTo( file ); a = new QAction( tr( "Open" ), Resource::loadPixmap( "fileopen" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( fileOpen() ) ); a->addTo( bar ); a->addTo( file ); a = new QAction( tr( "Save" ), Resource::loadPixmap("save") , QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( save() ) ); file->insertSeparator(); a->addTo( bar ); a->addTo( file ); a = new QAction( tr( "Save As" ), Resource::loadPixmap("save") , QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( saveAs() ) ); a->addTo( file ); a = new QAction( tr( "Cut" ), Resource::loadPixmap( "cut" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editCut() ) ); a->addTo( editBar ); a->addTo( edit ); a = new QAction( tr( "Copy" ), Resource::loadPixmap( "copy" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editCopy() ) ); a->addTo( editBar ); a->addTo( edit ); a = new QAction( tr( "Paste" ), Resource::loadPixmap( "paste" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editPaste() ) ); a->addTo( editBar ); a->addTo( edit ); #ifndef QT_NO_CLIPBOARD a = new QAction( tr( "Insert Time and Date" ), Resource::loadPixmap( "paste" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editPasteTimeDate() ) ); a->addTo( edit ); #endif a = new QAction( tr( "Goto Line..." ), Resource::loadPixmap( "find" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( gotoLine() ) ); edit->insertSeparator(); a->addTo( edit ); a = new QAction( tr( "Find..." ), Resource::loadPixmap( "find" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editFind() ) ); a->addTo( bar ); a->addTo( edit ); zin = new QAction( tr("Zoom in"), QString::null, 0, this, 0 ); connect( zin, SIGNAL( activated() ), this, SLOT( zoomIn() ) ); zin->addTo( font ); zout = new QAction( tr("Zoom out"), QString::null, 0, this, 0 ); connect( zout, SIGNAL( activated() ), this, SLOT( zoomOut() ) ); zout->addTo( font ); font->insertSeparator(); font->insertItem(tr("Font"), this, SLOT(changeFont()) ); font->insertSeparator(); font->insertItem(tr("Advanced Features"), advancedMenu); QAction *wa = new QAction( tr("Wrap lines"), QString::null, 0, this, 0 ); connect( wa, SIGNAL( toggled(bool) ), this, SLOT( setWordWrap(bool) ) ); wa->setToggleAction(true); wa->addTo( advancedMenu); nStart = new QAction( tr("Start with new file"), QString::null, 0, this, 0 ); connect( nStart, SIGNAL( toggled(bool) ), this, SLOT( changeStartConfig(bool) ) ); nStart->setToggleAction(true); nStart->addTo( advancedMenu ); nStart->setEnabled(false); nAdvanced = new QAction( tr("Prompt on Exit"), QString::null, 0, this, 0 ); connect( nAdvanced, SIGNAL( toggled(bool) ), this, SLOT( doPrompt(bool) ) ); nAdvanced->setToggleAction(true); nAdvanced->addTo( advancedMenu ); desktopAction = new QAction( tr("Always open linked file"), QString::null, 0, this, 0 ); connect( desktopAction, SIGNAL( toggled(bool) ), this, SLOT( doDesktop(bool) ) ); desktopAction->setToggleAction(true); desktopAction->addTo( advancedMenu); filePermAction = new QAction( tr("File Permissions"), QString::null, 0, this, 0 ); connect( filePermAction, SIGNAL( toggled(bool) ), this, SLOT( doFilePerms(bool) ) ); filePermAction->setToggleAction(true); filePermAction->addTo( advancedMenu); searchBarAction = new QAction( tr("Search Bar Open"), QString::null, 0, this, 0 ); connect( searchBarAction, SIGNAL( toggled(bool) ), this, SLOT( setSearchBar(bool) ) ); searchBarAction->setToggleAction(true); searchBarAction->addTo( advancedMenu); nAutoSave = new QAction( tr("Auto Save 5 min."), QString::null, 0, this, 0 ); connect( nAutoSave, SIGNAL( toggled(bool) ), this, SLOT( doTimer(bool) ) ); nAutoSave->setToggleAction(true); nAutoSave->addTo( advancedMenu); //font->insertSeparator(); //font->insertItem(tr("About"), this, SLOT( doAbout()) ); mb->insertItem( tr( "File" ), file ); mb->insertItem( tr( "Edit" ), edit ); mb->insertItem( tr( "View" ), font ); searchBar = new QToolBar(this); addToolBar( searchBar, "Search", QMainWindow::Top, true ); searchBar->setHorizontalStretchable( true ); searchEdit = new QLineEdit( searchBar, "searchEdit" ); searchBar->setStretchableWidget( searchEdit ); connect( searchEdit, SIGNAL( textChanged(const QString&) ), this, SLOT( search() ) ); a = new QAction( tr( "Find Next" ), Resource::loadPixmap( "next" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( findNext() ) ); a->addTo( searchBar ); a->addTo( edit ); a = new QAction( tr( "Close Find" ), Resource::loadPixmap( "close" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( findClose() ) ); a->addTo( searchBar ); edit->insertSeparator(); a = new QAction( tr( "Delete" ), Resource::loadPixmap( "close" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editDelete() ) ); a->addTo( edit ); searchBar->hide(); editor = new QpeEditor( this ); setCentralWidget( editor ); editor->setFrameStyle( QFrame::Panel | QFrame::Sunken ); connect( editor, SIGNAL( textChanged() ), this, SLOT( editorChanged() ) ); QPEApplication::setStylusOperation( editor, QPEApplication::RightOnHold); Config cfg("TextEdit"); cfg. setGroup ( "Font" ); QFont defaultFont = editor-> font ( ); QString family = cfg. readEntry ( "Family", defaultFont. family ( )); int size = cfg. readNumEntry ( "Size", defaultFont. pointSize ( )); int weight = cfg. readNumEntry ( "Weight", defaultFont. weight ( )); bool italic = cfg. readBoolEntry ( "Italic", defaultFont. italic ( )); defaultFont = QFont ( family, size, weight, italic ); editor-> setFont ( defaultFont ); // updateCaption(); cfg.setGroup ( "View" ); promptExit = cfg.readBoolEntry ( "PromptExit", false ); openDesktop = cfg.readBoolEntry ( "OpenDesktop", true ); filePerms = cfg.readBoolEntry ( "FilePermissions", false ); useSearchBar = cfg.readBoolEntry ( "SearchBar", false ); startWithNew = cfg.readBoolEntry ( "startNew", true); featureAutoSave = cfg.readBoolEntry( "autosave", false); if(useSearchBar) searchBarAction->setOn(true); if(promptExit) nAdvanced->setOn( true ); if(openDesktop) desktopAction->setOn( true ); if(filePerms) filePermAction->setOn( true ); if(startWithNew) nStart->setOn( true ); if(featureAutoSave) nAutoSave->setOn(true); // { // doTimer(true); // } bool wrap = cfg. readBoolEntry ( "Wrap", true ); wa-> setOn ( wrap ); setWordWrap ( wrap ); ///////////////// if( qApp->argc() > 1) { currentFileName=qApp->argv()[1]; QFileInfo fi(currentFileName); if(fi.baseName().left(1) == "") { openDotFile(currentFileName); } else { openFile(currentFileName); } } else { edited1=false; openDotFile(""); } viewSelection = cfg.readNumEntry( "FileView", 0 ); } TextEdit::~TextEdit() { owarn << "textedit d'tor" << oendl; delete editor; } void TextEdit::closeEvent(QCloseEvent *) { if( edited1 && promptExit) { switch( savePrompt() ) { case 1: { saveAs(); qApp->quit(); } break; case 2: { qApp->quit(); } break; case -1: break; }; } else qApp->quit(); } void TextEdit::cleanUp() { Config cfg ( "TextEdit" ); cfg. setGroup ( "Font" ); QFont f = editor->font(); cfg.writeEntry ( "Family", f. family ( )); cfg.writeEntry ( "Size", f. pointSize ( )); cfg.writeEntry ( "Weight", f. weight ( )); cfg.writeEntry ( "Italic", f. italic ( )); cfg.setGroup ( "View" ); cfg.writeEntry ( "Wrap", editor->wordWrap() == QMultiLineEdit::WidgetWidth ); cfg.writeEntry ( "FileView", viewSelection ); cfg.writeEntry ( "PromptExit", promptExit ); cfg.writeEntry ( "OpenDesktop", openDesktop ); cfg.writeEntry ( "FilePermissions", filePerms ); cfg.writeEntry ( "SearchBar", useSearchBar ); cfg.writeEntry ( "startNew", startWithNew ); } void TextEdit::accept() { if( edited1) saveAs(); qApp->quit(); } void TextEdit::zoomIn() { setFontSize(editor->font().pointSize()+1,false); } void TextEdit::zoomOut() { setFontSize(editor->font().pointSize()-1,true); } void TextEdit::setFontSize(int sz, bool round_down_not_up) { int s=10; for (int i=0; i<nfontsizes; i++) { if ( fontsize[i] == sz ) { s = sz; break; } else if ( round_down_not_up ) { if ( fontsize[i] < sz ) s = fontsize[i]; } else { if ( fontsize[i] > sz ) { s = fontsize[i]; break; } } } QFont f = editor->font(); f.setPointSize(s); editor->setFont(f); zin->setEnabled(s != fontsize[nfontsizes-1]); zout->setEnabled(s != fontsize[0]); } void TextEdit::setBold(bool y) { QFont f = editor->font(); f.setBold(y); editor->setFont(f); } void TextEdit::setItalic(bool y) { QFont f = editor->font(); f.setItalic(y); editor->setFont(f); } void TextEdit::setWordWrap(bool y) { bool state = editor->edited(); QString captionStr = caption(); bool b1 = edited1; bool b2 = edited; editor->setWordWrap(y ? QMultiLineEdit::WidgetWidth : QMultiLineEdit::NoWrap ); editor->setEdited( state ); edited1=b1; edited=b2; setCaption(captionStr); } void TextEdit::setSearchBar(bool b) { useSearchBar=b; Config cfg("TextEdit"); cfg.setGroup("View"); cfg.writeEntry ( "SearchBar", b ); searchBarAction->setOn(b); if(b) searchBar->show(); else searchBar->hide(); editor->setFocus(); } void TextEdit::fileNew() { // if( !bFromDocView ) { // saveAs(); // } newFile(DocLnk()); } void TextEdit::fileOpen() { Config cfg("TextEdit"); cfg. setGroup ( "View" ); QMap<QString, QStringList> map; map.insert(tr("All"), QStringList() ); QStringList text; text << "text/*"; map.insert(tr("Text"), text ); text << "*"; map.insert(tr("All"), text ); QString str = OFileDialog::getOpenFileName( 2, QString::null , QString::null, map); if( !str.isEmpty() && QFile(str).exists() && !QFileInfo(str).isDir() ) { openFile( str ); } else updateCaption(); } void TextEdit::doSearchBar() { if(!useSearchBar) searchBar->hide(); else searchBar->show(); } #if 0 void TextEdit::slotFind() { FindDialog frmFind( tr("Text Editor"), this ); connect( &frmFind, SIGNAL(signalFindClicked(const QString&,bool,bool,int)), editor, SLOT(slotDoFind(const QString&,bool,bool))); //case sensitive, backwards, [category] connect( editor, SIGNAL(notFound()), &frmFind, SLOT(slotNotFound()) ); connect( editor, SIGNAL(searchWrapped()), &frmFind, SLOT(slotWrapAround()) ); frmFind.exec(); } #endif void TextEdit::fileRevert() { clear(); fileOpen(); } void TextEdit::editCut() { #ifndef QT_NO_CLIPBOARD editor->cut(); #endif } void TextEdit::editCopy() { #ifndef QT_NO_CLIPBOARD editor->copy(); #endif } void TextEdit::editPaste() { #ifndef QT_NO_CLIPBOARD editor->paste(); #endif } void TextEdit::editFind() { searchBar->show(); searchEdit->setFocus(); } void TextEdit::findNext() { editor->find( searchEdit->text(), false, false ); } void TextEdit::findClose() { searchBar->hide(); } void TextEdit::search() { editor->find( searchEdit->text(), false, false ); } void TextEdit::newFile( const DocLnk &f ) { DocLnk nf = f; nf.setType("text/plain"); clear(); setWState (WState_Reserved1 ); editor->setFocus(); doc = new DocLnk(nf); currentFileName = "Unnamed"; odebug << "newFile "+currentFileName << oendl; updateCaption( currentFileName); // editor->setEdited( false); } void TextEdit::openDotFile( const QString &f ) { if(!currentFileName.isEmpty()) { currentFileName=f; odebug << "openFile dotfile " + currentFileName << oendl; QString txt; QFile file(f); file.open(IO_ReadWrite); QTextStream t(&file); while ( !t.atEnd()) { txt+=t.readLine()+"\n"; } editor->setText(txt); editor->setEdited( false); edited1=false; edited=false; } updateCaption( currentFileName); } void TextEdit::openFile( const QString &f ) { odebug << "filename is "+ f << oendl; QString filer; QFileInfo fi( f); // bFromDocView = true; if(f.find(".desktop",0,true) != -1 && !openDesktop ) { switch ( QMessageBox::warning(this,tr("Text Editor"),tr("Text Editor has detected<BR>you selected a <B>.desktop</B>file.<BR>Open<B>.desktop</B> file or <B>linked</B> file?"),tr(".desktop File"),tr("Linked Document"),0,1,1) ) { case 0: //desktop filer = f; break; case 1: //linked DocLnk sf(f); filer = sf.file(); break; }; } else if(fi.baseName().left(1) == "") { odebug << "opening dotfile" << oendl; currentFileName=f; openDotFile(currentFileName); return; } /* * The problem is a file where Config(f).isValid() and it does not * end with .desktop will be treated as desktop file */ else if (f.find(".desktop",0,true) != -1 ) { DocLnk sf(f); filer = sf.file(); if(filer.right(1) == "/") filer = f; } else filer = f; DocLnk nf; nf.setType("text/plain"); nf.setFile(filer); currentFileName=filer; nf.setName(fi.baseName()); openFile(nf); odebug << "openFile string "+currentFileName << oendl; showEditTools(); // Show filename in caption QString name = filer; int sep = name.findRev( '/' ); if ( sep > 0 ) name = name.mid( sep+1 ); updateCaption( name ); } void TextEdit::openFile( const DocLnk &f ) { // clear(); // bFromDocView = true; FileManager fm; QString txt; currentFileName=f.file(); odebug << "openFile doclnk " + currentFileName << oendl; if ( !fm.loadFile( f, txt ) ) { // ####### could be a new file odebug << "Cannot open file" << oendl; } // fileNew(); if ( doc ) delete doc; doc = new DocLnk(f); editor->setText(txt); editor->setEdited( false); edited1=false; edited=false; doc->setName(currentFileName); updateCaption(); setTimer(); } void TextEdit::showEditTools() { menu->show(); editBar->show(); if(!useSearchBar) searchBar->hide(); else searchBar->show(); setWState (WState_Reserved1 ); } /*! unprompted save */ bool TextEdit::save() { QString name, file; odebug << "saveAsFile " + currentFileName << oendl; if(currentFileName.isEmpty()) { saveAs(); return false; } name = currentFileName; if(doc) { file = doc->file(); odebug << "saver file "+file << oendl; name = doc->name(); odebug << "File named "+name << oendl; } else { file = currentFileName; name = QFileInfo(currentFileName).baseName(); } QString rt = editor->text(); if( !rt.isEmpty() ) { if(name.isEmpty()) { saveAs(); } else { currentFileName = name; odebug << "saveFile "+currentFileName << oendl; struct stat buf; mode_t mode; stat(file.latin1(), &buf); mode = buf.st_mode; if(!fileIs) { doc->setName( name); FileManager fm; if ( !fm.saveFile( *doc, rt ) ) { QMessageBox::message(tr("Text Edit"),tr("Save Failed")); return false; } } else { odebug << "regular save file" << oendl; QFile f(file); if( f.open(IO_WriteOnly)) { QCString crt = rt.utf8(); f.writeBlock(crt,crt.length()); } else { QMessageBox::message(tr("Text Edit"),tr("Write Failed")); return false; } } editor->setEdited( false); edited1=false; edited=false; if(caption().left(1)=="*") setCaption(caption().right(caption().length()-1)); chmod( file.latin1(), mode); } return true; } return false; } /*! prompted save */ bool TextEdit::saveAs() { if(caption() == tr("Text Editor")) return false; odebug << "saveAsFile " + currentFileName << oendl; // case of nothing to save... // if ( !doc && !currentFileName.isEmpty()) { // //|| !bFromDocView) // odebug << "no doc" << oendl; // return true; // } // if ( !editor->edited() ) { // delete doc; // doc = 0; // return true; // } QString rt = editor->text(); odebug << currentFileName << oendl; if( currentFileName.isEmpty() || currentFileName == tr("Unnamed") || currentFileName == tr("Text Editor")) { odebug << "do silly TT filename thing" << oendl; // if ( doc && doc->name().isEmpty() ) { QString pt = rt.simplifyWhiteSpace(); int i = pt.find( ' ' ); QString docname = pt; if ( i > 0 ) docname = pt.left( i ); // remove "." at the beginning while( docname.startsWith( "." ) ) docname = docname.mid( 1 ); docname.replace( QRegExp("/"), "_" ); // cut the length. filenames longer than that //don't make sense and something goes wrong when they get too long. if ( docname.length() > 40 ) docname = docname.left(40); if ( docname.isEmpty() ) docname = tr("Unnamed"); if(doc) doc->setName(docname); currentFileName=docname; // } // else // odebug << "hmmmmmm" << oendl; } QMap<QString, QStringList> map; map.insert(tr("All"), QStringList() ); QStringList text; text << "text/*"; map.insert(tr("Text"), text ); text << "*"; map.insert(tr("All"), text ); QFileInfo cuFi( currentFileName); QString filee = cuFi.fileName(); QString dire = cuFi.dirPath(); if(dire==".") dire = QPEApplication::documentDir(); QString str; if( !featureAutoSave) { str = OFileDialog::getSaveFileName( 2, dire, filee, map); } else str=currentFileName; if(!str.isEmpty()) { QString fileNm=str; odebug << "saving filename "+fileNm << oendl; QFileInfo fi(fileNm); currentFileName=fi.fileName(); if(doc) // QString file = doc->file(); // doc->removeFiles(); delete doc; DocLnk nf; nf.setType("text/plain"); nf.setFile( fileNm); doc = new DocLnk(nf); // editor->setText(rt); odebug << "Saving file as "+currentFileName << oendl; doc->setName( fi.baseName() /*currentFileName*/); updateCaption( currentFileName); FileManager fm; if ( !fm.saveFile( *doc, rt ) ) { QMessageBox::message(tr("Text Edit"),tr("Save Failed")); return false; } if( filePerms ) { filePermissions *filePerm; filePerm = new filePermissions(this, tr("Permissions"),true, 0,(const QString &)fileNm); QPEApplication::execDialog( filePerm ); if( filePerm) delete filePerm; } // } editor->setEdited( false); edited1 = false; edited = false; if(caption().left(1)=="*") setCaption(caption().right(caption().length()-1)); return true; } odebug << "returning false" << oendl; currentFileName = ""; return false; } //end saveAs void TextEdit::clear() { delete doc; doc = 0; editor->clear(); } void TextEdit::updateCaption( const QString &name ) { if ( name.isEmpty() ) setCaption( tr("Text Editor") ); else { QString s = name; if ( s.isNull() ) s = doc->name(); if ( s.isEmpty() ) { s = tr( "Unnamed" ); currentFileName=s; } // if(s.left(1) == "/") // s = s.right(s.length()-1); setCaption( tr("%1 - Text Editor").arg( s ) ); } } void TextEdit::setDocument(const QString& fileref) { if(fileref != "Unnamed") { currentFileName=fileref; odebug << "setDocument" << oendl; QFileInfo fi(currentFileName); odebug << "basename:"+fi.baseName()+": current filenmame "+currentFileName << oendl; if( (fi.baseName().left(1)).isEmpty() ) { openDotFile(currentFileName); } else { odebug << "setDoc open" << oendl; bFromDocView = true; openFile(fileref); editor->setEdited(true); edited1=false; edited=true; // fromSetDocument=false; // doSearchBar(); } } updateCaption( currentFileName); } void TextEdit::changeFont() { QDialog *d = new QDialog ( this, "FontDialog", true ); d-> setCaption ( tr( "Choose font" )); QBoxLayout *lay = new QVBoxLayout ( d ); OFontSelector *ofs = new OFontSelector ( true, d ); lay-> addWidget ( ofs ); ofs-> setSelectedFont ( editor-> font ( )); if ( QPEApplication::execDialog( d ) == QDialog::Accepted ) editor-> setFont ( ofs-> selectedFont ( )); delete d; } void TextEdit::editDelete() { switch ( QMessageBox::warning(this,tr("Text Editor"), tr("Do you really want<BR>to <B>delete</B> " "the current file\nfrom the disk?<BR>This is " "<B>irreversable!</B>"), tr("Yes"),tr("No"),0,0,1) ) { case 0: if(doc) { doc->removeFiles(); clear(); setCaption( tr("Text Editor") ); } break; case 1: // exit break; }; } void TextEdit::changeStartConfig( bool b ) { startWithNew=b; Config cfg("TextEdit"); cfg.setGroup("View"); cfg.writeEntry("startNew",b); update(); } void TextEdit::editorChanged() { // odebug << "editor changed" << oendl; if( /*editor->edited() &&*/ /*edited && */!edited1) { setCaption( "*"+caption()); edited1=true; } edited=true; } void TextEdit::receive(const QCString&msg, const QByteArray &) { odebug << "QCop "+msg << oendl; if ( msg == "setDocument(QString)" ) { odebug << "bugger all" << oendl; } } void TextEdit::doAbout() { QMessageBox::about(0,tr("Text Edit"),tr("Text Edit is copyright<BR>" "2000 Trolltech AS, and<BR>" "2002 by <B>L. J. Potter <BR>llornkcor@handhelds.org</B><BR>" "and is licensed under the GPL")); } void TextEdit::doPrompt(bool b) { promptExit=b; Config cfg("TextEdit"); cfg.setGroup ( "View" ); cfg.writeEntry ( "PromptExit", b); } void TextEdit::doDesktop(bool b) { openDesktop=b; Config cfg("TextEdit"); cfg.setGroup ( "View" ); cfg.writeEntry ( "OpenDesktop", b); } void TextEdit::doFilePerms(bool b) { filePerms=b; Config cfg("TextEdit"); cfg.setGroup ( "View" ); cfg.writeEntry ( "FilePermissions", b); } void TextEdit::editPasteTimeDate() { #ifndef QT_NO_CLIPBOARD QClipboard *cb = QApplication::clipboard(); QDateTime dt = QDateTime::currentDateTime(); cb->setText( dt.toString()); editor->paste(); #endif } int TextEdit::savePrompt() { switch( QMessageBox::information( 0, (tr("Textedit")), (tr("Textedit detected\n" "you have unsaved changes\n" "Go ahead and save?\n")), (tr("Save")), (tr("Don't Save")), (tr("&Cancel")), 2, 2 ) ) { case 0: { return 1; } break; case 1: { return 2; } break; case 2: { return -1; } break; }; return 0; } void TextEdit::timerCrank() { if(featureAutoSave && edited1) { if(currentFileName.isEmpty()) { currentFileName = QDir::homeDirPath()+"/textedit.tmp"; saveAs(); } else { // odebug << "autosave" << oendl; save(); } setTimer(); } } void TextEdit::doTimer(bool b) { Config cfg("TextEdit"); cfg.setGroup ( "View" ); cfg.writeEntry ( "autosave", b); featureAutoSave = b; nAutoSave->setOn(b); if(b) { // odebug << "doTimer true" << oendl; setTimer(); } // else // odebug << "doTimer false" << oendl; } void TextEdit::setTimer() { if(featureAutoSave) { // odebug << "setting autosave" << oendl; QTimer *timer = new QTimer(this ); connect( timer, SIGNAL(timeout()), this, SLOT(timerCrank()) ); timer->start( 300000, true); //5 minutes } } void TextEdit::gotoLine() { if( editor->length() < 1) return; QWidget *d = QApplication::desktop(); gotoEdit = new QLineEdit( 0, "Goto line"); gotoEdit->move( (d->width()/2) - ( gotoEdit->width()/2) , (d->height()/2) - (gotoEdit->height()/2)); gotoEdit->setFrame(true); gotoEdit->show(); connect (gotoEdit,SIGNAL(returnPressed()), this, SLOT(doGoto())); } void TextEdit::doGoto() { QString number = gotoEdit->text(); gotoEdit->hide(); if(gotoEdit) { delete gotoEdit; gotoEdit = 0; } bool ok; int lineNumber = number.toInt(&ok, 10); if( editor->numLines() < lineNumber) QMessageBox::message(tr("Text Edit"),tr("Not enough lines")); else { editor->setCursorPosition(lineNumber, 0, false); } } diff --git a/core/opie-login/loginwindowimpl.cpp b/core/opie-login/loginwindowimpl.cpp index 73c2cbe..ac24894 100644 --- a/core/opie-login/loginwindowimpl.cpp +++ b/core/opie-login/loginwindowimpl.cpp @@ -1,262 +1,262 @@ /* � � � � � � � �=. This file is part of the OPIE Project � � � � � � �.=l. Copyright (c) 2002 Robert Griebl <sandman@handhelds.org> � � � � � �.>+-= �_;:, � � .> � �:=|. This file is free software; you can .> <`_, � > �. � <= redistribute it and/or modify it under :`=1 )Y*s>-.-- � : the terms of the GNU General Public .="- .-=="i, � � .._ License as published by the Free Software �- . � .-<_> � � .<> Foundation; either version 2 of the License, � � �._= =} � � � : or (at your option) any later version. � � .%`+i> � � � _;_. � � .i_,=:_. � � �-<s. This file is distributed in the hope that � � �+ �. �-:. � � � = it will be useful, but WITHOUT ANY WARRANTY; � � : .. � �.:, � � . . . without even the implied warranty of � � =_ � � � �+ � � =;=|` MERCHANTABILITY or FITNESS FOR A � _.=:. � � � : � �:=>`: PARTICULAR PURPOSE. See the GNU General ..}^=.= � � � = � � � ; Public License for more details. ++= � -. � � .` � � .: �: � � = �...= . :.=- You should have received a copy of the GNU �-. � .:....=;==+<; General Public License along with this file; � -_. . . � )=. �= see the file COPYING. If not, write to the � � -- � � � �:-=` Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qpe/version.h> #include <qpushbutton.h> #include <qlayout.h> #include <qlineedit.h> #include <qtimer.h> #include <qcombobox.h> #include <qlabel.h> #include <qpopupmenu.h> #include <qmessagebox.h> -#if QT_VERSION < 300 +#if QT_VERSION < 0x030000 #include <qgfx_qws.h> #endif #include <qwindowsystem_qws.h> #include <qpe/resource.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/config.h> #include <opie2/odevice.h> #include <stdio.h> #include <stdlib.h> #include "passworddialogimpl.h" #include "loginwindowimpl.h" #include "loginapplication.h" #include "inputmethods.h" using namespace Opie::Core; LoginWindowImpl::LoginWindowImpl ( ) : LoginWindow ( 0, "LOGIN-WINDOW", WStyle_Customize | WStyle_NoBorder | WDestructiveClose ) { QPopupMenu *pop = new QPopupMenu ( this ); pop-> insertItem ( tr( "Restart" ), this, SLOT( restart())); pop-> insertItem ( tr( "Quit" ), this, SLOT( quit())); m_menu-> setPopup ( pop ); QCopChannel *channel = new QCopChannel ( "QPE/TaskBar", this ); connect ( channel, SIGNAL( received(const QCString&,const QByteArray&)), this, SLOT( receive(const QCString&,const QByteArray&))); QHBoxLayout *lay = new QHBoxLayout ( m_taskbar, 4, 4 ); m_input = new InputMethods ( m_taskbar ); connect ( m_input, SIGNAL( inputToggled(bool)), this, SLOT( calcMaxWindowRect())); lay-> addWidget ( m_input ); lay-> addStretch ( 10 ); setActiveWindow ( ); m_password-> setFocus ( ); m_user-> insertStringList ( lApp-> allUsers ( )); //there is no point in displaying the IM for a zaurus if (ODevice::inst ( )-> series ( ) != Model_Zaurus){ QTimer::singleShot ( 0, this, SLOT( showIM())); } QString opiedir = ::getenv ( "OPIEDIR" ); QPixmap bgpix ( opiedir + "/pics/launcher/opie-background.jpg" ); if ( !bgpix. isNull ( )) { setBackgroundPixmap ( bgpix ); m_caption-> setBackgroundPixmap ( bgpix); TextLabel1-> setBackgroundPixmap ( bgpix); TextLabel2-> setBackgroundPixmap ( bgpix); } // m_caption-> setText ( tr("<center>Welcome to OPIE %1</center><center>& %2 %3</center>"). arg(QPE_VERSION). arg ( ODevice::inst ( )-> systemString ( )). arg ( ODevice::inst ( )-> systemVersionString ( ))); Config cfg ( "opie-login" ); cfg. setGroup ( "General" ); QString last = cfg. readEntry ( "LastLogin" ); if ( !last. isEmpty ( )) m_user-> setEditText ( last ); calcMaxWindowRect ( ); if ( PasswordDialogImpl::needDialog() ) QTimer::singleShot(10, this, SLOT(showPasswordDialog()) ); } LoginWindowImpl::~LoginWindowImpl ( ) { } void LoginWindowImpl::receive ( const QCString &msg, const QByteArray &data ) { QDataStream stream ( data, IO_ReadOnly ); if ( msg == "hideInputMethod()" ) m_input-> hideInputMethod ( ); else if ( msg == "showInputMethod()" ) m_input-> showInputMethod ( ); else if ( msg == "reloadInputMethods()" ) m_input-> loadInputMethods ( ); } void LoginWindowImpl::calcMaxWindowRect ( ) { #ifdef Q_WS_QWS QRect wr; int displayWidth = qApp-> desktop ( )-> width ( ); QRect ir = m_input-> inputRect ( ); if ( ir.isValid() ) wr.setCoords( 0, 0, displayWidth-1, ir.top()-1 ); else wr.setCoords( 0, 0, displayWidth-1, m_taskbar->y()-1 ); -#if QT_VERSION < 300 +#if QT_VERSION < 0x030000 wr = qt_screen-> mapToDevice ( wr, QSize ( qt_screen-> width ( ), qt_screen-> height ( ))); #endif QWSServer::setMaxWindowRect( wr ); #endif } void LoginWindowImpl::keyPressEvent ( QKeyEvent *e ) { switch ( e-> key ( )) { case HardKey_Suspend: suspend ( ); break; case HardKey_Backlight: backlight ( ); break; default: e-> ignore ( ); break; } LoginWindow::keyPressEvent ( e ); } void LoginWindowImpl::toggleEchoMode ( bool t ) { m_password-> setEchoMode ( t ? QLineEdit::Normal : QLineEdit::Password ); } void LoginWindowImpl::showIM ( ) { m_input-> showInputMethod ( ); } void LoginWindowImpl::restart ( ) { qApp-> quit ( ); } void LoginWindowImpl::quit ( ) { lApp-> quitToConsole ( ); } void LoginWindowImpl::suspend ( ) { ODevice::inst ( )-> suspend ( ); QCopEnvelope e("QPE/System", "setBacklight(int)"); e << -3; // Force on } void LoginWindowImpl::backlight ( ) { QCopEnvelope e("QPE/System", "setBacklight(int)"); e << -2; // toggle } class WaitLogo : public QLabel { public: WaitLogo ( ) : QLabel ( 0, "wait hack!", WStyle_Customize | WStyle_NoBorder | WStyle_Tool ) { QImage img = Resource::loadImage ( "launcher/new_wait" ); QPixmap pix; pix. convertFromImage ( img ); setPixmap ( pix ); setAlignment ( AlignCenter ); move ( 0, 0 ); resize ( qApp-> desktop ( )-> width ( ), qApp-> desktop ( )-> height ( )); m_visible = false; show ( ); } virtual void showEvent ( QShowEvent *e ) { QLabel::showEvent ( e ); m_visible = true; } virtual void paintEvent ( QPaintEvent *e ) { QLabel::paintEvent ( e ); if ( m_visible ) qApp-> quit ( ); } private: bool m_visible; }; void LoginWindowImpl::login ( ) { const char *user = ::strdup ( m_user-> currentText ( ). local8Bit ( )); const char *pass = ::strdup ( m_password-> text ( ). local8Bit ( )); if ( !user || !user [0] ) return; if ( !pass ) pass = ""; if ( lApp-> checkPassword ( user, pass )) { Config cfg ( "opie-login" ); cfg. setGroup ( "General" ); cfg. writeEntry ( "LastLogin", user ); cfg. write ( ); lApp-> setLoginAs ( user ); // Draw a big wait icon, the image can be altered in later revisions m_input-> hideInputMethod ( ); new WaitLogo ( ); // WaitLogo::showEvent() calls qApp-> quit() } else { QMessageBox::warning ( this, tr( "Wrong password" ), tr( "The given password is incorrect." )); m_password-> clear ( ); } } void LoginWindowImpl::showPasswordDialog() { PasswordDialogImpl dia( this ); dia.showMaximized(); dia.exec(); } diff --git a/freetype/fontfactoryttf_qws.h b/freetype/fontfactoryttf_qws.h index 208ab61..ff0fcfc 100644 --- a/freetype/fontfactoryttf_qws.h +++ b/freetype/fontfactoryttf_qws.h @@ -1,63 +1,63 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #ifndef FONTFACTORY_FT_H #define FONTFACTORY_FT_H #include <qfontmanager_qws.h> -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 # include <private/qfontdata_p.h> #else # include "qfontdata_p.h" #endif #ifdef QT_NO_FREETYPE extern "C" { #include <freetype/freetype.h> } // ascent, descent, width(ch), width(string), maxwidth? // leftbearing, rightbearing, minleftbearing,minrightbearing // leading class QFontFactoryFT : public QFontFactory { public: QFontFactoryFT(); virtual ~QFontFactoryFT(); QRenderedFont * get(const QFontDef &,QDiskFont *); virtual void load(QDiskFont *) const; virtual QString name(); private: friend class QRenderedFontFT; FT_Library library; }; #endif // QT_NO_FREETYPE #endif // QFONTFACTORY_FT_H diff --git a/libopie2/opieui/oseparator.cpp b/libopie2/opieui/oseparator.cpp index bbc4381..177368b 100644 --- a/libopie2/opieui/oseparator.cpp +++ b/libopie2/opieui/oseparator.cpp @@ -1,129 +1,129 @@ /* � � � � � � � � This file is part of the Opie Project � � � � � � � Copyright (C) 2003 Michael 'Mickey' Lauer <mickey@tm.informatik.uni-frankfurt.de> Copyright (C) 1997 Michael Roth <mroth@wirlweb.de> =. .=l. � � � � � �.>+-= �_;:, � � .> � �:=|. This program is free software; you can .> <`_, � > �. � <= redistribute it and/or modify it under :`=1 )Y*s>-.-- � : the terms of the GNU Library General Public .="- .-=="i, � � .._ License as published by the Free Software �- . � .-<_> � � .<> Foundation; either version 2 of the License, � � �._= =} � � � : or (at your option) any later version. � � .%`+i> � � � _;_. � � .i_,=:_. � � �-<s. This program is distributed in the hope that � � �+ �. �-:. � � � = it will be useful, but WITHOUT ANY WARRANTY; � � : .. � �.:, � � . . . without even the implied warranty of � � =_ � � � �+ � � =;=|` MERCHANTABILITY or FITNESS FOR A � _.=:. � � � : � �:=>`: PARTICULAR PURPOSE. See the GNU ..}^=.= � � � = � � � ; Library General Public License for more ++= � -. � � .` � � .: details. �: � � = �...= . :.=- �-. � .:....=;==+<; You should have received a copy of the GNU � -_. . . � )=. �= Library General Public License along with � � -- � � � �:-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* OPIE */ #include <opie2/odebug.h> #include <opie2/oseparator.h> /* QT */ using namespace Opie::Core; using namespace Opie::Ui; OSeparator::OSeparator(QWidget* parent, const char* name, WFlags f) : QFrame(parent, name, f) { setLineWidth(1); setMidLineWidth(0); setOrientation( HLine ); } OSeparator::OSeparator(int orientation, QWidget* parent, const char* name, WFlags f) : QFrame(parent, name, f) { setLineWidth(1); setMidLineWidth(0); setOrientation( orientation ); } void OSeparator::setOrientation(int orientation) { switch(orientation) { case Vertical: case VLine: setFrameStyle( QFrame::VLine | QFrame::Sunken ); setMinimumSize(2, 0); break; default: owarn << "OSeparator::setOrientation(): invalid orientation, using default orientation HLine" << oendl; case Horizontal: case HLine: setFrameStyle( QFrame::HLine | QFrame::Sunken ); setMinimumSize(0, 2); break; } } int OSeparator::orientation() const { if ( frameStyle() & VLine ) return VLine; if ( frameStyle() & HLine ) return HLine; return 0; } void OSeparator::drawFrame(QPainter *p) { QPoint p1, p2; QRect r = frameRect(); const QColorGroup & g = colorGroup(); if ( frameStyle() & HLine ) { p1 = QPoint( r.x(), r.height()/2 ); p2 = QPoint( r.x()+r.width(), p1.y() ); } else { p1 = QPoint( r.x()+r.width()/2, 0 ); p2 = QPoint( p1.x(), r.height() ); } -#if QT_VERSION < 300 +#if QT_VERSION < 0x030000 style().drawSeparator( p, p1.x(), p1.y(), p2.x(), p2.y(), g, true, 1, midLineWidth() ); #else QStyleOption opt( lineWidth(), midLineWidth() ); style().drawPrimitive( QStyle::PE_Separator, p, QRect( p1, p2 ), g, QStyle::Style_Sunken, opt ); #endif } QSize OSeparator::sizeHint() const { if ( frameStyle() & VLine ) return QSize(2, 0); if ( frameStyle() & HLine ) return QSize(0, 2); return QSize(-1, -1); } diff --git a/libopie2/qt3/opieui/oeditlistbox.h b/libopie2/qt3/opieui/oeditlistbox.h index 63fab11..c9c207d 100644 --- a/libopie2/qt3/opieui/oeditlistbox.h +++ b/libopie2/qt3/opieui/oeditlistbox.h @@ -1,250 +1,250 @@ /* This file is part of the KDE libraries Copyright (C) 2000 David Faure <faure@kde.org>, Alexander Neundorf <neundorf@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef OEDITLISTBOX_H #define OEDITLISTBOX_H #include <qgroupbox.h> #include <qlistbox.h> class OLineEdit; class OComboBox; class QPushButton; -#if QT_VERSION < 300 +#if QT_VERSION < 0x030000 enum StringComparisonMode { CaseSensitive = 0x00001, // 0 0001 BeginsWith = 0x00002, // 0 0010 EndsWith = 0x00004, // 0 0100 Contains = 0x00008, // 0 1000 ExactMatch = 0x00010 // 1 0000 }; #endif class OEditListBoxPrivate; /** * An editable listbox * * This class provides a editable listbox ;-), this means * a listbox which is accompanied by a line edit to enter new * items into the listbox and pushbuttons to add and remove * items from the listbox and two buttons to move items up and down. */ class OEditListBox : public QGroupBox { Q_OBJECT public: /// @since 3.1 class CustomEditor { public: CustomEditor() : m_representationWidget( 0L ), m_lineEdit( 0L ) {} CustomEditor( QWidget *repWidget, OLineEdit *edit ) : m_representationWidget( repWidget ), m_lineEdit( edit ) {} CustomEditor( OComboBox *combo ); void setRepresentationWidget( QWidget *repWidget ) { m_representationWidget = repWidget; } void setLineEdit( OLineEdit *edit ) { m_lineEdit = edit; } virtual QWidget *representationWidget() const { return m_representationWidget; } virtual OLineEdit *lineEdit() const { return m_lineEdit; } protected: QWidget *m_representationWidget; OLineEdit *m_lineEdit; }; public: /** * Enumeration of the buttons, the listbox offers. Specify them in the * constructor in the buttons parameter. */ enum Button { Add = 1, Remove = 2, UpDown = 4, All = Add|Remove|UpDown }; /** * Create an editable listbox. * * If @p checkAtEntering is true, after every character you type * in the line edit OEditListBox will enable or disable * the Add-button, depending whether the current content of the * line edit is already in the listbox. Maybe this can become a * performance hit with large lists on slow machines. * If @p checkAtEntering is false, * it will be checked if you press the Add-button. It is not * possible to enter items twice into the listbox. */ OEditListBox(QWidget *parent = 0, const char *name = 0, bool checkAtEntering=false, int buttons = All ); /** * Create an editable listbox. * * The same as the other constructor, additionally it takes * @title, which will be the title of the frame around the listbox. */ OEditListBox(const QString& title, QWidget *parent = 0, const char *name = 0, bool checkAtEntering=false, int buttons = All ); /** * Another constructor, which allows to use a custom editing widget * instead of the standard OLineEdit widget. E.g. you can use a * @ref OURLRequester or a @ref OComboBox as input widget. The custom * editor must consist of a lineedit and optionally another widget that * is used as representation. A OComboBox or a OURLRequester have a * OLineEdit as child-widget for example, so the OComboBox is used as * the representation widget. * * @see OURLRequester::customEditor() * @since 3.1 */ OEditListBox( const QString& title, const CustomEditor &customEditor, QWidget *parent = 0, const char *name = 0, bool checkAtEntering = false, int buttons = All ); virtual ~OEditListBox(); /** * Return a pointer to the embedded QListBox. */ QListBox* listBox() const { return m_listBox; } /** * Return a pointer to the embedded QLineEdit. */ OLineEdit* lineEdit() const { return m_lineEdit; } /** * Return a pointer to the Add button */ QPushButton* addButton() const { return servNewButton; } /** * Return a pointer to the Remove button */ QPushButton* removeButton() const { return servRemoveButton; } /** * Return a pointer to the Up button */ QPushButton* upButton() const { return servUpButton; } /** * Return a pointer to the Down button */ QPushButton* downButton() const { return servDownButton; } /** * See @ref QListBox::count() */ int count() const { return int(m_listBox->count()); } /** * See @ref QListBox::insertStringList() */ void insertStringList(const QStringList& list, int index=-1); /** * See @ref QListBox::insertStringList() */ void insertStrList(const QStrList* list, int index=-1); /** * See @ref QListBox::insertStrList() */ void insertStrList(const QStrList& list, int index=-1); /** * See @ref QListBox::insertStrList() */ void insertStrList(const char ** list, int numStrings=-1, int index=-1); /** * See @ref QListBox::insertItem() */ void insertItem(const QString& text, int index=-1) {m_listBox->insertItem(text,index);} /** * Clears both the listbox and the line edit. */ void clear(); /** * See @ref QListBox::text() */ QString text(int index) const { return m_listBox->text(index); } /** * See @ref QListBox::currentItem() */ int currentItem() const; /** * See @ref QListBox::currentText() */ QString currentText() const { return m_listBox->currentText(); } /** * @returns a stringlist of all items in the listbox */ QStringList items() const; signals: void changed(); /** * This signal is emitted when the user adds a new string to the list, * the parameter is the added string. * @since 3.2 */ void added( const QString & text ); /** * This signal is emitted when the user removes a string from the list, * the parameter is the removed string. * @since 3.2 */ void removed( const QString & text ); protected slots: //the names should be self-explaining void moveItemUp(); void moveItemDown(); void addItem(); void removeItem(); void enableMoveButtons(int index); void typedSomething(const QString& text); private: QListBox *m_listBox; QPushButton *servUpButton, *servDownButton; QPushButton *servNewButton, *servRemoveButton; OLineEdit *m_lineEdit; //this is called in both ctors, to avoid code duplication void init( bool checkAtEntering, int buttons, QWidget *representationWidget = 0L ); protected: virtual void virtual_hook( int id, void* data ); private: //our lovely private d-pointer OEditListBoxPrivate *d; }; #endif // OEDITLISTBOX diff --git a/libopie2/qt3/opieui/ojanuswidget.cpp b/libopie2/qt3/opieui/ojanuswidget.cpp index 063e393..8bdbc03 100644 --- a/libopie2/qt3/opieui/ojanuswidget.cpp +++ b/libopie2/qt3/opieui/ojanuswidget.cpp @@ -1,1116 +1,1116 @@ /* � � � � � � � � This file is part of the Opie Project Originally part of the KDE project (C) 1999-2000 Espen Sand (espensa@online.no) =. .=l. � � � � � �.>+-= �_;:, � � .> � �:=|. This program is free software; you can .> <`_, � > �. � <= redistribute it and/or modify it under :`=1 )Y*s>-.-- � : the terms of the GNU Library General Public .="- .-=="i, � � .._ License as published by the Free Software �- . � .-<_> � � .<> Foundation; either version 2 of the License, � � �._= =} � � � : or (at your option) any later version. � � .%`+i> � � � _;_. � � .i_,=:_. � � �-<s. This program is distributed in the hope that � � �+ �. �-:. � � � = it will be useful, but WITHOUT ANY WARRANTY; � � : .. � �.:, � � . . . without even the implied warranty of � � =_ � � � �+ � � =;=|` MERCHANTABILITY or FITNESS FOR A � _.=:. � � � : � �:=>`: PARTICULAR PURPOSE. See the GNU ..}^=.= � � � = � � � ; Library General Public License for more ++= � -. � � .` � � .: details. �: � � = �...= . :.=- �-. � .:....=;==+<; You should have received a copy of the GNU � -_. . . � )=. �= Library General Public License along with � � -- � � � �:-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* QT */ #include <qbitmap.h> #include <qgrid.h> #include <qhbox.h> #include <qheader.h> #include <qlabel.h> #include <qlayout.h> #include <qobjectlist.h> #include <qpixmap.h> #include <qlistview.h> #include <qsplitter.h> #include <qtabwidget.h> #include <qvbox.h> #include <qwidgetstack.h> #include <qpainter.h> #include <qtimer.h> #include <qstyle.h> /* OPIE */ #include <opie2/odialog.h> #include <opie2/oseparator.h> #include <opie2/ojanuswidget.h> /*====================================================================================== * IconListItem *======================================================================================*/ class OJanusWidget::IconListItem : public QListBoxItem { public: IconListItem( QListBox *listbox, const QPixmap &pixmap, const QString &text ); virtual int height( const QListBox *lb ) const; virtual int width( const QListBox *lb ) const; int expandMinimumWidth( int width ); protected: const QPixmap &defaultPixmap(); void paint( QPainter *painter ); private: QPixmap mPixmap; int mMinimumWidth; }; template class QPtrList<QListViewItem>; /*====================================================================================== * OJanusWidget *======================================================================================*/ OJanusWidget::OJanusWidget( QWidget *parent, const char *name, int face ) : QWidget( parent, name, 0 ), mValid(false), mPageList(0), mTitleList(0), mFace(face), mTitleLabel(0), mActivePageWidget(0), mShowIconsInTreeList(false), d(0) { QVBoxLayout *topLayout = new QVBoxLayout( this ); if( mFace == TreeList || mFace == IconList ) { mPageList = new QPtrList<QWidget>; mTitleList = new QStringList(); QFrame *page; if( mFace == TreeList ) { QSplitter *splitter = new QSplitter( this ); topLayout->addWidget( splitter, 10 ); mTreeListResizeMode = QSplitter::KeepSize; mTreeList = new QListView( splitter ); mTreeList->addColumn( QString::fromLatin1("") ); mTreeList->header()->hide(); mTreeList->setRootIsDecorated(true); mTreeList->setSorting( -1 ); connect( mTreeList, SIGNAL(selectionChanged()), SLOT(slotShowPage()) ); connect( mTreeList, SIGNAL(clicked(QListViewItem*)), SLOT(slotItemClicked(QListViewItem*))); // // Page area. Title at top with a separator below and a pagestack using // all available space at bottom. // QFrame *p = new QFrame( splitter ); QHBoxLayout *hbox = new QHBoxLayout( p, 0, 0 ); hbox->addSpacing( ODialog::spacingHint() ); page = new QFrame( p ); hbox->addWidget( page, 10 ); } else { QHBoxLayout *hbox = new QHBoxLayout( topLayout ); mIconList = new IconListBox( this ); QFont listFont( mIconList->font() ); listFont.setBold( true ); mIconList->setFont( listFont ); mIconList->verticalScrollBar()->installEventFilter( this ); hbox->addWidget( mIconList ); connect( mIconList, SIGNAL(selectionChanged()), SLOT(slotShowPage())); hbox->addSpacing( ODialog::spacingHint() ); page = new QFrame( this ); hbox->addWidget( page, 10 ); } // // Rest of page area. Title at top with a separator below and a // pagestack using all available space at bottom. // QVBoxLayout *vbox = new QVBoxLayout( page, 0, ODialog::spacingHint() ); mTitleLabel = new QLabel( QString::fromLatin1("Empty page"), page, "OJanusWidgetTitleLabel" ); vbox->addWidget( mTitleLabel ); QFont titleFont( mTitleLabel->font() ); titleFont.setBold( true ); mTitleLabel->setFont( titleFont ); mTitleSep = new OSeparator( page ); mTitleSep->setFrameStyle( QFrame::HLine|QFrame::Plain ); vbox->addWidget( mTitleSep ); mPageStack = new QWidgetStack( page ); connect(mPageStack, SIGNAL(aboutToShow(QWidget*)), this, SIGNAL(aboutToShowPage(QWidget*))); vbox->addWidget( mPageStack, 10 ); } else if( mFace == Tabbed ) { mPageList = new QPtrList<QWidget>; mTabControl = new QTabWidget( this ); mTabControl->setMargin (ODialog::marginHint()); topLayout->addWidget( mTabControl, 10 ); } else if( mFace == Swallow ) { mSwallowPage = new QWidget( this ); topLayout->addWidget( mSwallowPage, 10 ); } else { mFace = Plain; mPlainPage = new QFrame( this ); topLayout->addWidget( mPlainPage, 10 ); } /* FIXME: Revise for Opie if ( kapp ) connect(kapp,SIGNAL(kdisplayFontChanged()),SLOT(slotFontChanged())); */ mValid = true; setSwallowedWidget(0); // Set default size if 'mFace' is Swallow. } OJanusWidget::~OJanusWidget() { delete mPageList; mPageList = 0; delete mTitleList; mTitleList = 0; } bool OJanusWidget::isValid() const { return( mValid ); } QFrame *OJanusWidget::plainPage() { return( mPlainPage ); } int OJanusWidget::face() const { return( mFace ); } QWidget *OJanusWidget::FindParent() { if( mFace == Tabbed ) { return mTabControl; } else { return this; } } QFrame *OJanusWidget::addPage( const QStringList &items, const QString &header, const QPixmap &pixmap ) { if( mValid == false ) { qDebug( "addPage: Invalid object" ); return( 0 ); } QFrame *page = new QFrame( FindParent(), "page" ); addPageWidget( page, items, header, pixmap ); return page; } void OJanusWidget::pageGone( QObject *obj ) { removePage( static_cast<QWidget*>( obj ) ); } void OJanusWidget::slotReopen( QListViewItem * item ) { if( item ) item->setOpen( true ); } QFrame *OJanusWidget::addPage( const QString &itemName, const QString &header, const QPixmap &pixmap ) { QStringList items; items << itemName; return addPage(items, header, pixmap); } QVBox *OJanusWidget::addVBoxPage( const QStringList &items, const QString &header, const QPixmap &pixmap ) { if( mValid == false ) { qDebug( "addPage: Invalid object" ); return( 0 ); } QVBox *page = new QVBox(FindParent() , "page" ); page->setSpacing( ODialog::spacingHint() ); addPageWidget( page, items, header, pixmap ); return page; } QVBox *OJanusWidget::addVBoxPage( const QString &itemName, const QString &header, const QPixmap &pixmap ) { QStringList items; items << itemName; return addVBoxPage(items, header, pixmap); } QHBox *OJanusWidget::addHBoxPage( const QStringList &items, const QString &header, const QPixmap &pixmap ) { if( mValid == false ) { qDebug( "addPage: Invalid object" ); return( 0 ); } QHBox *page = new QHBox(FindParent(), "page"); page->setSpacing( ODialog::spacingHint() ); addPageWidget( page, items, header, pixmap ); return page; } QHBox *OJanusWidget::addHBoxPage( const QString &itemName, const QString &header, const QPixmap &pixmap ) { QStringList items; items << itemName; return addHBoxPage(items, header, pixmap); } QGrid *OJanusWidget::addGridPage( int n, Orientation dir, const QStringList &items, const QString &header, const QPixmap &pixmap ) { if( mValid == false ) { qDebug( "addPage: Invalid object" ); return( 0 ); } QGrid *page = new QGrid( n, dir, FindParent(), "page" ); page->setSpacing( ODialog::spacingHint() ); addPageWidget( page, items, header, pixmap ); return page; } QGrid *OJanusWidget::addGridPage( int n, Orientation dir, const QString &itemName, const QString &header, const QPixmap &pixmap ) { QStringList items; items << itemName; return addGridPage(n, dir, items, header, pixmap); } void OJanusWidget::InsertTreeListItem(const QStringList &items, const QPixmap &pixmap, QFrame *page) { bool isTop = true; QListViewItem *curTop = 0, *child, *last, *newChild; unsigned int index = 1; QStringList curPath; for ( QStringList::ConstIterator it = items.begin(); it != items.end(); ++it, index++ ) { QString name = (*it); bool isPath = ( index != items.count() ); // Find the first child. if (isTop) { child = mTreeList->firstChild(); } else { child = curTop->firstChild(); } // Now search for a child with the current Name, and if it we doesn't // find it, then remember the location of the last child. for (last = 0; child && child->text(0) != name ; last = child, child = child->nextSibling()); if (last == 0 && child == 0) { // This node didn't have any children at all, lets just insert the // new child. if (isTop) newChild = new QListViewItem(mTreeList, name); else newChild = new QListViewItem(curTop, name); } else if (child != 0) { // we found the given name in this child. if (!isPath) { qDebug( "The element inserted was already in the TreeList box!" ); return; } else { // Ok we found the folder newChild = child; } } else { // the node had some children, but we didn't find the given name if (isTop) newChild = new QListViewItem(mTreeList, last, name); else newChild = new QListViewItem(curTop, last, name); } // Now make the element expandable if it is a path component, and make // ready for next loop if (isPath) { newChild->setExpandable(true); curTop = newChild; isTop = false; curPath << name; QString key = curPath.join("_/_"); if (mFolderIconMap.contains(key)) { QPixmap p = mFolderIconMap[key]; newChild->setPixmap(0,p); } } else { if (mShowIconsInTreeList) { newChild->setPixmap(0, pixmap); } mTreeListToPageStack.insert(newChild, page); } } } void OJanusWidget::addPageWidget( QFrame *page, const QStringList &items, const QString &header,const QPixmap &pixmap ) { connect(page, SIGNAL(destroyed(QObject*)), SLOT(pageGone(QObject*))); if( mFace == Tabbed ) { mTabControl->addTab (page, items.last()); mPageList->append (page); } else if( mFace == TreeList || mFace == IconList ) { mPageList->append( page ); mPageStack->addWidget( page, 0 ); if (items.count() == 0) { qDebug( "Invalid QStringList, with zero items" ); return; } if( mFace == TreeList ) { InsertTreeListItem(items, pixmap, page); } else // mFace == IconList { QString itemName = items.last(); IconListItem *item = new IconListItem( mIconList, pixmap, itemName ); // // 2000-06-01 Espen Sand: If I do this with Qt 2.1.1 all sorts of // strange things happen. With Qt <= 2.1 it worked but now I must // either specify the listbox in the constructor on the item // or as below, not both. // mIconList->insertItem( item ); // mIconListToPageStack.insert(item, page); mIconList->invalidateHeight(); mIconList->invalidateWidth(); if (mIconList->isVisible()) mIconList->updateWidth(); } // // Make sure the title label is sufficiently wide // QString lastName = items.last(); const QString &title = (header != QString::null ? header : lastName); QRect r = mTitleLabel->fontMetrics().boundingRect( title ); if( mTitleLabel->minimumWidth() < r.width() ) { mTitleLabel->setMinimumWidth( r.width() ); } mTitleList->append( title ); if( mTitleList->count() == 1 ) { showPage(0); } } else { qDebug( "OJanusWidget::addPageWidget: can only add a page in Tabbed, TreeList or IconList modes" ); } } void OJanusWidget::setFolderIcon(const QStringList &path, const QPixmap &pixmap) { QString key = path.join("_/_"); mFolderIconMap.insert(key,pixmap); } bool OJanusWidget::setSwallowedWidget( QWidget *widget ) { if( mFace != Swallow || mValid == false ) { return( false ); } // // Remove current layout and make a new. // if( mSwallowPage->layout() != 0 ) { delete mSwallowPage->layout(); } QGridLayout *gbox = new QGridLayout( mSwallowPage, 1, 1, 0 ); // // Hide old children // QObjectList *l = (QObjectList*)mSwallowPage->children(); // silence please for( uint i=0; i < l->count(); i++ ) { QObject *o = l->at(i); if( o->isWidgetType() ) { ((QWidget*)o)->hide(); } } // // Add new child or make default size // if( widget == 0 ) { gbox->addRowSpacing(0,100); gbox->addColSpacing(0,100); mSwallowPage->setMinimumSize(100,100); } else { if( widget->parent() != mSwallowPage ) { widget->reparent( mSwallowPage, 0, QPoint(0,0) ); } gbox->addWidget(widget, 0, 0 ); gbox->activate(); mSwallowPage->setMinimumSize( widget->minimumSize() ); } return( true ); } bool OJanusWidget::slotShowPage() { if( mValid == false ) { return( false ); } if( mFace == TreeList ) { QListViewItem *node = mTreeList->selectedItem(); if( node == 0 ) { return( false ); } QWidget *stackItem = mTreeListToPageStack[node]; return showPage(stackItem); } else if( mFace == IconList ) { QListBoxItem *node = mIconList->item( mIconList->currentItem() ); if( node == 0 ) { return( false ); } QWidget *stackItem = mIconListToPageStack[node]; return showPage(stackItem); } return( false ); } bool OJanusWidget::showPage( int index ) { if( mPageList == 0 || mValid == false ) { return( false ); } else { return showPage(mPageList->at(index)); } } bool OJanusWidget::showPage( QWidget *w ) { if( w == 0 || mValid == false ) { return( false ); } if( mFace == TreeList || mFace == IconList ) { mPageStack->raiseWidget( w ); mActivePageWidget = w; int index = mPageList->findRef( w ); mTitleLabel->setText( *mTitleList->at(index) ); if( mFace == TreeList ) { QMap<QListViewItem *, QWidget *>::Iterator it; for (it = mTreeListToPageStack.begin(); it != mTreeListToPageStack.end(); ++it){ QListViewItem *key = it.key(); QWidget *val = it.data(); if (val == w) { mTreeList->setSelected(key, true ); break; } } } else { QMap<QListBoxItem *, QWidget *>::Iterator it; for (it = mIconListToPageStack.begin(); it != mIconListToPageStack.end(); ++it){ QListBoxItem *key = it.key(); QWidget *val = it.data(); if (val == w) { mIconList->setSelected( key, true ); break; } } // // 2000-02-13 Espen Sand // Don't ask me why (because I don't know). If I select a page // with the mouse the page is not updated until it receives an // event. It seems this event get lost if the mouse is not moved // when released. The timer ensures the update // QTimer::singleShot( 0, mActivePageWidget, SLOT(update()) ); } } else if( mFace == Tabbed ) { mTabControl->showPage(w); mActivePageWidget = w; } else { return( false ); } return( true ); } int OJanusWidget::activePageIndex() const { if( mFace == TreeList) { QListViewItem *node = mTreeList->selectedItem(); if( node == 0 ) { return -1; } QWidget *stackItem = mTreeListToPageStack[node]; return mPageList->findRef(stackItem); } else if (mFace == IconList) { QListBoxItem *node = mIconList->item( mIconList->currentItem() ); if( node == 0 ) { return( false ); } QWidget *stackItem = mIconListToPageStack[node]; return mPageList->findRef(stackItem); } else if( mFace == Tabbed ) { QWidget *widget = mTabControl->currentPage(); return( widget == 0 ? -1 : mPageList->findRef( widget ) ); } else { return( -1 ); } } int OJanusWidget::pageIndex( QWidget *widget ) const { if( widget == 0 ) { return( -1 ); } else if( mFace == TreeList || mFace == IconList ) { return( mPageList->findRef( widget ) ); } else if( mFace == Tabbed ) { // // The user gets the real page widget with addVBoxPage(), addHBoxPage() // and addGridPage() but not with addPage() which returns a child of // the toplevel page. addPage() returns a QFrame so I check for that. // if( widget->isA("QFrame") ) { return( mPageList->findRef( widget->parentWidget() ) ); } else { return( mPageList->findRef( widget ) ); } } else { return( -1 ); } } void OJanusWidget::slotFontChanged() { #ifdef FIXME if ( mTitleLabel != 0 ) { mTitleLabel->setFont( KGlobalSettings::generalFont() ); QFont titleFont( mTitleLabel->font() ); titleFont.setBold( true ); mTitleLabel->setFont( titleFont ); } #endif if( mFace == IconList ) { QFont listFont( mIconList->font() ); listFont.setBold( true ); mIconList->setFont( listFont ); mIconList->invalidateHeight(); mIconList->invalidateWidth(); } } // makes the treelist behave like the list of kcontrol void OJanusWidget::slotItemClicked(QListViewItem *it) { if(it && (it->childCount()>0)) it->setOpen(!it->isOpen()); } void OJanusWidget::setFocus() { if( mValid == false ) { return; } if( mFace == TreeList ) { mTreeList->setFocus(); } if( mFace == IconList ) { mIconList->setFocus(); } else if( mFace == Tabbed ) { mTabControl->setFocus(); } else if( mFace == Swallow ) { mSwallowPage->setFocus(); } else if( mFace == Plain ) { mPlainPage->setFocus(); } } QSize OJanusWidget::minimumSizeHint() const { if( mFace == TreeList || mFace == IconList ) { QSize s1( ODialog::spacingHint(), ODialog::spacingHint()*2 ); QSize s2(0,0); QSize s3(0,0); QSize s4( mPageStack->sizeHint() ); if( mFace == TreeList ) { -#if QT_VERSION < 300 +#if QT_VERSION < 0x030000 s1.rwidth() += style().splitterWidth(); #else s1.rwidth() += style().pixelMetric( QStyle::PM_SplitterWidth ); #endif s2 = mTreeList->minimumSize(); } else { mIconList->updateMinimumHeight(); mIconList->updateWidth(); s2 = mIconList->minimumSize(); } if( mTitleLabel->isVisible() == true ) { s3 += mTitleLabel->sizeHint(); s3.rheight() += mTitleSep->minimumSize().height(); } // // Select the tallest item. It has only effect in IconList mode // int h1 = s1.rheight() + s3.rheight() + s4.height(); int h2 = QMAX( h1, s2.rheight() ); return( QSize( s1.width()+s2.width()+QMAX(s3.width(),s4.width()), h2 ) ); } else if( mFace == Tabbed ) { return( mTabControl->sizeHint() ); } else if( mFace == Swallow ) { return( mSwallowPage->minimumSize() ); } else if( mFace == Plain ) { return( mPlainPage->sizeHint() ); } else { return( QSize( 100, 100 ) ); // Should never happen though. } } QSize OJanusWidget::sizeHint() const { return( minimumSizeHint() ); } void OJanusWidget::setTreeListAutoResize( bool state ) { if( mFace == TreeList ) { mTreeListResizeMode = state == false ? QSplitter::KeepSize : QSplitter::Stretch; QSplitter *splitter = (QSplitter*)(mTreeList->parentWidget()); splitter->setResizeMode( mTreeList, mTreeListResizeMode ); } } void OJanusWidget::setIconListAllVisible( bool state ) { if( mFace == IconList ) { mIconList->setShowAll( state ); } } void OJanusWidget::setShowIconsInTreeList( bool state ) { mShowIconsInTreeList = state; } void OJanusWidget::setRootIsDecorated( bool state ) { if( mFace == TreeList ) { mTreeList->setRootIsDecorated(state); } } void OJanusWidget::unfoldTreeList( bool persist ) { if( mFace == TreeList ) { if( persist ) connect( mTreeList, SIGNAL( collapsed(QListViewItem*) ), this, SLOT( slotReopen(QListViewItem*) ) ); else disconnect( mTreeList, SIGNAL( collapsed(QListViewItem*) ), this, SLOT( slotReopen(QListViewItem*) ) ); for( QListViewItem * item = mTreeList->firstChild(); item; item = item->itemBelow() ) item->setOpen( true ); } } void OJanusWidget::showEvent( QShowEvent * ) { if( mFace == TreeList ) { QSplitter *splitter = (QSplitter*)(mTreeList->parentWidget()); splitter->setResizeMode( mTreeList, mTreeListResizeMode ); } } // // 2000-13-02 Espen Sand // It should be obvious that this eventfilter must only be // be installed on the vertical scrollbar of the mIconList. // bool OJanusWidget::eventFilter( QObject *o, QEvent *e ) { if( e->type() == QEvent::Show ) { IconListItem *item = (IconListItem*)mIconList->item(0); if( item != 0 ) { int lw = item->width( mIconList ); int sw = mIconList->verticalScrollBar()->sizeHint().width(); mIconList->setFixedWidth( lw+sw+mIconList->frameWidth()*2 ); } } else if( e->type() == QEvent::Hide ) { IconListItem *item = (IconListItem*)mIconList->item(0); if( item != 0 ) { int lw = item->width( mIconList ); mIconList->setFixedWidth( lw+mIconList->frameWidth()*2 ); } } return QWidget::eventFilter( o, e ); } // // Code for the icon list box // OJanusWidget::IconListBox::IconListBox( QWidget *parent, const char *name, WFlags f ) :QListBox( parent, name, f ), mShowAll(false), mHeightValid(false), mWidthValid(false) { } void OJanusWidget::IconListBox::updateMinimumHeight() { if( mShowAll == true && mHeightValid == false ) { int h = frameWidth()*2; for( QListBoxItem *i = item(0); i != 0; i = i->next() ) { h += i->height( this ); } setMinimumHeight( h ); mHeightValid = true; } } void OJanusWidget::IconListBox::updateWidth() { if( mWidthValid == false ) { int maxWidth = 10; for( QListBoxItem *i = item(0); i != 0; i = i->next() ) { int w = ((IconListItem *)i)->width(this); maxWidth = QMAX( w, maxWidth ); } for( QListBoxItem *i = item(0); i != 0; i = i->next() ) { ((IconListItem *)i)->expandMinimumWidth( maxWidth ); } if( verticalScrollBar()->isVisible() ) { maxWidth += verticalScrollBar()->sizeHint().width(); } setFixedWidth( maxWidth + frameWidth()*2 ); mWidthValid = true; } } void OJanusWidget::IconListBox::invalidateHeight() { mHeightValid = false; } void OJanusWidget::IconListBox::invalidateWidth() { mWidthValid = false; } void OJanusWidget::IconListBox::setShowAll( bool showAll ) { mShowAll = showAll; mHeightValid = false; } OJanusWidget::IconListItem::IconListItem( QListBox *listbox, const QPixmap &pixmap, const QString &text ) : QListBoxItem( listbox ) { mPixmap = pixmap; if( mPixmap.isNull() == true ) { mPixmap = defaultPixmap(); } setText( text ); mMinimumWidth = 0; } int OJanusWidget::IconListItem::expandMinimumWidth( int width ) { mMinimumWidth = QMAX( mMinimumWidth, width ); return( mMinimumWidth ); } const QPixmap &OJanusWidget::IconListItem::defaultPixmap() { static QPixmap *pix=0; if( pix == 0 ) { pix = new QPixmap( 32, 32 ); QPainter p( pix ); p.eraseRect( 0, 0, pix->width(), pix->height() ); p.setPen( Qt::red ); p.drawRect ( 0, 0, pix->width(), pix->height() ); p.end(); QBitmap mask( pix->width(), pix->height(), true ); mask.fill( Qt::black ); p.begin( &mask ); p.setPen( Qt::white ); p.drawRect ( 0, 0, pix->width(), pix->height() ); p.end(); pix->setMask( mask ); } return( *pix ); } void OJanusWidget::IconListItem::paint( QPainter *painter ) { QFontMetrics fm = painter->fontMetrics(); //int wt = fm.boundingRect(text()).width(); int wp = mPixmap.width(); int ht = fm.lineSpacing(); int hp = mPixmap.height(); painter->drawPixmap( (mMinimumWidth-wp)/2, 5, mPixmap ); if( text().isEmpty() == false ) { painter->drawText( 0, hp+7, mMinimumWidth, ht, Qt::AlignCenter, text() ); } } int OJanusWidget::IconListItem::height( const QListBox *lb ) const { if( text().isEmpty() == true ) { return( mPixmap.height() ); } else { return( mPixmap.height() + lb->fontMetrics().lineSpacing()+10 ); } } int OJanusWidget::IconListItem::width( const QListBox *lb ) const { int wt = lb->fontMetrics().boundingRect(text()).width()+10; int wp = mPixmap.width() + 10; int w = QMAX( wt, wp ); return( QMAX( w, mMinimumWidth ) ); } // Just remove the page from our stack of widgets. Do not modify the given widget in // any way. No memory leak occurs as parent is not changed. // Make this virtual in KDE 4.0. // Ravikiran Rajagopal <ravi@ee.eng.ohio-state.edu> void OJanusWidget::removePage( QWidget *page ) { if (!mPageList || !mPageList->containsRef(page)) return; int index = mPageList->findRef( page ); if ( mTitleList ) mTitleList->remove(mTitleList->at(index)); mPageList->removeRef(page); if ( mFace == TreeList ) { QMap<QListViewItem*, QWidget *>::Iterator i; for( i = mTreeListToPageStack.begin(); i != mTreeListToPageStack.end(); ++i ) if (i.data()==page) { delete i.key(); mPageStack->removeWidget(page); mTreeListToPageStack.remove(i); break; } } else if ( mFace == IconList ) { QMap<QListBoxItem*, QWidget *>::Iterator i; for( i = mIconListToPageStack.begin(); i != mIconListToPageStack.end(); ++i ) if (i.data()==page) { delete i.key(); mPageStack->removeWidget(page); mIconListToPageStack.remove(i); break; } } else // Tabbed { mTabControl->removePage(page); } } diff --git a/library/lightstyle.cpp b/library/lightstyle.cpp index f18bdca..3bd1623 100644 --- a/library/lightstyle.cpp +++ b/library/lightstyle.cpp @@ -1,1284 +1,1284 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "lightstyle.h" -#if QT_VERSION < 300 +#if QT_VERSION < 0x030000 #define INCLUDE_MENUITEM_DEF #include "qmenubar.h" #include "qapplication.h" #include "qpainter.h" #include "qpalette.h" #include "qframe.h" #include "qpushbutton.h" #include "qdrawutil.h" #include "qscrollbar.h" #include "qtabbar.h" #include "qguardedptr.h" #include "qlayout.h" #include "qlineedit.h" class LightStylePrivate { public: LightStylePrivate() : hoverWidget(0), ref(1), savePalette(0) { } QGuardedPtr<QWidget> hoverWidget; QPalette oldPalette, hoverPalette; int ref; QPoint mousePos; QPalette *savePalette; }; static LightStylePrivate *singleton = 0; LightStyle::LightStyle() : QWindowsStyle() { if (! singleton) { singleton = new LightStylePrivate; QPalette pal = QApplication::palette(); singleton->oldPalette = pal; QColor bg = pal.color(QPalette::Active, QColorGroup::Background); QColor prelight; if ( (bg.red() + bg.green() + bg.blue()) / 3 > 128) prelight = pal.color(QPalette::Active, QColorGroup::Background).light(110); else prelight = pal.color(QPalette::Active, QColorGroup::Background).light(120); QColorGroup active2(pal.color(QPalette::Active, QColorGroup::Foreground), // foreground prelight, // button prelight.light(), // light prelight.dark(), // dark prelight.dark(120), // mid pal.color(QPalette::Active, QColorGroup::Text), // text pal.color(QPalette::Active, QColorGroup::BrightText), // bright text pal.color(QPalette::Active, QColorGroup::Base), // base bg); // background active2.setColor(QColorGroup::Highlight, pal.color(QPalette::Active, QColorGroup::Highlight)); singleton->hoverPalette = pal; singleton->hoverPalette.setActive(active2); singleton->hoverPalette.setInactive(active2); } else singleton->ref++; } LightStyle::~LightStyle() { if (singleton && singleton->ref-- <= 0) { delete singleton; singleton = 0; } } QSize LightStyle::scrollBarExtent() const { return QSize(12 + defaultFrameWidth(), 12 + defaultFrameWidth()); } int LightStyle::buttonDefaultIndicatorWidth() const { return 2; } int LightStyle::sliderThickness() const { return 16; } int LightStyle::sliderLength() const { return 13; } int LightStyle::buttonMargin() const { return 4; } QSize LightStyle::exclusiveIndicatorSize() const { return QSize(13, 13); } int LightStyle::defaultFrameWidth() const { return 2; } QSize LightStyle::indicatorSize() const { return QSize(13, 13); } void LightStyle::polish(QWidget *widget) { if (widget->inherits("QPushButton")) widget->installEventFilter(this); -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 if (widget->inherits("QLineEdit")) { QLineEdit *lineedit = (QLineEdit *) widget; lineedit->setFrameShape(QFrame::StyledPanel); lineedit->setLineWidth(2); } #endif QWindowsStyle::polish(widget); } void LightStyle::unPolish(QWidget *widget) { if (widget->inherits("QPushButton")) widget->removeEventFilter(this); -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 if (widget->inherits("QLineEdit")) { QLineEdit *lineedit = (QLineEdit *) widget; lineedit->setLineWidth(1); lineedit->setFrameShape(QFrame::WinPanel); } #endif QWindowsStyle::unPolish(widget); } void LightStyle::polish(QApplication *app) { QPalette pal = app->palette(); QColorGroup active(pal.color(QPalette::Active, QColorGroup::Foreground), // foreground pal.color(QPalette::Active, QColorGroup::Button), // button pal.color(QPalette::Active, QColorGroup::Background).light(), // light pal.color(QPalette::Active, QColorGroup::Background).dark(175), // dark pal.color(QPalette::Active, QColorGroup::Background).dark(110), // mid pal.color(QPalette::Active, QColorGroup::Text), // text pal.color(QPalette::Active, QColorGroup::BrightText), // bright text pal.color(QPalette::Active, QColorGroup::Base), // base pal.color(QPalette::Active, QColorGroup::Background)), // background disabled(pal.color(QPalette::Disabled, QColorGroup::Foreground), // foreground pal.color(QPalette::Disabled, QColorGroup::Button), // button pal.color(QPalette::Disabled, QColorGroup::Background).light(), // light pal.color(QPalette::Disabled, QColorGroup::Background).dark(), // dark pal.color(QPalette::Disabled, QColorGroup::Background).dark(110), // mid pal.color(QPalette::Disabled, QColorGroup::Text), // text pal.color(QPalette::Disabled, QColorGroup::BrightText), // bright text pal.color(QPalette::Disabled, QColorGroup::Base), // base pal.color(QPalette::Disabled, QColorGroup::Background)); // background active.setColor(QColorGroup::Highlight, pal.color(QPalette::Active, QColorGroup::Highlight)); disabled.setColor(QColorGroup::Highlight, pal.color(QPalette::Disabled, QColorGroup::Highlight)); active.setColor(QColorGroup::HighlightedText, pal.color(QPalette::Active, QColorGroup::HighlightedText)); disabled.setColor(QColorGroup::HighlightedText, pal.color(QPalette::Disabled, QColorGroup::HighlightedText)); pal.setActive(active); pal.setInactive(active); pal.setDisabled(disabled); singleton->oldPalette = pal; QColor bg = pal.color(QPalette::Active, QColorGroup::Background); QColor prelight; if ( (bg.red() + bg.green() + bg.blue()) / 3 > 128) prelight = pal.color(QPalette::Active, QColorGroup::Background).light(110); else prelight = pal.color(QPalette::Active, QColorGroup::Background).light(120); QColorGroup active2(pal.color(QPalette::Active, QColorGroup::Foreground), // foreground prelight, // button prelight.light(), // light prelight.dark(), // dark prelight.dark(120), // mid pal.color(QPalette::Active, QColorGroup::Text), // text pal.color(QPalette::Active, QColorGroup::BrightText), // bright text pal.color(QPalette::Active, QColorGroup::Base), // base bg); // background active2.setColor(QColorGroup::Highlight, pal.color(QPalette::Active, QColorGroup::Highlight)); singleton->hoverPalette = pal; singleton->hoverPalette.setActive(active2); singleton->hoverPalette.setInactive(active2); app->setPalette(pal); } void LightStyle::unPolish(QApplication *app) { app->setPalette(singleton->oldPalette); } void LightStyle::polishPopupMenu(QPopupMenu *menu) { menu->setMouseTracking(TRUE); } void LightStyle::drawPushButton(QPushButton *button, QPainter *p) { int x1, y1, x2, y2; button->rect().coords(&x1, &y1, &x2, &y2); if (button->isDefault()) { p->save(); p->setPen(button->palette().active().color(QColorGroup::Highlight)); p->setBrush(button->palette().active().brush(QColorGroup::Highlight)); p->drawRoundRect(x1, y1, x2 - x1 + 1, y2 - y1 + 1, 15, 15); p->restore(); } if (button->isDefault() || button->autoDefault()) { x1 += buttonDefaultIndicatorWidth(); y1 += buttonDefaultIndicatorWidth(); x2 -= buttonDefaultIndicatorWidth(); y2 -= buttonDefaultIndicatorWidth(); if (button->isDefault()) { QPointArray pa(8); pa.setPoint(0, x1 + 2, y1 ); pa.setPoint(1, x2 - 1, y1 ); pa.setPoint(2, x2 + 1, y1 + 2); pa.setPoint(3, x2 + 1, y2 - 2); pa.setPoint(4, x2 - 2, y2 + 1); pa.setPoint(5, x1 + 2, y2 + 1); pa.setPoint(6, x1, y2 - 1); pa.setPoint(7, x1, y1 + 2); QRegion r(pa); p->setClipRegion(r); } } QBrush fill; if (button->isDown() || button->isOn()) fill = button->colorGroup().brush(QColorGroup::Mid); else fill = button->colorGroup().brush(QColorGroup::Button); if ( !button->isFlat() || button->isOn() || button->isDown() ) drawButton(p, x1, y1, x2 - x1 + 1, y2 - y1 + 1, button->colorGroup(), button->isOn() || button->isDown(), &fill); } void LightStyle::drawButton(QPainter *p, int x, int y, int w, int h, const QColorGroup &g, bool sunken, const QBrush *fill) { p->save(); if ( fill ) p->fillRect(x + 2, y + 2, w - 4, h - 4, *fill); else p->fillRect(x + 2, y + 2, w - 4, h - 4, QBrush(sunken ? g.mid() : g.button())); // frame p->setPen(g.dark()); p->drawLine(x, y + 2, x, y + h - 3); // left p->drawLine(x + 2, y, x + w - 3, y); // top p->drawLine(x + w - 1, y + 2, x + w - 1, y + h - 3); // right p->drawLine(x + 2, y + h - 1, x + w - 3, y + h - 1); // bottom p->drawPoint(x + 1, y + 1); p->drawPoint(x + 1, y + h - 2); p->drawPoint(x + w - 2, y + 1); p->drawPoint(x + w - 2, y + h - 2); // bevel if (sunken) p->setPen(g.mid()); else p->setPen(g.light()); p->drawLine(x + 1, y + 2, x + 1, y + h - 3); // left p->drawLine(x + 2, y + 1, x + w - 3, y + 1); // top if (sunken) p->setPen(g.light()); else p->setPen(g.mid()); p->drawLine(x + w - 2, y + 2, x + w - 2, y + h - 3); // right + 1 p->drawLine(x + 2, y + h - 2, x + w - 3, y + h - 2); // bottom + 1 p->restore(); } void LightStyle::drawBevelButton(QPainter *p, int x, int y, int w, int h, const QColorGroup &g, bool sunken, const QBrush *fill) { drawButton(p, x, y, w, h, g, sunken, fill); } void LightStyle::getButtonShift(int &x, int &y) const { x = y = 0; } void LightStyle::drawComboButton(QPainter *p, int x, int y, int w, int h, const QColorGroup &g, bool, bool editable, bool, const QBrush *fill) { drawButton(p, x, y, w, h, g, FALSE, fill); if (editable) { QRect r = comboButtonRect(x, y, w, h); qDrawShadePanel(p, r.x() - 1, r.y() - 1, r.width() + defaultFrameWidth(), r.height() + defaultFrameWidth(), g, TRUE); } int indent = ((y + h) / 2) - 3; int xpos = x; -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 if( QApplication::reverseLayout() ) xpos += indent; else #endif xpos += w - indent - 5; drawArrow(p, Qt::DownArrow, TRUE, xpos, indent, 5, 5, g, TRUE, fill); } QRect LightStyle::comboButtonRect( int x, int y, int w, int h ) const { QRect r(x + 3, y + 3, w - 6, h - 6); int indent = ((y + h) / 2) - 3; r.setRight(r.right() - indent - 10); -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 if( QApplication::reverseLayout() ) r.moveBy( indent + 10, 0 ); #endif return r; } QRect LightStyle::comboButtonFocusRect(int x, int y, int w, int h ) const { return comboButtonRect(x, y, w, h); } void LightStyle::drawPanel(QPainter *p, int x, int y, int w, int h, const QColorGroup &g, bool sunken, int lw, const QBrush *fill) { if (lw >= 2) { if ( fill ) p->fillRect(x + 2, y + 2, w - 4, h - 4, *fill); QPen oldpen = p->pen(); // frame p->setPen(g.dark()); p->drawLine(x, y + 2, x, y + h - 3); // left p->drawLine(x + 2, y, x + w - 3, y); // top p->drawLine(x + w - 1, y + 2, x + w - 1, y + h - 3); // right p->drawLine(x + 2, y + h - 1, x + w - 3, y + h - 1); // bottom p->drawPoint(x + 1, y + 1); p->drawPoint(x + 1, y + h - 2); p->drawPoint(x + w - 2, y + 1); p->drawPoint(x + w - 2, y + h - 2); // bevel if (sunken) p->setPen(g.mid()); else p->setPen(g.light()); p->drawLine(x + 1, y + 2, x + 1, y + h - 3); // left p->drawLine(x + 2, y + 1, x + w - 3, y + 1); // top if (sunken) p->setPen(g.light()); else p->setPen(g.mid()); p->drawLine(x + w - 2, y + 2, x + w - 2, y + h - 3); // right + 1 p->drawLine(x + 2, y + h - 2, x + w - 3, y + h - 2); // bottom + 1 // corners p->setPen(g.background()); p->drawLine(x, y, x + 1, y); p->drawLine(x, y + h - 1, x + 1, y + h - 1); p->drawLine(x + w - 2, y, x + w - 1, y); p->drawLine(x + w - 2, y + h - 1, x + w - 1, y + h - 1); p->drawPoint(x, y + 1); p->drawPoint(x, y + h - 2); p->drawPoint(x + w - 1, y + 1); p->drawPoint(x + w - 1, y + h - 2); p->setPen(oldpen); } else qDrawShadePanel(p, x, y, w, h, g, sunken, lw, fill); } void LightStyle::drawIndicator(QPainter *p, int x, int y ,int w, int h, const QColorGroup &g, int state, bool down, bool) { drawButton(p, x, y, w, h, g, TRUE, &g.brush(down ? QColorGroup::Mid : QColorGroup::Base)); p->save(); p->setPen(g.foreground()); if (state == QButton::NoChange) { p->drawLine(x + 3, y + h / 2, x + w - 4, y + h / 2); p->drawLine(x + 3, y + 1 + h / 2, x + w - 4, y + 1 + h / 2); p->drawLine(x + 3, y - 1 + h / 2, x + w - 4, y - 1 + h / 2); } else if (state == QButton::On) { p->drawLine(x + 4, y + 3, x + w - 4, y + h - 5); p->drawLine(x + 3, y + 3, x + w - 4, y + h - 4); p->drawLine(x + 3, y + 4, x + w - 5, y + h - 4); p->drawLine(x + 3, y + h - 5, x + w - 5, y + 3); p->drawLine(x + 3, y + h - 4, x + w - 4, y + 3); p->drawLine(x + 4, y + h - 4, x + w - 4, y + 4); } p->restore(); } void LightStyle::drawExclusiveIndicator(QPainter *p, int x, int y, int w, int h, const QColorGroup &g, bool on, bool down, bool) { p->save(); p->fillRect(x, y, w, h, g.brush(QColorGroup::Background)); p->setPen(g.dark()); p->drawArc(x, y, w, h, 0, 16*360); p->setPen(g.mid()); p->drawArc(x + 1, y + 1, w - 2, h - 2, 45*16, 180*16); p->setPen(g.light()); p->drawArc(x + 1, y + 1, w - 2, h - 2, 235*16, 180*16); p->setPen(down ? g.mid() : g.base()); p->setBrush(down ? g.mid() : g.base()); p->drawEllipse(x + 2, y + 2, w - 4, h - 4); if (on) { p->setBrush(g.foreground()); p->drawEllipse(x + 3, y + 3, w - x - 6, h - y - 6); } p->restore(); } #if 1 //copied from QPE style void LightStyle::drawTab( QPainter *p, const QTabBar *tb, QTab *t, bool selected ) { #if 0 //We can't do this, because QTabBar::focusInEvent redraws the // tab label with the default font. QFont f = tb->font(); f.setBold( selected ); p->setFont( f ); #endif QRect r( t->rect() ); if ( tb->shape() == QTabBar::RoundedAbove ) { p->setPen( tb->colorGroup().light() ); p->drawLine( r.left(), r.bottom(), r.right(), r.bottom() ); if ( r.left() == 0 ) p->drawPoint( tb->rect().bottomLeft() ); else { p->setPen( tb->colorGroup().light() ); p->drawLine( r.left(), r.bottom(), r.right(), r.bottom() ); } if ( selected ) { p->setPen( tb->colorGroup().background() ); p->drawLine( r.left()+2, r.top()+1, r.right()-2, r.top()+1 ); p->fillRect( QRect( r.left()+1, r.top()+2, r.width()-2, r.height()-2), tb->colorGroup().brush( QColorGroup::Background )); } else { r.setRect( r.left() + 2, r.top() + 2, r.width() - 4, r.height() - 2 ); p->setPen( tb->colorGroup().button() ); p->drawLine( r.left()+2, r.top()+1, r.right()-2, r.top()+1 ); p->fillRect( QRect( r.left()+1, r.top()+2, r.width()-2, r.height()-3), tb->colorGroup().brush( QColorGroup::Button )); //do shading; will not work for pixmap brushes QColor bg = tb->colorGroup().button(); // int h,s,v; // bg.hsv( &h, &s, &v ); int n = r.height()/2; int dark = 100; for ( int i = 1; i < n; i++ ) { dark = (dark * (100+(i*15)/n) )/100; p->setPen( bg.dark( dark ) ); int y = r.bottom()-n+i; int x1 = r.left()+1; int x2 = r.right()-1; p->drawLine( x1, y, x2, y ); } } p->setPen( tb->colorGroup().light() ); p->drawLine( r.left(), r.bottom()-1, r.left(), r.top() + 2 ); p->drawPoint( r.left()+1, r.top() + 1 ); p->drawLine( r.left()+2, r.top(), r.right() - 2, r.top() ); p->setPen( tb->colorGroup().dark() ); p->drawPoint( r.right() - 1, r.top() + 1 ); p->drawLine( r.right(), r.top() + 2, r.right(), r.bottom() - 1); } else if ( tb->shape() == QTabBar::RoundedBelow ) { if ( selected ) { p->setPen( tb->colorGroup().background() ); p->drawLine( r.left()+2, r.bottom()-1, r.right()-2, r.bottom()-1 ); p->fillRect( QRect( r.left()+1, r.top(), r.width()-2, r.height()-2), tb->palette().normal().brush( QColorGroup::Background )); } else { p->setPen( tb->colorGroup().dark() ); p->drawLine( r.left(), r.top(), r.right(), r.top() ); r.setRect( r.left() + 2, r.top(), r.width() - 4, r.height() - 2 ); p->setPen( tb->colorGroup().button() ); p->drawLine( r.left()+2, r.bottom()-1, r.right()-2, r.bottom()-1 ); p->fillRect( QRect( r.left()+1, r.top()+1, r.width()-2, r.height()-3), tb->palette().normal().brush( QColorGroup::Button )); } p->setPen( tb->colorGroup().dark() ); p->drawLine( r.right(), r.top(), r.right(), r.bottom() - 2 ); p->drawPoint( r.right() - 1, r.bottom() - 1 ); p->drawLine( r.right() - 2, r.bottom(), r.left() + 2, r.bottom() ); p->setPen( tb->colorGroup().light() ); p->drawLine( r.left(), r.top()+1, r.left(), r.bottom() - 2 ); p->drawPoint( r.left() + 1, r.bottom() - 1 ); if ( r.left() == 0 ) p->drawPoint( tb->rect().topLeft() ); } else { QCommonStyle::drawTab( p, tb, t, selected ); } } #else void LightStyle::drawTab(QPainter *p, const QTabBar *tabbar, QTab *tab, bool selected) { p->save(); QColorGroup g = tabbar->colorGroup(); QRect fr(tab->r); fr.setLeft(fr.left() + 2); if (! selected) { if (tabbar->shape() == QTabBar::RoundedAbove || tabbar->shape() == QTabBar::TriangularAbove) { fr.setTop(fr.top() + 2); } else { fr.setBottom(fr.bottom() - 2); } } QRegion tabr(tab->r); QPointArray cliptri(4); cliptri.setPoint(0, fr.left(), fr.top()); cliptri.setPoint(1, fr.left(), fr.top() + 5); cliptri.setPoint(2, fr.left() + 5, fr.top()); cliptri.setPoint(3, fr.left(), fr.top()); QRegion trir(cliptri); p->setClipRegion(tabr - trir); p->setPen( NoPen ); p->setBrush(g.brush(selected ? QColorGroup::Background : QColorGroup::Mid)); fr.setWidth(fr.width() - 1); p->drawRect(fr.left() + 1, fr.top() + 1, fr.width() - 2, fr.height() - 2); if (tabbar->shape() == QTabBar::RoundedAbove) { // "rounded" tabs on top fr.setBottom(fr.bottom() - 1); p->setPen(g.dark()); p->drawLine(fr.left(), fr.top() + 5, fr.left(), fr.bottom() - 1); p->drawLine(fr.left(), fr.top() + 5, fr.left() + 5, fr.top()); p->drawLine(fr.left() + 5, fr.top(), fr.right() - 1, fr.top()); p->drawLine(fr.right(), fr.top() + 1, fr.right(), fr.bottom() - 1); if (selected) { p->drawLine(fr.right(), fr.bottom(), fr.right() + 2, fr.bottom()); p->drawPoint(fr.left(), fr.bottom()); } else p->drawLine(fr.left(), fr.bottom(), fr.right() + 2, fr.bottom()); if (fr.left() == 2) { p->drawPoint(fr.left() - 1, fr.bottom() + 1); p->drawPoint(fr.left() - 2, fr.bottom() + 2); } if (selected) { p->setPen(g.mid()); p->drawLine(fr.right() - 1, fr.top() + 1, fr.right() - 1, fr.bottom() - 2); } p->setPen(g.light()); p->setPen(red); p->drawLine(fr.left() + 1, fr.top() + 6, fr.left() + 1, fr.bottom() - (selected ? 0 : 1)); p->drawLine(fr.left() + 1, fr.top() + 5, fr.left() + 5, fr.top() + 1); p->drawLine(fr.left() + 6, fr.top() + 1, fr.right() - 3, fr.top() + 1); if (selected) { p->drawLine(fr.right() + 1, fr.bottom() + 1, fr.right() + 2, fr.bottom() + 1); p->drawLine(fr.left(), fr.bottom() + 1, fr.left() + 1, fr.bottom() + 1); } else p->drawLine(fr.left(), fr.bottom() + 1, fr.right() + 2, fr.bottom() + 1); } else if (tabbar->shape() == QTabBar::RoundedBelow) { // "rounded" tabs on bottom fr.setTop(fr.top() + 1); p->setPen(g.dark()); p->drawLine(fr.left(), fr.top(), fr.left(), fr.bottom() - 1); p->drawLine(fr.left() + 1, fr.bottom(), fr.right() - 1, fr.bottom()); p->drawLine(fr.right(), fr.top(), fr.right(), fr.bottom() - 1); if (! selected) p->drawLine(fr.left(), fr.top(), fr.right() + 3, fr.top()); else p->drawLine(fr.right(), fr.top(), fr.right() + 3, fr.top()); p->setPen(g.mid()); if (selected) p->drawLine(fr.right() - 1, fr.top() + 1, fr.right() - 1, fr.bottom() - 1); else p->drawLine(fr.left(), fr.top() - 1, fr.right() + 3, fr.top() - 1); p->setPen(g.light()); p->drawLine(fr.left() + 1, fr.top() + (selected ? -1 : 2), fr.left() + 1, fr.bottom() - 1); } else { // triangular drawing code QCommonStyle::drawTab(p, tabbar, tab, selected); } p->restore(); } #endif void LightStyle::drawSlider(QPainter *p, int x, int y, int w, int h, const QColorGroup &g, Qt::Orientation orientation, bool above, bool below) { drawButton(p, x, y, w, h, g, FALSE, &g.brush(QColorGroup::Button)); if (orientation == Horizontal) { if (above && below) { drawArrow(p, Qt::UpArrow, FALSE, x + 1, y + 1, w, h / 2, g, TRUE); drawArrow(p, Qt::DownArrow, FALSE, x + 1, y + (h / 2) - 1, w, h / 2, g, TRUE); } else drawArrow(p, (above) ? Qt::UpArrow : Qt::DownArrow, FALSE, x + 1, y, w, h, g, TRUE); } else { if (above && below) { drawArrow(p, Qt::LeftArrow, FALSE, x + 1, y, w / 2, h, g, TRUE); drawArrow(p, Qt::RightArrow, FALSE, x + (w / 2) - 2, y, w / 2, h, g, TRUE); } else drawArrow(p, (above) ? Qt::LeftArrow : Qt::RightArrow, FALSE, x, y, w, h, g, TRUE); } } void LightStyle::drawSliderGroove(QPainter *p, int x, int y, int w, int h, const QColorGroup& g, QCOORD c, Qt::Orientation orientation) { if (orientation == Horizontal) drawButton(p, x, y+c - 3, w, 6, g, TRUE, &g.brush(QColorGroup::Mid)); else drawButton(p, x+c - 3, y, 6, h, g, TRUE, &g.brush(QColorGroup::Mid)); } void LightStyle::scrollBarMetrics(const QScrollBar *scrollbar, int &sliderMin, int &sliderMax, int &sliderLength, int &buttonDim) const { int maxLength; int length = ((scrollbar->orientation() == Horizontal) ? scrollbar->width() : scrollbar->height()); int extent = ((scrollbar->orientation() == Horizontal) ? scrollbar->height() : scrollbar->width()); extent--; if (length > (extent + defaultFrameWidth() - 1) * 2 + defaultFrameWidth()) buttonDim = extent - defaultFrameWidth(); else buttonDim = (length - defaultFrameWidth()) / 2 - 1; sliderMin = buttonDim; maxLength = length - buttonDim * 3; if (scrollbar->maxValue() != scrollbar->minValue()) { uint range = scrollbar->maxValue() - scrollbar->minValue(); sliderLength = (scrollbar->pageStep() * maxLength) / (range + scrollbar->pageStep()); if (sliderLength < buttonDim || range > INT_MAX / 2) sliderLength = buttonDim; if (sliderLength > maxLength) sliderLength = maxLength; } else sliderLength = maxLength; sliderMax = sliderMin + maxLength - sliderLength; } QStyle::ScrollControl LightStyle::scrollBarPointOver(const QScrollBar *scrollbar, int sliderStart, const QPoint &p) { if (! scrollbar->rect().contains(p)) return NoScroll; int sliderMin, sliderMax, sliderLength, buttonDim, pos; scrollBarMetrics( scrollbar, sliderMin, sliderMax, sliderLength, buttonDim ); if (scrollbar->orientation() == Horizontal) pos = p.x(); else pos = p.y(); if (pos < buttonDim) return SubLine; if (pos < sliderStart) return SubPage; if (pos < sliderStart + sliderLength) return Slider; if (pos < sliderMax + sliderLength) return AddPage; if (pos < sliderMax + sliderLength + buttonDim) return SubLine; return AddLine; } void LightStyle::drawScrollBarControls( QPainter* p, const QScrollBar* scrollbar, int sliderStart, uint controls, uint activeControl ) { QColorGroup g = scrollbar->colorGroup(); int sliderMin, sliderMax, sliderLength, buttonDim; scrollBarMetrics( scrollbar, sliderMin, sliderMax, sliderLength, buttonDim ); if (sliderStart > sliderMax) { // sanity check sliderStart = sliderMax; } QRect addR, subR, subR2, addPageR, subPageR, sliderR; int length = ((scrollbar->orientation() == Horizontal) ? scrollbar->width() : scrollbar->height()); int extent = ((scrollbar->orientation() == Horizontal) ? scrollbar->height() : scrollbar->width()); int fudge = 3; //####disgusting hack if (scrollbar->orientation() == Horizontal) { subR.setRect(0, defaultFrameWidth(), buttonDim + fudge, buttonDim); subR2.setRect(length - (buttonDim * 2), defaultFrameWidth() , buttonDim, buttonDim); addR.setRect(length - buttonDim, defaultFrameWidth(), buttonDim, buttonDim); } else { subR.setRect(defaultFrameWidth() + 1, 0, buttonDim, buttonDim + fudge); subR2.setRect(defaultFrameWidth() + 1, length - (buttonDim * 2), buttonDim, buttonDim); addR.setRect(defaultFrameWidth() + 1, length - buttonDim, buttonDim, buttonDim); } int sliderEnd = sliderStart + sliderLength; int sliderW = extent - defaultFrameWidth() - 1; if (scrollbar->orientation() == Horizontal) { subPageR.setRect( subR.right() + 1, defaultFrameWidth(), sliderStart - subR.right() - 1 , sliderW ); addPageR.setRect( sliderEnd, defaultFrameWidth(), subR2.left() - sliderEnd, sliderW ); sliderR.setRect( sliderStart, defaultFrameWidth(), sliderLength, sliderW ); } else { subPageR.setRect( defaultFrameWidth(), subR.bottom() + 1, sliderW, sliderStart - subR.bottom() - 1 ); addPageR.setRect( defaultFrameWidth(), sliderEnd, sliderW, subR2.top() - sliderEnd ); sliderR .setRect( defaultFrameWidth(), sliderStart, sliderW, sliderLength ); } if ( controls == ( AddLine | SubLine | AddPage | SubPage | Slider | First | Last ) ) { if (scrollbar->orientation() == Horizontal) qDrawShadePanel(p, 0, 0, length, 2, g, TRUE, 1, &g.brush(QColorGroup::Background)); else qDrawShadePanel(p, 0, 0, 2, length, g, TRUE, 1, &g.brush(QColorGroup::Background)); } if ( controls & AddLine ) drawArrow( p, (scrollbar->orientation() == Vertical) ? DownArrow : RightArrow, FALSE, addR.x(), addR.y(), addR.width(), addR.height(), (( activeControl == AddLine ) ? singleton->hoverPalette.active() : g), TRUE, &g.brush(QColorGroup::Background)); if ( controls & SubLine ) { drawArrow( p, (scrollbar->orientation() == Vertical) ? UpArrow : LeftArrow, FALSE, subR.x(), subR.y(), subR.width(), subR.height(), (( activeControl == SubLine ) ? singleton->hoverPalette.active() : g), TRUE, &g.brush(QColorGroup::Background)); drawArrow( p, (scrollbar->orientation() == Vertical) ? UpArrow : LeftArrow, FALSE, subR2.x(), subR2.y(), subR2.width(), subR2.height(), (( activeControl == SubLine ) ? singleton->hoverPalette.active() : g), TRUE, &g.brush(QColorGroup::Background)); } if ( controls & SubPage ) p->fillRect( subPageR, ((activeControl == SubPage) ? g.brush( QColorGroup::Dark ) : g.brush( QColorGroup::Mid ))); if ( controls & AddPage ) p->fillRect( addPageR, ((activeControl == AddPage) ? g.brush( QColorGroup::Dark ) : g.brush( QColorGroup::Mid ))); if ( controls & Slider ) { QPoint bo = p->brushOrigin(); p->setBrushOrigin(sliderR.topLeft()); if ( sliderR.isValid() ) { p->fillRect( sliderR.x(), sliderR.y(), 2, 2, g.brush( QColorGroup::Mid )); p->fillRect( sliderR.x() + sliderR.width() - 2, sliderR.y(), 2, 2, g.brush( QColorGroup::Mid )); p->fillRect( sliderR.x() + sliderR.width() - 2, sliderR.y() + sliderR.height() - 2, 2, 2, g.brush( QColorGroup::Mid )); p->fillRect( sliderR.x(), sliderR.y() + sliderR.height() - 2, 2, 2, g.brush( QColorGroup::Mid )); QColorGroup cg( g ); cg.setBrush( QColorGroup::Background, g.brush( QColorGroup::Mid ) ); drawBevelButton( p, sliderR.x(), sliderR.y(), sliderR.width(), sliderR.height(), cg, FALSE, &g.brush( QColorGroup::Button ) ); } p->setBrushOrigin(bo); } } void LightStyle::drawToolBarHandle(QPainter *p, const QRect &rect, Qt::Orientation orientation, bool, const QColorGroup &g, bool) { p->save(); p->setPen(g.mid()); p->setBrush(g.brush(QColorGroup::Mid)); if (orientation == Qt::Horizontal) { QRect l, r; l.setRect(rect.x() + 1, rect.y() + 1, rect.width() - 5, rect.height() - 2); r.setRect(l.right() + 1, l.y(), 3, l.height()); p->drawRect(l); qDrawShadePanel(p, r, g, FALSE); } else { QRect t, b; t.setRect(rect.x() + 1, rect.y() + 1, rect.width() - 2, rect.height() - 5); b.setRect(t.x(), t.bottom() + 1, t.width(), 3); p->drawRect(t); qDrawShadePanel(p, b, g, FALSE); } p->restore(); } bool LightStyle::eventFilter(QObject *object, QEvent *event) { switch(event->type()) { case QEvent::Enter: { if (! object->isWidgetType() || ! object->inherits("QPushButton")) break; singleton->hoverWidget = (QWidget *) object; if (! singleton->hoverWidget->isEnabled()) { singleton->hoverWidget = 0; break; } QPalette pal = singleton->hoverWidget->palette(); if (singleton->hoverWidget->ownPalette()) singleton->savePalette = new QPalette(pal); singleton->hoverWidget->setPalette(singleton->hoverPalette); break; } case QEvent::Leave: { if (object != singleton->hoverWidget) break; if (singleton->savePalette) { singleton->hoverWidget->setPalette(*(singleton->savePalette)); delete singleton->savePalette; singleton->savePalette = 0; } else singleton->hoverWidget->unsetPalette(); singleton->hoverWidget = 0; break; } default: { ; } } return QWindowsStyle::eventFilter(object, event); } static const int motifItemFrame = 1; // menu item frame width static const int motifSepHeight = 2; // separator item height static const int motifItemHMargin = 1; // menu item hor text margin static const int motifItemVMargin = 2; // menu item ver text margin static const int motifArrowHMargin = 0; // arrow horizontal margin static const int motifTabSpacing = 12; // space between text and tab static const int motifCheckMarkHMargin = 1; // horiz. margins of check mark static const int windowsRightBorder = 8; // right border on windows static const int windowsCheckMarkWidth = 2; // checkmarks width on windows /*! \reimp */ int LightStyle::extraPopupMenuItemWidth( bool checkable, int maxpmw, QMenuItem* mi, const QFontMetrics& /*fm*/ ) { #ifndef QT_NO_MENUDATA int w = 2*motifItemHMargin + 2*motifItemFrame; // a little bit of border can never harm if ( mi->isSeparator() ) return 10; // arbitrary else if ( mi->pixmap() ) w += mi->pixmap()->width(); // pixmap only if ( !mi->text().isNull() ) { if ( mi->text().find('\t') >= 0 ) // string contains tab w += motifTabSpacing; } if ( maxpmw ) { // we have iconsets w += maxpmw; w += 6; // add a little extra border around the iconset } if ( checkable && maxpmw < windowsCheckMarkWidth ) { w += windowsCheckMarkWidth - maxpmw; // space for the checkmarks } if ( maxpmw > 0 || checkable ) // we have a check-column ( iconsets or checkmarks) w += motifCheckMarkHMargin; // add space to separate the columns w += windowsRightBorder; // windows has a strange wide border on the right side return w; #endif } /*! \reimp */ int LightStyle::popupMenuItemHeight( bool /*checkable*/, QMenuItem* mi, const QFontMetrics& fm ) { #ifndef QT_NO_MENUDATA int h = 0; if ( mi->isSeparator() ) // separator height h = motifSepHeight; else if ( mi->pixmap() ) // pixmap height h = mi->pixmap()->height() + 2*motifItemFrame; else // text height h = fm.height() + 2*motifItemVMargin + 2*motifItemFrame; if ( !mi->isSeparator() && mi->iconSet() != 0 ) { h = QMAX( h, mi->iconSet()->pixmap( QIconSet::Small, QIconSet::Normal ).height() + 2*motifItemFrame ); } if ( mi->custom() ) h = QMAX( h, mi->custom()->sizeHint().height() + 2*motifItemVMargin + 2*motifItemFrame ) - 1; return h; #endif } void LightStyle::drawPopupMenuItem( QPainter* p, bool checkable, int maxpmw, int tab, QMenuItem* mi, const QPalette& pal, bool act, bool enabled, int x, int y, int w, int h) { #ifndef QT_NO_MENUDATA const QColorGroup & g = pal.active(); bool dis = !enabled; QColorGroup itemg = dis ? pal.disabled() : pal.active(); if ( checkable ) maxpmw = QMAX( maxpmw, 8 ); // space for the checkmarks int checkcol = maxpmw; if ( mi && mi->isSeparator() ) { // draw separator p->setPen( g.dark() ); p->drawLine( x, y, x+w, y ); p->setPen( g.light() ); p->drawLine( x, y+1, x+w, y+1 ); return; } QBrush fill = act? g.brush( QColorGroup::Highlight ) : g.brush( QColorGroup::Button ); p->fillRect( x, y, w, h, fill); if ( !mi ) return; if ( mi->isChecked() ) { if ( act && !dis ) { qDrawShadePanel( p, x, y, checkcol, h, g, TRUE, 1, &g.brush( QColorGroup::Button ) ); } else { qDrawShadePanel( p, x, y, checkcol, h, g, TRUE, 1, &g.brush( QColorGroup::Midlight ) ); } } else if ( !act ) { p->fillRect(x, y, checkcol , h, g.brush( QColorGroup::Button )); } if ( mi->iconSet() ) { // draw iconset QIconSet::Mode mode = dis ? QIconSet::Disabled : QIconSet::Normal; if (act && !dis ) mode = QIconSet::Active; QPixmap pixmap = mi->iconSet()->pixmap( QIconSet::Small, mode ); int pixw = pixmap.width(); int pixh = pixmap.height(); if ( act && !dis ) { if ( !mi->isChecked() ) qDrawShadePanel( p, x, y, checkcol, h, g, FALSE, 1, &g.brush( QColorGroup::Button ) ); } QRect cr( x, y, checkcol, h ); QRect pmr( 0, 0, pixw, pixh ); pmr.moveCenter( cr.center() ); p->setPen( itemg.text() ); p->drawPixmap( pmr.topLeft(), pixmap ); QBrush fill = act? g.brush( QColorGroup::Highlight ) : g.brush( QColorGroup::Button ); p->fillRect( x+checkcol + 1, y, w - checkcol - 1, h, fill); } else if ( checkable ) { // just "checking"... int mw = checkcol + motifItemFrame; int mh = h - 2*motifItemFrame; if ( mi->isChecked() ) { drawCheckMark( p, x + motifItemFrame + 2, y+motifItemFrame, mw, mh, itemg, act, dis ); } } p->setPen( act ? g.highlightedText() : g.buttonText() ); QColor discol; if ( dis ) { discol = itemg.text(); p->setPen( discol ); } int xm = motifItemFrame + checkcol + motifItemHMargin; if ( mi->custom() ) { int m = motifItemVMargin; p->save(); if ( dis && !act ) { p->setPen( g.light() ); mi->custom()->paint( p, itemg, act, enabled, x+xm+1, y+m+1, w-xm-tab+1, h-2*m ); p->setPen( discol ); } mi->custom()->paint( p, itemg, act, enabled, x+xm, y+m, w-xm-tab+1, h-2*m ); p->restore(); } QString s = mi->text(); if ( !s.isNull() ) { // draw text int t = s.find( '\t' ); int m = motifItemVMargin; const int text_flags = AlignVCenter|ShowPrefix | DontClip | SingleLine; if ( t >= 0 ) { // draw tab text if ( dis && !act ) { p->setPen( g.light() ); p->drawText( x+w-tab-windowsRightBorder-motifItemHMargin-motifItemFrame+1, y+m+1, tab, h-2*m, text_flags, s.mid( t+1 )); p->setPen( discol ); } p->drawText( x+w-tab-windowsRightBorder-motifItemHMargin-motifItemFrame, y+m, tab, h-2*m, text_flags, s.mid( t+1 ) ); } if ( dis && !act ) { p->setPen( g.light() ); p->drawText( x+xm+1, y+m+1, w-xm+1, h-2*m, text_flags, s, t ); p->setPen( discol ); } p->drawText( x+xm, y+m, w-xm-tab+1, h-2*m, text_flags, s, t ); } else if ( mi->pixmap() ) { // draw pixmap QPixmap *pixmap = mi->pixmap(); if ( pixmap->depth() == 1 ) p->setBackgroundMode( OpaqueMode ); p->drawPixmap( x+xm, y+motifItemFrame, *pixmap ); if ( pixmap->depth() == 1 ) p->setBackgroundMode( TransparentMode ); } if ( mi->popup() ) { // draw sub menu arrow int dim = (h-2*motifItemFrame) / 2; if ( act ) { if ( !dis ) discol = white; QColorGroup g2( discol, g.highlight(), white, white, dis ? discol : white, discol, white ); drawArrow( p, RightArrow, FALSE, x+w - motifArrowHMargin - motifItemFrame - dim, y+h/2-dim/2, dim, dim, g2, TRUE ); } else { drawArrow( p, RightArrow, FALSE, x+w - motifArrowHMargin - motifItemFrame - dim, y+h/2-dim/2, dim, dim, g, mi->isEnabled() ); } } #endif } #endif diff --git a/library/lightstyle.h b/library/lightstyle.h index c377cc2..0392957 100644 --- a/library/lightstyle.h +++ b/library/lightstyle.h @@ -1,120 +1,120 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #ifndef LIGHTSTYLE_H #define LIGHTSTYLE_H #ifndef QT_H #include <qstyle.h> #include <qwindowsstyle.h> #endif // QT_H -#if QT_VERSION < 300 +#if QT_VERSION < 0x030000 #ifdef QT_PLUGIN_STYLE_LIGHT # define Q_EXPORT_STYLE_LIGHT #else # define Q_EXPORT_STYLE_LIGHT Q_EXPORT #endif // QT_PLUGIN_STYLE_LIGHT class Q_EXPORT_STYLE_LIGHT LightStyle : public QWindowsStyle { public: LightStyle(); virtual ~LightStyle(); void polish(QWidget *widget); void unPolish(QWidget*widget); void polish(QApplication *app); void unPolish(QApplication *app); void polishPopupMenu(QPopupMenu *menu); void drawPushButton(QPushButton *button, QPainter *p); void drawButton(QPainter *p, int x, int y, int w, int h, const QColorGroup &g, bool sunken = FALSE, const QBrush *fill = 0); void drawBevelButton(QPainter *p, int x, int y, int w, int h, const QColorGroup &g, bool sunken = FALSE, const QBrush *fill = 0); void getButtonShift(int &x, int &y) const; void drawComboButton(QPainter *p, int x, int y, int w, int h, const QColorGroup &g, bool sunken = FALSE, bool editable = FALSE, bool = TRUE, const QBrush *fill = 0); QRect comboButtonRect(int x, int y, int w, int h) const; QRect comboButtonFocusRect(int x, int y, int w, int h) const; void drawIndicator(QPainter *p, int x, int y ,int w, int h, const QColorGroup &g, int state, bool = FALSE, bool = TRUE); QSize indicatorSize() const; void drawExclusiveIndicator(QPainter *p, int x, int y ,int w, int h, const QColorGroup &g, bool on, bool = FALSE, bool = TRUE); QSize exclusiveIndicatorSize() const; void drawPanel(QPainter * p, int x, int y, int w, int h, const QColorGroup &g, bool sunken = FALSE, int = 1, const QBrush * = 0); void scrollBarMetrics( const QScrollBar *, int &, int &, int &, int & ) const; void drawScrollBarControls(QPainter* p, const QScrollBar* sb, int sliderStart, uint controls, uint activeControl); QStyle::ScrollControl scrollBarPointOver(const QScrollBar *, int, const QPoint& p); void drawTab(QPainter *p, const QTabBar *tabbar, QTab *tab, bool selected); void drawSlider(QPainter *p, int x, int y, int w, int h, const QColorGroup &g, Qt::Orientation orientation, bool, bool); void drawSliderGroove(QPainter *p, int x, int y, int w, int h, const QColorGroup& g, QCOORD, Qt::Orientation ); void drawToolBarHandle(QPainter *, const QRect &, Qt::Orientation, bool, const QColorGroup &, bool = FALSE ); QSize scrollBarExtent() const; int buttonDefaultIndicatorWidth() const; int buttonMargin() const; int sliderThickness() const; int sliderLength() const; int defaultFrameWidth() const; int extraPopupMenuItemWidth( bool checkable, int maxpmw, QMenuItem*, const QFontMetrics& ); int popupMenuItemHeight( bool checkable, QMenuItem*, const QFontMetrics& ); void drawPopupMenuItem( QPainter* p, bool checkable, int maxpmw, int tab, QMenuItem* mi, const QPalette& pal, bool act, bool enabled, int x, int y, int w, int h); protected: bool eventFilter(QObject *, QEvent *); }; #endif #endif // LIGHTSTYLE_H diff --git a/library/qpeapplication.cpp b/library/qpeapplication.cpp index af00f49..1c5ced3 100644 --- a/library/qpeapplication.cpp +++ b/library/qpeapplication.cpp @@ -1,2322 +1,2322 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** */ #define QTOPIA_INTERNAL_LANGLIST #include <stdlib.h> #include <unistd.h> #ifndef Q_OS_MACX #include <linux/limits.h> // needed for some toolchains (PATH_MAX) #endif #include <qfile.h> #include <qqueue.h> #ifdef Q_WS_QWS #ifndef QT_NO_COP #if QT_VERSION <= 231 #define private public #define sendLocally processEvent #include "qcopenvelope_qws.h" #undef private #else #include "qcopenvelope_qws.h" #endif #endif #include <qwindowsystem_qws.h> #endif #include <qtextstream.h> #include <qpalette.h> #include <qbuffer.h> #include <qptrdict.h> #include <qregexp.h> #include <qdir.h> #include <qlabel.h> #include <qdialog.h> #include <qdragobject.h> #include <qtextcodec.h> #include <qevent.h> #include <qtooltip.h> #include <qsignal.h> #include <qmainwindow.h> #include <qwidgetlist.h> #include <qpixmapcache.h> #if defined(Q_WS_QWS) && !defined(QT_NO_COP) #define QTOPIA_INTERNAL_INITAPP #include "qpeapplication.h" #include "qpestyle.h" #include "styleinterface.h" -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 #include <qstylefactory.h> #else #include <qplatinumstyle.h> #include <qwindowsstyle.h> #include <qmotifstyle.h> #include <qmotifplusstyle.h> #include "lightstyle.h" #include <qpe/qlibrary.h> #endif #include "global.h" #include "resource.h" #if QT_VERSION <= 230 && defined(QT_NO_CODECS) #include "qutfcodec.h" #endif #include "config.h" #include "network.h" #ifdef QWS #include "fontmanager.h" #include "fontdatabase.h" #endif #include "alarmserver.h" #include "applnk.h" #include "qpemenubar.h" #include "textcodecinterface.h" #include "imagecodecinterface.h" #include <qtopia/qpeglobal.h> #include <unistd.h> #include <sys/file.h> #include <sys/ioctl.h> #ifndef QT_NO_SOUND #include <sys/soundcard.h> #endif #include "qt_override_p.h" #include <backend/rohfeedback.h> static bool useBigPixmaps = 0; class HackWidget : public QWidget { public: bool needsOk() { return (getWState() & WState_Reserved1 ); } QRect normalGeometry() { return topData()->normalGeometry; }; }; class QPEApplicationData { public: QPEApplicationData ( ) : presstimer( 0 ), presswidget( 0 ), rightpressed( false ), kbgrabbed( false ), notbusysent( false ), preloaded( false ), forceshow( false ), nomaximize( false ), keep_running( true ), qcopQok( false ), fontFamily( "Vera" ), fontSize( 10 ), smallIconSize( 14 ), bigIconSize( 32 ), qpe_main_widget( 0 ) { Config cfg( "qpe" ); cfg.setGroup( "Appearance" ); useBigPixmaps = cfg.readBoolEntry( "useBigPixmaps", false ); fontFamily = cfg.readEntry( "FontFamily", "Vera" ); fontSize = cfg.readNumEntry( "FontSize", 10 ); smallIconSize = cfg.readNumEntry( "SmallIconSize", 14 ); bigIconSize = cfg.readNumEntry( "BigIconSize", 32 ); #ifdef OPIE_WITHROHFEEDBACK RoH = 0; #endif } int presstimer; QWidget* presswidget; QPoint presspos; #ifdef OPIE_WITHROHFEEDBACK Opie::Internal::RoHFeedback *RoH; #endif bool rightpressed : 1; bool kbgrabbed : 1; bool notbusysent : 1; bool preloaded : 1; bool forceshow : 1; bool nomaximize : 1; bool keep_running : 1; bool qcopQok : 1; QCString fontFamily; int fontSize; int smallIconSize; int bigIconSize; QString appName; struct QCopRec { QCopRec( const QCString &ch, const QCString &msg, const QByteArray &d ) : channel( ch ), message( msg ), data( d ) { } QCString channel; QCString message; QByteArray data; }; QWidget* qpe_main_widget; QGuardedPtr<QWidget> lastraised; QQueue<QCopRec> qcopq; QString styleName; QString decorationName; void enqueueQCop( const QCString &ch, const QCString &msg, const QByteArray &data ) { qcopq.enqueue( new QCopRec( ch, msg, data ) ); } void sendQCopQ() { if (!qcopQok ) return; QCopRec * r; while((r=qcopq.dequeue())) { // remove from queue before sending... // event loop can come around again before getting // back from sendLocally #ifndef QT_NO_COP QCopChannel::sendLocally( r->channel, r->message, r->data ); #endif delete r; } } static void show_mx(QWidget* mw, bool nomaximize, QString &strName) { if ( mw->inherits("QMainWindow") || mw->isA("QMainWindow") ) { ( ( QMainWindow* ) mw )->setUsesBigPixmaps( useBigPixmaps ); } QPoint p; QSize s; bool max; if ( mw->isVisible() ) { if ( read_widget_rect(strName, max, p, s) && validate_widget_size(mw, p, s) ) { mw->resize(s); mw->move(p); } mw->raise(); } else { if ( mw->layout() && mw->inherits("QDialog") ) { if ( read_widget_rect(strName, max, p, s) && validate_widget_size(mw, p, s) ) { mw->resize(s); mw->move(p); if ( max && !nomaximize ) { mw->showMaximized(); } else { mw->show(); } } else { QPEApplication::showDialog((QDialog*)mw,nomaximize); } } else { if ( read_widget_rect(strName, max, p, s) && validate_widget_size(mw, p, s) ) { mw->resize(s); mw->move(p); } else { //no stored rectangle, make an estimation int x = (qApp->desktop()->width()-mw->frameGeometry().width())/2; int y = (qApp->desktop()->height()-mw->frameGeometry().height())/2; mw->move( QMAX(x,0), QMAX(y,0) ); #ifdef Q_WS_QWS if ( !nomaximize ) mw->showMaximized(); #endif } if ( max && !nomaximize ) mw->showMaximized(); else mw->show(); } } } static bool read_widget_rect(const QString &app, bool &maximized, QPoint &p, QSize &s) { maximized = TRUE; // 350 is the trigger in qwsdefaultdecoration for providing a resize button if ( qApp->desktop()->width() <= 350 ) return FALSE; Config cfg( "qpe" ); cfg.setGroup("ApplicationPositions"); QString str = cfg.readEntry( app, QString::null ); QStringList l = QStringList::split(",", str); if ( l.count() == 5) { p.setX( l[0].toInt() ); p.setY( l[1].toInt() ); s.setWidth( l[2].toInt() ); s.setHeight( l[3].toInt() ); maximized = l[4].toInt(); return TRUE; } return FALSE; } static bool validate_widget_size(const QWidget *w, QPoint &p, QSize &s) { #ifndef Q_WS_QWS QRect qt_maxWindowRect = qApp->desktop()->geometry(); #endif int maxX = qt_maxWindowRect.width(); int maxY = qt_maxWindowRect.height(); int wWidth = s.width() + ( w->frameGeometry().width() - w->geometry().width() ); int wHeight = s.height() + ( w->frameGeometry().height() - w->geometry().height() ); // total window size is not allowed to be larger than desktop window size if ( ( wWidth >= maxX ) && ( wHeight >= maxY ) ) return FALSE; if ( wWidth > maxX ) { s.setWidth( maxX - (w->frameGeometry().width() - w->geometry().width() ) ); wWidth = maxX; } if ( wHeight > maxY ) { s.setHeight( maxY - (w->frameGeometry().height() - w->geometry().height() ) ); wHeight = maxY; } // any smaller than this and the maximize/close/help buttons will be overlapping if ( wWidth < 80 || wHeight < 60 ) return FALSE; if ( p.x() < 0 ) p.setX(0); if ( p.y() < 0 ) p.setY(0); if ( p.x() + wWidth > maxX ) p.setX( maxX - wWidth ); if ( p.y() + wHeight > maxY ) p.setY( maxY - wHeight ); return TRUE; } static void store_widget_rect(QWidget *w, QString &app) { // 350 is the trigger in qwsdefaultdecoration for providing a resize button if ( qApp->desktop()->width() <= 350 ) return; // we use these to map the offset of geometry and pos. ( we can only use normalGeometry to // get the non-maximized version, so we have to do it the hard way ) int offsetX = w->x() - w->geometry().left(); int offsetY = w->y() - w->geometry().top(); QRect r; if ( w->isMaximized() ) r = ( (HackWidget *) w)->normalGeometry(); else r = w->geometry(); // Stores the window placement as pos(), size() (due to the offset mapping) Config cfg( "qpe" ); cfg.setGroup("ApplicationPositions"); QString s; s.sprintf("%d,%d,%d,%d,%d", r.left() + offsetX, r.top() + offsetY, r.width(), r.height(), w->isMaximized() ); cfg.writeEntry( app, s ); } static bool setWidgetCaptionFromAppName( QWidget* /*mw*/, const QString& /*appName*/, const QString& /*appsPath*/ ) { /* // This works but disable it for now until it is safe to apply // What is does is scan the .desktop files of all the apps for // the applnk that has the corresponding argv[0] as this program // then it uses the name stored in the .desktop file as the caption // for the main widget. This saves duplicating translations for // the app name in the program and in the .desktop files. AppLnkSet apps( appsPath ); QList<AppLnk> appsList = apps.children(); for ( QListIterator<AppLnk> it(appsList); it.current(); ++it ) { if ( (*it)->exec() == appName ) { mw->setCaption( (*it)->name() ); return TRUE; } } */ return FALSE; } void show(QWidget* mw, bool nomax) { setWidgetCaptionFromAppName( mw, appName, QPEApplication::qpeDir() + "apps" ); nomaximize = nomax; qpe_main_widget = mw; qcopQok = TRUE; #ifndef QT_NO_COP sendQCopQ(); #endif if ( preloaded ) { if (forceshow) show_mx(mw, nomax, appName); } else if ( keep_running ) { show_mx(mw, nomax, appName); } } void loadTextCodecs() { QString path = QPEApplication::qpeDir() + "plugins/textcodecs"; #ifdef Q_OS_MACX QDir dir( path, "lib*.dylib" ); #else QDir dir( path, "lib*.so" ); #endif QStringList list; if ( dir. exists ( )) list = dir.entryList(); QStringList::Iterator it; for ( it = list.begin(); it != list.end(); ++it ) { TextCodecInterface *iface = 0; QLibrary *lib = new QLibrary( path + "/" + *it ); if ( lib->queryInterface( IID_QtopiaTextCodec, (QUnknownInterface**)&iface ) == QS_OK && iface ) { QValueList<int> mibs = iface->mibEnums(); for (QValueList<int>::ConstIterator i = mibs.begin(); i != mibs.end(); ++i) { (void)iface->createForMib(*i); // ### it exists now; need to remember if we can delete it } } else { lib->unload(); delete lib; } } } void loadImageCodecs() { QString path = QPEApplication::qpeDir() + "plugins/imagecodecs"; #ifdef Q_OS_MACX QDir dir( path, "lib*.dylib" ); #else QDir dir( path, "lib*.so" ); #endif QStringList list; if ( dir. exists ( )) list = dir.entryList(); QStringList::Iterator it; for ( it = list.begin(); it != list.end(); ++it ) { ImageCodecInterface *iface = 0; QLibrary *lib = new QLibrary( path + "/" + *it ); if ( lib->queryInterface( IID_QtopiaImageCodec, (QUnknownInterface**)&iface ) == QS_OK && iface ) { QStringList formats = iface->keys(); for (QStringList::ConstIterator i = formats.begin(); i != formats.end(); ++i) { (void)iface->installIOHandler(*i); // ### it exists now; need to remember if we can delete it } } else { lib->unload(); delete lib; } } } }; class ResourceMimeFactory : public QMimeSourceFactory { public: ResourceMimeFactory() : resImage( 0 ) { setFilePath( Global::helpPath() ); setExtensionType( "html", "text/html;charset=UTF-8" ); } ~ResourceMimeFactory() { delete resImage; } const QMimeSource* data( const QString& abs_name ) const { const QMimeSource * r = QMimeSourceFactory::data( abs_name ); if ( !r ) { int sl = abs_name.length(); do { sl = abs_name.findRev( '/', sl - 1 ); QString name = sl >= 0 ? abs_name.mid( sl + 1 ) : abs_name; int dot = name.findRev( '.' ); if ( dot >= 0 ) name = name.left( dot ); QImage img = Resource::loadImage( name ); if ( !img.isNull() ) { delete resImage; resImage = new QImageDrag( img ); r = resImage; } } while ( !r && sl > 0 ); } return r; } private: mutable QImageDrag *resImage; }; static int& hack(int& i) { #if QT_VERSION <= 230 && defined(QT_NO_CODECS) // These should be created, but aren't in Qt 2.3.0 (void)new QUtf8Codec; (void)new QUtf16Codec; #endif return i; } static int muted = 0; static int micMuted = 0; static void setVolume( int t = 0, int percent = -1 ) { switch ( t ) { case 0: { Config cfg( "qpe" ); cfg.setGroup( "Volume" ); if ( percent < 0 ) percent = cfg.readNumEntry( "VolumePercent", 50 ); #ifndef QT_NO_SOUND int fd = 0; #ifdef QT_QWS_DEVFS if ( ( fd = open( "/dev/sound/mixer", O_RDWR ) ) >= 0 ) { #else if ( ( fd = open( "/dev/mixer", O_RDWR ) ) >= 0 ) { #endif int vol = muted ? 0 : percent; // set both channels to same volume vol |= vol << 8; ioctl( fd, MIXER_WRITE( SOUND_MIXER_VOLUME ), &vol ); ::close( fd ); } #endif } break; } } static void setMic( int t = 0, int percent = -1 ) { switch ( t ) { case 0: { Config cfg( "qpe" ); cfg.setGroup( "Volume" ); if ( percent < 0 ) percent = cfg.readNumEntry( "Mic", 50 ); #ifndef QT_NO_SOUND int fd = 0; int mic = micMuted ? 0 : percent; #ifdef QT_QWS_DEVFS if ( ( fd = open( "/dev/sound/mixer", O_RDWR ) ) >= 0 ) { #else if ( ( fd = open( "/dev/mixer", O_RDWR ) ) >= 0 ) { #endif ioctl( fd, MIXER_WRITE( SOUND_MIXER_MIC ), &mic ); ::close( fd ); } #endif } break; } } static void setBass( int t = 0, int percent = -1 ) { switch ( t ) { case 0: { Config cfg( "qpe" ); cfg.setGroup( "Volume" ); if ( percent < 0 ) percent = cfg.readNumEntry( "BassPercent", 50 ); #ifndef QT_NO_SOUND int fd = 0; int bass = percent; #ifdef QT_QWS_DEVFS if ( ( fd = open( "/dev/sound/mixer", O_RDWR ) ) >= 0 ) { #else if ( ( fd = open( "/dev/mixer", O_RDWR ) ) >= 0 ) { #endif ioctl( fd, MIXER_WRITE( SOUND_MIXER_BASS ), &bass ); ::close( fd ); } #endif } break; } } static void setTreble( int t = 0, int percent = -1 ) { switch ( t ) { case 0: { Config cfg( "qpe" ); cfg.setGroup( "Volume" ); if ( percent < 0 ) percent = cfg.readNumEntry( "TreblePercent", 50 ); #ifndef QT_NO_SOUND int fd = 0; int treble = percent; #ifdef QT_QWS_DEVFS if ( ( fd = open( "/dev/sound/mixer", O_RDWR ) ) >= 0 ) { #else if ( ( fd = open( "/dev/mixer", O_RDWR ) ) >= 0 ) { #endif ioctl( fd, MIXER_WRITE( SOUND_MIXER_TREBLE ), &treble ); ::close( fd ); } #endif } break; } } /** \class QPEApplication \brief The QPEApplication class implements various system services that are available to all Qtopia applications. Simply by using QPEApplication instead of QApplication, a standard Qt application becomes a Qtopia application. It automatically follows style changes, quits and raises, and in the case of \link docwidget.html document-oriented\endlink applications, changes the currently displayed document in response to the environment. To create a \link docwidget.html document-oriented\endlink application use showMainDocumentWidget(); to create a non-document-oriented application use showMainWidget(). The keepRunning() function indicates whether the application will continue running after it's processed the last \link qcop.html QCop\endlink message. This can be changed using setKeepRunning(). A variety of signals are emitted when certain events occur, for example, timeChanged(), clockChanged(), weekChanged(), dateFormatChanged() and volumeChanged(). If the application receives a \link qcop.html QCop\endlink message on the application's QPE/Application/\e{appname} channel, the appMessage() signal is emitted. There are also flush() and reload() signals, which are emitted when synching begins and ends respectively - upon these signals, the application should save and reload any data files that are involved in synching. Most of these signals will initially be received and unfiltered through the appMessage() signal. This class also provides a set of useful static functions. The qpeDir() and documentDir() functions return the respective paths. The grabKeyboard() and ungrabKeyboard() functions are used to control whether the application takes control of the device's physical buttons (e.g. application launch keys). The stylus' mode of operation is set with setStylusOperation() and retrieved with stylusOperation(). There are also setInputMethodHint() and inputMethodHint() functions. \ingroup qtopiaemb */ /*! \fn void QPEApplication::clientMoused() \internal */ /*! \fn void QPEApplication::timeChanged(); This signal is emitted when the time changes outside the normal passage of time, i.e. if the time is set backwards or forwards. */ /*! \fn void QPEApplication::clockChanged( bool ampm ); This signal is emitted when the user changes the clock's style. If \a ampm is TRUE, the user wants a 12-hour AM/PM clock, otherwise, they want a 24-hour clock. */ /*! \fn void QPEApplication::volumeChanged( bool muted ) This signal is emitted whenever the mute state is changed. If \a muted is TRUE, then sound output has been muted. */ /*! \fn void QPEApplication::weekChanged( bool startOnMonday ) This signal is emitted if the week start day is changed. If \a startOnMonday is TRUE then the first day of the week is Monday; if \a startOnMonday is FALSE then the first day of the week is Sunday. */ /*! \fn void QPEApplication::dateFormatChanged(DateFormat) This signal is emitted whenever the date format is changed. */ /*! \fn void QPEApplication::flush() ### */ /*! \fn void QPEApplication::reload() */ void QPEApplication::processQCopFile() { QString qcopfn("/tmp/qcop-msg-"); qcopfn += d->appName; // append command name QFile f(qcopfn); if ( f.open(IO_ReadWrite) ) { #ifndef Q_OS_WIN32 flock(f.handle(), LOCK_EX); #endif QDataStream ds(&f); QCString channel, message; QByteArray data; while(!ds.atEnd()) { ds >> channel >> message >> data; d->enqueueQCop(channel,message,data); } ::ftruncate(f.handle(), 0); #ifndef Q_OS_WIN32 f.flush(); flock(f.handle(), LOCK_UN); #endif } #endif } /*! \fn void QPEApplication::appMessage( const QCString& msg, const QByteArray& data ) This signal is emitted when a message is received on this application's QPE/Application/<i>appname</i> \link qcop.html QCop\endlink channel. The slot to which you connect this signal uses \a msg and \a data in the following way: \code void MyWidget::receive( const QCString& msg, const QByteArray& data ) { QDataStream stream( data, IO_ReadOnly ); if ( msg == "someMessage(int,int,int)" ) { int a,b,c; stream >> a >> b >> c; ... } else if ( msg == "otherMessage(QString)" ) { ... } } \endcode \sa qcop.html Note that messages received here may be processed by qpe application and emitted as signals, such as flush() and reload(). */ #ifndef QT_NO_TRANSLATION static void qtopia_loadTranslations( const QStringList& qms ) { QStringList langs = Global::languageList(); for (QStringList::ConstIterator it = langs.begin(); it!=langs.end(); ++it) { QString lang = *it; QTranslator * trans; QString tfn; for (QStringList::ConstIterator qmit = qms.begin(); qmit!=qms.end(); ++qmit) { trans = new QTranslator(qApp); tfn = QPEApplication::qpeDir() + "i18n/" + lang + "/" + *qmit + ".qm"; if ( trans->load( tfn )) qApp->installTranslator( trans ); else delete trans; } } } #endif /* Turn off qDebug in release mode */ static void qtopiaMsgHandler(QtMsgType type, const char* msg) { switch ( type ) { case QtDebugMsg: #ifdef QT_DEBUG fprintf( stderr, "Debug: %s\n", msg ); #endif break; case QtWarningMsg: #ifdef QT_DEBUG fprintf( stderr, "Warning: %s\n", msg ); #endif break; case QtFatalMsg: fprintf( stderr, "Fatal: %s\n", msg ); abort(); } } /*! Constructs a QPEApplication just as you would construct a QApplication, passing \a argc, \a argv, and \a t. For applications, \a t should be the default, GuiClient. Only the Qtopia server passes GuiServer. */ QPEApplication::QPEApplication( int & argc, char **argv, Type t ) : QApplication( hack(argc), argv, t ), pidChannel( 0 ) { QPixmapCache::setCacheLimit(256); // sensible default for smaller devices. qInstallMsgHandler(qtopiaMsgHandler); d = new QPEApplicationData; d->loadTextCodecs(); d->loadImageCodecs(); setFont( QFont( d->fontFamily, d->fontSize ) ); AppLnk::setSmallIconSize( d->smallIconSize ); AppLnk::setBigIconSize( d->bigIconSize ); QMimeSourceFactory::setDefaultFactory( new ResourceMimeFactory ); connect( this, SIGNAL( lastWindowClosed() ), this, SLOT( hideOrQuit() ) ); sysChannel = new QCopChannel( "QPE/System", this ); connect( sysChannel, SIGNAL( received(const QCString&,const QByteArray&) ), this, SLOT( systemMessage(const QCString&,const QByteArray&) ) ); /* COde now in initapp */ #if 0 #if defined(Q_WS_QWS) && !defined(QT_NO_COP) QString qcopfn( "/tmp/qcop-msg-" ); qcopfn += QString( argv[ 0 ] ); // append command name QFile f( qcopfn ); if ( f.open( IO_ReadOnly ) ) { flock( f.handle(), LOCK_EX ); } QCString channel = QCString( argv[ 0 ] ); channel.replace( QRegExp( ".*/" ), "" ); d->appName = channel; channel = "QPE/Application/" + channel; pidChannel = new QCopChannel( channel, this ); connect( pidChannel, SIGNAL( received(const QCString&,const QByteArray&) ), this, SLOT( pidMessage(const QCString&,const QByteArray&) ) ); if ( f.isOpen() ) { d->keep_running = FALSE; QDataStream ds( &f ); QCString channel, message; QByteArray data; while ( !ds.atEnd() ) { ds >> channel >> message >> data; d->enqueueQCop( channel, message, data ); } flock( f.handle(), LOCK_UN ); f.close(); f.remove(); } for ( int a = 0; a < argc; a++ ) { if ( qstrcmp( argv[ a ], "-preload" ) == 0 ) { argv[ a ] = argv[ a + 1 ]; a++; d->preloaded = TRUE; argc -= 1; } else if ( qstrcmp( argv[ a ], "-preload-show" ) == 0 ) { argv[ a ] = argv[ a + 1 ]; a++; d->preloaded = TRUE; d->forceshow = TRUE; argc -= 1; } } /* overide stored arguments */ setArgs( argc, argv ); #endif #else initApp( argc, argv ); #endif #ifdef Q_WS_QWS /* load the font renderer factories */ FontDatabase::loadRenderers(); #endif #ifndef QT_NO_TRANSLATION QStringList qms; qms << "libqpe"; qms << "libopie"; qms << d->appName; qtopia_loadTranslations(qms); #endif applyStyle(); if ( type() == GuiServer ) { setVolume(); } installEventFilter( this ); QPEMenuToolFocusManager::initialize(); #ifdef QT_NO_QWS_CURSOR // if we have no cursor, probably don't want tooltips QToolTip::setEnabled( FALSE ); #endif } #ifdef QTOPIA_INTERNAL_INITAPP void QPEApplication::initApp( int argc, char **argv ) { delete pidChannel; d->keep_running = TRUE; d->preloaded = FALSE; d->forceshow = FALSE; QCString channel = QCString(argv[0]); channel.replace(QRegExp(".*/"),""); d->appName = channel; #ifndef QT_NO_TRANSLATION qtopia_loadTranslations( QStringList()<<channel ); #endif #if QT_VERSION > 235 qt_fbdpy->setIdentity( channel ); // In Qt/E 2.3.6 #endif channel = "QPE/Application/" + channel; pidChannel = new QCopChannel( channel, this); connect( pidChannel, SIGNAL(received(const QCString&,const QByteArray&)), this, SLOT(pidMessage(const QCString&,const QByteArray&))); processQCopFile(); d->keep_running = d->qcopq.isEmpty(); for (int a=0; a<argc; a++) { if ( qstrcmp(argv[a],"-preload")==0 ) { argv[a] = argv[a+1]; a++; d->preloaded = TRUE; argc-=1; } else if ( qstrcmp(argv[a],"-preload-show")==0 ) { argv[a] = argv[a+1]; a++; d->preloaded = TRUE; d->forceshow = TRUE; argc-=1; } } /* overide stored arguments */ setArgs(argc, argv); } #endif static QPtrDict<void>* inputMethodDict = 0; static void createInputMethodDict() { if ( !inputMethodDict ) inputMethodDict = new QPtrDict<void>; } /*! Returns the currently set hint to the system as to whether widget \a w has any use for text input methods. \sa setInputMethodHint() InputMethodHint */ QPEApplication::InputMethodHint QPEApplication::inputMethodHint( QWidget * w ) { if ( inputMethodDict && w ) return ( InputMethodHint ) ( int ) inputMethodDict->find( w ); return Normal; } /*! \enum QPEApplication::InputMethodHint \value Normal the application sometimes needs text input (the default). \value AlwaysOff the application never needs text input. \value AlwaysOn the application always needs text input. */ /*! Hints to the system that widget \a w has use for text input methods as specified by \a mode. \sa inputMethodHint() InputMethodHint */ void QPEApplication::setInputMethodHint( QWidget * w, InputMethodHint mode ) { createInputMethodDict(); if ( mode == Normal ) { inputMethodDict->remove ( w ); } else { inputMethodDict->insert( w, ( void* ) mode ); } } class HackDialog : public QDialog { public: void acceptIt() { accept(); } void rejectIt() { reject(); } }; void QPEApplication::mapToDefaultAction( QWSKeyEvent * ke, int key ) { // specialised actions for certain widgets. May want to // add more stuff here. if ( activePopupWidget() && activePopupWidget() ->inherits( "QListBox" ) && activePopupWidget() ->parentWidget() && activePopupWidget() ->parentWidget() ->inherits( "QComboBox" ) ) key = Qt::Key_Return; if ( activePopupWidget() && activePopupWidget() ->inherits( "QPopupMenu" ) ) key = Qt::Key_Return; #ifdef QWS ke->simpleData.keycode = key; #endif } /*! \internal */ #ifdef QWS bool QPEApplication::qwsEventFilter( QWSEvent * e ) { if ( !d->notbusysent && e->type == QWSEvent::Focus ) { if ( qApp->type() != QApplication::GuiServer ) { QCopEnvelope e( "QPE/System", "notBusy(QString)" ); e << d->appName; } d->notbusysent = TRUE; } if ( type() == GuiServer ) { switch ( e->type ) { case QWSEvent::Mouse: if ( e->asMouse() ->simpleData.state && !QWidget::find( e->window() ) ) emit clientMoused(); break; default: break; } } if ( e->type == QWSEvent::Key ) { QWSKeyEvent *ke = ( QWSKeyEvent * ) e; if ( ke->simpleData.keycode == Qt::Key_F33 ) { // Use special "OK" key to press "OK" on top level widgets QWidget * active = activeWindow(); QWidget *popup = 0; if ( active && active->isPopup() ) { popup = active; active = active->parentWidget(); } if ( active && ( int ) active->winId() == ke->simpleData.window && !active->testWFlags( WStyle_Customize | WType_Popup | WType_Desktop ) ) { if ( ke->simpleData.is_press ) { if ( popup ) popup->close(); if ( active->inherits( "QDialog" ) ) { HackDialog * d = ( HackDialog * ) active; d->acceptIt(); return TRUE; } else if ( ( ( HackWidget * ) active ) ->needsOk() ) { QSignal s; s.connect( active, SLOT( accept() ) ); s.activate(); } else { // do the same as with the select key: Map to the default action of the widget: mapToDefaultAction( ke, Qt::Key_Return ); } } } } else if ( ke->simpleData.keycode == Qt::Key_F30 ) { // Use special "select" key to do whatever default action a widget has mapToDefaultAction( ke, Qt::Key_Space ); } else if ( ke->simpleData.keycode == Qt::Key_Escape && ke->simpleData.is_press ) { // Escape key closes app if focus on toplevel QWidget * active = activeWindow(); if ( active && active->testWFlags( WType_TopLevel ) && ( int ) active->winId() == ke->simpleData.window && !active->testWFlags( WStyle_Dialog | WStyle_Customize | WType_Popup | WType_Desktop ) ) { if ( active->inherits( "QDialog" ) ) { HackDialog * d = ( HackDialog * ) active; d->rejectIt(); return TRUE; } else /*if ( strcmp( argv() [ 0 ], "embeddedkonsole" ) != 0 )*/ { active->close(); } } } else if ( ke->simpleData.keycode >= Qt::Key_F1 && ke->simpleData.keycode <= Qt::Key_F29 ) { // this should be if ( ODevice::inst ( )-> buttonForKeycode ( ... )) // but we cannot access libopie function within libqpe :( QWidget * active = activeWindow ( ); if ( active && ((int) active-> winId ( ) == ke-> simpleData.window )) { if ( d-> kbgrabbed ) { // we grabbed the keyboard QChar ch ( ke-> simpleData.unicode ); QKeyEvent qke ( ke-> simpleData. is_press ? QEvent::KeyPress : QEvent::KeyRelease, ke-> simpleData.keycode, ch. latin1 ( ), ke-> simpleData.modifiers, QString ( ch ), ke-> simpleData.is_auto_repeat, 1 ); QObject *which = QWidget::keyboardGrabber ( ); if ( !which ) which = QApplication::focusWidget ( ); if ( !which ) which = QApplication::activeWindow ( ); if ( !which ) which = qApp; QApplication::sendEvent ( which, &qke ); } else { // we didn't grab the keyboard, so send the event to the launcher QCopEnvelope e ( "QPE/Launcher", "deviceButton(int,int,int)" ); e << int( ke-> simpleData.keycode ) << int( ke-> simpleData. is_press ) << int( ke-> simpleData.is_auto_repeat ); } } return true; } } if ( e->type == QWSEvent::Focus ) { QWSFocusEvent * fe = ( QWSFocusEvent* ) e; if ( !fe->simpleData.get_focus ) { QWidget * active = activeWindow(); while ( active && active->isPopup() ) { active->close(); active = activeWindow(); } } else { // make sure our modal widget is ALWAYS on top QWidget *topm = activeModalWidget(); if ( topm && static_cast<int>( topm->winId() ) != fe->simpleData.window) { topm->raise(); } } if ( fe->simpleData.get_focus && inputMethodDict ) { InputMethodHint m = inputMethodHint( QWidget::find( e->window() ) ); if ( m == AlwaysOff ) Global::hideInputMethod(); if ( m == AlwaysOn ) Global::showInputMethod(); } } return QApplication::qwsEventFilter( e ); } #endif /*! Destroys the QPEApplication. */ QPEApplication::~QPEApplication() { ungrabKeyboard(); #if defined(Q_WS_QWS) && !defined(QT_NO_COP) // Need to delete QCopChannels early, since the display will // be gone by the time we get to ~QObject(). delete sysChannel; delete pidChannel; #endif #ifdef OPIE_WITHROHFEEDBACK if( d->RoH ) delete d->RoH; #endif delete d; } /*! Returns <tt>$OPIEDIR/</tt>. */ QString QPEApplication::qpeDir() { QString base, dir; if (getenv( "OPIEDIR" )) base = QString(getenv("OPIEDIR")).stripWhiteSpace(); if ( !base.isNull() && (base.length() > 0 )){ #ifdef Q_OS_WIN32 QString temp(base); if (temp[(int)temp.length()-1] != QDir::separator()) temp.append(QDir::separator()); dir = temp; #else dir = QString( base ) + "/"; #endif }else{ dir = QString( ".." ) + QDir::separator(); } return dir; } /*! Returns the user's current Document directory. There is a trailing "/". .. well, it does now,, and there's no trailing '/' */ QString QPEApplication::documentDir() { const char* base = getenv( "HOME"); if ( base ) return QString( base ) + "/Documents"; return QString( "../Documents" ); } static int deforient = -1; /*! \internal */ int QPEApplication::defaultRotation() { if ( deforient < 0 ) { QString d = getenv( "QWS_DISPLAY" ); if ( d.contains( "Rot90" ) ) { deforient = 90; } else if ( d.contains( "Rot180" ) ) { deforient = 180; } else if ( d.contains( "Rot270" ) ) { deforient = 270; } else { deforient = 0; } } return deforient; } /*! \internal */ void QPEApplication::setDefaultRotation( int r ) { if ( qApp->type() == GuiServer ) { deforient = r; setenv( "QWS_DISPLAY", QString( "Transformed:Rot%1:0" ).arg( r ).latin1(), 1 ); Config config("qpe"); config.setGroup( "Rotation" ); config.writeEntry( "Rot", r ); } else { #ifndef QT_NO_COP { QCopEnvelope e( "QPE/System", "setDefaultRotation(int)" ); e << r; } #endif } } #include <qgfx_qws.h> #include <qwindowsystem_qws.h> #if QT_VERSION > 236 extern void qws_clearLoadedFonts(); #endif void QPEApplication::setCurrentMode( int x, int y, int depth ) { // Reset the caches #if QT_VERSION > 236 qws_clearLoadedFonts(); #endif QPixmapCache::clear(); // Change the screen mode qt_screen->setMode(x, y, depth); if ( qApp->type() == GuiServer ) { #if QT_VERSION > 236 // Reconfigure the GuiServer qwsServer->beginDisplayReconfigure(); qwsServer->endDisplayReconfigure(); #endif // Get all the running apps to reset QCopEnvelope env( "QPE/System", "reset()" ); } } void QPEApplication::reset() { // Reconnect to the screen qt_screen->disconnect(); qt_screen->connect( QString::null ); // Redraw everything applyStyle(); } #if (QT_VERSION < 238) && defined Q_OS_MACX bool qt_left_hand_scrollbars = false; #else extern bool qt_left_hand_scrollbars QPE_WEAK_SYMBOL; #endif /*! \internal */ void QPEApplication::applyStyle() { Config config( "qpe" ); config.setGroup( "Appearance" ); #if QT_VERSION > 233 #if !defined(OPIE_NO_OVERRIDE_QT) // don't block ourselves ... Opie::force_appearance = 0; static QString appname = Opie::binaryName ( ); QStringList ex = config. readListEntry ( "NoStyle", ';' ); int nostyle = 0; for ( QStringList::Iterator it = ex. begin ( ); it != ex. end ( ); ++it ) { if ( QRegExp (( *it ). mid ( 1 ), false, true ). find ( appname, 0 ) >= 0 ) { nostyle = ( *it ). left ( 1 ). toInt ( 0, 32 ); break; } } #else int nostyle = 0; #endif // Widget style QString style = config.readEntry( "Style", "FlatStyle" ); // don't set a custom style if ( nostyle & Opie::Force_Style ) style = "FlatStyle"; internalSetStyle ( style ); // Colors - from /etc/colors/Liquid.scheme QColor bgcolor( config.readEntry( "Background", "#E0E0E0" ) ); QColor btncolor( config.readEntry( "Button", "#96c8fa" ) ); QPalette pal( btncolor, bgcolor ); QString color = config.readEntry( "Highlight", "#73adef" ); pal.setColor( QColorGroup::Highlight, QColor( color ) ); color = config.readEntry( "HighlightedText", "#FFFFFF" ); pal.setColor( QColorGroup::HighlightedText, QColor( color ) ); color = config.readEntry( "Text", "#000000" ); pal.setColor( QColorGroup::Text, QColor( color ) ); color = config.readEntry( "ButtonText", "#000000" ); pal.setColor( QPalette::Active, QColorGroup::ButtonText, QColor( color ) ); color = config.readEntry( "Base", "#FFFFFF" ); pal.setColor( QColorGroup::Base, QColor( color ) ); pal.setColor( QPalette::Disabled, QColorGroup::Text, pal.color( QPalette::Active, QColorGroup::Background ).dark() ); setPalette( pal, TRUE ); // Set the ScrollBar on the 'right' side but only if the weak symbol is present if (&qt_left_hand_scrollbars ) qt_left_hand_scrollbars = config.readBoolEntry( "LeftHand", false ); // Window Decoration QString dec = config.readEntry( "Decoration", "Flat" ); // don't set a custom deco if ( nostyle & Opie::Force_Decoration ) dec = ""; if ( dec != d->decorationName ) { qwsSetDecoration( new QPEDecoration( dec ) ); d->decorationName = dec; } // Font QString ff = config.readEntry( "FontFamily", font().family() ); int fs = config.readNumEntry( "FontSize", font().pointSize() ); // don't set a custom font if ( nostyle & Opie::Force_Font ) { ff = "Vera"; fs = 10; } setFont ( QFont ( ff, fs ), true ); #if !defined(OPIE_NO_OVERRIDE_QT) // revert to global blocking policy ... Opie::force_appearance = config. readBoolEntry ( "ForceStyle", false ) ? Opie::Force_All : Opie::Force_None; Opie::force_appearance &= ~nostyle; #endif #endif } void QPEApplication::systemMessage( const QCString& msg, const QByteArray& data ) { #ifdef Q_WS_QWS QDataStream stream( data, IO_ReadOnly ); if ( msg == "applyStyle()" ) { applyStyle(); } else if ( msg == "toggleApplicationMenu()" ) { QWidget *active = activeWindow ( ); if ( active ) { QPEMenuToolFocusManager *man = QPEMenuToolFocusManager::manager ( ); bool oldactive = man-> isActive ( ); man-> setActive( !man-> isActive() ); if ( !oldactive && !man-> isActive ( )) { // no menubar to toggle -> try O-Menu QCopEnvelope e ( "QPE/TaskBar", "toggleStartMenu()" ); } } } else if ( msg == "setDefaultRotation(int)" ) { if ( type() == GuiServer ) { int r; stream >> r; setDefaultRotation( r ); } } else if ( msg == "setCurrentMode(int,int,int)" ) { // Added: 2003-06-11 by Tim Ansell <mithro@mithis.net> if ( type() == GuiServer ) { int x, y, depth; stream >> x; stream >> y; stream >> depth; setCurrentMode( x, y, depth ); } } else if ( msg == "reset()" ) { if ( type() != GuiServer ) reset(); } else if ( msg == "setCurrentRotation(int)" ) { int r; stream >> r; setCurrentRotation( r ); } else if ( msg == "shutdown()" ) { if ( type() == GuiServer ) shutdown(); } else if ( msg == "quit()" ) { if ( type() != GuiServer ) tryQuit(); } else if ( msg == "forceQuit()" ) { if ( type() != GuiServer ) quit(); } else if ( msg == "restart()" ) { if ( type() == GuiServer ) restart(); } else if ( msg == "language(QString)" ) { if ( type() == GuiServer ) { QString l; stream >> l; QString cl = getenv( "LANG" ); if ( cl != l ) { if ( l.isNull() ) unsetenv( "LANG" ); else setenv( "LANG", l.latin1(), 1 ); restart(); } } } else if ( msg == "timeChange(QString)" ) { QString t; stream >> t; if ( t.isNull() ) unsetenv( "TZ" ); else setenv( "TZ", t.latin1(), 1 ); // emit the signal so everyone else knows... emit timeChanged(); } else if ( msg == "addAlarm(QDateTime,QCString,QCString,int)" ) { if ( type() == GuiServer ) { QDateTime when; QCString channel, message; int data; stream >> when >> channel >> message >> data; AlarmServer::addAlarm( when, channel, message, data ); } } else if ( msg == "deleteAlarm(QDateTime,QCString,QCString,int)" ) { if ( type() == GuiServer ) { QDateTime when; QCString channel, message; int data; stream >> when >> channel >> message >> data; AlarmServer::deleteAlarm( when, channel, message, data ); } } else if ( msg == "clockChange(bool)" ) { int tmp; stream >> tmp; emit clockChanged( tmp ); } else if ( msg == "weekChange(bool)" ) { int tmp; stream >> tmp; emit weekChanged( tmp ); } else if ( msg == "setDateFormat(DateFormat)" ) { DateFormat tmp; stream >> tmp; emit dateFormatChanged( tmp ); } else if ( msg == "setVolume(int,int)" ) { int t, v; stream >> t >> v; setVolume( t, v ); emit volumeChanged( muted ); } else if ( msg == "volumeChange(bool)" ) { stream >> muted; setVolume(); emit volumeChanged( muted ); } else if ( msg == "setMic(int,int)" ) { // Added: 2002-02-08 by Jeremy Cowgar <jc@cowgar.com> int t, v; stream >> t >> v; setMic( t, v ); emit micChanged( micMuted ); } else if ( msg == "micChange(bool)" ) { // Added: 2002-02-08 by Jeremy Cowgar <jc@cowgar.com> stream >> micMuted; setMic(); emit micChanged( micMuted ); } else if ( msg == "setBass(int,int)" ) { // Added: 2002-12-13 by Maximilian Reiss <harlekin@handhelds.org> int t, v; stream >> t >> v; setBass( t, v ); } else if ( msg == "bassChange(bool)" ) { // Added: 2002-12-13 by Maximilian Reiss <harlekin@handhelds.org> setBass(); } else if ( msg == "setTreble(int,int)" ) { // Added: 2002-12-13 by Maximilian Reiss <harlekin@handhelds.org> int t, v; stream >> t >> v; setTreble( t, v ); } else if ( msg == "trebleChange(bool)" ) { // Added: 2002-12-13 by Maximilian Reiss <harlekin@handhelds.org> setTreble(); } else if ( msg == "getMarkedText()" ) { if ( type() == GuiServer ) { const ushort unicode = 'C'-'@'; const int scan = Key_C; qwsServer->processKeyEvent( unicode, scan, ControlButton, TRUE, FALSE ); qwsServer->processKeyEvent( unicode, scan, ControlButton, FALSE, FALSE ); } } else if ( msg == "newChannel(QString)") { QString myChannel = "QPE/Application/" + d->appName; QString channel; stream >> channel; if (channel == myChannel) { processQCopFile(); d->sendQCopQ(); } } #endif } /*! \internal */ bool QPEApplication::raiseAppropriateWindow() { bool r=FALSE; // 1. Raise the main widget QWidget *top = d->qpe_main_widget; if ( !top ) top = mainWidget(); if ( top && d->keep_running ) { if ( top->isVisible() ) r = TRUE; else if (d->preloaded) { // We are preloaded and not visible.. pretend we just started.. #ifndef QT_NO_COP QCopEnvelope e("QPE/System", "fastAppShowing(QString)"); e << d->appName; #endif } d->show_mx(top,d->nomaximize, d->appName); top->raise(); } QWidget *topm = activeModalWidget(); // 2. Raise any parentless widgets (except top and topm, as they // are raised before and after this loop). Order from most // recently raised as deepest to least recently as top, so // that repeated calls cycle through widgets. QWidgetList *list = topLevelWidgets(); if ( list ) { bool foundlast = FALSE; QWidget* topsub = 0; if ( d->lastraised ) { for (QWidget* w = list->first(); w; w = list->next()) { if ( !w->parentWidget() && w != topm && w->isVisible() && !w->isDesktop() ) { if ( w == d->lastraised ) foundlast = TRUE; if ( foundlast ) { w->raise(); topsub = w; } } } } for (QWidget* w = list->first(); w; w = list->next()) { if ( !w->parentWidget() && w != topm && w->isVisible() && !w->isDesktop() ) { if ( w == d->lastraised ) break; w->raise(); topsub = w; } } d->lastraised = topsub; delete list; } // 3. Raise the active modal widget. if ( topm ) { topm->show(); topm->raise(); // If we haven't already handled the fastAppShowing message if (!top && d->preloaded) { #ifndef QT_NO_COP QCopEnvelope e("QPE/System", "fastAppShowing(QString)"); e << d->appName; #endif } r = FALSE; } return r; } void QPEApplication::pidMessage( const QCString& msg, const QByteArray& data) { #ifdef Q_WS_QWS if ( msg == "quit()" ) { tryQuit(); } else if ( msg == "quitIfInvisible()" ) { if ( d->qpe_main_widget && !d->qpe_main_widget->isVisible() ) quit(); } else if ( msg == "close()" ) { hideOrQuit(); } else if ( msg == "disablePreload()" ) { d->preloaded = FALSE; d->keep_running = TRUE; /* so that quit will quit */ } else if ( msg == "enablePreload()" ) { if (d->qpe_main_widget) d->preloaded = TRUE; d->keep_running = TRUE; /* so next quit won't quit */ } else if ( msg == "raise()" ) { d->keep_running = TRUE; d->notbusysent = FALSE; raiseAppropriateWindow(); // Tell the system we're still chugging along... QCopEnvelope e("QPE/System", "appRaised(QString)"); e << d->appName; } else if ( msg == "flush()" ) { emit flush(); // we need to tell the desktop QCopEnvelope e( "QPE/Desktop", "flushDone(QString)" ); e << d->appName; } else if ( msg == "reload()" ) { emit reload(); } else if ( msg == "setDocument(QString)" ) { d->keep_running = TRUE; QDataStream stream( data, IO_ReadOnly ); QString doc; stream >> doc; QWidget *mw = mainWidget(); if ( !mw ) mw = d->qpe_main_widget; if ( mw ) Global::setDocument( mw, doc ); } else if ( msg == "QPEProcessQCop()" ) { processQCopFile(); d->sendQCopQ(); }else { bool p = d->keep_running; d->keep_running = FALSE; emit appMessage( msg, data); if ( d->keep_running ) { d->notbusysent = FALSE; raiseAppropriateWindow(); if ( !p ) { // Tell the system we're still chugging along... #ifndef QT_NO_COP QCopEnvelope e("QPE/System", "appRaised(QString)"); e << d->appName; #endif } } if ( p ) d->keep_running = p; } #endif } /*! Sets widget \a mw as the mainWidget() and shows it. For small windows, consider passing TRUE for \a nomaximize rather than the default FALSE. \sa showMainDocumentWidget() */ void QPEApplication::showMainWidget( QWidget* mw, bool nomaximize ) { // setMainWidget(mw); this breaks FastLoading because lastWindowClose() would quit d->show(mw, nomaximize ); } /*! Sets widget \a mw as the mainWidget() and shows it. For small windows, consider passing TRUE for \a nomaximize rather than the default FALSE. This calls designates the application as a \link docwidget.html document-oriented\endlink application. The \a mw widget \e must have this slot: setDocument(const QString&). \sa showMainWidget() */ void QPEApplication::showMainDocumentWidget( QWidget* mw, bool nomaximize ) { if ( mw && argc() == 2 ) Global::setDocument( mw, QString::fromUtf8(argv()[1]) ); // setMainWidget(mw); see above d->show(mw, nomaximize ); } /*! If an application is started via a \link qcop.html QCop\endlink message, the application will process the \link qcop.html QCop\endlink message and then quit. If the application calls this function while processing a \link qcop.html QCop\endlink message, after processing its outstanding \link qcop.html QCop\endlink messages the application will start 'properly' and show itself. \sa keepRunning() */ void QPEApplication::setKeepRunning() { if ( qApp && qApp->inherits( "QPEApplication" ) ) { QPEApplication * qpeApp = ( QPEApplication* ) qApp; qpeApp->d->keep_running = TRUE; } } /*! Returns TRUE if the application will quit after processing the current list of qcop messages; otherwise returns FALSE. \sa setKeepRunning() */ bool QPEApplication::keepRunning() const { return d->keep_running; } /*! \internal */ void QPEApplication::internalSetStyle( const QString &style ) { -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 if ( style == "QPE" ) { setStyle( new QPEStyle ); } else { QStyle *s = QStyleFactory::create( style ); if ( s ) setStyle( s ); } #else if ( style == "Windows" ) { setStyle( new QWindowsStyle ); } else if ( style == "QPE" ) { setStyle( new QPEStyle ); } else if ( style == "Light" ) { setStyle( new LightStyle ); } #ifndef QT_NO_STYLE_PLATINUM else if ( style == "Platinum" ) { setStyle( new QPlatinumStyle ); } #endif #ifndef QT_NO_STYLE_MOTIF else if ( style == "Motif" ) { setStyle( new QMotifStyle ); } #endif #ifndef QT_NO_STYLE_MOTIFPLUS else if ( style == "MotifPlus" ) { setStyle( new QMotifPlusStyle ); } #endif else { QStyle *sty = 0; QString path = QPEApplication::qpeDir ( ) + "plugins/styles/"; #ifdef Q_OS_MACX if ( style. find ( ".dylib" ) > 0 ) path += style; else path = path + "lib" + style. lower ( ) + ".dylib"; // compatibility #else if ( style. find ( ".so" ) > 0 ) path += style; else path = path + "lib" + style. lower ( ) + ".so"; // compatibility #endif static QLibrary *lastlib = 0; static StyleInterface *lastiface = 0; QLibrary *lib = new QLibrary ( path ); StyleInterface *iface = 0; if (( lib-> queryInterface ( IID_Style, ( QUnknownInterface ** ) &iface ) == QS_OK ) && iface ) sty = iface-> style ( ); if ( sty ) { setStyle ( sty ); if ( lastiface ) lastiface-> release ( ); lastiface = iface; if ( lastlib ) { lastlib-> unload ( ); delete lastlib; } lastlib = lib; } else { if ( iface ) iface-> release ( ); delete lib; setStyle ( new LightStyle ( )); } } #endif } /*! \internal */ void QPEApplication::prepareForTermination( bool willrestart ) { if ( willrestart ) { QLabel *lblWait = new QLabel( tr( "Please wait..." ), 0, "wait hack", QWidget::WStyle_Customize | QWidget::WStyle_NoBorder | QWidget::WStyle_Tool ); lblWait->setAlignment( QWidget::AlignCenter ); lblWait->show(); lblWait->showMaximized(); } { QCopEnvelope envelope( "QPE/System", "forceQuit()" ); } processEvents(); // ensure the message goes out. } /*! \internal */ void QPEApplication::shutdown() { // Implement in server's QPEApplication subclass } /*! \internal */ void QPEApplication::restart() { // Implement in server's QPEApplication subclass } static QPtrDict<void>* stylusDict = 0; static void createDict() { if ( !stylusDict ) stylusDict = new QPtrDict<void>; } /*! Returns the current StylusMode for widget \a w. \sa setStylusOperation() StylusMode */ QPEApplication::StylusMode QPEApplication::stylusOperation( QWidget* w ) { if ( stylusDict ) return ( StylusMode ) ( int ) stylusDict->find( w ); return LeftOnly; } /*! \enum QPEApplication::StylusMode \value LeftOnly the stylus only generates LeftButton events (the default). \value RightOnHold the stylus generates RightButton events if the user uses the press-and-hold gesture. \sa setStylusOperation() stylusOperation() */ /*! Causes widget \a w to receive mouse events according to the stylus \a mode. \sa stylusOperation() StylusMode */ void QPEApplication::setStylusOperation( QWidget * w, StylusMode mode ) { createDict(); if ( mode == LeftOnly ) { stylusDict->remove ( w ); w->removeEventFilter( qApp ); } else { stylusDict->insert( w, ( void* ) mode ); connect( w, SIGNAL( destroyed() ), qApp, SLOT( removeSenderFromStylusDict() ) ); w->installEventFilter( qApp ); } } /*! \reimp */ bool QPEApplication::eventFilter( QObject *o, QEvent *e ) { if ( !o->isWidgetType() ) return FALSE; if ( stylusDict && e->type() >= QEvent::MouseButtonPress && e->type() <= QEvent::MouseMove ) { QMouseEvent * me = ( QMouseEvent* ) e; StylusMode mode = (StylusMode)(int)stylusDict->find(o); switch (mode) { case RightOnHold: switch ( me->type() ) { case QEvent::MouseButtonPress: if ( me->button() == LeftButton ) { static long Pref = 500; // #### pref. d->presswidget = (QWidget*)o; d->presspos = me->pos(); d->rightpressed = FALSE; #ifdef OPIE_WITHROHFEEDBACK if( ! d->RoH ) d->RoH = new Opie::Internal::RoHFeedback; d->RoH->init( me->globalPos(), d->presswidget ); Pref = d->RoH->delay(); #endif if (!d->presstimer ) d->presstimer = startTimer( Pref ); // #### pref. } break; case QEvent::MouseMove: if (d->presstimer && (me->pos() - d->presspos).manhattanLength() > 8) { killTimer(d->presstimer); #ifdef OPIE_WITHROHFEEDBACK d->RoH->stop(); #endif d->presstimer = 0; } break; case QEvent::MouseButtonRelease: if ( me->button() == LeftButton ) { if ( d->presstimer ) { killTimer(d->presstimer); #ifdef OPIE_WITHROHFEEDBACK d->RoH->stop( ); #endif d->presstimer = 0; } if ( d->rightpressed && d->presswidget ) { printf( "Send ButtonRelease\n" ); // Right released postEvent( d->presswidget, new QMouseEvent( QEvent::MouseButtonRelease, me->pos(), RightButton, LeftButton + RightButton ) ); // Left released, off-widget postEvent( d->presswidget, new QMouseEvent( QEvent::MouseMove, QPoint( -1, -1), LeftButton, LeftButton ) ); postEvent( d->presswidget, new QMouseEvent( QEvent::MouseButtonRelease, QPoint( -1, -1), LeftButton, LeftButton ) ); d->rightpressed = FALSE; return TRUE; // don't send the real Left release } } break; default: break; } break; default: ; } } else if ( e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease ) { QKeyEvent *ke = (QKeyEvent *)e; if ( ke->key() == Key_Enter ) { if ( o->isA( "QRadioButton" ) || o->isA( "QCheckBox" ) ) { postEvent( o, new QKeyEvent( e->type(), Key_Space, ' ', ke->state(), " ", ke->isAutoRepeat(), ke->count() ) ); return TRUE; } } } return FALSE; } /*! \reimp */ void QPEApplication::timerEvent( QTimerEvent *e ) { if ( e->timerId() == d->presstimer && d->presswidget ) { // Right pressed postEvent( d->presswidget, new QMouseEvent( QEvent::MouseButtonPress, d->presspos, RightButton, LeftButton ) ); killTimer( d->presstimer ); d->presstimer = 0; d->rightpressed = TRUE; #ifdef OPIE_WITHROHFEEDBACK d->RoH->stop(); #endif } } void QPEApplication::removeSenderFromStylusDict() { stylusDict->remove ( ( void* ) sender() ); if ( d->presswidget == sender() ) d->presswidget = 0; } /*! \internal */ bool QPEApplication::keyboardGrabbed() const { return d->kbgrabbed; } /*! Reverses the effect of grabKeyboard(). This is called automatically on program exit. */ void QPEApplication::ungrabKeyboard() { ((QPEApplication *) qApp )-> d-> kbgrabbed = false; } /*! Grabs the physical keyboard keys, e.g. the application's launching keys. Instead of launching applications when these keys are pressed the signals emitted are sent to this application instead. Some games programs take over the launch keys in this way to make interaction easier. \sa ungrabKeyboard() */ void QPEApplication::grabKeyboard() { ((QPEApplication *) qApp )-> d-> kbgrabbed = true; } /*! \reimp */ int QPEApplication::exec() { d->qcopQok = true; #ifndef QT_NO_COP d->sendQCopQ(); if ( !d->keep_running ) processEvents(); // we may have received QCop messages in the meantime. #endif if ( d->keep_running ) //|| d->qpe_main_widget && d->qpe_main_widget->isVisible() ) return QApplication::exec(); #ifndef QT_NO_COP { QCopEnvelope e( "QPE/System", "closing(QString)" ); e << d->appName; } #endif processEvents(); return 0; } /*! \internal External request for application to quit. Quits if possible without loosing state. */ void QPEApplication::tryQuit() { if ( activeModalWidget() ) return ; // Inside modal loop or konsole. Too hard to save state. #ifndef QT_NO_COP { QCopEnvelope e( "QPE/System", "closing(QString)" ); e << d->appName; } #endif if ( d->keep_running ) d->store_widget_rect(d->qpe_main_widget, d->appName); processEvents(); quit(); } /*! \internal User initiated quit. Makes the window 'Go Away'. If preloaded this means hiding the window. If not it means quitting the application. As this is user initiated we don't need to check state. */ void QPEApplication::hideOrQuit() { if ( d->keep_running ) d->store_widget_rect(d->qpe_main_widget, d->appName); processEvents(); // If we are a preloaded application we don't actually quit, so emit // a System message indicating we're quasi-closing. if ( d->preloaded && d->qpe_main_widget ) #ifndef QT_NO_COP { QCopEnvelope e("QPE/System", "fastAppHiding(QString)" ); e << d->appName; d->qpe_main_widget->hide(); } #endif else quit(); } #if (__GNUC__ > 2 ) extern "C" void __cxa_pure_virtual(); void __cxa_pure_virtual() { fprintf( stderr, "Pure virtual called\n"); abort(); } #endif #if defined(OPIE_NEW_MALLOC) // The libraries with the skiff package (and possibly others) have // completely useless implementations of builtin new and delete that // use about 50% of your CPU. Here we revert to the simple libc // functions. void* operator new[]( size_t size ) { return malloc( size ); } void* operator new( size_t size ) { return malloc( size ); } void operator delete[]( void* p ) { if ( p ) free( p ); } void operator delete[]( void* p, size_t /*size*/ ) { if ( p ) free( p ); } void operator delete( void* p ) { if ( p ) free( p ); } void operator delete( void* p, size_t /*size*/ ) { if ( p ) free( p ); } #endif #if ( QT_VERSION <= 230 ) && !defined(SINGLE_APP) #include <qwidgetlist.h> #ifdef QWS #include <qgfx_qws.h> extern QRect qt_maxWindowRect; void qt_setMaxWindowRect(const QRect& r ) { qt_maxWindowRect = qt_screen->mapFromDevice( r, qt_screen->mapToDevice( QSize( qt_screen->width(), qt_screen->height() ) ) ); // Re-resize any maximized windows QWidgetList* l = QApplication::topLevelWidgets(); if ( l ) { QWidget * w = l->first(); while ( w ) { if ( w->isVisible() && w->isMaximized() ) { w->showMaximized(); } w = l->next(); } delete l; } } #endif #endif diff --git a/library/qpestyle.cpp b/library/qpestyle.cpp index b61ada4..0566f6b 100644 --- a/library/qpestyle.cpp +++ b/library/qpestyle.cpp @@ -1,1191 +1,1191 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "qpestyle.h" #define QCOORDARRLEN(x) sizeof(x)/(sizeof(QCOORD)*2) -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 #include <qdrawutil.h> #include <qcombobox.h> #include <qtabbar.h> QPEStyle::QPEStyle() { } QPEStyle::~QPEStyle() { } void QPEStyle::drawPrimitive( PrimitiveElement pe, QPainter *p, const QRect &r, const QColorGroup &cg, SFlags flags, const QStyleOption &data) const { switch ( pe ) { case PE_ButtonTool: { QColorGroup mycg = cg; if ( flags & Style_On ) { QBrush fill( cg.mid(), Dense4Pattern ); mycg.setBrush( QColorGroup::Button, fill ); } drawPrimitive( PE_ButtonBevel, p, r, mycg, flags, data ); break; } case PE_ButtonCommand: case PE_ButtonDefault: case PE_ButtonBevel: case PE_HeaderSection: { QPen oldPen = p->pen(); p->fillRect( r.x()+1, r.y()+1, r.width()-2, r.height()-2, cg.brush(QColorGroup::Button) ); int x2 = r.right(); int y2 = r.bottom(); if ( flags & (Style_Sunken | Style_Down | Style_On) ) p->setPen( cg.dark() ); else p->setPen( cg.light() ); p->drawLine( r.x(), r.y()+1, r.x(), y2-1 ); p->drawLine( r.x()+1, r.y(), x2-1, r.y() ); if ( flags & (Style_Sunken | Style_Down | Style_On) ) p->setPen( cg.light() ); else p->setPen( cg.dark() ); p->drawLine( x2, r.y()+1, x2, y2-1 ); p->drawLine( r.x()+1, y2, x2-1, y2 ); p->setPen( oldPen ); break; } case PE_FocusRect: break; case PE_Indicator: { QColorGroup mycg( cg ); QBrush fill; if ( flags & Style_Down ) fill = cg.brush( QColorGroup::Button ); else fill = cg.brush( (flags&Style_Enabled) ? QColorGroup::Base : QColorGroup::Background ); mycg.setBrush( QColorGroup::Button, fill ); if ( flags&Style_Enabled ) flags |= Style_Sunken; drawPrimitive( PE_ButtonBevel, p, r, mycg, flags ); if ( flags & Style_On ) { QPointArray a( 7*2 ); int i, xx, yy; xx = r.x()+3; yy = r.y()+5; for ( i=0; i<3; i++ ) { a.setPoint( 2*i, xx, yy ); a.setPoint( 2*i+1, xx, yy+2 ); xx++; yy++; } yy -= 2; for ( i=3; i<7; i++ ) { a.setPoint( 2*i, xx, yy ); a.setPoint( 2*i+1, xx, yy+2 ); xx++; yy--; } if ( flags & Style_NoChange ) { p->setPen( mycg.dark() ); } else { p->setPen( mycg.text() ); } p->drawLineSegments( a ); } break; } case PE_ExclusiveIndicator: { static const QCOORD pts1[] = { // dark lines 1,9, 1,8, 0,7, 0,4, 1,3, 1,2, 2,1, 3,1, 4,0, 7,0, 8,1, 9,1 }; static const QCOORD pts4[] = { // white lines 2,10, 3,10, 4,11, 7,11, 8,10, 9,10, 10,9, 10,8, 11,7, 11,4, 10,3, 10,2 }; static const QCOORD pts5[] = { // inner fill 4,2, 7,2, 9,4, 9,7, 7,9, 4,9, 2,7, 2,4 }; int x, y, w, h; r.rect( &x, &y, &w, &h ); p->eraseRect( x, y, w, h ); QPointArray a( QCOORDARRLEN(pts1), pts1 ); a.translate( x, y ); p->setPen( cg.dark() ); p->drawPolyline( a ); a.setPoints( QCOORDARRLEN(pts4), pts4 ); a.translate( x, y ); p->setPen( cg.light() ); p->drawPolyline( a ); a.setPoints( QCOORDARRLEN(pts5), pts5 ); a.translate( x, y ); QColor fillColor = ( flags&Style_Down || !(flags&Style_Enabled) ) ? cg.button() : cg.base(); p->setPen( fillColor ); p->setBrush( fillColor ) ; p->drawPolygon( a ); if ( flags&Style_On ) { p->setPen( NoPen ); p->setBrush( cg.text() ); p->drawRect( x+5, y+4, 2, 4 ); p->drawRect( x+4, y+5, 4, 2 ); } break; } default: QWindowsStyle::drawPrimitive( pe, p, r, cg, flags, data ); break; } } void QPEStyle::drawControl( ControlElement ce, QPainter *p, const QWidget *widget, const QRect &r, const QColorGroup &cg, SFlags how, const QStyleOption &data) const { switch ( ce ) { case CE_PushButton: { const QPushButton *btn = (QPushButton*)widget; SFlags flags; flags = Style_Default; if ( btn->isDown() ) flags |= Style_Down; if ( btn->isOn() ) flags |= Style_On; if ( btn->isEnabled() ) flags |= Style_Enabled; if ( btn->isDefault() ) flags |= Style_Default; if (! btn->isFlat() && !(flags & Style_Down)) flags |= Style_Raised; p->setPen( cg.foreground() ); p->setBrush( QBrush(cg.button(), NoBrush) ); QColorGroup mycg( cg ); if ( flags & Style_On ) { QBrush fill = QBrush( cg.mid(), Dense4Pattern ); mycg.setBrush( QColorGroup::Button, fill ); } drawPrimitive( PE_ButtonBevel, p, r, mycg, flags, data ); break; } case CE_TabBarTab: { if ( !widget || !widget->parentWidget() ) break; const QTabBar *tb = (const QTabBar *) widget; bool selected = how & Style_Selected; QRect r2(r); if ( tb->shape() == QTabBar::RoundedAbove ) { p->setPen( cg.light() ); p->drawLine( r2.left(), r2.bottom(), r2.right(), r2.bottom() ); if ( r2.left() == 0 ) p->drawPoint( tb->rect().bottomLeft() ); else { p->setPen( cg.light() ); p->drawLine( r2.left(), r2.bottom(), r2.right(), r2.bottom() ); } if ( selected ) { p->setPen( cg.background() ); p->drawLine( r2.left()+2, r2.top()+1, r2.right()-2, r2.top()+1 ); p->fillRect( QRect( r2.left()+1, r2.top()+2, r2.width()-2, r2.height()-2), cg.brush( QColorGroup::Background )); } else { r2.setRect( r2.left() + 2, r2.top() + 2, r2.width() - 4, r2.height() - 2 ); p->setPen( cg.button() ); p->drawLine( r2.left()+2, r2.top()+1, r2.right()-2, r2.top()+1 ); p->fillRect( QRect( r2.left()+1, r2.top()+2, r2.width()-2, r2.height()-3), cg.brush( QColorGroup::Button )); //do shading; will not work for pixmap brushes QColor bg = cg.button(); // int h,s,v; // bg.hsv( &h, &s, &v ); int n = r2.height()/2; int dark = 100; for ( int i = 1; i < n; i++ ) { dark = (dark * (100+(i*15)/n) )/100; p->setPen( bg.dark( dark ) ); int y = r2.bottom()-n+i; int x1 = r2.left()+1; int x2 = r2.right()-1; p->drawLine( x1, y, x2, y ); } } p->setPen( cg.light() ); p->drawLine( r2.left(), r2.bottom()-1, r2.left(), r2.top() + 2 ); p->drawPoint( r2.left()+1, r2.top() + 1 ); p->drawLine( r2.left()+2, r2.top(), r2.right() - 2, r2.top() ); p->setPen( cg.dark() ); p->drawPoint( r2.right() - 1, r2.top() + 1 ); p->drawLine( r2.right(), r2.top() + 2, r2.right(), r2.bottom() - 1); } else if ( tb->shape() == QTabBar::RoundedBelow ) { if ( selected ) { p->setPen( cg.background() ); p->drawLine( r2.left()+2, r2.bottom()-1, r2.right()-2, r2.bottom()-1 ); p->fillRect( QRect( r2.left()+1, r2.top(), r2.width()-2, r2.height()-2), tb->palette().normal().brush( QColorGroup::Background )); } else { p->setPen( cg.dark() ); p->drawLine( r2.left(), r2.top(), r2.right(), r2.top() ); r2.setRect( r2.left() + 2, r2.top(), r2.width() - 4, r2.height() - 2 ); p->setPen( cg.button() ); p->drawLine( r2.left()+2, r2.bottom()-1, r2.right()-2, r2.bottom()-1 ); p->fillRect( QRect( r2.left()+1, r2.top()+1, r2.width()-2, r2.height()-3), tb->palette().normal().brush( QColorGroup::Button )); } p->setPen( cg.dark() ); p->drawLine( r2.right(), r2.top(), r2.right(), r2.bottom() - 2 ); p->drawPoint( r2.right() - 1, r2.bottom() - 1 ); p->drawLine( r2.right() - 2, r2.bottom(), r2.left() + 2, r2.bottom() ); p->setPen( cg.light() ); p->drawLine( r2.left(), r2.top()+1, r2.left(), r2.bottom() - 2 ); p->drawPoint( r2.left() + 1, r2.bottom() - 1 ); if ( r2.left() == 0 ) p->drawPoint( tb->rect().topLeft() ); } else { QCommonStyle::drawControl( ce, p, widget, r, cg, how, data ); } break; } default: QWindowsStyle::drawControl( ce, p, widget, r, cg, how, data ); break; } } void QPEStyle::drawComplexControl( ComplexControl control, QPainter *p, const QWidget *widget, const QRect &r, const QColorGroup &cg, SFlags how, SCFlags sub, SCFlags subActive, const QStyleOption &data) const { switch ( control ) { case CC_ComboBox: if ( sub & SC_ComboBoxArrow ) { SFlags flags = Style_Default; drawPrimitive( PE_ButtonBevel, p, r, cg, flags, data ); QRect ar = QStyle::visualRect( querySubControlMetrics( CC_ComboBox, widget, SC_ComboBoxArrow ), widget ); if ( subActive == SC_ComboBoxArrow ) { p->setPen( cg.dark() ); p->setBrush( cg.brush( QColorGroup::Button ) ); p->drawRect( ar ); } ar.addCoords( 2, 2, -2, -2 ); if ( widget->isEnabled() ) flags |= Style_Enabled; if ( subActive & Style_Sunken ) { flags |= Style_Sunken; } drawPrimitive( PE_ArrowDown, p, ar, cg, flags ); } if ( sub & SC_ComboBoxEditField ) { const QComboBox * cb = (const QComboBox *) widget; QRect re = QStyle::visualRect( querySubControlMetrics( CC_ComboBox, widget, SC_ComboBoxEditField ), widget ); if ( cb->hasFocus() && !cb->editable() ) p->fillRect( re.x(), re.y(), re.width(), re.height(), cg.brush( QColorGroup::Highlight ) ); if ( cb->hasFocus() ) { p->setPen( cg.highlightedText() ); p->setBackgroundColor( cg.highlight() ); } else { p->setPen( cg.text() ); p->setBackgroundColor( cg.background() ); } if ( cb->hasFocus() && !cb->editable() ) { QRect re = QStyle::visualRect( subRect( SR_ComboBoxFocusRect, cb ), widget ); drawPrimitive( PE_FocusRect, p, re, cg, Style_FocusAtBorder, QStyleOption(cg.highlight())); } } break; default: QWindowsStyle::drawComplexControl( control, p, widget, r, cg, how, sub, subActive, data ); break; } } int QPEStyle::pixelMetric( PixelMetric metric, const QWidget *widget ) const { int ret; switch( metric ) { case PM_ButtonMargin: ret = 2; break; case PM_DefaultFrameWidth: ret = 1; break; case PM_ButtonDefaultIndicator: ret = 2; break; case PM_ButtonShiftHorizontal: case PM_ButtonShiftVertical: ret = -1; break; case PM_IndicatorWidth: ret = 15; break; case PM_IndicatorHeight: ret = 13; break; case PM_ExclusiveIndicatorHeight: case PM_ExclusiveIndicatorWidth: ret = 15; break; case PM_ScrollBarExtent: ret = 13; break; case PM_SliderLength: ret = 12; break; default: ret = QWindowsStyle::pixelMetric( metric, widget ); break; } return ret; } QSize QPEStyle::sizeFromContents( ContentsType contents, const QWidget *widget, const QSize &contentsSize, const QStyleOption &data) const { QSize sz(contentsSize); switch ( contents ) { case CT_PopupMenuItem: { if ( !widget || data.isDefault() ) break; sz = QWindowsStyle::sizeFromContents( contents, widget, contentsSize, data ); sz = QSize( sz.width(), sz.height()-2 ); break; } default: sz = QWindowsStyle::sizeFromContents( contents, widget, contentsSize, data ); break; } return sz; } #else #include <qfontmetrics.h> #include <qpalette.h> #include <qdrawutil.h> #include <qscrollbar.h> #include <qbutton.h> #include <qframe.h> #include <qtabbar.h> #define INCLUDE_MENUITEM_DEF #include <qmenudata.h> QPEStyle::QPEStyle() { -#if QT_VERSION < 300 +#if QT_VERSION < 0x030000 setButtonMargin(buttonMargin()); setScrollBarExtent(scrollBarExtent().width(),scrollBarExtent().height()); #endif } QPEStyle::~QPEStyle() { } int QPEStyle::buttonMargin() const { return 2; } QSize QPEStyle::scrollBarExtent() const { return QSize(13,13); } void QPEStyle::polish ( QPalette & ) { } void QPEStyle::polish( QWidget *w ) { if ( w->inherits( "QListBox" ) || w->inherits( "QListView" ) || w->inherits( "QPopupMenu" ) || w->inherits( "QSpinBox" ) ) { QFrame *f = (QFrame *)w; f->setFrameShape( QFrame::StyledPanel ); f->setLineWidth( 1 ); } } void QPEStyle::unPolish( QWidget *w ) { if ( w->inherits( "QListBox" ) || w->inherits( "QListView" ) || w->inherits( "QPopupMenu" ) || w->inherits( "QSpinBox" ) ) { QFrame *f = (QFrame *)w; f->setFrameShape( QFrame::StyledPanel ); f->setLineWidth( 2 ); } } int QPEStyle::defaultFrameWidth() const { return 1; } void QPEStyle::drawPanel ( QPainter * p, int x, int y, int w, int h, const QColorGroup &g, bool sunken, int lineWidth, const QBrush * fill ) { qDrawShadePanel( p, QRect(x, y, w, h), g, sunken, lineWidth, fill ); } void QPEStyle::drawButton( QPainter *p, int x, int y, int w, int h, const QColorGroup &g, bool sunken, const QBrush* fill ) { QPen oldPen = p->pen(); if ( sunken ) p->setPen( g.dark() ); else p->setPen( g.light() ); int x2 = x+w-1; int y2 = y+h-1; p->drawLine( x, y, x, y2 ); p->drawLine( x, y, x2, y ); if ( sunken ) p->setPen( g.light() ); else p->setPen( g.dark() ); p->drawLine( x2, y, x2, y2 ); p->drawLine( x, y2, x2, y2 ); p->setPen( oldPen ); p->fillRect( x+1, y+1, w-2, h-2, fill?(*fill):g.brush(QColorGroup::Button) ); } void QPEStyle::drawButtonMask ( QPainter * p, int x, int y, int w, int h ) { p->fillRect( x, y, w, h, color1 ); } void QPEStyle::drawBevelButton( QPainter *p, int x, int y, int w, int h, const QColorGroup &g, bool sunken, const QBrush* fill ) { drawButton( p, x, y, w, h, g, sunken, fill ); } QRect QPEStyle::comboButtonRect( int x, int y, int w, int h) { return QRect(x+1, y+1, w-2-14, h-2); } QRect QPEStyle::comboButtonFocusRect( int x, int y, int w, int h) { return QRect(x+2, y+2, w-4-14, h-4); } void QPEStyle::drawComboButton( QPainter *p, int x, int y, int w, int h, const QColorGroup &g, bool sunken, bool /*editable*/, bool enabled, const QBrush *fill ) { drawBevelButton( p, x, y, w, h, g, FALSE, fill ); drawBevelButton( p, x+w-14, y, 14, h, g, sunken, fill ); drawArrow( p, QStyle::DownArrow, sunken, x+w-14+ 2, y+ 2, 14- 4, h- 4, g, enabled, &g.brush( QColorGroup::Button ) ); } void QPEStyle::drawExclusiveIndicator ( QPainter * p, int x, int y, int w, int h, const QColorGroup & g, bool on, bool down, bool enabled ) { static const QCOORD pts1[] = { // dark lines 1,9, 1,8, 0,7, 0,4, 1,3, 1,2, 2,1, 3,1, 4,0, 7,0, 8,1, 9,1 }; static const QCOORD pts4[] = { // white lines 2,10, 3,10, 4,11, 7,11, 8,10, 9,10, 10,9, 10,8, 11,7, 11,4, 10,3, 10,2 }; static const QCOORD pts5[] = { // inner fill 4,2, 7,2, 9,4, 9,7, 7,9, 4,9, 2,7, 2,4 }; p->eraseRect( x, y, w, h ); QPointArray a( QCOORDARRLEN(pts1), pts1 ); a.translate( x, y ); p->setPen( g.dark() ); p->drawPolyline( a ); a.setPoints( QCOORDARRLEN(pts4), pts4 ); a.translate( x, y ); p->setPen( g.light() ); p->drawPolyline( a ); a.setPoints( QCOORDARRLEN(pts5), pts5 ); a.translate( x, y ); QColor fillColor = ( down || !enabled ) ? g.button() : g.base(); p->setPen( fillColor ); p->setBrush( fillColor ) ; p->drawPolygon( a ); if ( on ) { p->setPen( NoPen ); p->setBrush( g.text() ); p->drawRect( x+5, y+4, 2, 4 ); p->drawRect( x+4, y+5, 4, 2 ); } } void QPEStyle::drawIndicator ( QPainter * p, int x, int y, int w, int h, const QColorGroup & g, int state, bool down, bool enabled ) { QBrush fill; if ( state == QButton::NoChange ) { QBrush b = p->brush(); QColor c = p->backgroundColor(); p->setBackgroundMode( TransparentMode ); p->setBackgroundColor( green ); fill = QBrush(g.base(), Dense4Pattern); p->setBackgroundColor( c ); p->setBrush( b ); } else if ( down ) fill = g.brush( QColorGroup::Button ); else fill = g.brush( enabled ? QColorGroup::Base : QColorGroup::Background ); drawPanel( p, x, y, w, h, g, TRUE, 1, &fill ); if ( state != QButton::Off ) { QPointArray a( 7*2 ); int i, xx, yy; xx = x+3; yy = y+5; for ( i=0; i<3; i++ ) { a.setPoint( 2*i, xx, yy ); a.setPoint( 2*i+1, xx, yy+2 ); xx++; yy++; } yy -= 2; for ( i=3; i<7; i++ ) { a.setPoint( 2*i, xx, yy ); a.setPoint( 2*i+1, xx, yy+2 ); xx++; yy--; } if ( state == QButton::NoChange ) { p->setPen( g.dark() ); } else { p->setPen( g.text() ); } p->drawLineSegments( a ); } } #define HORIZONTAL (sb->orientation() == QScrollBar::Horizontal) #define VERTICAL !HORIZONTAL #define MOTIF_BORDER 2 #define SLIDER_MIN 9 // ### motif says 6 but that's too small /*! \reimp */ void QPEStyle::scrollBarMetrics( const QScrollBar* sb, int &sliderMin, int &sliderMax, int &sliderLength, int& buttonDim ) { int maxLength; int length = HORIZONTAL ? sb->width() : sb->height(); int extent = HORIZONTAL ? sb->height() : sb->width(); if ( length > (extent - 1)*2 ) buttonDim = extent; else buttonDim = length/2 - 1; sliderMin = 0; maxLength = length - buttonDim*2; if ( sb->maxValue() == sb->minValue() ) { sliderLength = maxLength; } else { sliderLength = (sb->pageStep()*maxLength)/ (sb->maxValue()-sb->minValue()+sb->pageStep()); uint range = sb->maxValue()-sb->minValue(); if ( sliderLength < SLIDER_MIN || range > INT_MAX/2 ) sliderLength = SLIDER_MIN; if ( sliderLength > maxLength ) sliderLength = maxLength; } sliderMax = sliderMin + maxLength - sliderLength; } /*!\reimp */ QStyle::ScrollControl QPEStyle::scrollBarPointOver( const QScrollBar* sb, int sliderStart, const QPoint& p ) { if ( !sb->rect().contains( p ) ) return NoScroll; int sliderMin, sliderMax, sliderLength, buttonDim, pos; scrollBarMetrics( sb, sliderMin, sliderMax, sliderLength, buttonDim ); if (sb->orientation() == QScrollBar::Horizontal) pos = p.x(); else pos = p.y(); if (pos < sliderStart) return SubPage; if (pos < sliderStart + sliderLength) return Slider; if (pos < sliderMax + sliderLength) return AddPage; if (pos < sliderMax + sliderLength + buttonDim) return SubLine; return AddLine; } /*! \reimp */ void QPEStyle::drawScrollBarControls( QPainter* p, const QScrollBar* sb, int sliderStart, uint controls, uint activeControl ) { #define ADD_LINE_ACTIVE ( activeControl == AddLine ) #define SUB_LINE_ACTIVE ( activeControl == SubLine ) QColorGroup g = sb->colorGroup(); int sliderMin, sliderMax, sliderLength, buttonDim; scrollBarMetrics( sb, sliderMin, sliderMax, sliderLength, buttonDim ); if ( controls == (AddLine | SubLine | AddPage | SubPage | Slider | First | Last ) ) p->fillRect( 0, 0, sb->width(), sb->height(), g.brush( QColorGroup::Mid )); if (sliderStart > sliderMax) { // sanity check sliderStart = sliderMax; } int dimB = buttonDim; QRect addB; QRect subB; QRect addPageR; QRect subPageR; QRect sliderR; int addX, addY, subX, subY; int length = HORIZONTAL ? sb->width() : sb->height(); int extent = HORIZONTAL ? sb->height() : sb->width(); if ( HORIZONTAL ) { subY = addY = ( extent - dimB ) / 2; subX = length - dimB - dimB; addX = length - dimB; } else { subX = addX = ( extent - dimB ) / 2; subY = length - dimB - dimB; addY = length - dimB; } int sliderEnd = sliderStart + sliderLength; int sliderW = extent; if ( HORIZONTAL ) { subB.setRect( subX,subY+1,dimB,dimB-1 ); addB.setRect( addX,addY+1,dimB,dimB-1 ); subPageR.setRect( 0, 0, sliderStart+1, sliderW ); addPageR.setRect( sliderEnd-1, 0, subX - sliderEnd+1, sliderW ); sliderR .setRect( sliderStart, 1, sliderLength, sliderW-1 ); } else { subB.setRect( subX+1,subY,dimB-1,dimB ); addB.setRect( addX+1,addY,dimB-1,dimB ); subPageR.setRect( 0, 0, sliderW, sliderStart+1 ); addPageR.setRect( 0, sliderEnd-1, sliderW, subY - sliderEnd+1 ); sliderR .setRect( 1, sliderStart, sliderW-1, sliderLength ); } bool maxedOut = (sb->maxValue() == sb->minValue()); if ( controls & AddLine ) { drawBevelButton( p, addB.x(), addB.y(), addB.width(), addB.height(), g, ADD_LINE_ACTIVE); p->setPen(g.shadow()); drawArrow( p, VERTICAL ? DownArrow : RightArrow, FALSE, addB.x()+2, addB.y()+2, addB.width()-4, addB.height()-4, g, !maxedOut, &g.brush( QColorGroup::Button )); } if ( controls & SubLine ) { drawBevelButton( p, subB.x(), subB.y(), subB.width(), subB.height(), g, SUB_LINE_ACTIVE ); p->setPen(g.shadow()); drawArrow( p, VERTICAL ? UpArrow : LeftArrow, FALSE, subB.x()+2, subB.y()+2, subB.width()-4, subB.height()-4, g, !maxedOut, &g.brush( QColorGroup::Button )); } if ( controls & SubPage ) p->fillRect( subPageR.x(), subPageR.y(), subPageR.width(), subPageR.height(), g.brush( QColorGroup::Mid )); if ( controls & AddPage ) p->fillRect( addPageR.x(), addPageR.y(), addPageR.width(), addPageR.height(), g.brush( QColorGroup::Mid )); if ( controls & Slider ) { QPoint bo = p->brushOrigin(); p->setBrushOrigin(sliderR.topLeft()); drawBevelButton( p, sliderR.x(), sliderR.y(), sliderR.width(), sliderR.height(), g, FALSE, &g.brush( QColorGroup::Button ) ); p->setBrushOrigin(bo); drawRiffles( p, sliderR.x(), sliderR.y(), sliderR.width(), sliderR.height(), g, HORIZONTAL ); } // ### perhaps this should not be able to accept focus if maxedOut? if ( sb->hasFocus() && (controls & Slider) ) p->drawWinFocusRect( sliderR.x()+2, sliderR.y()+2, sliderR.width()-5, sliderR.height()-5, sb->backgroundColor() ); } void QPEStyle::drawRiffles( QPainter* p, int x, int y, int w, int h, const QColorGroup &g, bool horizontal ) { if (!horizontal) { if (h > 20) { y += (h-20)/2 ; h = 20; } if (h > 12) { int n = 3; int my = y+h/2-4; int i ; p->setPen(g.light()); for (i=0; i<n; i++) { p->drawLine(x+2, my+3*i, x+w-4, my+3*i); } p->setPen(g.dark()); my++; for (i=0; i<n; i++) { p->drawLine(x+2, my+3*i, x+w-4, my+3*i); } } } else { if (w > 20) { x += (w-20)/2 ; w = 20; } if (w > 12) { int n = 3; int mx = x+w/2-4; int i ; p->setPen(g.light()); for (i=0; i<n; i++) { p->drawLine(mx+3*i, y+2, mx + 3*i, y+h-4); } p->setPen(g.dark()); mx++; for (i=0; i<n; i++) { p->drawLine(mx+3*i, y+2, mx + 3*i, y+h-4); } } } } int QPEStyle::sliderLength() const { return 12; } void QPEStyle::drawSlider( QPainter *p, int x, int y, int w, int h, const QColorGroup &g, Orientation o, bool tickAbove, bool tickBelow ) { int a = tickAbove ? 3 : 0; int b = tickBelow ? 3 : 0; if ( o == Horizontal ) { drawBevelButton( p, x, y+a, w, h-a-b, g, FALSE, &g.brush( QColorGroup::Button ) ); int xp = x + w/2; qDrawShadeLine( p, xp, y+a+2, xp, y+h-b-3, g ); } else { drawBevelButton( p, x+a, y, w-a-b, h, g, FALSE, &g.brush( QColorGroup::Button ) ); int yp = y + h/2; qDrawShadeLine( p, x+a+2, yp, x+w-b-3, yp, g ); } } void QPEStyle::drawSliderMask ( QPainter * p, int x, int y, int w, int h, Orientation o, bool tickAbove, bool tickBelow ) { int a = tickAbove ? 3 : 0; int b = tickBelow ? 3 : 0; if ( o == Horizontal ) p->fillRect( x, y+a, w, h-a-b, color1 ); else p->fillRect( x+a, y, w-a-b, h, color1 ); } /*!\reimp */ void QPEStyle::drawSliderGrooveMask( QPainter *p, int x, int y, int w, int h, const QColorGroup& , QCOORD c, Orientation orient ) { if ( orient == Horizontal ) p->fillRect( x, y + c - 2, w, 4, color1 ); else p->fillRect( x + c - 2, y, 4, h, color1 ); } void QPEStyle::drawTab( QPainter *p, const QTabBar *tb, QTab *t, bool selected ) { QRect r( t->rect() ); if ( tb->shape() == QTabBar::RoundedAbove ) { p->setPen( tb->colorGroup().light() ); p->drawLine( r.left(), r.bottom(), r.right(), r.bottom() ); if ( r.left() == 0 ) p->drawPoint( tb->rect().bottomLeft() ); else { p->setPen( tb->colorGroup().light() ); p->drawLine( r.left(), r.bottom(), r.right(), r.bottom() ); } if ( selected ) { p->setPen( tb->colorGroup().background() ); p->drawLine( r.left()+2, r.top()+1, r.right()-2, r.top()+1 ); p->fillRect( QRect( r.left()+1, r.top()+2, r.width()-2, r.height()-2), tb->colorGroup().brush( QColorGroup::Background )); } else { r.setRect( r.left() + 2, r.top() + 2, r.width() - 4, r.height() - 2 ); p->setPen( tb->colorGroup().button() ); p->drawLine( r.left()+2, r.top()+1, r.right()-2, r.top()+1 ); p->fillRect( QRect( r.left()+1, r.top()+2, r.width()-2, r.height()-3), tb->colorGroup().brush( QColorGroup::Button )); //do shading; will not work for pixmap brushes QColor bg = tb->colorGroup().button(); // int h,s,v; // bg.hsv( &h, &s, &v ); int n = r.height()/2; int dark = 100; for ( int i = 1; i < n; i++ ) { dark = (dark * (100+(i*15)/n) )/100; p->setPen( bg.dark( dark ) ); int y = r.bottom()-n+i; int x1 = r.left()+1; int x2 = r.right()-1; p->drawLine( x1, y, x2, y ); } } p->setPen( tb->colorGroup().light() ); p->drawLine( r.left(), r.bottom()-1, r.left(), r.top() + 2 ); p->drawPoint( r.left()+1, r.top() + 1 ); p->drawLine( r.left()+2, r.top(), r.right() - 2, r.top() ); p->setPen( tb->colorGroup().dark() ); p->drawPoint( r.right() - 1, r.top() + 1 ); p->drawLine( r.right(), r.top() + 2, r.right(), r.bottom() - 1); } else if ( tb->shape() == QTabBar::RoundedBelow ) { if ( selected ) { p->setPen( tb->colorGroup().background() ); p->drawLine( r.left()+2, r.bottom()-1, r.right()-2, r.bottom()-1 ); p->fillRect( QRect( r.left()+1, r.top(), r.width()-2, r.height()-2), tb->palette().normal().brush( QColorGroup::Background )); } else { p->setPen( tb->colorGroup().dark() ); p->drawLine( r.left(), r.top(), r.right(), r.top() ); r.setRect( r.left() + 2, r.top(), r.width() - 4, r.height() - 2 ); p->setPen( tb->colorGroup().button() ); p->drawLine( r.left()+2, r.bottom()-1, r.right()-2, r.bottom()-1 ); p->fillRect( QRect( r.left()+1, r.top()+1, r.width()-2, r.height()-3), tb->palette().normal().brush( QColorGroup::Button )); } p->setPen( tb->colorGroup().dark() ); p->drawLine( r.right(), r.top(), r.right(), r.bottom() - 2 ); p->drawPoint( r.right() - 1, r.bottom() - 1 ); p->drawLine( r.right() - 2, r.bottom(), r.left() + 2, r.bottom() ); p->setPen( tb->colorGroup().light() ); p->drawLine( r.left(), r.top()+1, r.left(), r.bottom() - 2 ); p->drawPoint( r.left() + 1, r.bottom() - 1 ); if ( r.left() == 0 ) p->drawPoint( tb->rect().topLeft() ); } else { QCommonStyle::drawTab( p, tb, t, selected ); } } static const int motifItemFrame = 0; // menu item frame width static const int motifSepHeight = 2; // separator item height static const int motifItemHMargin = 1; // menu item hor text margin static const int motifItemVMargin = 2; // menu item ver text margin static const int motifArrowHMargin = 0; // arrow horizontal margin static const int motifTabSpacing = 12; // space between text and tab static const int motifCheckMarkHMargin = 1; // horiz. margins of check mark static const int windowsRightBorder = 8; // right border on windows static const int windowsCheckMarkWidth = 2; // checkmarks width on windows /*! \reimp */ int QPEStyle::extraPopupMenuItemWidth( bool checkable, int maxpmw, QMenuItem* mi, const QFontMetrics& /*fm*/ ) { #ifndef QT_NO_MENUDATA int w = 2*motifItemHMargin + 2*motifItemFrame; // a little bit of border can never harm if ( mi->isSeparator() ) return 10; // arbitrary else if ( mi->pixmap() ) w += mi->pixmap()->width(); // pixmap only if ( !mi->text().isNull() ) { if ( mi->text().find('\t') >= 0 ) // string contains tab w += motifTabSpacing; } if ( maxpmw ) { // we have iconsets w += maxpmw; w += 6; // add a little extra border around the iconset } if ( checkable && maxpmw < windowsCheckMarkWidth ) { w += windowsCheckMarkWidth - maxpmw; // space for the checkmarks } if ( maxpmw > 0 || checkable ) // we have a check-column ( iconsets or checkmarks) w += motifCheckMarkHMargin; // add space to separate the columns w += windowsRightBorder; // windows has a strange wide border on the right side return w; #endif } /*! \reimp */ int QPEStyle::popupMenuItemHeight( bool /*checkable*/, QMenuItem* mi, const QFontMetrics& fm ) { #ifndef QT_NO_MENUDATA int h = 0; if ( mi->isSeparator() ) // separator height h = motifSepHeight; else if ( mi->pixmap() ) // pixmap height h = mi->pixmap()->height() + 2*motifItemFrame; else // text height h = fm.height() + 2*motifItemVMargin + 2*motifItemFrame - 1; if ( !mi->isSeparator() && mi->iconSet() != 0 ) { h = QMAX( h, mi->iconSet()->pixmap( QIconSet::Small, QIconSet::Normal ).height() + 2*motifItemFrame ); } if ( mi->custom() ) h = QMAX( h, mi->custom()->sizeHint().height() + 2*motifItemVMargin + 2*motifItemFrame ) - 1; return h; #endif } void QPEStyle::drawPopupMenuItem( QPainter* p, bool checkable, int maxpmw, int tab, QMenuItem* mi, const QPalette& pal, bool act, bool enabled, int x, int y, int w, int h) { #ifndef QT_NO_MENUDATA const QColorGroup & g = pal.active(); bool dis = !enabled; QColorGroup itemg = dis ? pal.disabled() : pal.active(); if ( checkable ) maxpmw = QMAX( maxpmw, 8 ); // space for the checkmarks int checkcol = maxpmw; if ( mi && mi->isSeparator() ) { // draw separator p->setPen( g.dark() ); p->drawLine( x, y, x+w, y ); p->setPen( g.light() ); p->drawLine( x, y+1, x+w, y+1 ); return; } QBrush fill = act? g.brush( QColorGroup::Highlight ) : g.brush( QColorGroup::Button ); p->fillRect( x, y, w, h, fill); if ( !mi ) return; if ( mi->isChecked() ) { if ( act && !dis ) { qDrawShadePanel( p, x, y, checkcol, h, g, TRUE, 1, &g.brush( QColorGroup::Button ) ); } else { qDrawShadePanel( p, x, y, checkcol, h, g, TRUE, 1, &g.brush( QColorGroup::Midlight ) ); } } else if ( !act ) { p->fillRect(x, y, checkcol , h, g.brush( QColorGroup::Button )); } if ( mi->iconSet() ) { // draw iconset QIconSet::Mode mode = dis ? QIconSet::Disabled : QIconSet::Normal; if (act && !dis ) mode = QIconSet::Active; QPixmap pixmap = mi->iconSet()->pixmap( QIconSet::Small, mode ); int pixw = pixmap.width(); int pixh = pixmap.height(); if ( act && !dis ) { if ( !mi->isChecked() ) qDrawShadePanel( p, x, y, checkcol, h, g, FALSE, 1, &g.brush( QColorGroup::Button ) ); } QRect cr( x, y, checkcol, h ); QRect pmr( 0, 0, pixw, pixh ); pmr.moveCenter( cr.center() ); p->setPen( itemg.text() ); p->drawPixmap( pmr.topLeft(), pixmap ); QBrush fill = act? g.brush( QColorGroup::Highlight ) : g.brush( QColorGroup::Button ); p->fillRect( x+checkcol + 1, y, w - checkcol - 1, h, fill); } else if ( checkable ) { // just "checking"... int mw = checkcol + motifItemFrame; int mh = h - 2*motifItemFrame; if ( mi->isChecked() ) { drawCheckMark( p, x + motifItemFrame + 2, y+motifItemFrame, mw, mh, itemg, act, dis ); } } p->setPen( act ? g.highlightedText() : g.buttonText() ); QColor discol; if ( dis ) { discol = itemg.text(); p->setPen( discol ); } int xm = motifItemFrame + checkcol + motifItemHMargin; if ( mi->custom() ) { int m = motifItemVMargin; p->save(); if ( dis && !act ) { p->setPen( g.light() ); mi->custom()->paint( p, itemg, act, enabled, x+xm+1, y+m+1, w-xm-tab+1, h-2*m ); p->setPen( discol ); } mi->custom()->paint( p, itemg, act, enabled, x+xm, y+m, w-xm-tab+1, h-2*m ); p->restore(); } QString s = mi->text(); if ( !s.isNull() ) { // draw text int t = s.find( '\t' ); int m = motifItemVMargin; const int text_flags = AlignVCenter|ShowPrefix | DontClip | SingleLine; if ( t >= 0 ) { // draw tab text if ( dis && !act ) { p->setPen( g.light() ); p->drawText( x+w-tab-windowsRightBorder-motifItemHMargin-motifItemFrame+1, y+m+1, tab, h-2*m, text_flags, s.mid( t+1 )); p->setPen( discol ); } p->drawText( x+w-tab-windowsRightBorder-motifItemHMargin-motifItemFrame, y+m, tab, h-2*m, text_flags, s.mid( t+1 ) ); } if ( dis && !act ) { p->setPen( g.light() ); p->drawText( x+xm+1, y+m+1, w-xm+1, h-2*m, text_flags, s, t ); p->setPen( discol ); } p->drawText( x+xm, y+m, w-xm-tab+1, h-2*m, text_flags, s, t ); } else if ( mi->pixmap() ) { // draw pixmap QPixmap *pixmap = mi->pixmap(); if ( pixmap->depth() == 1 ) p->setBackgroundMode( OpaqueMode ); p->drawPixmap( x+xm, y+motifItemFrame, *pixmap ); if ( pixmap->depth() == 1 ) p->setBackgroundMode( TransparentMode ); } if ( mi->popup() ) { // draw sub menu arrow int dim = (h-2*motifItemFrame) / 2; if ( act ) { if ( !dis ) discol = white; QColorGroup g2( discol, g.highlight(), white, white, dis ? discol : white, discol, white ); drawArrow( p, RightArrow, FALSE, x+w - motifArrowHMargin - motifItemFrame - dim, y+h/2-dim/2, dim, dim, g2, TRUE ); } else { drawArrow( p, RightArrow, FALSE, x+w - motifArrowHMargin - motifItemFrame - dim, y+h/2-dim/2, dim, dim, g, mi->isEnabled() ); } } #endif } #endif diff --git a/library/qpestyle.h b/library/qpestyle.h index 19ef346..1bde0ff 100644 --- a/library/qpestyle.h +++ b/library/qpestyle.h @@ -1,102 +1,102 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #ifndef QPESTYLE_H #define QPESTYLE_H #ifndef QT_H #include "qwindowsstyle.h" #endif // QT_H -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 class Q_EXPORT QPEStyle : public QWindowsStyle { public: QPEStyle(); virtual ~QPEStyle(); virtual void drawPrimitive( PrimitiveElement pe, QPainter *p, const QRect &r, const QColorGroup &cg, SFlags flags=Style_Default, const QStyleOption & = QStyleOption::Default) const; virtual void drawControl( ControlElement ce, QPainter *p, const QWidget *widget, const QRect &r, const QColorGroup &cg, SFlags how=Style_Default, const QStyleOption & = QStyleOption::Default) const; virtual void drawComplexControl( ComplexControl control, QPainter *p, const QWidget *widget, const QRect &r, const QColorGroup &cg, SFlags how=Style_Default, SCFlags sub=SC_All, SCFlags subActive=SC_None, const QStyleOption & = QStyleOption::Default) const; virtual int pixelMetric( PixelMetric metric, const QWidget *widget=0 ) const; virtual QSize sizeFromContents( ContentsType contents, const QWidget *widget, const QSize &contentsSize, const QStyleOption & = QStyleOption::Default) const; }; #else class Q_EXPORT QPEStyle : public QWindowsStyle { public: QPEStyle(); virtual ~QPEStyle(); virtual void polish( QPalette &p ); virtual void polish( QWidget *w ); virtual void unPolish( QWidget *w ); int defaultFrameWidth () const; void drawPanel ( QPainter * p, int x, int y, int w, int h, const QColorGroup &, bool sunken=FALSE, int lineWidth = 1, const QBrush * fill = 0 ); void drawButton( QPainter *p, int x, int y, int w, int h, const QColorGroup &g, bool sunken, const QBrush* fill ); void drawButtonMask ( QPainter * p, int x, int y, int w, int h ); void drawBevelButton( QPainter *p, int x, int y, int w, int h, const QColorGroup &g, bool sunken=FALSE, const QBrush* fill=0 ); QRect comboButtonRect( int x, int y, int w, int h); QRect comboButtonFocusRect( int x, int y, int w, int h); void drawComboButton( QPainter *p, int x, int y, int w, int h, const QColorGroup &g, bool sunken, bool, bool enabled, const QBrush *fill ); void drawExclusiveIndicator ( QPainter * p, int x, int y, int w, int h, const QColorGroup & g, bool on, bool down = FALSE, bool enabled = TRUE ); void drawIndicator ( QPainter * p, int x, int y, int w, int h, const QColorGroup & g, int state, bool down = FALSE, bool enabled = TRUE ); void scrollBarMetrics( const QScrollBar*, int&, int&, int&, int&); void drawScrollBarControls( QPainter*, const QScrollBar*, int sliderStart, uint controls, uint activeControl ); ScrollControl scrollBarPointOver( const QScrollBar* sb, int sliderStart, const QPoint& p ); void drawRiffles( QPainter* p, int x, int y, int w, int h, const QColorGroup &g, bool horizontal ); int sliderLength() const; void drawSlider( QPainter *p, int x, int y, int w, int h, const QColorGroup &g, Orientation, bool tickAbove, bool tickBelow ); void drawSliderMask( QPainter *p, int x, int y, int w, int h, Orientation, bool tickAbove, bool tickBelow ); void drawSliderGrooveMask( QPainter *p, int x, int y, int w, int h, const QColorGroup& , QCOORD c, Orientation orient ); void drawTab( QPainter *, const QTabBar *, QTab *, bool selected ); int extraPopupMenuItemWidth( bool checkable, int maxpmw, QMenuItem*, const QFontMetrics& ); int popupMenuItemHeight( bool checkable, QMenuItem*, const QFontMetrics& ); void drawPopupMenuItem( QPainter* p, bool checkable, int maxpmw, int tab, QMenuItem* mi, const QPalette& pal, bool act, bool enabled, int x, int y, int w, int h); int buttonMargin() const; QSize scrollBarExtent() const; private: // Disabled copy constructor and operator= #if defined(Q_DISABLE_COPY) QPEStyle( const QPEStyle & ); QPEStyle& operator=( const QPEStyle & ); #endif }; #endif #endif // QPESTYLE_H diff --git a/noncore/apps/opie-console/TEWidget.cpp b/noncore/apps/opie-console/TEWidget.cpp index 98c1793..1199e4f 100644 --- a/noncore/apps/opie-console/TEWidget.cpp +++ b/noncore/apps/opie-console/TEWidget.cpp @@ -1,1352 +1,1352 @@ /* ------------------------------------------------------------------------ */ /* */ /* [TEWidget.C] Terminal Emulation Widget */ /* */ /* ------------------------------------------------------------------------ */ /* */ /* Copyright (c) 1997,1998 by Lars Doelle <lars.doelle@on-line.de> */ /* */ /* This file is part of Konsole - an X terminal for KDE */ /* */ /* ------------------------------------------------------------------------ */ /* */ /* Ported Konsole to Qt/Embedded */ /* */ /* Copyright (C) 2000 by John Ryland <jryland@trolltech.com> */ /* */ /* -------------------------------------------------------------------------- */ /*! \class TEWidget \brief Visible screen contents This class is responsible to map the `image' of a terminal emulation to the display. All the dependency of the emulation to a specific GUI or toolkit is localized here. Further, this widget has no knowledge about being part of an emulation, it simply work within the terminal emulation framework by exposing size and key events and by being ordered to show a new image. <ul> <li> The internal image has the size of the widget (evtl. rounded up) <li> The external image used in setImage can have any size. <li> (internally) the external image is simply copied to the internal when a setImage happens. During a resizeEvent no painting is done a paintEvent is expected to follow anyway. </ul> \sa TEScreen \sa Emulation */ /* FIXME: - 'image' may also be used uninitialized (it isn't in fact) in resizeEvent - 'font_a' not used in mouse events - add destructor */ /* TODO - evtl. be sensitive to `paletteChange' while using default colors. - set different 'rounding' styles? I.e. have a mode to show clipped chars? */ // #include "config.h" #include "TEWidget.h" #include <qpe/config.h> #include <qapplication.h> #include <qclipboard.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <ctype.h> #include <sys/stat.h> #include <sys/types.h> #include <signal.h> #include <assert.h> // #include "TEWidget.moc" //#include <kapp.h> //#include <kcursor.h> //#include <kurl.h> //#include <kdebug.h> //#include <klocale.h> #define HERE printf("%s(%d): %s\n",__FILE__,__LINE__,__FUNCTION__) #define HCNT(Name) // { static int cnt = 1; printf("%s(%d): %s %d\n",__FILE__,__LINE__,Name,cnt++); } #define loc(X,Y) ((Y)*columns+(X)) //FIXME: the rim should normally be 1, 0 only when running in full screen mode. #define rimX 0 // left/right rim width #define rimY 0 // top/bottom rim high #define yMouseScroll 1 // scroll increment used when dragging selection at top/bottom of window. /* Button XPM */ namespace { static char * menu_xpm[] = { "12 12 5 1", " c None", ". c #000000", "+ c #FFFDAD", "@ c #FFFF00", "# c #E5E100", " ", " ", " ......... ", " .+++++++. ", " .+@@@@#. ", " .+@@@#. ", " .+@@#. ", " .+@#. ", " .+#. ", " .+. ", " .. ", " "}; } /* ------------------------------------------------------------------------- */ /* */ /* Colors */ /* */ /* ------------------------------------------------------------------------- */ //FIXME: the default color table is in session.C now. // We need a way to get rid of this one, here. static const ColorEntry base_color_table[TABLE_COLORS] = // The following are almost IBM standard color codes, with some slight // gamma correction for the dim colors to compensate for bright X screens. // It contains the 8 ansiterm/xterm colors in 2 intensities. { // Fixme: could add faint colors here, also. // normal ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 1, 0 ), // Dfore, Dback ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0x18), 0, 0 ), // Black, Red ColorEntry(QColor(0x18,0xB2,0x18), 0, 0 ), ColorEntry( QColor(0xB2,0x68,0x18), 0, 0 ), // Green, Yellow ColorEntry(QColor(0x18,0x18,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ), // Blue, Magenta ColorEntry(QColor(0x18,0xB2,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 0, 0 ), // Cyan, White // intensiv ColorEntry(QColor(0x00,0x00,0x00), 0, 1 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 1, 0 ), ColorEntry(QColor(0x68,0x68,0x68), 0, 0 ), ColorEntry( QColor(0xFF,0x54,0x54), 0, 0 ), ColorEntry(QColor(0x54,0xFF,0x54), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0x54), 0, 0 ), ColorEntry(QColor(0x54,0x54,0xFF), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ), ColorEntry(QColor(0x54,0xFF,0xFF), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 0, 0 ) }; /* Note that we use ANSI color order (bgr), while IBMPC color order is (rgb) Code 0 1 2 3 4 5 6 7 ----------- ------- ------- ------- ------- ------- ------- ------- ------- ANSI (bgr) Black Red Green Yellow Blue Magenta Cyan White IBMPC (rgb) Black Blue Green Cyan Red Magenta Yellow White */ QColor TEWidget::getDefaultBackColor() { return color_table[DEFAULT_BACK_COLOR].color; } const ColorEntry* TEWidget::getColorTable() const { return color_table; } const ColorEntry* TEWidget::getdefaultColorTable() const { return base_color_table; } const QPixmap *TEWidget::backgroundPixmap() { static QPixmap *bg = new QPixmap("~/qpim/main/pics/faded_bg.xpm"); const QPixmap *pm = bg; return pm; } void TEWidget::setColorTable(const ColorEntry table[]) { for (int i = 0; i < TABLE_COLORS; i++) color_table[i] = table[i]; const QPixmap* pm = backgroundPixmap(); if (!pm) setBackgroundColor(color_table[DEFAULT_BACK_COLOR].color); update(); } //FIXME: add backgroundPixmapChanged. /* ------------------------------------------------------------------------- */ /* */ /* Font */ /* */ /* ------------------------------------------------------------------------- */ /* The VT100 has 32 special graphical characters. The usual vt100 extended xterm fonts have these at 0x00..0x1f. QT's iso mapping leaves 0x00..0x7f without any changes. But the graphicals come in here as proper unicode characters. We treat non-iso10646 fonts as VT100 extended and do the requiered mapping from unicode to 0x00..0x1f. The remaining translation is then left to the QCodec. */ // assert for i in [0..31] : vt100extended(vt100_graphics[i]) == i. unsigned short 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 }; static QChar vt100extended(QChar c) { switch (c.unicode()) { case 0x25c6 : return 1; case 0x2592 : return 2; case 0x2409 : return 3; case 0x240c : return 4; case 0x240d : return 5; case 0x240a : return 6; case 0x00b0 : return 7; case 0x00b1 : return 8; case 0x2424 : return 9; case 0x240b : return 10; case 0x2518 : return 11; case 0x2510 : return 12; case 0x250c : return 13; case 0x2514 : return 14; case 0x253c : return 15; case 0xf800 : return 16; case 0xf801 : return 17; case 0x2500 : return 18; case 0xf803 : return 19; case 0xf804 : return 20; case 0x251c : return 21; case 0x2524 : return 22; case 0x2534 : return 23; case 0x252c : return 24; case 0x2502 : return 25; case 0x2264 : return 26; case 0x2265 : return 27; case 0x03c0 : return 28; case 0x2260 : return 29; case 0x00a3 : return 30; case 0x00b7 : return 31; } return c; } static QChar identicalMap(QChar c) { return c; } void TEWidget::fontChange(const QFont &) { QFontMetrics fm(font()); font_h = fm.height(); font_w = fm.maxWidth(); font_a = fm.ascent(); //printf("font_h: %d\n",font_h); //printf("font_w: %d\n",font_w); //printf("font_a: %d\n",font_a); //printf("charset: %s\n",QFont::encodingName(font().charSet()).ascii()); //printf("rawname: %s\n",font().rawName().ascii()); fontMap = -#if QT_VERSION < 300 +#if QT_VERSION < 0x030000 strcmp(QFont::encodingName(font().charSet()).ascii(),"iso10646") ? vt100extended : #endif identicalMap; propagateSize(); update(); } void TEWidget::setVTFont(const QFont& f) { QFrame::setFont(f); } QFont TEWidget::getVTFont() { return font(); } void TEWidget::setFont(const QFont &) { // ignore font change request if not coming from konsole itself } /* ------------------------------------------------------------------------- */ /* */ /* Constructor / Destructor */ /* */ /* ----------------------------------------------------------------------- */ TEWidget::TEWidget(QWidget *parent, const char *name) : QFrame(parent,name) { #ifndef QT_NO_CLIPBOARD cb = QApplication::clipboard(); QObject::connect( (QObject*)cb, SIGNAL(dataChanged()), this, SLOT(onClearSelection()) ); #endif scrollbar = new QScrollBar( this ); scrollbar->setCursor( arrowCursor ); connect(scrollbar, SIGNAL(valueChanged(int)), this, SLOT(scrollChanged(int))); hscrollbar = new QScrollBar( Qt::Horizontal, this ); hscrollbar->setCursor( arrowCursor ); connect(hscrollbar, SIGNAL(valueChanged(int)), this, SLOT(hscrollChanged(int))); m_cornerButton = new QPushButton( this ); m_cornerButton->setPixmap( QPixmap( (const char**)menu_xpm ) ); m_cornerButton->setMaximumSize( 14, 14 ); m_cornerButton->hide(); Config cfg("Konsole"); cfg.setGroup("ScrollBar"); switch( cfg.readNumEntry("Position",2)){ case 0: scrollLoc = SCRNONE; break; case 1: scrollLoc = SCRLEFT; break; case 2: scrollLoc = SCRRIGHT; break; }; blinkT = new QTimer(this); connect(blinkT, SIGNAL(timeout()), this, SLOT(blinkEvent())); // blinking = FALSE; blinking = TRUE; resizing = FALSE; actSel = 0; image = 0; lines = 1; columns = 1; font_w = 1; font_h = 1; font_a = 1; word_selection_mode = FALSE; vcolumns = 0; hposition = 0; setMouseMarks(TRUE); setVTFont( QFont("fixed") ); setColorTable(base_color_table); // init color table qApp->installEventFilter( this ); //FIXME: see below // KCursor::setAutoHideCursor( this, true ); // Init DnD //////////////////////////////////////////////////////////////// currentSession = NULL; // setAcceptDrops(true); // attempt // m_drop = new QPopupMenu(this); // m_drop->insertItem( QString("Paste"), 0); // m_drop->insertItem( QString("cd"), 1); // connect(m_drop, SIGNAL(activated(int)), SLOT(drop_menu_activated(int))); // we need focus so that the auto-hide cursor feature works setFocus(); setFocusPolicy( WheelFocus ); } //FIXME: make proper destructor // Here's a start (David) TEWidget::~TEWidget() { qApp->removeEventFilter( this ); if (image) free(image); } /* ------------------------------------------------------------------------- */ /* */ /* Display Operations */ /* */ /* ------------------------------------------------------------------------- */ /*! attributed string draw primitive */ void TEWidget::drawAttrStr(QPainter &paint, QRect rect, QString& str, ca attr, BOOL pm, BOOL clear) { if (pm && color_table[attr.b].transparent) { paint.setBackgroundMode( TransparentMode ); if (clear) erase(rect); } else { if (blinking) paint.fillRect(rect, color_table[attr.b].color); else { paint.setBackgroundMode( OpaqueMode ); paint.setBackgroundColor( color_table[attr.b].color ); } } if (color_table[attr.f].bold) paint.setPen(QColor( 0x8F, 0x00, 0x00 )); else paint.setPen(color_table[attr.f].color); paint.drawText(rect.x(),rect.y()+font_a, str); if (attr.r & RE_UNDERLINE) paint.drawLine(rect.left(), rect.y()+font_a+1, rect.right(),rect.y()+font_a+1 ); } /*! The image can only be set completely. The size of the new image may or may not match the size of the widget. */ void TEWidget::setImage(const ca* const newimg, int lines, int columns) { int y,x,len; const QPixmap* pm = backgroundPixmap(); QPainter paint; setUpdatesEnabled(FALSE); paint.begin( this ); HCNT("setImage"); QPoint tL = contentsRect().topLeft(); int tLx = tL.x(); int tLy = tL.y(); hasBlinker = FALSE; int cf = -1; // undefined int cb = -1; // undefined int cr = -1; // undefined int lins = QMIN(this->lines, QMAX(0,lines )); int cols = QMIN(this->columns,QMAX(0,columns)); QChar *disstrU = new QChar[cols]; //{ static int cnt = 0; printf("setImage %d\n",cnt++); } for (y = 0; y < lins; y++) { const ca* lcl = &image[y*this->columns]; const ca* const ext = &newimg[y*columns]; if (!resizing) // not while resizing, we're expecting a paintEvent for (x = 0; x < cols; x++) { hasBlinker |= (ext[x].r & RE_BLINK); if (ext[x] != lcl[x]) { cr = ext[x].r; cb = ext[x].b; if (ext[x].f != cf) cf = ext[x].f; int lln = cols - x; disstrU[0] = fontMap(ext[x+0].c); for (len = 1; len < lln; len++) { if (ext[x+len].f != cf || ext[x+len].b != cb || ext[x+len].r != cr || ext[x+len] == lcl[x+len] ) break; disstrU[len] = fontMap(ext[x+len].c); } QString unistr(disstrU,len); drawAttrStr(paint, QRect(blX+tLx+font_w*x,bY+tLy+font_h*y,font_w*len,font_h), unistr, ext[x], pm != NULL, true); x += len - 1; } } // finally, make `image' become `newimg'. memcpy((void*)lcl,(const void*)ext,cols*sizeof(ca)); } drawFrame( &paint ); paint.end(); setUpdatesEnabled(TRUE); if ( hasBlinker && !blinkT->isActive()) blinkT->start(1000); // 1000 ms if (!hasBlinker && blinkT->isActive()) { blinkT->stop(); blinking = FALSE; } delete [] disstrU; } // paint Event //////////////////////////////////////////////////// /*! The difference of this routine vs. the `setImage' is, that the drawing does not include a difference analysis between the old and the new image. Instead, the internal image is used and the painting bound by the PaintEvent box. */ void TEWidget::paintEvent( QPaintEvent* pe ) { //{ static int cnt = 0; printf("paint %d\n",cnt++); } const QPixmap* pm = backgroundPixmap(); QPainter paint; setUpdatesEnabled(FALSE); paint.begin( this ); paint.setBackgroundMode( TransparentMode ); HCNT("paintEvent"); // Note that the actual widget size can be slightly larger // that the image (the size is truncated towards the smaller // number of characters in `resizeEvent'. The paint rectangle // can thus be larger than the image, but less then the size // of one character. QRect rect = pe->rect().intersect(contentsRect()); QPoint tL = contentsRect().topLeft(); int tLx = tL.x(); int tLy = tL.y(); int lux = QMIN(columns-1, QMAX(0,(rect.left() - tLx - blX ) / font_w)); int luy = QMIN(lines-1, QMAX(0,(rect.top() - tLy - bY ) / font_h)); int rlx = QMIN(columns-1, QMAX(0,(rect.right() - tLx - blX ) / font_w)); int rly = QMIN(lines-1, QMAX(0,(rect.bottom() - tLy - bY ) / font_h)); /* printf("paintEvent: %d..%d, %d..%d (%d..%d, %d..%d)\n",lux,rlx,luy,rly, rect.left(), rect.right(), rect.top(), rect.bottom()); */ // if (pm != NULL && color_table[image->b].transparent) // erase(rect); // BL: I have no idea why we need this, and it breaks the refresh. QChar *disstrU = new QChar[columns]; for (int y = luy; y <= rly; y++) for (int x = lux; x <= rlx; x++) { int len = 1; disstrU[0] = fontMap(image[loc(x,y)].c); int cf = image[loc(x,y)].f; int cb = image[loc(x,y)].b; int cr = image[loc(x,y)].r; while (x+len <= rlx && image[loc(x+len,y)].f == cf && image[loc(x+len,y)].b == cb && image[loc(x+len,y)].r == cr ) { disstrU[len] = fontMap(image[loc(x+len,y)].c); len += 1; } QString unistr(disstrU,len); drawAttrStr(paint, QRect(blX+tLx+font_w*x,bY+tLy+font_h*y,font_w*len,font_h), unistr, image[loc(x,y)], pm != NULL, false); x += len - 1; } delete [] disstrU; drawFrame( &paint ); paint.end(); setUpdatesEnabled(TRUE); } void TEWidget::blinkEvent() { blinking = !blinking; repaint(FALSE); } /* ------------------------------------------------------------------------- */ /* */ /* Resizing */ /* */ /* ------------------------------------------------------------------------- */ void TEWidget::resizeEvent(QResizeEvent* ev) { // printf("resize: %d,%d\n",ev->size().width(),ev->size().height()); //printf("approx: %d,%d\n",ev->size().width()/font_w,ev->size().height()/font_h); //printf("leaves: %d,%d\n",ev->size().width()%font_w,ev->size().height()%font_h); //printf("curren: %d,%d\n",width(),height()); HCNT("resizeEvent"); // see comment in `paintEvent' concerning the rounding. //FIXME: could make a routine here; check width(),height() assert(ev->size().width() == width()); assert(ev->size().height() == height()); propagateSize(); } void TEWidget::propagateSize() { ca* oldimg = image; int oldlin = lines; int oldcol = columns; makeImage(); // we copy the old image to reduce flicker int lins = QMIN(oldlin,lines); int cols = QMIN(oldcol,columns); if (oldimg) { for (int lin = 0; lin < lins; lin++) memcpy((void*)&image[columns*lin], (void*)&oldimg[oldcol*lin],cols*sizeof(ca)); free(oldimg); //FIXME: try new,delete } else clearImage(); //NOTE: control flows from the back through the chest right into the eye. // `emu' will call back via `setImage'. resizing = TRUE; emit changedImageSizeSignal(lines, columns); // expose resizeEvent resizing = FALSE; } /* ------------------------------------------------------------------------- */ /* */ /* Scrollbar */ /* */ /* ------------------------------------------------------------------------- */ void TEWidget::scrollChanged(int) { emit changedHistoryCursor(scrollbar->value()); //expose } void TEWidget::hscrollChanged(int loc) { hposition = loc; propagateSize(); update(); } void TEWidget::setScroll(int cursor, int slines) { disconnect(scrollbar, SIGNAL(valueChanged(int)), this, SLOT(scrollChanged(int))); scrollbar->setRange(0,slines); scrollbar->setSteps(1,lines); scrollbar->setValue(cursor); connect(scrollbar, SIGNAL(valueChanged(int)), this, SLOT(scrollChanged(int))); } void TEWidget::setScrollbarLocation(int loc) { if (scrollLoc == loc) return; // quickly scrollLoc = loc; propagateSize(); update(); } /* ------------------------------------------------------------------------- */ /* */ /* Mouse */ /* */ /* ------------------------------------------------------------------------- */ /*! Three different operations can be performed using the mouse, and the routines in this section serve all of them: 1) The press/release events are exposed to the application 2) Marking (press and move left button) and Pasting (press middle button) 3) The right mouse button is used from the configuration menu NOTE: During the marking process we attempt to keep the cursor within the bounds of the text as being displayed by setting the mouse position whenever the mouse has left the text area. Two reasons to do so: 1) QT does not allow the `grabMouse' to confine-to the TEWidget. Thus a `XGrapPointer' would have to be used instead. 2) Even if so, this would not help too much, since the text area of the TEWidget is normally not identical with it's bounds. The disadvantage of the current handling is, that the mouse can visibly leave the bounds of the widget and is then moved back. Because of the current construction, and the reasons mentioned above, we cannot do better without changing the overall construction. */ /*! */ void TEWidget::mousePressEvent(QMouseEvent* ev) { //printf("press [%d,%d] %d\n",ev->x()/font_w,ev->y()/font_h,ev->button()); if ( !contentsRect().contains(ev->pos()) ) return; QPoint tL = contentsRect().topLeft(); int tLx = tL.x(); int tLy = tL.y(); word_selection_mode = FALSE; //printf("press top left [%d,%d] by=%d\n",tLx,tLy, bY); if ( ev->button() == LeftButton) { QPoint pos = QPoint((ev->x()-tLx-blX)/font_w,(ev->y()-tLy-bY)/font_h); if ( ev->state() & ControlButton ) preserve_line_breaks = FALSE ; if (mouse_marks || (ev->state() & ShiftButton)) { emit clearSelectionSignal(); iPntSel = pntSel = pos; actSel = 1; // left mouse button pressed but nothing selected yet. grabMouse( /*crossCursor*/ ); // handle with care! } else { emit mouseSignal( 0, pos.x() + 1, pos.y() + 1 ); // left button } } if ( ev->button() == MidButton ) { emitSelection(); } if ( ev->button() == RightButton ) // Configure { emit configureRequest( this, ev->state()&(ShiftButton|ControlButton), ev->x(), ev->y() ); } } void TEWidget::mouseMoveEvent(QMouseEvent* ev) { // for auto-hiding the cursor, we need mouseTracking if (ev->state() == NoButton ) return; if (actSel == 0) return; // don't extend selection while pasting if (ev->state() & MidButton) return; //if ( !contentsRect().contains(ev->pos()) ) return; QPoint tL = contentsRect().topLeft(); int tLx = tL.x(); int tLy = tL.y(); int scroll = scrollbar->value(); // we're in the process of moving the mouse with the left button pressed // the mouse cursor will kept catched within the bounds of the text in // this widget. // Adjust position within text area bounds. See FIXME above. QPoint pos = ev->pos(); if ( pos.x() < tLx+blX ) pos.setX( tLx+blX ); if ( pos.x() > tLx+blX+columns*font_w-1 ) pos.setX( tLx+blX+columns*font_w ); if ( pos.y() < tLy+bY ) pos.setY( tLy+bY ); if ( pos.y() > tLy+bY+lines*font_h-1 ) pos.setY( tLy+bY+lines*font_h-1 ); // check if we produce a mouse move event by this if ( pos != ev->pos() ) cursor().setPos(mapToGlobal(pos)); if ( pos.y() == tLy+bY+lines*font_h-1 ) { scrollbar->setValue(scrollbar->value()+yMouseScroll); // scrollforward } if ( pos.y() == tLy+bY ) { scrollbar->setValue(scrollbar->value()-yMouseScroll); // scrollback } QPoint here = QPoint((pos.x()-tLx-blX)/font_w,(pos.y()-tLy-bY)/font_h); QPoint ohere; bool swapping = FALSE; if ( word_selection_mode ) { // Extend to word boundaries int i; int selClass; bool left_not_right = ( here.y() < iPntSel.y() || here.y() == iPntSel.y() && here.x() < iPntSel.x() ); bool old_left_not_right = ( pntSel.y() < iPntSel.y() || pntSel.y() == iPntSel.y() && pntSel.x() < iPntSel.x() ); swapping = left_not_right != old_left_not_right; // Find left (left_not_right ? from here : from start) QPoint left = left_not_right ? here : iPntSel; i = loc(left.x(),left.y()); selClass = charClass(image[i].c); while ( left.x() > 0 && charClass(image[i-1].c) == selClass ) { i--; left.rx()--; } // Find left (left_not_right ? from start : from here) QPoint right = left_not_right ? iPntSel : here; i = loc(right.x(),right.y()); selClass = charClass(image[i].c); while ( right.x() < columns-1 && charClass(image[i+1].c) == selClass ) { i++; right.rx()++; } // Pick which is start (ohere) and which is extension (here) if ( left_not_right ) { here = left; ohere = right; } else { here = right; ohere = left; } } if (here == pntSel && scroll == scrollbar->value()) return; // not moved if ( word_selection_mode ) { if ( actSel < 2 || swapping ) { emit beginSelectionSignal( ohere.x(), ohere.y() ); } } else if ( actSel < 2 ) { emit beginSelectionSignal( pntSel.x(), pntSel.y() ); } actSel = 2; // within selection pntSel = here; emit extendSelectionSignal( here.x(), here.y() ); } void TEWidget::mouseReleaseEvent(QMouseEvent* ev) { //printf("release [%d,%d] %d\n",ev->x()/font_w,ev->y()/font_h,ev->button()); if ( ev->button() == LeftButton) { if ( actSel > 1 ) emit endSelectionSignal(preserve_line_breaks); preserve_line_breaks = TRUE; actSel = 0; //FIXME: emits a release event even if the mouse is // outside the range. The procedure used in `mouseMoveEvent' // applies here, too. QPoint tL = contentsRect().topLeft(); int tLx = tL.x(); int tLy = tL.y(); if (!mouse_marks && !(ev->state() & ShiftButton)) emit mouseSignal( 3, // release (ev->x()-tLx-blX)/font_w + 1, (ev->y()-tLy-bY)/font_h + 1 ); releaseMouse(); } } void TEWidget::mouseDoubleClickEvent(QMouseEvent* ev) { if ( ev->button() != LeftButton) return; QPoint tL = contentsRect().topLeft(); int tLx = tL.x(); int tLy = tL.y(); QPoint pos = QPoint((ev->x()-tLx-blX)/font_w,(ev->y()-tLy-bY)/font_h); // pass on double click as two clicks. if (!mouse_marks && !(ev->state() & ShiftButton)) { emit mouseSignal( 0, pos.x()+1, pos.y()+1 ); // left button emit mouseSignal( 3, pos.x()+1, pos.y()+1 ); // release emit mouseSignal( 0, pos.x()+1, pos.y()+1 ); // left button return; } emit clearSelectionSignal(); QPoint bgnSel = pos; QPoint endSel = QPoint((ev->x()-tLx-blX)/font_w,(ev->y()-tLy-bY)/font_h); int i = loc(bgnSel.x(),bgnSel.y()); iPntSel = bgnSel; word_selection_mode = TRUE; // find word boundaries... int selClass = charClass(image[i].c); { // set the start... int x = bgnSel.x(); while ( x > 0 && charClass(image[i-1].c) == selClass ) { i--; x--; } bgnSel.setX(x); emit beginSelectionSignal( bgnSel.x(), bgnSel.y() ); // set the end... i = loc( endSel.x(), endSel.y() ); x = endSel.x(); while( x < columns-1 && charClass(image[i+1].c) == selClass ) { i++; x++ ; } endSel.setX(x); actSel = 2; // within selection emit extendSelectionSignal( endSel.x(), endSel.y() ); emit endSelectionSignal(preserve_line_breaks); preserve_line_breaks = TRUE; } } void TEWidget::focusInEvent( QFocusEvent * ) { // do nothing, to prevent repainting } void TEWidget::focusOutEvent( QFocusEvent * ) { // do nothing, to prevent repainting } bool TEWidget::focusNextPrevChild( bool next ) { if (next) return false; // This disables changing the active part in konqueror // when pressing Tab return QFrame::focusNextPrevChild( next ); } int TEWidget::charClass(char ch) const { // This might seem like overkill, but imagine if ch was a Unicode // character (Qt 2.0 QChar) - it might then be sensible to separate // the different language ranges, etc. if ( isspace(ch) ) return ' '; static const char *word_characters = ":@-./_~"; if ( isalnum(ch) || strchr(word_characters, ch) ) return 'a'; // Everything else is weird return 1; } void TEWidget::setMouseMarks(bool on) { mouse_marks = on; setCursor( mouse_marks ? ibeamCursor : arrowCursor ); } /* ------------------------------------------------------------------------- */ /* */ /* Clipboard */ /* */ /* ------------------------------------------------------------------------- */ #undef KeyPress void TEWidget::emitSelection() // Paste Clipboard by simulating keypress events { #ifndef QT_NO_CLIPBOARD QString text = QApplication::clipboard()->text(); if ( ! text.isNull() ) { text.replace(QRegExp("\n"), "\r"); QKeyEvent e(QEvent::KeyPress, 0, -1, 0, text); emit keyPressedSignal(&e); // expose as a big fat keypress event emit clearSelectionSignal(); } #endif } void TEWidget::emitText(QString text) { QKeyEvent e(QEvent::KeyPress, 0, -1, 0, text); emit keyPressedSignal(&e); // expose as a big fat keypress event } void TEWidget::pasteClipboard( ) { emitSelection(); } void TEWidget::setSelection(const QString& t) { #ifndef QT_NO_CLIPBOARD // Disconnect signal while WE set the clipboard QObject *cb = QApplication::clipboard(); QObject::disconnect( cb, SIGNAL(dataChanged()), this, SLOT(onClearSelection()) ); QApplication::clipboard()->setText(t); QObject::connect( cb, SIGNAL(dataChanged()), this, SLOT(onClearSelection()) ); #endif } void TEWidget::onClearSelection() { emit clearSelectionSignal(); } /* ------------------------------------------------------------------------- */ /* */ /* Keyboard */ /* */ /* ------------------------------------------------------------------------- */ //FIXME: an `eventFilter' has been installed instead of a `keyPressEvent' // due to a bug in `QT' or the ignorance of the author to prevent // repaint events being emitted to the screen whenever one leaves // or reenters the screen to/from another application. // // Troll says one needs to change focusInEvent() and focusOutEvent(), // which would also let you have an in-focus cursor and an out-focus // cursor like xterm does. // for the auto-hide cursor feature, I added empty focusInEvent() and // focusOutEvent() so that update() isn't called. // For auto-hide, we need to get keypress-events, but we only get them when // we have focus. void TEWidget::doScroll(int lines) { scrollbar->setValue(scrollbar->value()+lines); } bool TEWidget::eventFilter( QObject *obj, QEvent *e ) { if ( (e->type() == QEvent::Accel || e->type() == QEvent::AccelAvailable ) && qApp->focusWidget() == this ) { static_cast<QKeyEvent *>( e )->ignore(); return true; } if ( obj != this /* when embedded */ && obj != parent() /* when standalone */ ) return FALSE; // not us if ( e->type() == QEvent::Wheel) { QApplication::sendEvent(scrollbar, e); } #ifdef FAKE_CTRL_AND_ALT static bool control = FALSE; static bool alt = FALSE; bool dele=FALSE; if ( e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease ) { QKeyEvent* ke = (QKeyEvent*)e; bool keydown = e->type() == QEvent::KeyPress || ke->isAutoRepeat(); switch (ke->key()) { case Key_F9: // let this be "Control" control = keydown; e = new QKeyEvent(QEvent::KeyPress, Key_Control, 0, ke->state()); dele=TRUE; break; case Key_F13: // let this be "Alt" alt = keydown; e = new QKeyEvent(QEvent::KeyPress, Key_Alt, 0, ke->state()); dele=TRUE; break; default: if ( control ) { int a = toupper(ke->ascii())-64; if ( a >= 0 && a < ' ' ) { e = new QKeyEvent(e->type(), ke->key(), a, ke->state()|ControlButton, QChar(a,0)); dele=TRUE; } } if ( alt ) { e = new QKeyEvent(e->type(), ke->key(), ke->ascii(), ke->state()|AltButton, ke->text()); dele=TRUE; } } } #endif if ( e->type() == QEvent::KeyPress ) { QKeyEvent* ke = (QKeyEvent*)e; actSel=0; // Key stroke implies a screen update, so TEWidget won't // know where the current selection is. if( ke->state() == ShiftButton && ke->key() == Key_Tab) { //lets hardcode this sucker emitText("\\"); // expose } else emit keyPressedSignal(ke); // expose ke->accept(); #ifdef FAKE_CTRL_AND_ALT if ( dele ) delete e; #endif return true; // stop the event } if ( e->type() == QEvent::Enter ) { QObject::disconnect( (QObject*)cb, SIGNAL(dataChanged()), this, SLOT(onClearSelection()) ); } if ( e->type() == QEvent::Leave ) { QObject::connect( (QObject*)cb, SIGNAL(dataChanged()), this, SLOT(onClearSelection()) ); } return QFrame::eventFilter( obj, e ); } /* ------------------------------------------------------------------------- */ /* */ /* Frame */ /* */ /* ------------------------------------------------------------------------- */ void TEWidget::frameChanged() { propagateSize(); update(); } /* ------------------------------------------------------------------------- */ /* */ /* Sound */ /* */ /* ------------------------------------------------------------------------- */ void TEWidget::Bell() { QApplication::beep(); } /* ------------------------------------------------------------------------- */ /* */ /* Auxiluary */ /* */ /* ------------------------------------------------------------------------- */ void TEWidget::clearImage() // initialize the image // for internal use only { for (int y = 0; y < lines; y++) for (int x = 0; x < columns; x++) { image[loc(x,y)].c = 0xff; //' '; image[loc(x,y)].f = 0xff; //DEFAULT_FORE_COLOR; image[loc(x,y)].b = 0xff; //DEFAULT_BACK_COLOR; image[loc(x,y)].r = 0xff; //DEFAULT_RENDITION; } } // Create Image /////////////////////////////////////////////////////// void TEWidget::calcGeometry() { //FIXME: set rimX == rimY == 0 when running in full screen mode. int showhscrollbar = 1; int hwidth = 0; int dcolumns; if(vcolumns == 0) showhscrollbar = 0; if(showhscrollbar == 1) hwidth = QApplication::style().scrollBarExtent().width(); scrollbar->resize(QApplication::style().scrollBarExtent().width(), contentsRect().height() - hwidth); if(!showhscrollbar) cornerButton()->move(0, 0); else cornerButton()->move(contentsRect().width() - hwidth, contentsRect().height() - hwidth); switch(scrollLoc) { case SCRNONE : columns = ( contentsRect().width() - 2 * rimX ) / font_w; dcolumns = columns; if(vcolumns) columns = vcolumns; blX = (contentsRect().width() - (columns*font_w) ) / 2; if(showhscrollbar) blX = -hposition * font_w; brX = blX; scrollbar->hide(); break; case SCRLEFT : columns = ( contentsRect().width() - 2 * rimX - scrollbar->width()) / font_w; dcolumns = columns; if(vcolumns) columns = vcolumns; brX = (contentsRect().width() - (columns*font_w) - scrollbar->width() ) / 2; if(showhscrollbar) brX = -hposition * font_w; blX = brX + scrollbar->width(); scrollbar->move(contentsRect().topLeft()); scrollbar->show(); break; case SCRRIGHT: columns = ( contentsRect().width() - 2 * rimX - scrollbar->width()) / font_w; dcolumns = columns; if(vcolumns) columns = vcolumns; blX = (contentsRect().width() - (columns*font_w) - scrollbar->width() ) / 2; if(showhscrollbar) blX = -hposition * font_w; brX = blX; scrollbar->move(contentsRect().topRight() - QPoint(scrollbar->width()-1,0)); scrollbar->show(); break; } //FIXME: support 'rounding' styles lines = ( contentsRect().height() - 2 * rimY ) / font_h; bY = (contentsRect().height() - (lines *font_h)) / 2; if(showhscrollbar == 1) { hscrollbar->resize(contentsRect().width() - hwidth, hwidth); hscrollbar->setRange(0, vcolumns - dcolumns); QPoint p = contentsRect().bottomLeft(); hscrollbar->move(QPoint(p.x(), p.y() - hwidth)); hscrollbar->show(); } else hscrollbar->hide(); if(showhscrollbar == 1) { lines = lines - (hwidth / font_h) - 1; if(lines < 1) lines = 1; } } void TEWidget::makeImage() //FIXME: rename 'calcGeometry? { calcGeometry(); image = (ca*) malloc(lines*columns*sizeof(ca)); clearImage(); } // calculate the needed size QSize TEWidget::calcSize(int cols, int lins) const { int frw = width() - contentsRect().width(); int frh = height() - contentsRect().height(); int scw = (scrollLoc==SCRNONE?0:scrollbar->width()); return QSize( font_w*cols + 2*rimX + frw + scw, font_h*lins + 2*rimY + frh ); } QSize TEWidget::sizeHint() const { return size(); } void TEWidget::styleChange(QStyle &) { propagateSize(); } #ifdef QT_NO_DRAGANDDROP_FOO /* --------------------------------------------------------------------- */ /* */ /* Drag & Drop */ /* */ /* --------------------------------------------------------------------- */ void TEWidget::dragEnterEvent(QDragEnterEvent* e) { e->accept(QTextDrag::canDecode(e) || QUriDrag::canDecode(e)); } void TEWidget::dropEvent(QDropEvent* event) { // The current behaviour when url(s) are dropped is // * if there is only ONE url and if it's a LOCAL one, ask for paste or cd // * in all other cases, just paste // (for non-local ones, or for a list of URLs, 'cd' is nonsense) QStrList strlist; int file_count = 0; dropText = ""; bool bPopup = true; if(QUriDrag::decode(event, strlist)) { if (strlist.count()) { for(const char* p = strlist.first(); p; p = strlist.next()) { if(file_count++ > 0) { dropText += " "; bPopup = false; // more than one file, don't popup } /* KURL url(p); if (url.isLocalFile()) { dropText += url.path(); // local URL : remove protocol } else { dropText += url.prettyURL(); bPopup = false; // a non-local file, don't popup } */ } if (bPopup) // m_drop->popup(pos() + event->pos()); m_drop->popup(mapToGlobal(event->pos())); else { if (currentSession) { currentSession->getEmulation()->sendString(dropText.local8Bit()); } // kdDebug() << "Drop:" << dropText.local8Bit() << "\n"; } } } else if(QTextDrag::decode(event, dropText)) { // kdDebug() << "Drop:" << dropText.local8Bit() << "\n"; if (currentSession) { currentSession->getEmulation()->sendString(dropText.local8Bit()); } // Paste it } } #endif void TEWidget::drop_menu_activated(int) { #ifdef QT_NO_DRAGANDDROP_FOO switch (item) { case 0: // paste currentSession->getEmulation()->sendString(dropText.local8Bit()); // KWM::activate((Window)this->winId()); break; case 1: // cd ... currentSession->getEmulation()->sendString("cd "); struct stat statbuf; if ( ::stat( QFile::encodeName( dropText ), &statbuf ) == 0 ) { if ( !S_ISDIR(statbuf.st_mode) ) { /* KURL url; url.setPath( dropText ); dropText = url.directory( true, false ); // remove filename */ } } dropText.replace(QRegExp(" "), "\\ "); // escape spaces currentSession->getEmulation()->sendString(dropText.local8Bit()); currentSession->getEmulation()->sendString("\n"); // KWM::activate((Window)this->winId()); break; } #endif } QPushButton* TEWidget::cornerButton() { return m_cornerButton; } void TEWidget::setWrapAt(int columns) { vcolumns = columns; propagateSize(); update(); } diff --git a/noncore/apps/tinykate/libkate/qt3back/qregexp3.cpp b/noncore/apps/tinykate/libkate/qt3back/qregexp3.cpp index 78635b2..7b30b1a 100644 --- a/noncore/apps/tinykate/libkate/qt3back/qregexp3.cpp +++ b/noncore/apps/tinykate/libkate/qt3back/qregexp3.cpp @@ -1,3773 +1,3773 @@ /**************************************************************************** ** $Id$ ** ** Implementation of QRegExp class ** ** Created : 950126 ** ** Copyright (C) 1992-2000 Trolltech AS. All rights reserved. ** ** This file is part of the tools module of the Qt GUI Toolkit. ** ** This file may be distributed under the terms of the Q Public License ** as defined by Trolltech AS of Norway and appearing in the file ** LICENSE.QPL included in the packaging of this file. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition ** licenses may use this file in accordance with the Qt Commercial License ** Agreement provided with the Software. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for ** information about Qt Commercial License Agreements. ** See http://www.trolltech.com/qpl/ for QPL licensing information. ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ -#if QT_VERSION >=300 +#if QT_VERSION >= 0x030000 #error QRegExp3 is now in QT 3 use QRegExp instead #endif -#if QT_VERSION < 300 +#if QT_VERSION < 0x030000 #include "./qregexp3.h" #else #include "qregexp.h" #endif /* OPIE */ #include <opie2/odebug.h> /* QT */ #include <qarray.h> #include <qbitarray.h> #include <qcache.h> #include <qintdict.h> #include <qmap.h> #include <qstring.h> #include <qtl.h> #include <qvector.h> /* STD */ #include <limits.h> /* WARNING! Be sure to read qregexp.tex before modifying this file. */ /*! \class QRegExp3 qregexp.h \brief The QRegExp class provides pattern matching using regular expressions. \ingroup tools \ingroup misc \ingroup shared Regular expressions, "regexps", provide a way to find patterns within text. This is useful in many contexts, for example: <ol> <li>\e Validation. A regexp can be used to check whether a piece of text meets some criteria, e.g. is an integer or contains no whitespace. <li>\e Searching. Regexps provide a much more powerful means of searching text than simple string matching does. For example we can create a regexp which says "find one of the words 'mail', 'letter' or 'correspondence' but not any of the words 'email', 'mailman' 'mailer', 'letterbox' etc." <li><em>Search and Replace.</em> A regexp can be used to replace a pattern with a piece of text, for example replace all occurrences of '&' with '\&' except where the '&' is already followed by 'amp;'. <li><em>String Splitting.</em> A regexp can be used to identify where a string should be split into its component fields, e.g. splitting tab delimited strings. </ol> We present a very brief introduction to regexps, a description of Qt's regexp language, some code examples, and finally the function documentation. QRegExp is modelled on Perl's regexp engine and fully supports Unicode. QRegExp may also be used in the weaker 'wildcard' (globbing) mode which works in a similar way to command shells. A good text on regexps is <i>Mastering Regular Expressions: Powerful Techniques for Perl and Other Tools</i> by Jeffrey E. Friedl, ISBN 1565922573. Experienced regexp users may prefer to skip the introduction and go directly to the relevant information: <ul> <li><a href="#characters-and-abbreviations-for-sets-of-characters"> Characters and Abbreviations for Sets of Characters</a> <li><a href="#sets-of-characters">Sets of Characters</a> <li><a href="#quantifiers">Quantifiers</a> <li><a href="#capturing-text">Capturing Text</a> <li><a href="#assertions">Assertions</a> <li><a href="#wildcard-matching">Wildcard Matching (globbing)</a> <li><a href="#perl-users">Notes for Perl Users</a> <li><a href="#code-examples">Code Examples</a> <li><a href="#member-function-documentation">Member Function Documentation</a> </ul> <b>Introduction</b> Regexps are built up from expressions, quantifiers and assertions. The simplest form of expression is simply a character, e.g. <b>x</b> or <b>5</b>. An expression can also be a set of characters. For example, <b>[ABCD]</b>, will match an <b>A</b> or a <b>B</b> or a <b>C</b> or a <b>D</b>. As a shorthand we could write this as <b>[A-D]</b>. If we want to match any of the captital letters in the English alphabet we can write <b>[A-Z]</b>. A quantifier tells the regexp engine how many occurrences of the expression we want, e.g. <b>x{1,1}</b> means match an <b>x</b> which occurs at least once and at most once. We'll look at assertions and more complex expressions later. Note that regexps cannot be used to check for balanced brackets or tags (unless you know the maximum level of nesting). We'll start by writing a regexp to match integers in the range 0 to 99. We will require at least one digit so we will start with <b>[0-9]{1,1}</b> which means match a digit exactly once. This regexp alone will match integers in the range 0 to 9. To match one or two digits we can increase the maximum number of occurrences so the regexp becomes <b>[0-9]{1,2}</b> meaning match a digit at least once and at most twice. However, this regexp as it stands will not match correctly. This regexp will match one or two digits \e within a string. To ensure that we match against the whole string we must use the anchor assertions. We need <b>^</b> (caret) which when it is the first character in the regexp means that the regexp must match from the beginning of the string. And we also need <b>$</b> (dollar) which when it is the last character in the regexp means that the regexp must match until the end of the string. So now our regexp is <b>^[0-9]{1,2}$</b>. Note that assertions do not match any characters. If you've seen regexps elsewhere they may have looked different from the one above. This is because some sets of characters and some quantifiers are so common that they have special symbols to represent them. <b>[0-9]</b> can be replaced with the symbol <b>\d</b>. The quantifier to match exactly one occurrence, <b>{1,1}</b>, can be replaced with the expression itself. This means that <b>x{1,1}</b> is exactly the same as <b>x</b> alone. So our 0 to 99 matcher could be written: <b>^\d{1,2}$</b>, although most people would write it <b>^\d\d?$</b>. The <b>?</b> is the same as the quantifier <b>{0,1}</b>, i.e. a minimum of no occurrences a maximum of one occurrence. This is used to make an expression optional. The regexp <b>^\d\d?$</b> means "from the beginning of the string match one digit followed by zero or one digits and then the end of the string". Our second example is matching the words 'mail', 'letter' or 'correspondence' but without matching 'email', 'mailman', 'mailer', 'letterbox' etc. We'll start by just matching 'mail'. In full the regexp is, <b>m{1,1}a{1,1}i{1,1}l{1,1}</b>, but since an expression itself is automatically quantified by <b>{1,1}</b> we can simply write this as <b>mail</b>; an 'm' followed by an 'a' followed by an 'i' followed by an 'l'. The symbol '|' (bar) is used for \e alternation, so our regexp now becomes <b>mail|letter|correspondence</b> which means match 'mail' \e or 'letter' \e or 'correspondence'. Whilst this regexp will find the words we want it will also find words we don't want such as 'email'. We will start by putting our regexp in parenthesis <b>(mail|letter|correspondence)</b>. Parenthesis have two effects, firstly they group expressions together and secondly they identify parts of the regexp that we wish to <a href="#capturing-text">capture</a>. Our regexp still matches any of the three words but now they are grouped together as a unit. This is useful for building up more complex regexps. It is also useful because it allows us to examine which of the words actually matched. We need to use another assertion, this time <b>\b</b> "word boundary": <b>\b(mail|letter|correspondence)\b</b>. This regexp means "match a word boundary followed by the expression in parenthesis followed by another word boundary". The <b>\b</b> assertion matches at a \e position in the regexp not a \e character in the regexp. A word boundary is any non-word character such as a space a newline or the beginning or end of the string. For our third example we want to replace ampersands with the HTML entity '\&'. The regexp to match is simple: <b>\&</b>, i.e. match one ampersand. Unfortunately this will mess up our text if some of the ampersands have already been turned into HTML entities. So what we really want to say is replace an ampersand providing it is not followed by 'amp;'. For this we need the negative lookahead assertion and our regexp becomes: <b>\&(?!amp;)</b>. The negative lookahead assertion is introduced with '(?!' and finishes at the ')'. It means that the text it contains, 'amp;' in our example, must \e not follow the expression that preceeds it. Regexps provide a rich language that can be used in a variety of ways. For example suppose we want to count all the occurrences of 'Eric' and 'Eirik' in a string. Two valid regexps to match these are <b>\\</b><b>b(Eric|Eirik)</b><b>\\</b><b>b</b> and <b>\\</b><b>bEi?ri[ck]</b><b>\\</b><b>b</b>. We need the word boundary '\b' so we don't get 'Ericsson' etc. The second regexp actually matches more than we want, 'Eric', 'Erik', 'Eiric' and 'Eirik'. We will implement some the examples above in the <a href="#code-examples">code examples</a> section. <a name="characters-and-abbreviations-for-sets-of-characters"> <b>Characters and Abbreviations for Sets of Characters</b></a> <ul> <li><b>c</b> Any character represents itself unless it has a special regexp meaning. Thus <b>c</b> matches the character \e c. <li><b>\\</b><b>c</b> A character that follows a backslash matches the character itself except where mentioned below. For example if you wished to match a literal caret at the beginning of a string you would write <b>\^</b>. <li><b>\\</b><b>a</b> This matches the ASCII bell character (BEL, 0x07). <li><b>\\</b><b>f</b> This matches the ASCII form feed character (FF, 0x0C). <li><b>\\</b><b>n</b> This matches the ASCII line feed character (LF, 0x0A), (Unix newline). <li><b>\\</b><b>r</b> This matches the ASCII carriage return character (CR, 0x0D). <li><b>\\</b><b>t</b> This matches the ASCII horizontal tab character (HT, 0x09). <li><b>\\</b><b>v</b> This matches the ASCII vertical tab character (VT, 0x0B). <li><b>\\</b><b>xhhhh</b> This matches the Unicode character corresponding to the hexadecimal number hhhh (between 0x0000 and 0xFFFF). \0ooo (i.e., \zero ooo) matches the ASCII/Latin-1 character corresponding to the octal number ooo (between 0 and 0377). <li><b>. (dot)</b> This matches any character (including newline). <li><b>\\</b><b>d</b> This matches a digit (see QChar::isDigit()). <li><b>\\</b><b>D</b> This matches a non-digit. <li><b>\\</b><b>s</b> This matches a whitespace (see QChar::isSpace()). <li><b>\\</b><b>S</b> This matches a non-whitespace. <li><b>\\</b><b>w</b> This matches a word character (see QChar::isLetterOrNumber()). <li><b>\\</b><b>W</b> This matches a non-word character. <li><b>\\</b><b>n</b> The n<sup>th</sup> <a href="#capturing-text">backreference</a>, e.g. \1, \2, etc. </ul> <em>Note that the C++ compiler transforms backslashes in strings so to include a <b>\\</b> in a regexp you will need to enter it twice, i.e. <b>\\</b><b>\\</b>.</em> <a name="sets-of-characters"><b>Sets of Characters</b></a> Square brackets are used to match any character in the set of characters contained within the square brackets. All the character set abbreviations described above can be used within square brackets. Apart from the character set abbreviations and the following two exceptions no characters have special meanings in square brackets. <ul> <li><b>^</b> The caret negates the character set if it occurs as the first character, i.e. immediately after the opening square bracket. For example, <b>[abc]</b> matches 'a' or 'b' or 'c', but <b>[^abc]</b> matches anything \e except 'a' or 'b' or 'c'. <li><b>-</b> The dash is used to indicate a range of characters, for example <b>[W-Z]</b> matches 'W' or 'X' or 'Y' or 'Z'. </ul> Using the predefined character set abbreviations is more portable than using character ranges across platforms and languages. For example, <b>[0-9]</b> matches a digit in Western alphabets but <b>\d</b> matches a digit in \e any alphabet. Note that in most regexp literature sets of characters are called "character classes". <a name="quantifiers"><b>Quantifiers</b></a> By default an expression is automatically quantified by <b>{1,1}</b>, i.e. it should occur exactly once. In the following list <b><i>E</i></b> stands for any expression. An expression is a character or an abbreviation for a set of characters or a set of characters in square brackets or any parenthesised expression. <ul> <li><b><i>E</i>?</b> Matches zero or one occurrence of <i>E</i>. This quantifier means "the previous expression is optional" since it will match whether or not the expression occurs in the string. It is the same as <b><i>E</i>{0,1}</b>. For example <b>dents?</b> will match 'dent' and 'dents'. <li><b><i>E</i>+</b> Matches one or more occurrences of <i>E</i>. This is the same as <b><i>E</i>{1,MAXINT}</b>. For example, <b>0+</b> will match '0', '00', '000', etc. <li><b><i>E</i>*</b> Matches zero or more occurrences of <i>E</i>. This is the same as <b><i>E</i>{0,MAXINT}</b>. The <b>*</b> quantifier is often used by a mistake. Since it matches \e zero or more occurrences it will match no occurrences at all. For example if we want to match strings that end in whitespace and use the regexp <b>\s*$</b> we would get a match on every string. This is because we have said find zero or more whitespace followed by the end of string, so even strings that don't end in whitespace will match. The regexp we want in this case is <b>\s+$</b> to match strings that have at least one whitespace at the end. <li><b><i>E</i>{n}</b> Matches exactly \e n occurrences of the expression. This is the same as repeating the expression \e n times. For example, <b>x{5}</b> is the same as <b>xxxxx</b>. It is also the same as <b><i>E</i>{n,n}</b>, e.g. <b>x{5,5}</b>. <li><b><i>E</i>{n,}</b> Matches at least \e n occurrences of the expression. This is the same as <b><i>E</i>{n,MAXINT}</b>. <li><b><i>E</i>{,m}</b> Matches at most \e m occurrences of the expression. This is the same as <b><i>E</i>{0,m}</b>. <li><b><i>E</i>{n,m}</b> Matches at least \e n occurrences of the expression and at most \e m occurrences of the expression. </ul> (MAXINT is implementation dependent but will not be smaller than 16384.) If we wish to apply a quantifier to more than just the preceeding character we can use parenthesis to group characters together in an expression. For example, <b>tag+</b> matches a 't' followed by an 'a' followed by at least one 'g', whereas <b>(tag)+</b> matches at least one occurrence of 'tag'. Note that quantifiers are "greedy", they will match as much text as they can. For example, <b>0+</b> will match as many zeros as it can from the first zero it finds, e.g. '2.<u>000</u>5'. Quantifiers can be made non-greedy, see setMinimal(). <a name="capturing-text"><b>Capturing Text</b></a> Parenthesis allow us to group elements together so that we can quantify and capture them. For example if we have the expression <b>mail|letter|correspondence</b> that matches a string we know that \e one of the words matched but not which one. Using parenthesis allows us to "capture" whatever is matched within their bounds, so if we used <b>(mail|letter|correspondence)</b> and matched this regexp against the string "I sent you some email" we can use the cap() or capturedTexts() functions to extract the matched characters, in this case 'mail'. We can use captured text within the regexp itself. To refer to the captured text we use \e backreferences which are indexed from 1 the same as for cap(). For example we could search for duplicate words in a string using <b>\b(\w+)\W+\1\b</b> which means match a word boundary followed by one or more word characters followed by one or more non-word characters followed by the same text as the first parenthesised expression followed by a word boundary. If we want to use parenthesis purely for grouping and not for capturing we use the non-capturing syntax, e.g. <b>(?:green|blue)</b>. Non-capturing parenthesis begin '(?:' and end ')'. In this example we match either 'green' or 'blue' but we do not capture the match so we can only know whether or not we matched but not which color we actually found. Using non-capturing parenthesis is more efficient than using capturing parenthesis since the regexp engine has to do less book-keeping. Both capturing and non-capturing parenthesis may be nested. <a name="assertions"><b>Assertions</b></a> Assertions make some statement about the text at the point where they occur in the regexp but they do not match any characters. In the following list <b><i>E</i></b> stands for any expression. <ul> <li><b>^</b> If the caret is the first character in the regexp (apart from opening parenthesis) it signifies the beginning of the string. It has no special meaning elsewhere (except as the first character of a set of characters in square brackets). For example, <b>^#include</b> will only match strings which \e begin with the characters '#include'. <li><b>$</b> If the dollar is the last character in the regexp (apart from closing parenthesis) it signifies the end of the string. It has no special meaning elsewhere. For example, <b>\d\s*$</b> will match strings which end with a digit optionally followed by whitespace. <li><b>\\</b><b>b</b> A word boundary. For example the regexp <b>\\</b><b>bOK</b>\\</b><b>b</b> means match immediately after a word boundary (e.g. start of string or whitespace) the letter 'O' then the letter 'K' immediately before another word boundary (e.g. end of string or whitespace). But note that the assertion does not actually match any whitespace so if we write <b>(</b><b>\\</b><b>bOK</b>\\</b><b>b)</b> and we have a match it will only contain 'OK' even if the string is "Its <u>OK</u> now". <li><b>\\</b><b>B</b> A non-word boundary. This assertion is true wherever <b>\\</b><b>b</b> is false. For example if we searched for <b>\\</b><b>Bon</b>\\</b><b>B</b> in "Left on" the match would fail (space and end of string aren't non-word boundaries), but it would match in "t<u>on</u>ne". <li><b>(?=<i>E</i>)</b> Positive lookahead. This assertion is true if the expression matches at this point in the regex. This assertion does not match any characters. For example, <b>^#define\s+(\w+)(?=MAX)</b> will match strings which begin with '#define' followed by at least one whitespace followed by at least one word character followed by 'MAX'. The first set of parenthesis will capture the word character(s) matched. This regexp will not match '#define DEBUG' but will match '#define <u>INT</u>MAX 32767'. <li><b>(?!<i>E</i>)</b> Negative lookahead. This assertion is true if the expression does not match at this point in the regex. This assertion does not match any characters. For example, <b>^#define\s+(\w+)\s*$</b> will match strings which begin with '#define' followed by at least one whitespace followed by at least one word character optionally followed by whitespace. This regexp will match define's that exist but have no value, i.e. it will not match '#define INTMAX 32767' but it will match '#define <u>DEBUG</u>'. </ul> <a name="wildcard-matching"><b>Wildcard Matching (globbing)</b></a> Most command shells such as \e bash or \e cmd support "file globbing", the ability to identify a group of files by using wildcards. Wildcard matching is much simpler than full regexps and has only four features: <ul> <li><b>c</b> Any character represents itself apart from those mentioned below. Thus <b>c</b> matches the character \e c. <li><b>?</b> This matches any single character. It is the same as <b>.</b> in full regexps. <li><b>*</b> This matches zero or more of any characters. It is the same as <b>.*</b> in full regexps. <li><b>[...]</b> Sets of characters can be represented in square brackets the same as for full regexps. <!-- JASMIN: Are the character classes, \w, etc supported in wildcards? --> </ul> For example if we are in wildcard mode and have strings which contain filenames we could identify HTML files with <b>*.html</b>. This will match zero or more characters followed by a dot followed by 'h', 't', 'm' and 'l'. <a name="perl-users"><b>Notes for Perl Users</b></a> Most of the character class abbreviations supported by Perl are supported by QRegExp, see <a href="#characters-and-abbreviations-for-sets-of-characters"> characters and abbreviations for sets of characters</a>. QRegExp's quantifiers are the same as Perl's greedy quantifiers. Non-greedy matching cannot be applied to individual quantifiers, but can be applied to all the quantifiers in the pattern. For example, to match the Perl regex <b>ro+?m</b> requires: \code QRegExp rx( "ro+m" ); rx.setMinimal( TRUE ); \endcode The equivalent of Perl's <tt>/i</tt> option is setCaseSensitive(FALSE). Perl's <tt>/g</tt> option can be emulated using a <a href="#cap_in_a_loop">loop</a>. In QRegExp <b>.</b> matches any character, therefore all QRegExp regexps have the equivalent of Perl's <tt>/s</tt> option. QRegExp does not have an equivalent to Perl's <tt>/m</tt> option, but this can be emulated in various ways for example by splitting the input into lines or by looping with a regexp that searches for newlines. Because QRegExp is string oriented there are no \A, \Z or \z assertions. The \G assertion is not supported but can be emulated in a loop. Perl's $& is cap(0) or capturedTexts()[0]. There are no QRegExp equivalents for $`, $' or $+. $1, $2 etc correspond to cap(1) or capturedTexts()[1], cap(2) or capturedTexts()[2], etc. To substitute a pattern use QString::replace(). Perl's extended <tt>/x</tt> syntax is not supported, nor are regexp comments (?#comment) or directives, e.g. (?i). Both zero-width positive and zero-width negative lookahead assertions (?=pattern) and (?!pattern) are supported with the same syntax as Perl. Perl's lookbehind assertions, "independent" subexpressions and conditional expressions are not supported. Non-capturing parenthesis are also supported, with the same (?:pattern) syntax. See QStringList::split() and QStringList::join() for equivalents to Perl's split and join functions. Note: because C++ transforms \\'s they must be written \e twice in code, e.g. <b>\\</b><b>b</b> must be written <b>\\</b><b>\\</b><b>b</b>. <a name="code-examples"><b>Code Examples</b></a> \code QRegExp rx( "^\\d\\d?$" ); // Match integers 0 to 99 rx.search( "123" ); // Returns -1 (no match) rx.search( "-6" ); // Returns -1 (no match) rx.search( "6" ); // Returns 0 (matched as position 0) \endcode The third string matches '<u>6</u>'. This is a simple validation regexp for integers in the range 0 to 99. \code QRegExp rx( "^\\S+$" ); // Match strings which have no whitespace rx.search( "Hello world" ); // Returns -1 (no match) rx.search( "This_is-OK" ); // Returns 0 (matched at position 0) \endcode The second string matches '<u>This_is-OK</u>'. We've used the character set abbreviation '\S' (non-whitespace) and the anchors to match strings which contain no whitespace. In the following example we match strings containing 'mail' or 'letter' or 'correspondence' but only match whole words i.e. not 'email' \code QRegExp rx( "\\b(mail|letter|correspondence)\\b" ); rx.search( "I sent you an email" ); // Returns -1 (no match) rx.search( "Please write the letter" ); // Returns 17 (matched at position 17) \endcode The second string matches "Please write the <u>letter</u>". The word 'letter' is also captured (because of the parenthesis). We can see what text we've captured like this: \code QString captured = rx.cap( 1 ); // captured contains "letter" \endcode This will capture the text from the first set of capturing parenthesis (counting capturing left parenthesis from left to right). The parenthesis are counted from 1 since cap( 0 ) is the whole matched regexp (equivalent to '&' in most regexp engines). \code QRegExp rx( "&(?!amp;)" ); // Match ampersands but not & QString line1 = "This & that"; line1.replace( rx, "&" ); // line1 == "This & that" QString line2 = "His & hers & theirs"; line2.replace( rx, "&" ); // line2 == "His & hers & theirs" \endcode Here we've passed the QRegExp to QString's replace() function to replace the matched text with new text. \code QString str = "One Eric another Eirik, and an Ericsson. How many Eiriks, Eric?"; QRegExp rx( "\\b(Eric|Eirik)\\b" ); // Match Eric or Eirik int pos = 0; // Where we are in the string int count = 0; // How many Eric and Eirik's we've counted while ( pos >= 0 ) { pos = rx.search( str, pos ); if ( pos >= 0 ) { pos++; // Move along in str count++; // Count our Eric or Eirik } } \endcode We've used the search() function to repeatedly match the regexp in the string. Note that instead of moving forward by one character at a time <tt>pos++</tt> we could have written <tt>pos += rx.matchedLength()</tt> to skip over the already matched string. The count will equal 3, matching 'One <u>Eric</u> another <u>Eirik</u>, and an Ericsson. How many Eiriks, <u>Eric</u>?'; it doesn't match 'Ericsson' or 'Eiriks' because they are not bounded by non-word boundaries. One common use of regexps is to split lines of delimited data into their component fields. \code str = "Trolltech AS\twww.trolltech.com\tNorway"; QString company, web, country; rx.setPattern( "^([^\t]+)\t([^\t]+)\t([^\t]+)$" ); if ( rx.search( str ) != -1 ) { company = rx.cap( 1 ); web = rx.cap( 2 ); country = rx.cap( 3 ); } \endcode In this example our input lines have the format company name, web address and country. Unfortunately the regexp is rather long and not very versatile -- the code will break if we add any more fields. A simpler and better solution is to look for the separator, '\t' in this case, and take the surrounding text. The QStringList split() function can take a separator string or regexp as an argument and split a string accordingly. \code QStringList field = QStringList::split( "\t", str ); \endcode Here field[0] is the company, field[1] the web address and so on. To immitate the matching of a shell we can use wildcard mode. \code QRegExp rx( "*.html" ); // Invalid regexp: * doesn't quantify anything rx.setWildcard( TRUE ); // Now its a valid wildcard regexp rx.search( "index.html" ); // Returns 0 (matched at position 0) rx.search( "default.htm" ); // Returns -1 (no match) rx.search( "readme.txt" ); // Returns -1 (no match) \endcode Wildcard matching can be convenient because of its simplicity, but any wildcard regex can be defined using full regexps, e.g. <b>.*\.html$</b>. Notice that we can't match both \c .html and \c .htm files with a wildcard unless we use <b>*.htm*</b> which will also match 'test.html.bak'. A full regexp gives us the precision we need, <b>.*\.html?$</b>. QRegExp can match case insensitively using setCaseSensitive(), and can use non-greedy matching, see setMinimal(). By default QRegExp uses full regexps but this can be changed with setWildcard(). Searching can be forward with search() or backward with searchRev(). Captured text can be accessed using capturedTexts() which returns a string list of all captured strings, or using cap() which returns the captured string for the given index. The pos() function takes a match index and returns the position in the string where the match was made (or -1 if there was no match). \sa QRegExpValidator QString QStringList <a name="member-function-documentation"/> */ static const int NumBadChars = 128; #define BadChar( ch ) ( (ch).cell() % NumBadChars ) static const int NoOccurrence = INT_MAX; static const int EmptyCapture = INT_MAX; static const int InftyLen = INT_MAX; static const int InftyRep = 1000; static const int EOS = -1; #ifndef QT_NO_REGEXP_OPTIM static int engCount = 0; static QArray<int> *noOccurrences = 0; static QArray<int> *firstOccurrenceAtZero = 0; #endif /* Merges two QArrays of ints and puts the result into the first one. */ static void mergeInto( QArray<int> *a, const QArray<int>& b ) { int asize = a->size(); int bsize = b.size(); if ( asize == 0 ) { *a = b.copy(); #ifndef QT_NO_REGEXP_OPTIM } else if ( bsize == 1 && (*a)[asize - 1] < b[0] ) { a->resize( asize + 1 ); (*a)[asize] = b[0]; #endif } else if ( bsize >= 1 ) { int csize = asize + bsize; QArray<int> c( csize ); int i = 0, j = 0, k = 0; while ( i < asize ) { if ( j < bsize ) { if ( (*a)[i] == b[j] ) { i++; csize--; } else if ( (*a)[i] < b[j] ) { c[k++] = (*a)[i++]; } else { c[k++] = b[j++]; } } else { memcpy( c.data() + k, (*a).data() + i, (asize - i) * sizeof(int) ); break; } } c.resize( csize ); if ( j < bsize ) memcpy( c.data() + k, b.data() + j, (bsize - j) * sizeof(int) ); *a = c; } } /* Merges two disjoint QMaps of (int, int) pairs and puts the result into the first one. */ static void mergeInto( QMap<int, int> *a, const QMap<int, int>& b ) { QMap<int, int>::ConstIterator it; for ( it = b.begin(); it != b.end(); ++it ) a->insert( it.key(), *it ); } /* Returns the value associated to key k in QMap m of (int, int) pairs, or 0 if no such value is explicitly present. */ static int at( const QMap<int, int>& m, int k ) { QMap<int, int>::ConstIterator it = m.find( k ); if ( it == m.end() ) return 0; else return *it; } #ifndef QT_NO_REGEXP_WILDCARD /* Translates a wildcard pattern to an equivalent regular expression pattern (e.g., *.cpp to .*\.cpp). */ static QString wc2rx( const QString& wc ) { int wclen = wc.length(); QString rx = QString::fromLatin1( "" ); int i = 0; while ( i < wclen ) { QChar c = wc[i++]; switch ( c.unicode() ) { case '*': rx += QString::fromLatin1( ".*" ); break; case '?': rx += QChar( '.' ); break; case '$': case '(': case ')': case '+': case '.': case '\\': case '^': case '{': case '|': case '}': rx += QChar( '\\' ); rx += c; break; case '[': rx += c; if ( wc[i] == QChar('^') ) rx += wc[i++]; if ( i < wclen ) { if ( rx[i] == ']' ) rx += wc[i++]; while ( i < wclen && wc[i] != QChar(']') ) { if ( wc[i] == '\\' ) rx += QChar( '\\' ); rx += wc[i++]; } } break; default: rx += c; } } return rx; } #endif /* The class QRegExpEngine encapsulates a modified nondeterministic finite automaton (NFA). */ class QRegExpEngine : public QShared { public: #ifndef QT_NO_REGEXP_CCLASS /* The class CharClass represents a set of characters, such as can be found in regular expressions (e.g., [a-z] denotes the set {a, b, ..., z}). */ class CharClass { public: CharClass(); CharClass( const CharClass& cc ) { operator=( cc ); } CharClass& operator=( const CharClass& cc ); void clear(); bool negative() const { return n; } void setNegative( bool negative ); void addCategories( int cats ); void addRange( ushort from, ushort to ); void addSingleton( ushort ch ) { addRange( ch, ch ); } bool in( QChar ch ) const; #ifndef QT_NO_REGEXP_OPTIM const QArray<int>& firstOccurrence() const { return occ1; } #endif #if defined(QT_DEBUG) void dump() const; #endif private: /* The struct Range represents a range of characters (e.g., [0-9] denotes range 48 to 57). */ struct Range { ushort from; // 48 ushort to; // 57 }; int c; // character classes QArray<Range> r; // character ranges bool n; // negative? #ifndef QT_NO_REGEXP_OPTIM QArray<int> occ1; // first-occurrence array #endif }; #else struct CharClass { int x; // dummy #ifndef QT_NO_REGEXP_OPTIM const QArray<int>& firstOccurrence() const { return *firstOccurrenceAtZero; } #endif }; #endif QRegExpEngine( bool caseSensitive ) { setup( caseSensitive ); } QRegExpEngine( const QString& rx, bool caseSensitive ); #ifndef QT_NO_REGEXP_OPTIM ~QRegExpEngine(); #endif bool isValid() const { return valid; } bool caseSensitive() const { return cs; } int numCaptures() const { return realncap; } QArray<int> match( const QString& str, int pos, bool minimal, bool oneTest ); int matchedLength() const { return mmMatchedLen; } int createState( QChar ch ); int createState( const CharClass& cc ); #ifndef QT_NO_REGEXP_BACKREF int createState( int bref ); #endif void addCatTransitions( const QArray<int>& from, const QArray<int>& to ); #ifndef QT_NO_REGEXP_CAPTURE void addPlusTransitions( const QArray<int>& from, const QArray<int>& to, int atom ); #endif #ifndef QT_NO_REGEXP_ANCHOR_ALT int anchorAlternation( int a, int b ); int anchorConcatenation( int a, int b ); #else int anchorAlternation( int a, int b ) { return a & b; } int anchorConcatenation( int a, int b ) { return a | b; } #endif void addAnchors( int from, int to, int a ); #ifndef QT_NO_REGEXP_OPTIM void setupGoodStringHeuristic( int earlyStart, int lateStart, const QString& str ); void setupBadCharHeuristic( int minLen, const QArray<int>& firstOcc ); void heuristicallyChooseHeuristic(); #endif #if defined(QT_DEBUG) void dump() const; #endif private: enum { CharClassBit = 0x10000, BackRefBit = 0x20000 }; /* The struct State represents one state in a modified NFA. The input characters matched are stored in the state instead of on the transitions, something possible for an automaton constructed from a regular expression. */ struct State { #ifndef QT_NO_REGEXP_CAPTURE int atom; // which atom does this state belong to? #endif int match; // what does it match? (see CharClassBit and BackRefBit) QArray<int> outs; // out-transitions QMap<int, int> *reenter; // atoms reentered when transiting out QMap<int, int> *anchors; // anchors met when transiting out #ifndef QT_NO_REGEXP_CAPTURE State( int a, int m ) : atom( a ), match( m ), reenter( 0 ), anchors( 0 ) { } #else State( int m ) : match( m ), reenter( 0 ), anchors( 0 ) { } #endif ~State() { delete reenter; delete anchors; } }; #ifndef QT_NO_REGEXP_LOOKAHEAD /* The struct Lookahead represents a lookahead a la Perl (e.g., (?=foo) and (?!bar)). */ struct Lookahead { QRegExpEngine *eng; // NFA representing the embedded regular expression bool neg; // negative lookahead? Lookahead( QRegExpEngine *eng0, bool neg0 ) : eng( eng0 ), neg( neg0 ) { } ~Lookahead() { delete eng; } }; #endif #ifndef QT_NO_REGEXP_CAPTURE /* The struct Atom represents one node in the hierarchy of regular expression atoms. */ struct Atom { int parent; // index of parent in array of atoms int capture; // index of capture, from 1 to ncap }; #endif #ifndef QT_NO_REGEXP_ANCHOR_ALT /* The struct AnchorAlternation represents a pair of anchors with OR semantics. */ struct AnchorAlternation { int a; // this anchor... int b; // ...or this one }; #endif enum { InitialState = 0, FinalState = 1 }; void setup( bool caseSensitive ); int setupState( int match ); /* Let's hope that 13 lookaheads and 14 back-references are enough. */ enum { MaxLookaheads = 13, MaxBackRefs = 14 }; enum { Anchor_Dollar = 0x00000001, Anchor_Caret = 0x00000002, Anchor_Word = 0x00000004, Anchor_NonWord = 0x00000008, Anchor_FirstLookahead = 0x00000010, Anchor_BackRef1Empty = Anchor_FirstLookahead << MaxLookaheads, Anchor_BackRef0Empty = Anchor_BackRef1Empty >> 1, Anchor_Alternation = Anchor_BackRef1Empty << MaxBackRefs, Anchor_LookaheadMask = ( Anchor_FirstLookahead - 1 ) ^ ( (Anchor_FirstLookahead << MaxLookaheads) - 1 ) }; #ifndef QT_NO_REGEXP_CAPTURE int startAtom( bool capture ); void finishAtom( int atom ) { cf = f[atom].parent; } #endif #ifndef QT_NO_REGEXP_LOOKAHEAD int addLookahead( QRegExpEngine *eng, bool negative ); #endif #ifndef QT_NO_REGEXP_CAPTURE bool isBetterCapture( const int *begin1, const int *end1, const int *begin2, const int *end2 ); #endif bool testAnchor( int i, int a, const int *capBegin ); #ifndef QT_NO_REGEXP_OPTIM bool goodStringMatch(); bool badCharMatch(); #else bool bruteMatch(); #endif bool matchHere(); QVector<State> s; // array of states int ns; // number of states #ifndef QT_NO_REGEXP_CAPTURE QArray<Atom> f; // atom hierarchy int nf; // number of atoms int cf; // current atom #endif int realncap; // number of captures, seen from the outside int ncap; // number of captures, seen from the inside #ifndef QT_NO_REGEXP_CCLASS QVector<CharClass> cl; // array of character classes #endif #ifndef QT_NO_REGEXP_LOOKAHEAD QVector<Lookahead> ahead; // array of lookaheads #endif #ifndef QT_NO_REGEXP_ANCHOR_ALT QArray<AnchorAlternation> aa; // array of (a, b) pairs of anchors #endif #ifndef QT_NO_REGEXP_OPTIM bool caretAnchored; // does the regexp start with ^? #endif bool valid; // is the regular expression valid? bool cs; // case sensitive? #ifndef QT_NO_REGEXP_BACKREF int nbrefs; // number of back-references #endif #ifndef QT_NO_REGEXP_OPTIM bool useGoodStringHeuristic; // use goodStringMatch? otherwise badCharMatch int goodEarlyStart; // the index where goodStr can first occur in a match int goodLateStart; // the index where goodStr can last occur in a match QString goodStr; // the string that any match has to contain int minl; // the minimum length of a match QArray<int> occ1; // first-occurrence array #endif /* The class Box is an abstraction for a regular expression fragment. It can also be seen as one node in the syntax tree of a regular expression with synthetized attributes. It's interface is ugly for performance reasons. */ class Box { public: Box( QRegExpEngine *engine ); Box( const Box& b ) { operator=( b ); } Box& operator=( const Box& b ); void clear() { operator=(Box(eng)); } void set( QChar ch ); void set( const CharClass& cc ); #ifndef QT_NO_REGEXP_BACKREF void set( int bref ); #endif void cat( const Box& b ); void orx( const Box& b ); void plus( int atom ); void opt(); void catAnchor( int a ); #ifndef QT_NO_REGEXP_OPTIM void setupHeuristics(); #endif #if defined(QT_DEBUG) void dump() const; #endif private: void addAnchorsToEngine( const Box& to ) const; QRegExpEngine *eng; // the automaton under construction QArray<int> ls; // the left states (firstpos) QArray<int> rs; // the right states (lastpos) QMap<int, int> lanchors; // the left anchors QMap<int, int> ranchors; // the right anchors int skipanchors; // the anchors to match if the box is skipped #ifndef QT_NO_REGEXP_OPTIM int earlyStart; // the index where str can first occur int lateStart; // the index where str can last occur QString str; // a string that has to occur in any match QString leftStr; // a string occurring at the left of this box QString rightStr; // a string occurring at the right of this box int maxl; // the maximum length of this box (possibly InftyLen) #endif int minl; // the minimum length of this box #ifndef QT_NO_REGEXP_OPTIM QArray<int> occ1; // first-occurrence array #endif }; friend class Box; /* This is the lexical analyzer for regular expressions. */ enum { Tok_Eos, Tok_Dollar, Tok_LeftParen, Tok_MagicLeftParen, Tok_PosLookahead, Tok_NegLookahead, Tok_RightParen, Tok_CharClass, Tok_Caret, Tok_Quantifier, Tok_Bar, Tok_Word, Tok_NonWord, Tok_Char = 0x10000, Tok_BackRef = 0x20000 }; int getChar(); int getEscape(); #ifndef QT_NO_REGEXP_INTERVAL int getRep( int def ); #endif #ifndef QT_NO_REGEXP_LOOKAHEAD void skipChars( int n ); #endif void startTokenizer( const QChar *rx, int len ); int getToken(); const QChar *yyIn; // a pointer to the input regular expression pattern int yyPos0; // the position of yyTok in the input pattern int yyPos; // the position of the next character to read int yyLen; // the length of yyIn int yyCh; // the last character read CharClass *yyCharClass; // attribute for Tok_CharClass tokens int yyMinRep; // attribute for Tok_Quantifier int yyMaxRep; // ditto bool yyError; // syntax error or overflow during parsing? /* This is the syntactic analyzer for regular expressions. */ int parse( const QChar *rx, int len ); void parseAtom( Box *box ); void parseFactor( Box *box ); void parseTerm( Box *box ); void parseExpression( Box *box ); int yyTok; // the last token read bool yyMayCapture; // set this to FALSE to disable capturing /* This is the engine state during matching. */ const QString *mmStr; // a pointer to the input QString const QChar *mmIn; // a pointer to the input string data int mmPos; // the current position in the string int mmLen; // the length of the input string bool mmMinimal; // minimal matching? QArray<int> mmCaptured; // an array of pairs (start, len) QArray<int> mmCapturedNoMatch; // an array of pairs (-1, -1) QArray<int> mmBigArray; // big QArray<int> array int *mmInNextStack; // is state is mmNextStack? int *mmCurStack; // stack of current states int *mmNextStack; // stack of next states int *mmCurCapBegin; // start of current states' captures int *mmNextCapBegin; // start of next states' captures int *mmCurCapEnd; // end of current states' captures int *mmNextCapEnd; // end of next states' captures int *mmTempCapBegin; // start of temporary captures int *mmTempCapEnd; // end of temporary captures int *mmCapBegin; // start of captures for a next state int *mmCapEnd; // end of captures for a next state int *mmSlideTab; // bump-along slide table for bad-character heuristic int mmSlideTabSize; // size of slide table #ifndef QT_NO_REGEXP_BACKREF QIntDict<int> mmSleeping; // dictionary of back-reference sleepers #endif int mmMatchedLen; // length of match or of matched string for partial match }; QRegExpEngine::QRegExpEngine( const QString& rx, bool caseSensitive ) #ifndef QT_NO_REGEXP_BACKREF : mmSleeping( 101 ) #endif { setup( caseSensitive ); valid = ( parse(rx.unicode(), rx.length()) == (int) rx.length() ); } #ifndef QT_NO_REGEXP_OPTIM QRegExpEngine::~QRegExpEngine() { if ( --engCount == 0 ) { delete noOccurrences; noOccurrences = 0; delete firstOccurrenceAtZero; firstOccurrenceAtZero = 0; } } #endif /* Tries to match in str and returns an array of (begin, length) pairs for captured text. If there is no match, all pairs are (-1, -1). */ QArray<int> QRegExpEngine::match( const QString& str, int pos, bool minimal, bool oneTest ) { mmStr = &str; mmIn = str.unicode(); if ( mmIn == 0 ) mmIn = &QChar::null; mmPos = pos; mmLen = str.length(); mmMinimal = minimal; mmMatchedLen = 0; bool matched = FALSE; if ( valid && mmPos >= 0 && mmPos <= mmLen ) { #ifndef QT_NO_REGEXP_OPTIM if ( mmPos <= mmLen - minl ) { if ( caretAnchored || oneTest ) matched = matchHere(); else if ( useGoodStringHeuristic ) matched = goodStringMatch(); else matched = badCharMatch(); } #else matched = oneTest ? matchHere() : bruteMatch(); #endif } if ( matched ) { mmCaptured.detach(); mmCaptured[0] = mmPos; mmCaptured[1] = mmMatchedLen; for ( int j = 0; j < realncap; j++ ) { int len = mmCapEnd[j] - mmCapBegin[j]; mmCaptured[2 + 2 * j] = len > 0 ? mmPos + mmCapBegin[j] : 0; mmCaptured[2 + 2 * j + 1] = len; } return mmCaptured; } else { return mmCapturedNoMatch; } } /* The three following functions add one state to the automaton and return the number of the state. */ int QRegExpEngine::createState( QChar ch ) { return setupState( ch.unicode() ); } int QRegExpEngine::createState( const CharClass& cc ) { #ifndef QT_NO_REGEXP_CCLASS int n = cl.size(); cl.resize( n + 1 ); cl.insert( n, new CharClass(cc) ); return setupState( CharClassBit | n ); #else Q_UNUSED( cc ); return setupState( CharClassBit ); #endif } #ifndef QT_NO_REGEXP_BACKREF int QRegExpEngine::createState( int bref ) { if ( bref > nbrefs ) { nbrefs = bref; if ( nbrefs > MaxBackRefs ) { yyError = TRUE; return 0; } } return setupState( BackRefBit | bref ); } #endif /* The two following functions add a transition between all pairs of states (i, j) where i is fond in from, and j is found in to. Cat-transitions are distinguished from plus-transitions for capturing. */ void QRegExpEngine::addCatTransitions( const QArray<int>& from, const QArray<int>& to ) { for ( int i = 0; i < (int) from.size(); i++ ) { State *st = s[from[i]]; mergeInto( &st->outs, to ); } } #ifndef QT_NO_REGEXP_CAPTURE void QRegExpEngine::addPlusTransitions( const QArray<int>& from, const QArray<int>& to, int atom ) { for ( int i = 0; i < (int) from.size(); i++ ) { State *st = s[from[i]]; QArray<int> oldOuts = st->outs.copy(); mergeInto( &st->outs, to ); if ( f[atom].capture >= 0 ) { if ( st->reenter == 0 ) st->reenter = new QMap<int, int>; for ( int j = 0; j < (int) to.size(); j++ ) { if ( !st->reenter->contains(to[j]) && oldOuts.bsearch(to[j]) < 0 ) st->reenter->insert( to[j], atom ); } } } } #endif #ifndef QT_NO_REGEXP_ANCHOR_ALT /* Returns an anchor that means a OR b. */ int QRegExpEngine::anchorAlternation( int a, int b ) { if ( ((a & b) == a || (a & b) == b) && ((a | b) & Anchor_Alternation) == 0 ) return a & b; int n = aa.size(); aa.resize( n + 1 ); aa[n].a = a; aa[n].b = b; return Anchor_Alternation | n; } /* Returns an anchor that means a AND b. */ int QRegExpEngine::anchorConcatenation( int a, int b ) { if ( ((a | b) & Anchor_Alternation) == 0 ) return a | b; if ( (b & Anchor_Alternation) != 0 ) qSwap( a, b ); int aprime = anchorConcatenation( aa[a ^ Anchor_Alternation].a, b ); int bprime = anchorConcatenation( aa[a ^ Anchor_Alternation].b, b ); return anchorAlternation( aprime, bprime ); } #endif /* Adds anchor a on a transition caracterised by its from state and its to state. */ void QRegExpEngine::addAnchors( int from, int to, int a ) { State *st = s[from]; if ( st->anchors == 0 ) st->anchors = new QMap<int, int>; if ( st->anchors->contains(to) ) a = anchorAlternation( (*st->anchors)[to], a ); st->anchors->insert( to, a ); } #ifndef QT_NO_REGEXP_OPTIM /* The two following functions provide the engine with the information needed by its matching heuristics. */ void QRegExpEngine::setupGoodStringHeuristic( int earlyStart, int lateStart, const QString& str ) { goodEarlyStart = earlyStart; goodLateStart = lateStart; goodStr = cs ? str : str.lower(); } void QRegExpEngine::setupBadCharHeuristic( int minLen, const QArray<int>& firstOcc ) { minl = minLen; occ1 = cs ? firstOcc : *firstOccurrenceAtZero; } /* This function chooses between the good-string and the bad-character heuristics. It computes two scores and chooses the heuristic with the highest score. Here are some common-sense constraints on the scores that should be respected if the formulas are ever modified: (1) If goodStr is empty, the good-string heuristic scores 0. (2) If the search is case insensitive, the good-string heuristic should be used, unless it scores 0. (Case insensitivity turns all entries of occ1 to 0.) (3) If (goodLateStart - goodEarlyStart) is big, the good-string heuristic should score less. */ void QRegExpEngine::heuristicallyChooseHeuristic() { int i; if ( minl == 0 ) return; /* Magic formula: The good string has to constitute a good proportion of the minimum-length string, and appear at a more-or-less known index. */ int goodStringScore = ( 64 * goodStr.length() / minl ) - ( goodLateStart - goodEarlyStart ); /* Less magic formula: We pick a couple of characters at random, and check whether they are good or bad. */ int badCharScore = 0; int step = QMAX( 1, NumBadChars / 32 ); for ( i = 1; i < NumBadChars; i += step ) { if ( occ1[i] == NoOccurrence ) badCharScore += minl; else badCharScore += occ1[i]; } badCharScore /= minl; useGoodStringHeuristic = ( goodStringScore > badCharScore ); } #endif #if defined(QT_DEBUG) void QRegExpEngine::dump() const { int i, j; odebug << "Case " << (cs ? "" : "in") << "sensitive engine" << oendl; odebug << " States" << oendl; for ( i = 0; i < ns; i++ ) { odebug << " " << i << (i == InitialState ? " (initial)" : i == FinalState ? " (final)" : "") << oendl; #ifndef QT_NO_REGEXP_CAPTURE odebug << " in atom " << s[i]->atom << oendl; #endif int m = s[i]->match; if ( (m & CharClassBit) != 0 ) { odebug << " match character class " << (m ^ CharClassBit) << oendl; #ifndef QT_NO_REGEXP_CCLASS cl[m ^ CharClassBit]->dump(); #else odebug << " negative character class" << oendl; #endif } else if ( (m & BackRefBit) != 0 ) { odebug << " match back-reference " << (m ^ BackRefBit) << oendl; } else if ( m >= 0x20 && m <= 0x7e ) { odebug << " match " << QString().sprintf( "0x%.4x", m) << " (" << m << ")" << oendl; } else { odebug << " match " << QString().sprintf( "0x%.4x", m) << oendl; } for ( j = 0; j < (int) s[i]->outs.size(); j++ ) { int next = s[i]->outs[j]; odebug << " -> " << next << oendl; if ( s[i]->reenter != 0 && s[i]->reenter->contains(next) ) odebug << " [reenter " << (*s[i]->reenter)[next] << "]" << oendl; if ( s[i]->anchors != 0 && at(*s[i]->anchors, next) != 0 ) odebug << " [anchors " << QString().sprintf( "0x%.8x]", (*s[i]->anchors)[next] ) << oendl; } } #ifndef QT_NO_REGEXP_CAPTURE if ( nf > 0 ) { odebug << " Atom Parent Capture" << oendl; for ( i = 0; i < nf; i++ ) odebug << QString().sprintf(" %6d %6d %6d", i, f[i].parent, f[i].capture ) << oendl; } #endif #ifndef QT_NO_REGEXP_ANCHOR_ALT for ( i = 0; i < (int) aa.size(); i++ ) odebug << QString().sprintf(" Anchor alternation 0x%.8x: 0x%.8x 0x%.9x", i, aa[i].a, aa[i].b ) << oendl; #endif } #endif void QRegExpEngine::setup( bool caseSensitive ) { #ifndef QT_NO_REGEXP_OPTIM if ( engCount++ == 0 ) { noOccurrences = new QArray<int>( NumBadChars ); firstOccurrenceAtZero = new QArray<int>( NumBadChars ); noOccurrences->fill( NoOccurrence ); firstOccurrenceAtZero->fill( 0 ); } #endif s.setAutoDelete( TRUE ); s.resize( 32 ); ns = 0; #ifndef QT_NO_REGEXP_CAPTURE f.resize( 32 ); nf = 0; cf = -1; #endif realncap = 0; ncap = 0; #ifndef QT_NO_REGEXP_CCLASS cl.setAutoDelete( TRUE ); #endif #ifndef QT_NO_REGEXP_LOOKAHEAD ahead.setAutoDelete( TRUE ); #endif #ifndef QT_NO_REGEXP_OPTIM caretAnchored = TRUE; #endif valid = FALSE; cs = caseSensitive; #ifndef QT_NO_REGEXP_BACKREF nbrefs = 0; #endif #ifndef QT_NO_REGEXP_OPTIM useGoodStringHeuristic = FALSE; minl = 0; occ1 = *firstOccurrenceAtZero; #endif mmCapturedNoMatch.fill( -1, 2 ); } int QRegExpEngine::setupState( int match ) { if ( (ns & (ns + 1)) == 0 && ns + 1 >= (int) s.size() ) s.resize( (ns + 1) << 1 ); #ifndef QT_NO_REGEXP_CAPTURE s.insert( ns, new State(cf, match) ); #else s.insert( ns, new State(match) ); #endif return ns++; } #ifndef QT_NO_REGEXP_CAPTURE /* Functions startAtom() and finishAtom() should be called to delimit atoms. When a state is created, it is assigned to the current atom. The information is later used for capturing. */ int QRegExpEngine::startAtom( bool capture ) { if ( (nf & (nf + 1)) == 0 && nf + 1 >= (int) f.size() ) f.resize( (nf + 1) << 1 ); f[nf].parent = cf; cf = nf++; f[cf].capture = capture ? ncap++ : -1; return cf; } #endif #ifndef QT_NO_REGEXP_LOOKAHEAD /* Creates a lookahead anchor. */ int QRegExpEngine::addLookahead( QRegExpEngine *eng, bool negative ) { int n = ahead.size(); if ( n == MaxLookaheads ) { yyError = TRUE; return 0; } ahead.resize( n + 1 ); ahead.insert( n, new Lookahead(eng, negative) ); return Anchor_FirstLookahead << n; } #endif #ifndef QT_NO_REGEXP_CAPTURE /* We want the longest leftmost captures. */ bool QRegExpEngine::isBetterCapture( const int *begin1, const int *end1, const int *begin2, const int *end2 ) { for ( int i = 0; i < ncap; i++ ) { int delta = begin2[i] - begin1[i]; // it has to start early... if ( delta == 0 ) delta = end1[i] - end2[i]; // ...and end late (like a party) if ( delta != 0 ) return delta > 0; } return FALSE; } #endif /* Returns TRUE if anchor a matches at position mmPos + i in the input string, otherwise FALSE. */ bool QRegExpEngine::testAnchor( int i, int a, const int *capBegin ) { int j; #ifndef QT_NO_REGEXP_ANCHOR_ALT if ( (a & Anchor_Alternation) != 0 ) { return testAnchor( i, aa[a ^ Anchor_Alternation].a, capBegin ) || testAnchor( i, aa[a ^ Anchor_Alternation].b, capBegin ); } #endif if ( (a & Anchor_Caret) != 0 ) { if ( mmPos + i != 0 ) return FALSE; } if ( (a & Anchor_Dollar) != 0 ) { if ( mmPos + i != mmLen ) return FALSE; } #ifndef QT_NO_REGEXP_ESCAPE if ( (a & (Anchor_Word | Anchor_NonWord)) != 0 ) { bool before = FALSE, after = FALSE; if ( mmPos + i != 0 ) before = mmIn[mmPos + i - 1].isLetterOrNumber(); if ( mmPos + i != mmLen ) after = mmIn[mmPos + i].isLetterOrNumber(); if ( (a & Anchor_Word) != 0 && (before == after) ) return FALSE; if ( (a & Anchor_NonWord) != 0 && (before != after) ) return FALSE; } #endif #ifndef QT_NO_REGEXP_LOOKAHEAD bool catchx = TRUE; if ( (a & Anchor_LookaheadMask) != 0 ) { QConstString cstr = QConstString( (QChar *) mmIn + mmPos + i, mmLen - mmPos - i ); for ( j = 0; j < (int) ahead.size(); j++ ) { if ( (a & (Anchor_FirstLookahead << j)) != 0 ) { catchx = ( ahead[j]->eng->match(cstr.string(), 0, TRUE, TRUE)[0] == 0 ); if ( catchx == ahead[j]->neg ) return FALSE; } } } #endif #ifndef QT_NO_REGEXP_CAPTURE #ifndef QT_NO_REGEXP_BACKREF for ( j = 0; j < nbrefs; j++ ) { if ( (a & (Anchor_BackRef1Empty << j)) != 0 ) { if ( capBegin[j] != EmptyCapture ) return FALSE; } } #endif #endif return TRUE; } #ifndef QT_NO_REGEXP_OPTIM /* The three following functions are what Jeffrey Friedl would call transmissions (or bump-alongs). Using one or the other should make no difference, except in performance. */ bool QRegExpEngine::goodStringMatch() { int k = mmPos + goodEarlyStart; while ( (k = mmStr->find(goodStr, k, cs)) != -1 ) { int from = k - goodLateStart; int to = k - goodEarlyStart; if ( from > mmPos ) mmPos = from; while ( mmPos <= to ) { if ( matchHere() ) return TRUE; mmPos++; } k++; } return FALSE; } bool QRegExpEngine::badCharMatch() { int slideHead = 0; int slideNext = 0; int i; int lastPos = mmLen - minl; memset( mmSlideTab, 0, mmSlideTabSize * sizeof(int) ); /* Set up the slide table, used for the bad-character heuristic, using the table of first occurrence of each character. */ for ( i = 0; i < minl; i++ ) { int sk = occ1[BadChar(mmIn[mmPos + i])]; if ( sk == NoOccurrence ) sk = i + 1; if ( sk > 0 ) { int k = i + 1 - sk; if ( k < 0 ) { sk = i + 1; k = 0; } if ( sk > mmSlideTab[k] ) mmSlideTab[k] = sk; } } if ( mmPos > lastPos ) return FALSE; while ( TRUE ) { if ( ++slideNext >= mmSlideTabSize ) slideNext = 0; if ( mmSlideTab[slideHead] > 0 ) { if ( mmSlideTab[slideHead] - 1 > mmSlideTab[slideNext] ) mmSlideTab[slideNext] = mmSlideTab[slideHead] - 1; mmSlideTab[slideHead] = 0; } else { if ( matchHere() ) return TRUE; } if ( mmPos == lastPos ) break; /* Update the slide table. This code has much in common with the initialization code. */ int sk = occ1[BadChar(mmIn[mmPos + minl])]; if ( sk == NoOccurrence ) { mmSlideTab[slideNext] = minl; } else if ( sk > 0 ) { int k = slideNext + minl - sk; if ( k >= mmSlideTabSize ) k -= mmSlideTabSize; if ( sk > mmSlideTab[k] ) mmSlideTab[k] = sk; } slideHead = slideNext; mmPos++; } return FALSE; } #else bool QRegExpEngine::bruteMatch() { while ( mmPos <= mmLen ) { if ( matchHere() ) return TRUE; mmPos++; } return FALSE; } #endif /* Here's the core of the engine. It tries to do a match here and now. */ bool QRegExpEngine::matchHere() { int ncur = 1, nnext = 0; int i = 0, j, k, m; bool match = FALSE; mmMatchedLen = -1; mmCurStack[0] = InitialState; #ifndef QT_NO_REGEXP_CAPTURE if ( ncap > 0 ) { for ( j = 0; j < ncap; j++ ) { mmCurCapBegin[j] = EmptyCapture; mmCurCapEnd[j] = EmptyCapture; } } #endif #ifndef QT_NO_REGEXP_BACKREF int *zzZ = 0; while ( (ncur > 0 || mmSleeping.count() > 0) && i <= mmLen - mmPos && !match ) #else while ( ncur > 0 && i <= mmLen - mmPos && !match ) #endif { int ch = ( i < mmLen - mmPos ) ? mmIn[mmPos + i].unicode() : 0; for ( j = 0; j < ncur; j++ ) { int cur = mmCurStack[j]; State *scur = s[cur]; QArray<int>& outs = scur->outs; for ( k = 0; k < (int) outs.size(); k++ ) { int next = outs[k]; State *snext = s[next]; bool in = TRUE; #ifndef QT_NO_REGEXP_BACKREF int needSomeSleep = 0; #endif /* First, check if the anchors are anchored properly. */ if ( scur->anchors != 0 ) { int a = at( *scur->anchors, next ); if ( a != 0 && !testAnchor(i, a, mmCurCapBegin + j * ncap) ) in = FALSE; } /* If indeed they are, check if the input character is correct for this transition. */ if ( in ) { m = snext->match; if ( (m & (CharClassBit | BackRefBit)) == 0 ) { if ( cs ) in = ( m == ch ); else in = ( QChar(m).lower() == QChar(ch).lower() ); } else if ( next == FinalState ) { mmMatchedLen = i; match = mmMinimal; in = TRUE; } else if ( (m & CharClassBit) != 0 ) { #ifndef QT_NO_REGEXP_CCLASS const CharClass *cc = cl[m ^ CharClassBit]; if ( cs ) in = cc->in( ch ); else if ( cc->negative() ) in = cc->in( QChar(ch).lower() ) && cc->in( QChar(ch).upper() ); else in = cc->in( QChar(ch).lower() ) || cc->in( QChar(ch).upper() ); #endif #ifndef QT_NO_REGEXP_BACKREF } else { /* ( (m & BackRefBit) != 0 ) */ int bref = m ^ BackRefBit; int ell = j * ncap + ( bref - 1 ); in = bref <= ncap && mmCurCapBegin[ell] != EmptyCapture; if ( in ) { if ( cs ) in = ( mmIn[mmPos + mmCurCapBegin[ell]] == QChar(ch) ); else in = ( mmIn[mmPos + mmCurCapBegin[ell]].lower() == QChar(ch).lower() ); } if ( in ) { int delta; if ( mmCurCapEnd[ell] == EmptyCapture ) delta = i - mmCurCapBegin[ell]; else delta = mmCurCapEnd[ell] - mmCurCapBegin[ell]; in = ( delta <= mmLen - mmPos ); if ( in && delta > 1 ) { int n; if ( cs ) { for ( n = 1; n < delta; n++ ) { if ( mmIn[mmPos + mmCurCapBegin[ell] + n] != mmIn[mmPos + i + n] ) break; } } else { for ( n = 1; n < delta; n++ ) { QChar a = mmIn[mmPos + mmCurCapBegin[ell] + n]; QChar b = mmIn[mmPos + i + n]; if ( a.lower() != b.lower() ) break; } } in = ( n == delta ); if ( in ) needSomeSleep = delta - 1; } } #endif } } /* All is right. We must now update our data structures. */ if ( in ) { #ifndef QT_NO_REGEXP_CAPTURE int *capBegin, *capEnd; #endif /* If the next state was not encountered yet, all is fine. */ if ( (m = mmInNextStack[next]) == -1 ) { m = nnext++; mmNextStack[m] = next; mmInNextStack[next] = m; #ifndef QT_NO_REGEXP_CAPTURE capBegin = mmNextCapBegin + m * ncap; capEnd = mmNextCapEnd + m * ncap; /* Otherwise, we'll first maintain captures in temporary arrays, and decide at the end whether it's best to keep the previous capture zones or the new ones. */ } else { capBegin = mmTempCapBegin; capEnd = mmTempCapEnd; #endif } #ifndef QT_NO_REGEXP_CAPTURE /* Updating the capture zones is much of a task. */ if ( ncap > 0 ) { memcpy( capBegin, mmCurCapBegin + j * ncap, ncap * sizeof(int) ); memcpy( capEnd, mmCurCapEnd + j * ncap, ncap * sizeof(int) ); int c = scur->atom, n = snext->atom; int p = -1, q = -1; int cap; /* Lemma 1. For any x in the range [0..nf), we have f[x].parent < x. Proof. By looking at startAtom(), it is clear that cf < nf holds all the time, and thus that f[nf].parent < nf. */ /* If we are reentering an atom, we empty all capture zones inside it. */ if ( scur->reenter != 0 && (q = at(*scur->reenter, next)) != 0 ) { QBitArray b; b.fill( FALSE, nf ); b.setBit( q, TRUE ); for ( int ell = q + 1; ell < nf; ell++ ) { if ( b.testBit(f[ell].parent) ) { b.setBit( ell, TRUE ); cap = f[ell].capture; if ( cap >= 0 ) { capBegin[cap] = EmptyCapture; capEnd[cap] = EmptyCapture; } } } p = f[q].parent; /* Otherwise, close the capture zones we are leaving. We are leaving f[c].capture, f[f[c].parent].capture, f[f[f[c].parent].parent].capture, ..., until f[x].capture, with x such that f[x].parent is the youngest common ancestor for c and n. We go up along c's and n's ancestry until we find x. */ } else { p = c; q = n; while ( p != q ) { if ( p > q ) { cap = f[p].capture; if ( cap >= 0 ) { if ( capBegin[cap] == i ) { capBegin[cap] = EmptyCapture; capEnd[cap] = EmptyCapture; } else { capEnd[cap] = i; } } p = f[p].parent; } else { q = f[q].parent; } } } /* In any case, we now open the capture zones we are entering. We work upwards from n until we reach p (the parent of the atom we reenter or the youngest common ancestor). */ while ( n > p ) { cap = f[n].capture; if ( cap >= 0 ) { capBegin[cap] = i; capEnd[cap] = EmptyCapture; } n = f[n].parent; } /* If the next state was already in mmNextStack, we must choose carefully which capture zones we want to keep. */ if ( capBegin == mmTempCapBegin && isBetterCapture(capBegin, capEnd, mmNextCapBegin + m * ncap, mmNextCapEnd + m * ncap) ) { memcpy( mmNextCapBegin + m * ncap, capBegin, ncap * sizeof(int) ); memcpy( mmNextCapEnd + m * ncap, capEnd, ncap * sizeof(int) ); } } #ifndef QT_NO_REGEXP_BACKREF /* We are done with updating the capture zones. It's now time to put the next state to sleep, if it needs to, and to remove it from mmNextStack. */ if ( needSomeSleep > 0 ) { zzZ = new int[1 + 2 * ncap]; zzZ[0] = next; if ( ncap > 0 ) { memcpy( zzZ + 1, capBegin, ncap * sizeof(int) ); memcpy( zzZ + 1 + ncap, capEnd, ncap * sizeof(int) ); } mmInNextStack[mmNextStack[--nnext]] = -1; mmSleeping.insert( i + needSomeSleep, zzZ ); } #endif #endif } } } #ifndef QT_NO_REGEXP_CAPTURE /* If we reached the final state, hurray! Copy the captured zone. */ if ( ncap > 0 && (m = mmInNextStack[FinalState]) != -1 ) { memcpy( mmCapBegin, mmNextCapBegin + m * ncap, ncap * sizeof(int) ); memcpy( mmCapEnd, mmNextCapEnd + m * ncap, ncap * sizeof(int) ); } #ifndef QT_NO_REGEXP_BACKREF /* It's time to wake up the sleepers. */ if ( mmSleeping.count() > 0 ) { while ( (zzZ = mmSleeping.take(i)) != 0 ) { int next = zzZ[0]; int *capBegin = zzZ + 1; int *capEnd = zzZ + 1 + ncap; bool copyOver = TRUE; if ( (m = mmInNextStack[zzZ[0]]) == -1 ) { m = nnext++; mmNextStack[m] = next; mmInNextStack[next] = m; } else { copyOver = isBetterCapture( mmNextCapBegin + m * ncap, mmNextCapEnd + m * ncap, capBegin, capEnd ); } if ( copyOver ) { memcpy( mmNextCapBegin + m * ncap, capBegin, ncap * sizeof(int) ); memcpy( mmNextCapEnd + m * ncap, capEnd, ncap * sizeof(int) ); } delete[] zzZ; } } #endif #endif for ( j = 0; j < nnext; j++ ) mmInNextStack[mmNextStack[j]] = -1; qSwap( mmCurStack, mmNextStack ); #ifndef QT_NO_REGEXP_CAPTURE qSwap( mmCurCapBegin, mmNextCapBegin ); qSwap( mmCurCapEnd, mmNextCapEnd ); #endif ncur = nnext; nnext = 0; i++; } #ifndef QT_NO_REGEXP_BACKREF /* If minimal matching is enabled, we might have some sleepers left. */ while ( !mmSleeping.isEmpty() ) { zzZ = mmSleeping.take( *QIntDictIterator<int>(mmSleeping) ); delete[] zzZ; } #endif match = ( mmMatchedLen >= 0 ); if ( !match ) mmMatchedLen = i - 1; return match; } #ifndef QT_NO_REGEXP_CCLASS QRegExpEngine::CharClass::CharClass() : c( 0 ), n( FALSE ) #ifndef QT_NO_REGEXP_OPTIM , occ1( *noOccurrences ) #endif { } QRegExpEngine::CharClass& QRegExpEngine::CharClass::operator=( const CharClass& cc ) { c = cc.c; r = cc.r.copy(); n = cc.n; #ifndef QT_NO_REGEXP_OPTIM occ1 = cc.occ1; #endif return *this; } void QRegExpEngine::CharClass::clear() { c = 0; r.resize( 0 ); n = FALSE; } void QRegExpEngine::CharClass::setNegative( bool negative ) { n = negative; #ifndef QT_NO_REGEXP_OPTIM occ1 = *firstOccurrenceAtZero; #endif } void QRegExpEngine::CharClass::addCategories( int cats ) { c |= cats; #ifndef QT_NO_REGEXP_OPTIM occ1 = *firstOccurrenceAtZero; #endif } void QRegExpEngine::CharClass::addRange( ushort from, ushort to ) { if ( from > to ) qSwap( from, to ); int n = r.size(); r.resize( n + 1 ); r[n].from = from; r[n].to = to; #ifndef QT_NO_REGEXP_OPTIM int i; if ( to - from < NumBadChars ) { occ1.detach(); if ( from % NumBadChars <= to % NumBadChars ) { for ( i = from % NumBadChars; i <= to % NumBadChars; i++ ) occ1[i] = 0; } else { for ( i = 0; i <= to % NumBadChars; i++ ) occ1[i] = 0; for ( i = from % NumBadChars; i < NumBadChars; i++ ) occ1[i] = 0; } } else { occ1 = *firstOccurrenceAtZero; } #endif } bool QRegExpEngine::CharClass::in( QChar ch ) const { #ifndef QT_NO_REGEXP_OPTIM if ( occ1[BadChar(ch)] == NoOccurrence ) return n; #endif if ( c != 0 && (c & (1 << (int) ch.category())) != 0 ) return !n; for ( int i = 0; i < (int) r.size(); i++ ) { if ( ch.unicode() >= r[i].from && ch.unicode() <= r[i].to ) return !n; } return n; } #if defined(QT_DEBUG) void QRegExpEngine::CharClass::dump() const { int i; odebug << " " << (n ? "nega" : "posi") << "tive character class" << oendl; #ifndef QT_NO_REGEXP_CCLASS if ( c != 0 ) odebug << QString().sprintf(" categories 0x%.8x", c ) << oendl; #endif for ( i = 0; i < (int) r.size(); i++ ) odebug << QString().sprintf(" 0x%.4x through 0x%.4x", r[i].from, r[i].to ) << oendl; } #endif #endif QRegExpEngine::Box::Box( QRegExpEngine *engine ) : eng( engine ), skipanchors( 0 ) #ifndef QT_NO_REGEXP_OPTIM , earlyStart( 0 ), lateStart( 0 ), maxl( 0 ), occ1( *noOccurrences ) #endif { minl = 0; } QRegExpEngine::Box& QRegExpEngine::Box::operator=( const Box& b ) { eng = b.eng; ls = b.ls; rs = b.rs; lanchors = b.lanchors; ranchors = b.ranchors; skipanchors = b.skipanchors; #ifndef QT_NO_REGEXP_OPTIM earlyStart = b.earlyStart; lateStart = b.lateStart; str = b.str; leftStr = b.leftStr; rightStr = b.rightStr; maxl = b.maxl; occ1 = b.occ1; #endif minl = b.minl; return *this; } void QRegExpEngine::Box::set( QChar ch ) { ls.resize( 1 ); ls[0] = eng->createState( ch ); rs = ls; rs.detach(); #ifndef QT_NO_REGEXP_OPTIM str = ch; leftStr = ch; rightStr = ch; maxl = 1; occ1.detach(); occ1[BadChar(ch)] = 0; #endif minl = 1; } void QRegExpEngine::Box::set( const CharClass& cc ) { ls.resize( 1 ); ls[0] = eng->createState( cc ); rs = ls; rs.detach(); #ifndef QT_NO_REGEXP_OPTIM maxl = 1; occ1 = cc.firstOccurrence(); #endif minl = 1; } #ifndef QT_NO_REGEXP_BACKREF void QRegExpEngine::Box::set( int bref ) { ls.resize( 1 ); ls[0] = eng->createState( bref ); rs = ls; rs.detach(); if ( bref >= 1 && bref <= MaxBackRefs ) skipanchors = Anchor_BackRef0Empty << bref; #ifndef QT_NO_REGEXP_OPTIM maxl = InftyLen; #endif minl = 0; } #endif void QRegExpEngine::Box::cat( const Box& b ) { eng->addCatTransitions( rs, b.ls ); addAnchorsToEngine( b ); if ( minl == 0 ) { mergeInto( &lanchors, b.lanchors ); if ( skipanchors != 0 ) { for ( int i = 0; i < (int) b.ls.size(); i++ ) { int a = eng->anchorConcatenation( at(lanchors, b.ls[i]), skipanchors ); lanchors.insert( b.ls[i], a ); } } mergeInto( &ls, b.ls ); } if ( b.minl == 0 ) { mergeInto( &ranchors, b.ranchors ); if ( b.skipanchors != 0 ) { for ( int i = 0; i < (int) rs.size(); i++ ) { int a = eng->anchorConcatenation( at(ranchors, rs[i]), b.skipanchors ); ranchors.insert( rs[i], a ); } } mergeInto( &rs, b.rs ); } else { ranchors = b.ranchors; rs = b.rs; } #ifndef QT_NO_REGEXP_OPTIM if ( maxl != InftyLen ) { if ( rightStr.length() + b.leftStr.length() > QMAX(str.length(), b.str.length()) ) { earlyStart = minl - rightStr.length(); lateStart = maxl - rightStr.length(); str = rightStr + b.leftStr; } else if ( b.str.length() > str.length() ) { earlyStart = minl + b.earlyStart; lateStart = maxl + b.lateStart; str = b.str; } } if ( (int) leftStr.length() == maxl ) leftStr += b.leftStr; if ( (int) b.rightStr.length() == b.maxl ) rightStr += b.rightStr; else rightStr = b.rightStr; if ( maxl == InftyLen || b.maxl == InftyLen ) maxl = InftyLen; else maxl += b.maxl; occ1.detach(); for ( int i = 0; i < NumBadChars; i++ ) { if ( b.occ1[i] != NoOccurrence && minl + b.occ1[i] < occ1[i] ) occ1[i] = minl + b.occ1[i]; } #endif minl += b.minl; if ( minl == 0 ) skipanchors = eng->anchorConcatenation( skipanchors, b.skipanchors ); else skipanchors = 0; } void QRegExpEngine::Box::orx( const Box& b ) { mergeInto( &ls, b.ls ); mergeInto( &lanchors, b.lanchors ); mergeInto( &rs, b.rs ); mergeInto( &ranchors, b.ranchors ); skipanchors = eng->anchorAlternation( skipanchors, b.skipanchors ); #ifndef QT_NO_REGEXP_OPTIM occ1.detach(); for ( int i = 0; i < NumBadChars; i++ ) { if ( occ1[i] > b.occ1[i] ) occ1[i] = b.occ1[i]; } earlyStart = 0; lateStart = 0; str = QString::null; leftStr = QString::null; rightStr = QString::null; if ( b.maxl > maxl ) maxl = b.maxl; #endif if ( b.minl < minl ) minl = b.minl; } void QRegExpEngine::Box::plus( int atom ) { #ifndef QT_NO_REGEXP_CAPTURE eng->addPlusTransitions( rs, ls, atom ); #else Q_UNUSED( atom ); eng->addCatTransitions( rs, ls ); #endif addAnchorsToEngine( *this ); #ifndef QT_NO_REGEXP_OPTIM maxl = InftyLen; #endif } void QRegExpEngine::Box::opt() { #ifndef QT_NO_REGEXP_OPTIM earlyStart = 0; lateStart = 0; str = QString::null; leftStr = QString::null; rightStr = QString::null; #endif skipanchors = 0; minl = 0; } void QRegExpEngine::Box::catAnchor( int a ) { if ( a != 0 ) { for ( int i = 0; i < (int) rs.size(); i++ ) { a = eng->anchorConcatenation( at(ranchors, rs[i]), a ); ranchors.insert( rs[i], a ); } if ( minl == 0 ) skipanchors = eng->anchorConcatenation( skipanchors, a ); } } #ifndef QT_NO_REGEXP_OPTIM void QRegExpEngine::Box::setupHeuristics() { eng->setupGoodStringHeuristic( earlyStart, lateStart, str ); /* A regular expression such as 112|1 has occ1['2'] = 2 and minl = 1 at this point. An entry of occ1 has to be at most minl or infinity for the rest of the algorithm to go well. We waited until here before normalizing these cases (instead of doing it in Box::orx()) because sometimes things improve by themselves; consider (112|1)34. */ for ( int i = 0; i < NumBadChars; i++ ) { if ( occ1[i] != NoOccurrence && occ1[i] >= minl ) occ1[i] = minl; } eng->setupBadCharHeuristic( minl, occ1 ); eng->heuristicallyChooseHeuristic(); } #endif #if defined(QT_DEBUG) void QRegExpEngine::Box::dump() const { int i; odebug << "Box of at least " << minl << " character" << (minl == 1 ? "" : "s") << oendl; odebug << " Left states:" << oendl; for ( i = 0; i < (int) ls.size(); i++ ) { if ( at(lanchors, ls[i]) == 0 ) odebug << " " << ls[i] << oendl; else odebug << " " << ls[i] << QString().sprintf(" [anchors 0x%.8x]", lanchors[ls[i]]) << oendl; } odebug << " Right states:" << oendl; for ( i = 0; i < (int) rs.size(); i++ ) { if ( at(ranchors, ls[i]) == 0 ) odebug << " " << rs[i] << oendl; else odebug << " " << rs[i] << QString().sprintf(" [anchors 0x%.8x]", ranchors[rs[i]]) << oendl; } odebug << QString().sprintf(" Skip anchors: 0x%.8x", skipanchors) << oendl; } #endif void QRegExpEngine::Box::addAnchorsToEngine( const Box& to ) const { for ( int i = 0; i < (int) to.ls.size(); i++ ) { for ( int j = 0; j < (int) rs.size(); j++ ) { int a = eng->anchorConcatenation( at(ranchors, rs[j]), at(to.lanchors, to.ls[i]) ); eng->addAnchors( rs[j], to.ls[i], a ); } } } int QRegExpEngine::getChar() { return ( yyPos == yyLen ) ? EOS : yyIn[yyPos++].unicode(); } int QRegExpEngine::getEscape() { #ifndef QT_NO_REGEXP_ESCAPE const char tab[] = "afnrtv"; // no b, as \b means word boundary const char backTab[] = "\a\f\n\r\t\v"; ushort low; int i; #endif ushort val; int prevCh = yyCh; if ( prevCh == EOS ) { yyError = TRUE; return Tok_Char | '\\'; } yyCh = getChar(); #ifndef QT_NO_REGEXP_ESCAPE if ( (prevCh & ~0xff) == 0 ) { const char *p = strchr( tab, prevCh ); if ( p != 0 ) return Tok_Char | backTab[p - tab]; } #endif switch ( prevCh ) { #ifndef QT_NO_REGEXP_ESCAPE case '0': val = 0; for ( i = 0; i < 3; i++ ) { if ( yyCh >= '0' && yyCh <= '7' ) val = ( val << 3 ) | ( yyCh - '0' ); else break; yyCh = getChar(); } if ( (val & ~0377) != 0 ) yyError = TRUE; return Tok_Char | val; #endif #ifndef QT_NO_REGEXP_ESCAPE case 'B': return Tok_NonWord; #endif #ifndef QT_NO_REGEXP_CCLASS case 'D': // see QChar::isDigit() yyCharClass->addCategories( 0x7fffffef ); return Tok_CharClass; case 'S': // see QChar::isSpace() yyCharClass->addCategories( 0x7ffff87f ); yyCharClass->addRange( 0x0000, 0x0008 ); yyCharClass->addRange( 0x000e, 0x001f ); yyCharClass->addRange( 0x007f, 0x009f ); return Tok_CharClass; case 'W': // see QChar::isLetterOrNumber() yyCharClass->addCategories( 0x7ff07f8f ); return Tok_CharClass; #endif #ifndef QT_NO_REGEXP_ESCAPE case 'b': return Tok_Word; #endif #ifndef QT_NO_REGEXP_CCLASS case 'd': // see QChar::isDigit() yyCharClass->addCategories( 0x00000010 ); return Tok_CharClass; case 's': // see QChar::isSpace() yyCharClass->addCategories( 0x00000380 ); yyCharClass->addRange( 0x0009, 0x000d ); return Tok_CharClass; case 'w': // see QChar::isLetterOrNumber() yyCharClass->addCategories( 0x000f8070 ); return Tok_CharClass; #endif #ifndef QT_NO_REGEXP_ESCAPE case 'x': val = 0; for ( i = 0; i < 4; i++ ) { low = QChar( yyCh ).lower(); if ( low >= '0' && low <= '9' ) val = ( val << 4 ) | ( low - '0' ); else if ( low >= 'a' && low <= 'f' ) val = ( val << 4 ) | ( low - 'a' + 10 ); else break; yyCh = getChar(); } return Tok_Char | val; #endif default: if ( prevCh >= '1' && prevCh <= '9' ) { #ifndef QT_NO_REGEXP_BACKREF val = prevCh - '0'; while ( yyCh >= '0' && yyCh <= '9' ) { val = ( val *= 10 ) | ( yyCh - '0' ); yyCh = getChar(); } return Tok_BackRef | val; #else yyError = TRUE; #endif } return Tok_Char | prevCh; } } #ifndef QT_NO_REGEXP_INTERVAL int QRegExpEngine::getRep( int def ) { if ( yyCh >= '0' && yyCh <= '9' ) { int rep = 0; do { rep = 10 * rep + yyCh - '0'; if ( rep >= InftyRep ) { yyError = TRUE; rep = def; } yyCh = getChar(); } while ( yyCh >= '0' && yyCh <= '9' ); return rep; } else { return def; } } #endif #ifndef QT_NO_REGEXP_LOOKAHEAD void QRegExpEngine::skipChars( int n ) { if ( n > 0 ) { yyPos += n - 1; yyCh = getChar(); } } #endif void QRegExpEngine::startTokenizer( const QChar *rx, int len ) { yyIn = rx; yyPos0 = 0; yyPos = 0; yyLen = len; yyCh = getChar(); yyCharClass = new CharClass; yyMinRep = 0; yyMaxRep = 0; yyError = FALSE; } int QRegExpEngine::getToken() { #ifndef QT_NO_REGEXP_CCLASS ushort pendingCh = 0; bool charPending; bool rangePending; int tok; #endif int prevCh = yyCh; yyPos0 = yyPos - 1; #ifndef QT_NO_REGEXP_CCLASS yyCharClass->clear(); #endif yyMinRep = 0; yyMaxRep = 0; yyCh = getChar(); switch ( prevCh ) { case EOS: yyPos0 = yyPos; return Tok_Eos; case '$': return Tok_Dollar; case '(': if ( yyCh == '?' ) { prevCh = getChar(); yyCh = getChar(); switch ( prevCh ) { #ifndef QT_NO_REGEXP_LOOKAHEAD case '!': return Tok_NegLookahead; case '=': return Tok_PosLookahead; #endif case ':': return Tok_MagicLeftParen; default: yyError = TRUE; return Tok_MagicLeftParen; } } else { return Tok_LeftParen; } case ')': return Tok_RightParen; case '*': yyMinRep = 0; yyMaxRep = InftyRep; return Tok_Quantifier; case '+': yyMinRep = 1; yyMaxRep = InftyRep; return Tok_Quantifier; case '.': #ifndef QT_NO_REGEXP_CCLASS yyCharClass->setNegative( TRUE ); #endif return Tok_CharClass; case '?': yyMinRep = 0; yyMaxRep = 1; return Tok_Quantifier; case '[': #ifndef QT_NO_REGEXP_CCLASS if ( yyCh == '^' ) { yyCharClass->setNegative( TRUE ); yyCh = getChar(); } charPending = FALSE; rangePending = FALSE; do { if ( yyCh == '-' && charPending && !rangePending ) { rangePending = TRUE; yyCh = getChar(); } else { if ( charPending && !rangePending ) { yyCharClass->addSingleton( pendingCh ); charPending = FALSE; } if ( yyCh == '\\' ) { yyCh = getChar(); tok = getEscape(); if ( tok == Tok_Word ) tok = '\b'; } else { tok = Tok_Char | yyCh; yyCh = getChar(); } if ( tok == Tok_CharClass ) { if ( rangePending ) { yyCharClass->addSingleton( '-' ); yyCharClass->addSingleton( pendingCh ); charPending = FALSE; rangePending = FALSE; } } else if ( (tok & Tok_Char) != 0 ) { if ( rangePending ) { yyCharClass->addRange( pendingCh, tok ^ Tok_Char ); charPending = FALSE; rangePending = FALSE; } else { pendingCh = tok ^ Tok_Char; charPending = TRUE; } } else { yyError = TRUE; } } } while ( yyCh != ']' && yyCh != EOS ); if ( rangePending ) yyCharClass->addSingleton( '-' ); if ( charPending ) yyCharClass->addSingleton( pendingCh ); if ( yyCh == EOS ) yyError = TRUE; else yyCh = getChar(); return Tok_CharClass; #else yyError = TRUE; return Tok_Char | '['; #endif case '\\': return getEscape(); case ']': yyError = TRUE; return Tok_Char | ']'; case '^': return Tok_Caret; #ifndef QT_NO_REGEXP_INTERVAL case '{': yyMinRep = getRep( 0 ); yyMaxRep = yyMinRep; if ( yyCh == ',' ) { yyCh = getChar(); yyMaxRep = getRep( InftyRep ); } if ( yyMaxRep < yyMinRep ) qSwap( yyMinRep, yyMaxRep ); if ( yyCh != '}' ) yyError = TRUE; yyCh = getChar(); return Tok_Quantifier; #else yyError = TRUE; return Tok_Char | '{'; #endif case '|': return Tok_Bar; case '}': yyError = TRUE; return Tok_Char | '}'; default: return Tok_Char | prevCh; } } int QRegExpEngine::parse( const QChar *pattern, int len ) { valid = TRUE; startTokenizer( pattern, len ); yyTok = getToken(); #ifndef QT_NO_REGEXP_CAPTURE yyMayCapture = TRUE; #else yyMayCapture = FALSE; #endif #ifndef QT_NO_REGEXP_CAPTURE int atom = startAtom( FALSE ); #endif CharClass anything; Box box( this ); // create InitialState box.set( anything ); Box rightBox( this ); // create FinalState rightBox.set( anything ); Box middleBox( this ); parseExpression( &middleBox ); #ifndef QT_NO_REGEXP_CAPTURE finishAtom( atom ); #endif #ifndef QT_NO_REGEXP_OPTIM middleBox.setupHeuristics(); #endif box.cat( middleBox ); box.cat( rightBox ); delete yyCharClass; yyCharClass = 0; realncap = ncap; #ifndef QT_NO_REGEXP_BACKREF if ( nbrefs > ncap ) ncap = nbrefs; #endif mmCaptured.resize( 2 + 2 * realncap ); mmCapturedNoMatch.fill( -1, 2 + 2 * realncap ); /* We use one QArray<int> for all the big data used a lot in matchHere() and friends. */ #ifndef QT_NO_REGEXP_OPTIM mmSlideTabSize = QMAX( minl + 1, 16 ); #else mmSlideTabSize = 0; #endif mmBigArray.resize( (3 + 4 * ncap) * ns + 4 * ncap + mmSlideTabSize ); mmInNextStack = mmBigArray.data(); memset( mmInNextStack, -1, ns * sizeof(int) ); mmCurStack = mmInNextStack + ns; mmNextStack = mmInNextStack + 2 * ns; mmCurCapBegin = mmInNextStack + 3 * ns; mmNextCapBegin = mmCurCapBegin + ncap * ns; mmCurCapEnd = mmCurCapBegin + 2 * ncap * ns; mmNextCapEnd = mmCurCapBegin + 3 * ncap * ns; mmTempCapBegin = mmCurCapBegin + 4 * ncap * ns; mmTempCapEnd = mmTempCapBegin + ncap; mmCapBegin = mmTempCapBegin + 2 * ncap; mmCapEnd = mmTempCapBegin + 3 * ncap; mmSlideTab = mmTempCapBegin + 4 * ncap; if ( yyError ) return -1; #ifndef QT_NO_REGEXP_OPTIM State *sinit = s[InitialState]; caretAnchored = ( sinit->anchors != 0 ); if ( caretAnchored ) { QMap<int, int>& anchors = *sinit->anchors; QMap<int, int>::ConstIterator a; for ( a = anchors.begin(); a != anchors.end(); ++a ) { #ifndef QT_NO_REGEXP_ANCHOR_ALT if ( (*a & Anchor_Alternation) != 0 ) break; #endif if ( (*a & Anchor_Caret) == 0 ) { caretAnchored = FALSE; break; } } } #endif return yyPos0; } void QRegExpEngine::parseAtom( Box *box ) { #ifndef QT_NO_REGEXP_LOOKAHEAD QRegExpEngine *eng = 0; bool neg; int len; #endif switch ( yyTok ) { case Tok_Dollar: box->catAnchor( Anchor_Dollar ); break; case Tok_Caret: box->catAnchor( Anchor_Caret ); break; #ifndef QT_NO_REGEXP_LOOKAHEAD case Tok_PosLookahead: case Tok_NegLookahead: neg = ( yyTok == Tok_NegLookahead ); eng = new QRegExpEngine( cs ); len = eng->parse( yyIn + yyPos - 1, yyLen - yyPos + 1 ); if ( len >= 0 ) skipChars( len ); else yyError = TRUE; box->catAnchor( addLookahead(eng, neg) ); yyTok = getToken(); if ( yyTok != Tok_RightParen ) yyError = TRUE; break; #endif #ifndef QT_NO_REGEXP_ESCAPE case Tok_Word: box->catAnchor( Anchor_Word ); break; case Tok_NonWord: box->catAnchor( Anchor_NonWord ); break; #endif case Tok_LeftParen: case Tok_MagicLeftParen: yyTok = getToken(); parseExpression( box ); if ( yyTok != Tok_RightParen ) yyError = TRUE; break; case Tok_CharClass: box->set( *yyCharClass ); break; default: if ( (yyTok & Tok_Char) != 0 ) box->set( QChar(yyTok ^ Tok_Char) ); #ifndef QT_NO_REGEXP_BACKREF else if ( (yyTok & Tok_BackRef) != 0 ) box->set( yyTok ^ Tok_BackRef ); #endif else yyError = TRUE; } yyTok = getToken(); } void QRegExpEngine::parseFactor( Box *box ) { #ifndef QT_NO_REGEXP_CAPTURE int atom = startAtom( yyMayCapture && yyTok == Tok_LeftParen ); #else static const int atom = 0; #endif #ifndef QT_NO_REGEXP_INTERVAL #define YYREDO() \ yyIn = in, yyPos0 = pos0, yyPos = pos, yyLen = len, yyCh = ch, \ *yyCharClass = charClass, yyMinRep = 0, yyMaxRep = 0, yyTok = tok const QChar *in = yyIn; int pos0 = yyPos0; int pos = yyPos; int len = yyLen; int ch = yyCh; CharClass charClass; if ( yyTok == Tok_CharClass ) charClass = *yyCharClass; int tok = yyTok; bool mayCapture = yyMayCapture; #endif parseAtom( box ); #ifndef QT_NO_REGEXP_CAPTURE finishAtom( atom ); #endif if ( yyTok == Tok_Quantifier ) { if ( yyMaxRep == InftyRep ) { box->plus( atom ); #ifndef QT_NO_REGEXP_INTERVAL } else if ( yyMaxRep == 0 ) { box->clear(); #endif } if ( yyMinRep == 0 ) box->opt(); #ifndef QT_NO_REGEXP_INTERVAL yyMayCapture = FALSE; int alpha = ( yyMinRep == 0 ) ? 0 : yyMinRep - 1; int beta = ( yyMaxRep == InftyRep ) ? 0 : yyMaxRep - ( alpha + 1 ); Box rightBox( this ); int i; for ( i = 0; i < beta; i++ ) { YYREDO(); Box leftBox( this ); parseAtom( &leftBox ); leftBox.cat( rightBox ); leftBox.opt(); rightBox = leftBox; } for ( i = 0; i < alpha; i++ ) { YYREDO(); Box leftBox( this ); parseAtom( &leftBox ); leftBox.cat( rightBox ); rightBox = leftBox; } rightBox.cat( *box ); *box = rightBox; #endif yyTok = getToken(); #ifndef QT_NO_REGEXP_INTERVAL yyMayCapture = mayCapture; #endif } #undef YYREDO } void QRegExpEngine::parseTerm( Box *box ) { #ifndef QT_NO_REGEXP_OPTIM if ( yyTok != Tok_Eos && yyTok != Tok_RightParen && yyTok != Tok_Bar ) parseFactor( box ); #endif while ( yyTok != Tok_Eos && yyTok != Tok_RightParen && yyTok != Tok_Bar ) { Box rightBox( this ); parseFactor( &rightBox ); box->cat( rightBox ); } } void QRegExpEngine::parseExpression( Box *box ) { parseTerm( box ); while ( yyTok == Tok_Bar ) { Box rightBox( this ); yyTok = getToken(); parseTerm( &rightBox ); box->orx( rightBox ); } } /* The class QRegExpPrivate contains the private data of a regular expression other than the automaton. It makes it possible for many QRegExp objects to use the same QRegExpEngine object with different QRegExpPrivate objects. */ struct QRegExpPrivate { QString pattern; // regular-expression or wildcard pattern QString rxpattern; // regular-expression pattern #ifndef QT_NO_REGEXP_WILDCARD bool wc; // wildcard mode? #endif bool min; // minimal matching? (instead of maximal) #ifndef QT_NO_REGEXP_CAPTURE QString t; // last string passed to QRegExp::search() or searchRev() QStringList capturedCache; // what QRegExp::capturedTexts() returned last #endif QArray<int> captured; // what QRegExpEngine::search() returned last QRegExpPrivate() { captured.fill( -1, 2 ); } }; #ifndef QT_NO_REGEXP_OPTIM static QCache<QRegExpEngine> *engineCache = 0; #endif static QRegExpEngine *newEngine( const QString& pattern, bool caseSensitive ) { #ifndef QT_NO_REGEXP_OPTIM if ( engineCache != 0 ) { QRegExpEngine *eng = engineCache->take( pattern ); if ( eng == 0 || eng->caseSensitive() != caseSensitive ) { delete eng; } else { eng->ref(); return eng; } } #endif return new QRegExpEngine( pattern, caseSensitive ); } static void derefEngine( QRegExpEngine *eng, const QString& pattern ) { if ( eng != 0 && eng->deref() ) { #ifndef QT_NO_REGEXP_OPTIM if ( engineCache == 0 ) { engineCache = new QCache<QRegExpEngine>; engineCache->setAutoDelete( TRUE ); } if ( !pattern.isNull() && engineCache->insert(pattern, eng, 4 + pattern.length() / 4) ) return; #else Q_UNUSED( pattern ); #endif delete eng; } } /*! Constructs an empty regexp. \sa isValid() */ QRegExp3::QRegExp3() { eng = new QRegExpEngine( TRUE ); priv = new QRegExpPrivate; priv->pattern = QString::null; #ifndef QT_NO_REGEXP_WILDCARD priv->wc = FALSE; #endif priv->min = FALSE; compile( TRUE ); } /*! Constructs a regular expression object for the given \a pattern string. The pattern must be given using wildcard notation if \a wildcard is TRUE (default is FALSE). The pattern is case sensitive, unless \a caseSensitive is FALSE. Matching is greedy (maximal), but can be changed by calling setMinimal(). \sa setPattern() setCaseSensitive() setWildcard() setMinimal() */ QRegExp3::QRegExp3( const QString& pattern, bool caseSensitive, bool wildcard ) { eng = 0; priv = new QRegExpPrivate; priv->pattern = pattern; #ifndef QT_NO_REGEXP_WILDCARD priv->wc = wildcard; #endif priv->min = FALSE; compile( caseSensitive ); } /*! Constructs a regular expression as a copy of \a rx. \sa operator=() */ QRegExp3::QRegExp3( const QRegExp3& rx ) { eng = 0; priv = new QRegExpPrivate; operator=( rx ); } /*! Destroys the regular expression and cleans up its internal data. */ QRegExp3::~QRegExp3() { derefEngine( eng, priv->rxpattern ); delete priv; } /*! Copies the regular expression \a rx and returns a reference to the copy. The case sensitivity, wildcard and minimal matching options are copied as well. */ QRegExp3& QRegExp3::operator=( const QRegExp3& rx ) { rx.eng->ref(); derefEngine( eng, priv->rxpattern ); eng = rx.eng; priv->pattern = rx.priv->pattern; priv->rxpattern = rx.priv->rxpattern; #ifndef QT_NO_REGEXP_WILDCARD priv->wc = rx.priv->wc; #endif priv->min = rx.priv->min; #ifndef QT_NO_REGEXP_CAPTURE priv->t = rx.priv->t; priv->capturedCache = rx.priv->capturedCache; #endif priv->captured = rx.priv->captured; return *this; } /*! Returns TRUE if this regular expression is equal to \a rx, otherwise returns FALSE. Two QRegExp3 objects are equal if they have the same pattern strings and the same settings for case sensitivity, wildcard and minimal matching. */ bool QRegExp3::operator==( const QRegExp3& rx ) const { return priv->pattern == rx.priv->pattern && eng->caseSensitive() == rx.eng->caseSensitive() && #ifndef QT_NO_REGEXP_WILDCARD priv->wc == rx.priv->wc && #endif priv->min == rx.priv->min; } /*! \fn bool QRegExp3::operator!=( const QRegExp& rx ) const Returns TRUE if this regular expression is not equal to \a rx, otherwise FALSE. \sa operator==() */ /*! Returns TRUE if the pattern string is empty, otherwise FALSE. If you call match() with an empty pattern on an empty string it will return TRUE otherwise it returns FALSE since match() operates over the whole string. If you call search() with an empty pattern on \e any string it will return the start position (0 by default) since it will match at the start position, because the empty pattern matches the 'emptiness' at the start of the string, and the length of the match returned by matchedLength() will be 0. See QString::isEmpty(). */ bool QRegExp3::isEmpty() const { return priv->pattern.isEmpty(); } /*! Returns TRUE if the regular expression is valid, or FALSE if it's invalid. An invalid regular expression never matches. The pattern <b>[a-z</b> is an example of an invalid pattern, since it lacks a closing square bracket. Note that the validity of a regexp may also depend on the setting of the wildcard flag, for example <b>*.html</b> is a valid wildcard regexp but an invalid full regexp. */ bool QRegExp3::isValid() const { return eng->isValid(); } /*! Returns the pattern string of the regular expression. The pattern has either regular expression syntax or wildcard syntax, depending on wildcard(). \sa setPattern() */ QString QRegExp3::pattern() const { return priv->pattern; } /*! Sets the pattern string to \a pattern and returns a reference to this regular expression. The case sensitivity, wildcard and minimal matching options are not changed. \sa pattern() */ void QRegExp3::setPattern( const QString& pattern ) { if ( priv->pattern != pattern ) { priv->pattern = pattern; compile( caseSensitive() ); } } /*! Returns TRUE if case sensitivity is enabled, otherwise FALSE. The default is TRUE. \sa setCaseSensitive() */ bool QRegExp3::caseSensitive() const { return eng->caseSensitive(); } /*! Sets case sensitive matching to \a sensitive. If \a sensitive is TRUE, <b>\\</b><b>.txt$</b> matches <tt>readme.txt</tt> but not <tt>README.TXT</tt>. \sa caseSensitive() */ void QRegExp3::setCaseSensitive( bool sensitive ) { if ( sensitive != eng->caseSensitive() ) compile( sensitive ); } #ifndef QT_NO_REGEXP_WILDCARD /*! Returns TRUE if wildcard mode is enabled, otherwise FALSE. The default is FALSE. \sa setWildcard() */ bool QRegExp3::wildcard() const { return priv->wc; } /*! Sets the wildcard mode for the regular expression. The default is FALSE. Setting \a wildcard to TRUE enables simple shell-like wildcard matching. (See <a href="#wildcard-matching">wildcard matching (globbing)</a>.) For example, <b>r*.txt</b> matches the string <tt>readme.txt</tt> in wildcard mode, but does not match <tt>readme</tt>. \sa wildcard() */ void QRegExp3::setWildcard( bool wildcard ) { if ( wildcard != priv->wc ) { priv->wc = wildcard; compile( caseSensitive() ); } } #endif /*! Returns TRUE if minimal (non-greedy) matching is enabled, otherwise returns FALSE. \sa setMinimal() */ bool QRegExp3::minimal() const { return priv->min; } /*! Enables or disables minimal matching. If \a minimal is FALSE, matching is greedy (maximal) which is the default. For example, suppose we have the input string "We must be \<b>bold\</b>, very \<b>bold\</b>!" and the pattern <b>\<b>.*\</b></b>. With the default greedy (maximal) matching, the match is "We must be <u>\<b>bold\</b>, very \<b>bold\</b></u>!". But with minimal (non-greedy) matching the first match is: "We must be <u>\<b>bold\</b></u>, very \<b>bold\</b>!" and the second match is "We must be \<b>bold\</b>, very <u>\<b>bold\</b></u>!". In practice we might use the pattern <b>\<b>[^\<]+\</b></b>, although this will still fail for nested tags. \sa minimal() */ void QRegExp3::setMinimal( bool minimal ) { priv->min = minimal; } /*! Returns TRUE if \a str is matched exactly by this regular expression otherwise it returns FALSE. You can determine how much of the string was matched by calling matchedLength(). For a given regexp string, R, <tt>match("R")</tt> is the equivalent of <tt>search("^R$")</tt> since match() effectively encloses the regexp in the start of string and end of string anchors. For example, if the regular expression is <b>blue</b>, then match() returns TRUE only for input <tt>blue</tt>. For inputs <tt>bluebell</tt>, <tt>blutak</tt> and <tt>lightblue</tt>, match() returns FALSE and matchedLength() will return 4, 3 and 0 respectively. \sa search() searchRev() QRegExpValidator */ bool QRegExp3::exactMatch( const QString& str ) { #ifndef QT_NO_REGEXP_CAPTURE priv->t = str; priv->capturedCache.clear(); #endif priv->captured = eng->match( str, 0, priv->min, TRUE ); if ( priv->captured[1] == (int) str.length() ) { return TRUE; } else { priv->captured.detach(); priv->captured[0] = 0; priv->captured[1] = eng->matchedLength(); return FALSE; } } /*! \overload This version does not set matchedLength(), capturedTexts() and friends. */ bool QRegExp3::exactMatch( const QString& str ) const { return eng->match(str, 0, priv->min, TRUE)[0] == 0 && eng->matchedLength() == (int) str.length(); } /*! \obsolete Attempts to match in \a str, starting from position \a index. Returns the position of the match, or -1 if there was no match. The length of the match is stored in \a *len, unless \a len is a null pointer. If \a indexIsStart is TRUE (the default), the position \a index in the string will match the start of string anchor, <b>^</b>, in the regexp, if present. Otherwise, position 0 in \a str will match. Use search() and matchedLength() instead of this function. If you really need the \a indexIsStart functionality, try this: \code QRegExp3 rx( "some pattern" ); int pos = rx.search( str.mid( index ) ); if ( pos != -1 ) pos += index; int len = rx.matchedLength(); \endcode */ #ifndef QT_NO_COMPAT int QRegExp3::match( const QString& str, int index, int *len, bool indexIsStart ) { int pos; if ( indexIsStart ) { pos = search( str.mid(index) ); if ( pos >= 0 ) { pos += index; if ( len != 0 ) *len = matchedLength(); } else { if ( len != 0 ) *len = 0; } } else { pos = search( str, index ); if ( len != 0 ) *len = matchedLength(); } return pos; } #endif /*! Attempts to find a match in \a str from position \a start (0 by default). If \a start is -1, the search starts at the last character; if -2, at the next to last character; etc. Returns the position of the first match, or -1 if there was no match. You might prefer to use QString::find(), QString::contains() or even QStringList::grep(). To replace matches use QString::replace(). Example: \code QString str = "offsets: 1.23 .50 71.00 6.00"; QRegExp3 rx( "\\d*\\.\\d+" ); // very simple floating point matching int count = 0; int pos = 0; while ( pos >= 0 ) { pos = rx.search( str, pos ); count++; } // pos will be 9, 14, 18 and finally 24; count will end up as 4. \endcode \sa searchRev() match() matchedLength() capturedTexts() */ // QChar versions #ifdef QCHAR_SUPPORT const QString makeString(const QChar *str) { // A sentinel value checked in case the QChar *ptr is never null terminated const uint MAXLENGTH=65535; const QChar *s=str; uint i=0; while(i < MAXLENGTH && *s != QChar::null) { i++;s++ ;} return QString(str,i); } int QRegExp3::search(const QChar *str,int start) { return search(makeString(str),start); } int QRegExp3::search(const QChar *str,int start) const { return search(makeString(str),start); } int QRegExp3::searchRev(const QChar *str,int start) { return searchRev(makeString(str),start); } int QRegExp3::searchRev(const QChar *str,int start) const { return searchRev(makeString(str),start); } bool QRegExp3::exactMatch(const QChar *str) { return exactMatch(makeString(str)); } bool QRegExp3::exactMatch(const QChar *str) const { return exactMatch(makeString(str)); } #endif // QCHAR_SUPPORT int QRegExp3::search( const QString& str, int start ) { if ( start < 0 ) start += str.length(); #ifndef QT_NO_REGEXP_CAPTURE priv->t = str; priv->capturedCache.clear(); #endif priv->captured = eng->match( str, start, priv->min, FALSE ); return priv->captured[0]; } /*! \overload This version does not set matchedLength(), capturedTexts() and friends. */ int QRegExp3::search( const QString& str, int start ) const { if ( start < 0 ) start += str.length(); return eng->match( str, start, priv->min, FALSE )[0]; } /*! Attempts to find a match backwards in \a str from position \a start. If \a start is -1 (the default), the search starts at the last character; if -2, at the next to last character; etc. Returns the position of the first match, or -1 if there was no match. You might prefer to use QString::findRev(). \sa search() matchedLength() capturedTexts() */ int QRegExp3::searchRev( const QString& str, int start ) { if ( start < 0 ) start += str.length(); #ifndef QT_NO_REGEXP_CAPTURE priv->t = str; priv->capturedCache.clear(); #endif if ( start < 0 || start > (int) str.length() ) { priv->captured.detach(); priv->captured.fill( -1 ); return -1; } while ( start >= 0 ) { priv->captured = eng->match( str, start, priv->min, TRUE ); if ( priv->captured[0] == start ) return start; start--; } return -1; } /*! \overload This version does not set matchedLength(), capturedText() and friends. */ int QRegExp3::searchRev( const QString& str, int start ) const { if ( start < 0 ) start += str.length(); if ( start < 0 || start > (int) str.length() ) return -1; while ( start >= 0 ) { if ( eng->match(str, start, priv->min, TRUE)[0] == start ) return start; start--; } return -1; } /*! Returns the length of the last matched string, or -1 if there was no match. \sa match() search() */ int QRegExp3::matchedLength() { return priv->captured[1]; } #ifndef QT_NO_REGEXP_CAPTURE /*! Returns a list of the captured text strings. The first string in the list is the entire matched string. Each subsequent list element contains a string that matched a (capturing) subexpression of the regexp. For example: \code QRegExp3 rx( "(\\d+)(\\s*)(cm|inch(es)?)" ); int pos = rx.search( "Length: 36 inches" ); QStringList list = rx.capturedTexts(); // list is now ( "36 inches", "36", " ", "inches", "es" ). \endcode The above example also captures elements that may be present but which we have no interest in. This problem can be solved by using non-capturing parenthesis: \code QRegExp3 rx( "(\\d+)(?:\\s*)(cm|inch(?:es)?)" ); int pos = rx.search( "Length: 36 inches" ); QStringList list = rx.capturedTexts(); // list is now ( "36 inches", "36", "inches" ). \endcode Some regexps can match an indeterminate number of times. For example if the input string is "Offsets: 12 14 99 231 7" and the regexp, <tt>rx</tt>, is <b>(</b><b>\\</b><b>d+)+</b>, we would hope to get a list of all the numbers matched. However, after calling <tt>rx.search(str)</tt>, capturedTexts() will return the list ( "12", "12" ), i.e. the entire match was "12" and the first subexpression matched was "12". The correct approach is to use cap() in a <a href="#cap_in_a_loop">loop</a>. The order of elements in the string list is as follows. The first element is the entire matching string. Each subsequent element corresponds to the next capturing open left parenthesis. Thus capturedTexts()[1] is the text of the first capturing parenthesis, capturedTexts()[2] is the text of the second and so on (corresponding to $1, $2 etc. in some other regexp languages). \sa cap() pos() */ QStringList QRegExp3::capturedTexts() { if ( priv->capturedCache.isEmpty() ) { for ( int i = 0; i < (int) priv->captured.size(); i += 2 ) { QString m; if ( priv->captured[i + 1] == 0 ) m = QString::fromLatin1( "" ); else if ( priv->captured[i] >= 0 ) m = priv->t.mid( priv->captured[i], priv->captured[i + 1] ); priv->capturedCache.append( m ); } priv->t = QString::null; } return priv->capturedCache; } /*! Returns the text captured by the \a nth subexpression. The entire match has index 0 and the parenthesised subexpressions have indices starting from 1 (excluding non-capturing parenthesis). \code QRegExp3 rxlen( "(\\d+)(?:\\s*)(cm|inch)" ); int pos = rxlen.search( "Length: 189cm" ); if ( pos > -1 ) { QString value = rxlen.cap( 1 ); // "189" QString unit = rxlen.cap( 2 ); // "cm" // ... } \endcode <a name="cap_in_a_loop"> Some patterns may lead to a number of matches which cannot be determined in advance, for example:</a> \code QRegExp3 rx( "(\\d+)" ); str = "Offsets: 12 14 99 231 7"; QStringList list; pos = 0; while ( pos >= 0 ) { pos = rx.search( str, pos ); if ( pos > -1 ) { list += rx.cap( 1 ); pos += rx.matchedLength(); } } // list contains: ( "12", "14", "99", "231", "7" ). \endcode The order of elements matched by cap() is as follows. The first element, cap( 0 ), is the entire matching string. Each subsequent element corresponds to the next capturing open left parenthesis. Thus cap( 1 ) is the text of the first capturing parenthesis, cap( 2 ) is the text of the second and so on. \sa search() pos() capturedTexts() */ QString QRegExp3::cap( int nth ) { if ( nth < 0 || nth >= (int) priv->captured.size() / 2 ) return QString::null; else return capturedTexts()[nth]; } /*! Returns the position of the \a nth captured text in the searched string. If \a nth is 0 (the default), pos() returns the position of the whole match. Example: \code QRegExp3 rx( "/([a-z]+)/([a-z]+)" ); rx.search( "Output /dev/null" ); // Returns 7 (position of /dev/null) rx.pos( 0 ); // Returns 7 (position of /dev/null) rx.pos( 1 ); // Returns 8 (position of dev) rx.pos( 2 ); // Returns 12 (position of null) \endcode Note that pos() returns -1 for zero-length matches. (For example, if cap(4) would return an empty string, pos(4) returns -1.) This is due to an implementation tradeoff. \sa capturedTexts() cap() */ int QRegExp3::pos( int nth ) { if ( nth < 0 || nth >= (int) priv->captured.size() / 2 ) return -1; else return priv->captured[2 * nth]; } #endif void QRegExp3::compile( bool caseSensitive ) { derefEngine( eng, priv->rxpattern ); #ifndef QT_NO_REGEXP_WILDCARD if ( priv->wc ) priv->rxpattern = wc2rx( priv->pattern ); else #endif priv->rxpattern = priv->pattern.isNull() ? QString::fromLatin1( "" ) : priv->pattern; eng = newEngine( priv->rxpattern, caseSensitive ); #ifndef QT_NO_REGEXP_CAPTURE priv->t = QString::null; priv->capturedCache.clear(); #endif priv->captured.detach(); priv->captured.fill( -1, 2 + 2 * eng->numCaptures() ); } diff --git a/noncore/apps/tinykate/libkate/qt3back/qregexp3.h b/noncore/apps/tinykate/libkate/qt3back/qregexp3.h index 5b75131..fd6bc78 100644 --- a/noncore/apps/tinykate/libkate/qt3back/qregexp3.h +++ b/noncore/apps/tinykate/libkate/qt3back/qregexp3.h @@ -1,111 +1,111 @@ /**************************************************************************** ** $Id$ ** ** Definition of QRegExp class ** ** Created : 950126 ** ** Copyright (C) 1992-2000 Trolltech AS. All rights reserved. ** ** This file is part of the tools module of the Qt GUI Toolkit. ** ** This file may be distributed under the terms of the Q Public License ** as defined by Trolltech AS of Norway and appearing in the file ** LICENSE.QPL included in the packaging of this file. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition ** licenses may use this file in accordance with the Qt Commercial License ** Agreement provided with the Software. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for ** information about Qt Commercial License Agreements. ** See http://www.trolltech.com/qpl/ for QPL licensing information. ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #ifndef QREGEXP3_H #define QREGEXP3_H #ifndef QT_H #include "qstringlist.h" #endif // QT_H -#if QT_VERSION >=300 +#if QT_VERSION >= 0x030000 #include <qregexp.h> #else class QRegExpEngine; struct QRegExpPrivate; class Q_EXPORT QRegExp3 { public: QRegExp3(); QRegExp3( const QString& pattern, bool caseSensitive = TRUE, bool wildcard = FALSE ); QRegExp3( const QRegExp3& rx ); ~QRegExp3(); QRegExp3& operator=( const QRegExp3& rx ); bool operator==( const QRegExp3& rx ) const; bool operator!=( const QRegExp3& rx ) const { return !operator==( rx ); } bool isEmpty() const; bool isValid() const; QString pattern() const; void setPattern( const QString& pattern ); bool caseSensitive() const; void setCaseSensitive( bool sensitive ); #ifndef QT_NO_REGEXP_WILDCARD bool wildcard() const; void setWildcard( bool wildcard ); #endif bool minimal() const; void setMinimal( bool minimal ); bool exactMatch( const QString& str ); bool exactMatch( const QString& str ) const; #ifndef QT_NO_COMPAT int match( const QString& str, int index, int *len = 0, bool indexIsStart = TRUE ); #endif int search( const QString& str, int start = 0 ); int search( const QString& str, int start = 0 ) const; // QChar versions #ifdef QCHAR_SUPPORT int search(const QChar *str,int start=0); int search(const QChar *str,int start=0) const; int searchRev(const QChar *str,int start=-1); int searchRev(const QChar *str,int start=-1) const ; bool exactMatch(const QChar *str); bool exactMatch(const QChar *str) const; // end QChar versions #endif int searchRev( const QString& str, int start = -1 ); int searchRev( const QString& str, int start = -1 ) const; int matchedLength(); #ifndef QT_NO_REGEXP_CAPTURE QStringList capturedTexts(); QString cap( int nth = 0 ); int pos( int nth = 0 ); #endif private: void compile( bool caseSensitive ); QRegExpEngine *eng; QRegExpPrivate *priv; }; -#endif // QT_VERSION >= 300 +#endif // QT_VERSION >= 0x030000 #endif // QREGEXP_H diff --git a/noncore/apps/zsafe/shadedlistitem.cpp b/noncore/apps/zsafe/shadedlistitem.cpp index 72c6261..7f340f9 100644 --- a/noncore/apps/zsafe/shadedlistitem.cpp +++ b/noncore/apps/zsafe/shadedlistitem.cpp @@ -1,69 +1,69 @@ /* * shadedlistitem.cpp * * (c) 2003 by Jeremy Bowman <jmbowman@alum.mit.edu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #include "zsafe.h" #include "shadedlistitem.h" ShadedListItem::ShadedListItem(int index, QListViewItem *parent) : QListViewItem(parent) { oddRow = (index % 2 != 0); } ShadedListItem::ShadedListItem(int index, QListView *parent) : QListViewItem(parent), lv(parent) { oddRow = (index % 2 != 0); } ShadedListItem::ShadedListItem(int index, QListView *parent, QListViewItem *after) : QListViewItem(parent, after), lv(parent) { oddRow = (index % 2 != 0); } ShadedListItem::ShadedListItem(int index, QListView *parent, QString label1, QString label2, QString label3) : QListViewItem(parent, label1, label2, label3), lv(parent) { oddRow = (index % 2 != 0); } ShadedListItem::ShadedListItem(int index, QListView *parent, QListViewItem *after, QString label1, QString label2, QString label3) : QListViewItem(parent, after, label1, label2, label3), lv(parent) { oddRow = (index % 2 != 0); } ShadedListItem::~ShadedListItem() { } void ShadedListItem::paintCell(QPainter *p, const QColorGroup &cg, int column, int width, int alignment) { QColorGroup colors(cg); -#if QT_VERSION >=300 +#if QT_VERSION >= 0x030000 const QColorGroup::ColorRole crole = QColorGroup::Base; // const QWidget::BackgroundMode bgmode = lv->viewport()->backgroundMode(); // const QColorGroup::ColorRole crole = QPalette::backgroundRoleFromMode(bgmode); #else const QColorGroup::ColorRole crole = QColorGroup::Base; #endif if (oddRow) { colors.setColor(crole, *ZSafe::oddRowColor); } else { colors.setColor(crole, *ZSafe::evenRowColor); } QListViewItem::paintCell(p, colors, column, width, alignment); } diff --git a/noncore/net/wellenreiter/gui/configwindow.cpp b/noncore/net/wellenreiter/gui/configwindow.cpp index 1670f93..9ec5af9 100644 --- a/noncore/net/wellenreiter/gui/configwindow.cpp +++ b/noncore/net/wellenreiter/gui/configwindow.cpp @@ -1,496 +1,496 @@ /********************************************************************** ** Copyright (C) 2002-2004 Michael 'Mickey' Lauer. All rights reserved. ** ** This file is part of Wellenreiter II. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** **********************************************************************/ /* LOCAL */ #include "configwindow.h" #include "mainwindow.h" #include "protolistview.h" /* OPIE */ #include <opie2/onetwork.h> #ifdef QWS #include <opie2/oapplication.h> #include <opie2/oconfig.h> #include <opie2/odevice.h> #include <opie2/odebug.h> using namespace Opie::Core; using namespace Opie::Net; #endif /* QT */ #include <qapplication.h> #include <qcheckbox.h> #include <qcombobox.h> #include <qfile.h> #include <qlineedit.h> #include <qlayout.h> #include <qmap.h> #include <qpushbutton.h> #include <qradiobutton.h> #include <qspinbox.h> #include <qtabwidget.h> #include <qtoolbutton.h> #include <qtextstream.h> /* STD */ #include <assert.h> WellenreiterConfigWindow* WellenreiterConfigWindow::_instance = 0; WellenreiterConfigWindow::WellenreiterConfigWindow( QWidget * parent, const char * name, WFlags f ) :WellenreiterConfigBase( parent, name, true, f ) { _devicetype[ "cisco" ] = DEVTYPE_CISCO; _devicetype[ "wlan-ng" ] = DEVTYPE_WLAN_NG; _devicetype[ "hostap" ] = DEVTYPE_HOSTAP; _devicetype[ "orinoco" ] = DEVTYPE_ORINOCO; _devicetype[ "<manual>" ] = DEVTYPE_MANUAL; _devicetype[ "<file>" ] = DEVTYPE_FILE; // gather possible interface names from ONetwork ONetwork* net = ONetwork::instance(); ONetwork::InterfaceIterator it = net->iterator(); while ( it.current() ) { if ( it.current()->isWireless() ) interfaceName->insertItem( it.current()->name() ); ++it; } load(); #ifdef Q_WS_X11 // We're on X11: adding an Ok-Button for the Dialog here QPushButton* okButton = new QPushButton( "ok", this ); okButton->show(); WellenreiterConfigBaseLayout->addWidget( okButton, 0, 3 ); //FIXME: rename this in configbase.ui connect( okButton, SIGNAL( clicked() ), this, SLOT( accept() ) ); #endif WellenreiterConfigWindow::_instance = this; connect( deviceType, SIGNAL( activated(int) ), this, SLOT( changedDeviceType(int) ) ); connect( newNetworkAction, SIGNAL( activated(int) ), this, SLOT( changedNetworkAction(int) ) ); connect( newClientAction, SIGNAL( activated(int) ), this, SLOT( changedClientAction(int) ) ); connect( newStationAction, SIGNAL( activated(int) ), this, SLOT( changedStationAction(int) ) ); connect( getCaptureFileName, SIGNAL( clicked() ), this, SLOT( getCaptureFileNameClicked() ) ); // make the checkbox 'channelAll' control all other channels connect( channelAll, SIGNAL( stateChanged(int) ), this, SLOT( channelAllClicked(int) ) ); connect( autodetect, SIGNAL( clicked() ), this, SLOT( performAutodetection() ) ); // hide tab4 (parse) until Wellenreiter 1.2 tab->removePage( tab_4 ); }; void WellenreiterConfigWindow::accept() { save(); QDialog::accept(); } WellenreiterConfigWindow::~WellenreiterConfigWindow() { } void WellenreiterConfigWindow::performAutodetection() { //TODO: insert modal splash screen here // and sleep a second, so that it looks // like we're actually doing something fancy... ;-) odebug << "WellenreiterConfigWindow::performAutodetection()" << oendl; // try to guess device type QFile m( "/proc/modules" ); if ( m.open( IO_ReadOnly ) ) { int devicetype(0); QString line; QTextStream modules( &m ); while( !modules.atEnd() && !devicetype ) { modules >> line; if ( line.contains( "cisco" ) ) devicetype = DEVTYPE_CISCO; else if ( line.contains( "hostap" ) ) devicetype = DEVTYPE_HOSTAP; else if ( line.contains( "prism" ) ) devicetype = DEVTYPE_WLAN_NG; else if ( line.contains( "orinoco" ) ) devicetype = DEVTYPE_ORINOCO; } if ( devicetype ) { deviceType->setCurrentItem( devicetype ); _guess = devicetype; odebug << "Wellenreiter: guessed device type to be #" << devicetype << "" << oendl; } } } int WellenreiterConfigWindow::driverType() const { QString name = deviceType->currentText(); if ( _devicetype.contains( name ) ) { return _devicetype[name]; } else { return 0; } }; int WellenreiterConfigWindow::hoppingInterval() const { return hopInterval->cleanText().toInt(); } bool WellenreiterConfigWindow::usePrismHeader() const { return prismHeader->isChecked(); } bool WellenreiterConfigWindow::isChannelChecked( int channel ) const { switch ( channel ) { case 1: return channel1->isOn(); case 2: return channel2->isOn(); case 3: return channel3->isOn(); case 4: return channel4->isOn(); case 5: return channel5->isOn(); case 6: return channel6->isOn(); case 7: return channel7->isOn(); case 8: return channel8->isOn(); case 9: return channel9->isOn(); case 10: return channel10->isOn(); case 11: return channel11->isOn(); case 12: return channel12->isOn(); case 13: return channel13->isOn(); case 14: return channel14->isOn(); default: return false; } } void WellenreiterConfigWindow::changedDeviceType(int t) { if ( t != DEVTYPE_FILE ) return; QString name = ( (WellenreiterMainWindow*) qApp->mainWidget() )->getFileName(false); if ( !name.isEmpty() && QFile::exists( name ) ) { interfaceName->insertItem( name ); interfaceName->setCurrentItem( interfaceName->count()-1 ); } else { deviceType->setCurrentItem( _guess ); } } void WellenreiterConfigWindow::synchronizeActionsAndScripts() { if ( newNetworkAction->currentItem() == 4 ) newNetworkScript->show(); else newNetworkScript->hide(); if ( newClientAction->currentItem() == 4 ) newClientScript->show(); else newClientScript->hide(); if ( newStationAction->currentItem() == 4 ) newStationScript->show(); else newStationScript->hide(); //newNetworkScript->setEnabled( newNetworkAction->currentItem() == 4 ); //newClientScript->setEnabled( newClientAction->currentItem() == 4 ); //newStationScript->setEnabled( newStationAction->currentItem() == 4 ); } void WellenreiterConfigWindow::changedNetworkAction(int ) { synchronizeActionsAndScripts(); } void WellenreiterConfigWindow::changedClientAction(int ) { synchronizeActionsAndScripts(); } void WellenreiterConfigWindow::changedStationAction(int ) { synchronizeActionsAndScripts(); } void WellenreiterConfigWindow::getCaptureFileNameClicked() { QString name = ( (WellenreiterMainWindow*) qApp->mainWidget() )->getFileName(true); odebug << "name = " << name << "" << oendl; if ( !name.isEmpty() ) { captureFileName->setText( name ); } } void WellenreiterConfigWindow::channelAllClicked(int state) { bool b = state; channel1->setChecked( b ); channel2->setChecked( b ); channel3->setChecked( b ); channel4->setChecked( b ); channel5->setChecked( b ); channel6->setChecked( b ); channel7->setChecked( b ); channel8->setChecked( b ); channel9->setChecked( b ); channel10->setChecked( b ); channel11->setChecked( b ); channel12->setChecked( b ); channel13->setChecked( b ); channel14->setChecked( b ); } bool WellenreiterConfigWindow::useGPS() const { return enableGPS->isChecked(); } const QString WellenreiterConfigWindow::gpsHost() const { return useGPS() ? gpsdHost->currentText() : QString::null; } int WellenreiterConfigWindow::gpsPort() const { return useGPS() ? gpsdPort->value() : -1; } void WellenreiterConfigWindow::performAction( const QString& type, const QString& essid, const QString& mac, bool wep, int channel, int /* signal */ /* , const GpsLocation& loc */ ) { int action; QString script; if ( type == "network" ) { action = newNetworkAction->currentItem(); script = newNetworkScript->text(); } else if ( type == "managed" || type == "adhoc" ) { action = newClientAction->currentItem(); script = newClientScript->text(); } else if ( type == "station" ) { action = newStationAction->currentItem(); script = newStationScript->text(); } else { owarn << "WellenreiterConfigWindow::performAction(): unknown type '" << type << "'" << oendl; return; } odebug << "for event '" << type << "' I'm going to perform action " << action << " (script='" << script << "')" << oendl; switch( action ) { case 0: /* Ignore */ return; case 1: /* Play Alarm */ ODevice::inst()->playAlarmSound(); return; case 2: /* Play Click */ ODevice::inst()->playTouchSound(); return; case 3: /* Blink LED */ break; //FIXME: Implement this case 4: /* Run Script */ { /** * * Script Substitution Information: * * $SSID = SSID * $MAC = MAC * $WEP = Wep * $CHAN = Channel * **/ script = script.replace( QRegExp( "$SSID" ), essid ); script = script.replace( QRegExp( "$MAC" ), mac ); script = script.replace( QRegExp( "$WEP" ), wep ? QString( "true" ) : QString( "false" ) ); script = script.replace( QRegExp( "$CHAN" ), QString::number( channel ) ); odebug << "going to call script '" << script << "'" << oendl; ::system( script ); odebug << "script returned." << oendl; return; } default: assert( false ); } } void WellenreiterConfigWindow::load() { #ifdef Q_WS_X11 #warning Persistent Configuration not yet implemented for standalone X11 build performAutodetection(); #else odebug << "loading configuration settings..." << oendl; /* This is dumb monkey typing stuff... We _need_ to do this automatically! */ OConfig* c = oApp->config(); c->setGroup( "Interface" ); QString interface = c->readEntry( "name", "<none>" ); if ( interface != "<none>" ) { -#if QT_VERSION < 300 +#if QT_VERSION < 0x030000 interfaceName->insertItem( interface, 0 ); interfaceName->setCurrentItem( 0 ); #else interfaceName->setCurrentText( interface ); #endif QString device = c->readEntry( "type", "<select>" ); -#if QT_VERSION < 300 +#if QT_VERSION < 0x030000 for ( int i = 0; i < deviceType->count(); ++i ) { if ( deviceType->text( i ) == device ) { deviceType->setCurrentItem( i ); break; } } #else deviceType->setCurrentText( device ); #endif } else { performAutodetection(); } prismHeader->setChecked( c->readBoolEntry( "prism", false ) ); hopChannels->setChecked( c->readBoolEntry( "hop", true ) ); hopInterval->setValue( c->readNumEntry( "interval", 250 ) ); adaptiveHopping->setChecked( c->readBoolEntry( "adaptive", true ) ); c->setGroup( "Capture" ); writeCaptureFile->setChecked( c->readBoolEntry( "writeCaptureFile", true ) ); captureFileName->setEnabled( writeCaptureFile->isChecked() ); getCaptureFileName->setEnabled( writeCaptureFile->isChecked() ); parsePackets->setEnabled( writeCaptureFile->isChecked() ); captureFileName->setText( c->readEntry( "filename", "/tmp/capture" ) ); hexViewBufferUnlimited->setChecked( c->readBoolEntry( "hexViewBufferUnlimited", true ) ); hexViewBufferLimited->setChecked( !c->readBoolEntry( "hexViewBufferUnlimited", true ) ); hexViewBufferSize->setValue( c->readNumEntry( "hexViewBufferSize", 2000 ) ); c->setGroup( "UI" ); lookupVendor->setChecked( c->readBoolEntry( "lookupVendor", true ) ); openTree->setChecked( c->readBoolEntry( "openTree", true ) ); disablePM->setChecked( c->readBoolEntry( "disablePM", true ) ); newNetworkAction->setCurrentItem( c->readNumEntry( "newNetworkAction", 1 ) ); // Default: Play Alarm newNetworkScript->setText( c->readEntry( "newNetworkScript", "" ) ); newClientAction->setCurrentItem( c->readNumEntry( "newClientAction", 2 ) ); // Default: Play Click newClientScript->setText( c->readEntry( "newClientScript", "" ) ); newStationAction->setCurrentItem( c->readNumEntry( "newStationAction", 2 ) ); // Default: Play Click newStationScript->setText( c->readEntry( "newStationScript", "" ) ); synchronizeActionsAndScripts(); // needed for showing/hiding the script QLineEdit on demand c->setGroup( "GPS" ); enableGPS->setChecked( c->readBoolEntry( "use", false ) ); -#if QT_VERSION < 300 +#if QT_VERSION < 0x030000 gpsdHost->insertItem( c->readEntry( "host", "localhost" ), 0 ); gpsdHost->setCurrentItem( 0 ); #else gpsdHost->setCurrentText( c->readEntry( "host", "localhost" ) ); #endif gpsdPort->setValue( c->readNumEntry( "port", 2947 ) ); startGPS->setChecked( c->readBoolEntry( "start", false ) ); commandGPS->setText( c->readEntry( "command", "gpsd -p /dev/ttyS3 -s 57600" ) ); #endif } void WellenreiterConfigWindow::save() { #ifdef Q_WS_X11 #warning Persistent Configuration not yet implemented for standalone X11 build #else odebug << "saving configuration settings..." << oendl; /* This is dumb monkey typing stuff... We _need_ to do this automatically! */ OConfig* c = oApp->config(); c->setGroup( "Interface" ); c->writeEntry( "name", interfaceName->currentText() ); c->writeEntry( "type", deviceType->currentText() ); c->writeEntry( "prism", prismHeader->isChecked() ); c->writeEntry( "hop", hopChannels->isChecked() ); c->writeEntry( "interval", hopInterval->value() ); c->writeEntry( "adaptive", adaptiveHopping->isChecked() ); c->setGroup( "Capture" ); c->writeEntry( "writeCaptureFile", writeCaptureFile->isChecked() ); c->writeEntry( "filename", captureFileName->text() ); c->writeEntry( "hexViewBufferUnlimited", hexViewBufferUnlimited->isChecked() ); c->writeEntry( "hexViewBufferSize", hexViewBufferSize->value() ); c->setGroup( "UI" ); c->writeEntry( "lookupVendor", lookupVendor->isChecked() ); c->writeEntry( "openTree", openTree->isChecked() ); c->writeEntry( "disablePM", disablePM->isChecked() ); c->writeEntry( "newNetworkAction", newNetworkAction->currentItem() ); c->writeEntry( "newNetworkScript", newNetworkScript->text() ); c->writeEntry( "newClientAction", newClientAction->currentItem() ); c->writeEntry( "newClientScript", newClientScript->text() ); c->writeEntry( "newStationAction", newStationAction->currentItem() ); c->writeEntry( "newStationScript", newStationScript->text() ); c->setGroup( "GPS" ); c->writeEntry( "use", enableGPS->isChecked() ); c->writeEntry( "host", gpsdHost->currentText() ); c->writeEntry( "port", gpsdPort->value() ); c->writeEntry( "start", startGPS->isChecked() ); c->writeEntry( "command", commandGPS->text() ); c->write(); #endif } int WellenreiterConfigWindow::hexViewBuffer() const { return hexViewBufferUnlimited->isChecked() ? -1 : hexViewBufferSize->value(); } diff --git a/noncore/settings/appearance2/appearance.cpp b/noncore/settings/appearance2/appearance.cpp index 9638686..088171c 100644 --- a/noncore/settings/appearance2/appearance.cpp +++ b/noncore/settings/appearance2/appearance.cpp @@ -1,892 +1,892 @@ /* � � � � � � � � This file is part of the OPIE Project Copyright (c) 2002 Trolltech AS <info@trolltech.com> =. Copyright (c) 2002 Dan Williams <williamsdr@acm.org> � � � � � � �.=l. Copyright (c) 2002 Robert Griebl <sandman@handhelds.org> � � � � � �.>+-= �_;:, � � .> � �:=|. This file is free software; you can .> <`_, � > �. � <= redistribute it and/or modify it under :`=1 )Y*s>-.-- � : the terms of the GNU General Public .="- .-=="i, � � .._ License as published by the Free Software �- . � .-<_> � � .<> Foundation; either version 2 of the License, � � �._= =} � � � : or (at your option) any later version. � � .%`+i> � � � _;_. � � .i_,=:_. � � �-<s. This file is distributed in the hope that � � �+ �. �-:. � � � = it will be useful, but WITHOUT ANY WARRANTY; � � : .. � �.:, � � . . . without even the implied warranty of � � =_ � � � �+ � � =;=|` MERCHANTABILITY or FITNESS FOR A � _.=:. � � � : � �:=>`: PARTICULAR PURPOSE. See the GNU General ..}^=.= � � � = � � � ; Public License for more details. ++= � -. � � .` � � .: �: � � = �...= . :.=- You should have received a copy of the GNU �-. � .:....=;==+<; General Public License along with this file; � -_. . . � )=. �= see the file COPYING. If not, write to the � � -- � � � �:-=` Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "appearance.h" #include "editScheme.h" #include "stylelistitem.h" #include "decolistitem.h" #include "colorlistitem.h" #include "exceptlistitem.h" #include "sample.h" /* OPIE */ #include <opie2/odevice.h> #include <opie2/ofiledialog.h> #include <opie2/otabwidget.h> #include <opie2/odebug.h> #include <qpe/config.h> #include <qpe/global.h> #include <qpe/qpeapplication.h> #include <qpe/qpemessagebox.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/qpestyle.h> #include <qpe/lightstyle.h> #include <qpe/styleinterface.h> /* QT */ #include <qbuttongroup.h> #include <qcheckbox.h> #include <qcombobox.h> #include <qdialog.h> #include <qdir.h> #include <qlabel.h> #include <qlayout.h> #include <qlineedit.h> #include <qlistbox.h> #include <qmessagebox.h> #include <qpushbutton.h> #include <qradiobutton.h> -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 #include <qstylefactory.h> #endif #include <qtoolbutton.h> #include <qwindowsstyle.h> #include <qlistview.h> #include <qheader.h> #include <qvbox.h> #include <qwhatsthis.h> using namespace Opie; using namespace Opie::Ui; using namespace Opie::Core; class DefaultWindowDecoration : public WindowDecorationInterface { public: DefaultWindowDecoration() : ref(0) {} QString name() const { return "Default"; } QPixmap icon() const { return QPixmap(); } QRESULT queryInterface( const QUuid &uuid, QUnknownInterface **iface ) { *iface = 0; if ( uuid == IID_QUnknown ) *iface = this; else if ( uuid == IID_WindowDecoration ) *iface = this; if ( *iface ) (*iface)->addRef(); return QS_OK; } Q_REFCOUNT private: ulong ref; }; QWidget *Appearance::createStyleTab ( QWidget *parent, Config &cfg ) { QWidget* tab = new QWidget( parent, "StyleTab" ); QVBoxLayout* vertLayout = new QVBoxLayout( tab, 3, 3 ); m_style_list = new QListBox( tab, "m_style_list" ); vertLayout->addWidget( m_style_list ); QWhatsThis::add( m_style_list, tr( "Styles control the way items such as buttons and scroll bars appear in all applications.\n\nClick here to select an available style." ) ); m_style_settings = new QPushButton ( tr( "Settings..." ), tab ); connect ( m_style_settings, SIGNAL( clicked()), this, SLOT( styleSettingsClicked())); vertLayout-> addWidget ( m_style_settings ); QWhatsThis::add( m_style_settings, tr( "Click here to configure the currently selected style.\n\nNote: This option is not available for all styles." ) ); QString s = cfg. readEntry ( "Style", "Light" ); -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 m_style_list->insertStringList(QStyleFactory::styles()); #else m_style_list-> insertItem ( new StyleListItem ( "Windows", new QWindowsStyle ( ))); m_style_list-> insertItem ( new StyleListItem ( "Light", new LightStyle ( ))); m_style_list-> insertItem ( new StyleListItem ( "QPE", new QPEStyle ( ))); #endif { QString path = QPEApplication::qpeDir ( ); path.append( "/plugins/styles/" ); QStringList sl = QDir ( path, "lib*.so" ). entryList ( ); for ( QStringList::Iterator it = sl. begin ( ); it != sl. end ( ); ++it ) { QString libstr = path; libstr.append( "/" ); libstr.append( *it ); QLibrary *lib = new QLibrary ( libstr ); StyleInterface *iface; if (( lib-> queryInterface ( IID_Style, (QUnknownInterface **) &iface ) == QS_OK ) && iface ) { StyleListItem *slit = new StyleListItem ( lib, iface ); m_style_list-> insertItem ( slit ); if ( slit-> key ( ) == s ) m_style_list-> setCurrentItem ( slit ); } else delete lib; } } m_original_style = m_style_list-> currentItem ( ); styleClicked ( m_original_style ); connect( m_style_list, SIGNAL( highlighted(int) ), this, SLOT( styleClicked(int) ) ); return tab; } QWidget *Appearance::createDecoTab ( QWidget *parent, Config &cfg ) { QWidget* tab = new QWidget( parent, "DecoTab" ); QVBoxLayout* vertLayout = new QVBoxLayout( tab, 3, 3 ); m_deco_list = new QListBox( tab, "m_deco_list" ); vertLayout->addWidget( m_deco_list ); QWhatsThis::add( m_deco_list, tr( "Window decorations control the way the application title bar and its buttons appear.\n\nClick here to select an available decoration." ) ); QString s = cfg. readEntry ( "Decoration", "libflat.so" ); m_deco_list-> insertItem ( new DecoListItem ( "QPE" )); { QString path = QPEApplication::qpeDir(); path.append( "/plugins/decorations/" ); QStringList sl = QDir ( path, "lib*.so" ). entryList ( ); for ( QStringList::Iterator it = sl. begin ( ); it != sl. end ( ); ++it ) { QString libstr = path; libstr.append( "/" ); libstr.append( *it ); QLibrary *lib = new QLibrary ( libstr ); WindowDecorationInterface *iface; if ( lib-> queryInterface ( IID_WindowDecoration, (QUnknownInterface **) &iface ) == QS_OK ) { DecoListItem *dlit = new DecoListItem ( lib, iface ); m_deco_list-> insertItem ( dlit ); if ( dlit-> key ( ) == s ) m_deco_list-> setCurrentItem ( dlit ); } else delete lib; } } m_original_deco = m_deco_list-> currentItem ( ); if ( m_deco_list-> currentItem ( ) < 0 ) m_deco_list-> setCurrentItem ( 0 ); decoClicked ( m_original_deco ); connect( m_deco_list, SIGNAL( highlighted(int) ), this, SLOT( decoClicked(int) ) ); return tab; } QWidget *Appearance::createFontTab ( QWidget *parent, Config &cfg ) { QString familyStr = cfg. readEntry ( "FontFamily", "Helvetica" ); QString styleStr = cfg. readEntry ( "FontStyle", "Regular" ); int size = cfg. readNumEntry ( "FontSize", 10 ); m_fontselect = new OFontSelector ( false, parent, "FontTab" ); m_fontselect-> setSelectedFont ( familyStr, styleStr, size ); QWhatsThis::add( m_fontselect, tr( "Select the desired name, style and size of the default font applications will use." ) ); connect( m_fontselect, SIGNAL( fontSelected(const QFont&)), this, SLOT( fontClicked(const QFont&))); return m_fontselect; } QWidget *Appearance::createColorTab ( QWidget *parent, Config &cfg ) { QWidget *tab = new QWidget( parent, "ColorTab" ); QGridLayout *gridLayout = new QGridLayout( tab, 0, 0, 3, 3 ); gridLayout->setRowStretch ( 3, 10 ); m_color_list = new QListBox ( tab ); gridLayout->addMultiCellWidget ( m_color_list, 0, 3, 0, 0 ); connect( m_color_list, SIGNAL( highlighted(int) ), this, SLOT( colorClicked(int) ) ); QWhatsThis::add( m_color_list, tr( "Color schemes are a collection of colors which are used for various parts of the display.\n\nClick here to select an available scheme." ) ); m_color_list-> insertItem ( new ColorListItem ( tr( "Current scheme" ), cfg )); QString path = QPEApplication::qpeDir ( ); path.append( "/etc/colors/" ); QStringList sl = QDir ( path ). entryList ( "*.scheme" ); for ( QStringList::Iterator it = sl. begin ( ); it != sl. end ( ); ++it ) { QString name = (*it). left ((*it). find ( ".scheme" )); QString pathstr = path; pathstr.append( *it ); Config config ( pathstr, Config::File ); config. setGroup ( "Colors" ); m_color_list-> insertItem ( new ColorListItem ( name, config )); } m_color_list-> setCurrentItem ( 0 ); QPushButton* tempButton = new QPushButton( tab, "editSchemeButton" ); tempButton->setText( tr( "Edit..." ) ); connect( tempButton, SIGNAL( clicked() ), this, SLOT( editSchemeClicked() ) ); gridLayout->addWidget( tempButton, 0, 1 ); QWhatsThis::add( tempButton, tr( "Click here to change the colors in the current color scheme." ) ); tempButton = new QPushButton( tab, "deleteSchemeButton" ); tempButton->setText( tr( "Delete" ) ); connect( tempButton, SIGNAL( clicked() ), this, SLOT( deleteSchemeClicked() ) ); gridLayout->addWidget( tempButton, 1, 1 ); QWhatsThis::add( tempButton, tr( "Click here to delete the color scheme selected in the list to the left." ) ); tempButton = new QPushButton( tab, "saveSchemeButton" ); tempButton->setText( tr( "Save" ) ); connect( tempButton, SIGNAL( clicked() ), this, SLOT( saveSchemeClicked() ) ); gridLayout->addWidget( tempButton, 2, 1 ); QWhatsThis::add( tempButton, tr( "Click here to name and save the current color scheme." ) ); return tab; } QWidget *Appearance::createAdvancedTab ( QWidget *parent, Config &cfg ) { QWidget *tab = new QWidget ( parent ); QVBoxLayout *vertLayout = new QVBoxLayout( tab, 3, 3 ); QGridLayout *lay = new QGridLayout ( vertLayout, 0, 0, 3, 0 ); m_force = new QCheckBox ( tr( "Force styling for all applications." ), tab ); m_force-> setChecked ( cfg. readBoolEntry ( "ForceStyle" )); lay-> addMultiCellWidget ( m_force, 0, 0, 0, 1 ); QWhatsThis::add( m_force, tr( "Click here to allow all applications to use global appearance settings." ) ); QLabel *l = new QLabel ( tab ); l-> setText ( QString ( "<p>%1</p>" ). arg ( tr( "Disable styling for these applications ( <b>*</b> can be used as a wildcard):" ))); lay-> addMultiCellWidget ( l, 1, 1, 0, 1 ); QWhatsThis::add( l, tr( "If some applications do not display correctly with the global appearance settings, certain features can be turned off for that application.\n\nThis area allows you to select an application and which settings you wish to disable." ) ); m_except = new QListView ( tab ); m_except-> addColumn ( Resource::loadIconSet ( "appearance" ), "", 24 ); m_except-> addColumn ( Resource::loadIconSet ( "font" ), "", 24 ); m_except-> addColumn ( Resource::loadIconSet ( "appearance/deco" ), "", 24 ); m_except-> addColumn ( tr( "Binary file(s)" )); m_except-> setColumnAlignment ( 0, AlignCenter ); m_except-> setColumnAlignment ( 1, AlignCenter ); m_except-> setColumnAlignment ( 2, AlignCenter ); m_except-> setAllColumnsShowFocus ( true ); m_except-> setMinimumHeight ( 30 ); m_except-> header ( )-> setClickEnabled ( false ); m_except-> header ( )-> setResizeEnabled ( false ); m_except-> header ( )-> setMovingEnabled ( false ); m_except-> setSorting ( -1 ); lay-> addMultiCellWidget ( m_except, 2, 6, 0, 0 ); QWhatsThis::add( m_except, tr( "If some applications do not display correctly with the global appearance settings, certain features can be turned off for that application.\n\nThis area allows you to select an application and which settings you wish to disable." ) ); connect ( m_except, SIGNAL( clicked(QListViewItem*,const QPoint&,int)), this, SLOT( clickedExcept(QListViewItem*,const QPoint&,int))); QToolButton *tb = new QToolButton ( tab ); tb-> setIconSet ( Resource::loadIconSet ( "appearance/add" )); tb-> setFocusPolicy ( QWidget::StrongFocus ); lay-> addWidget ( tb, 2, 1 ); connect ( tb, SIGNAL( clicked()), this, SLOT( addExcept())); QWhatsThis::add( tb, tr( "Click here to add an application to the list above." ) ); tb = new QToolButton ( tab ); tb-> setIconSet ( Resource::loadIconSet ( "editdelete" )); tb-> setFocusPolicy ( QWidget::StrongFocus ); lay-> addWidget ( tb, 3, 1 ); connect ( tb, SIGNAL( clicked()), this, SLOT( delExcept())); QWhatsThis::add( tb, tr( "Click here to delete the currently selected application." ) ); tb = new QToolButton ( tab ); tb-> setIconSet ( Resource::loadIconSet ( "up" )); tb-> setFocusPolicy ( QWidget::StrongFocus ); lay-> addWidget ( tb, 4, 1 ); connect ( tb, SIGNAL( clicked()), this, SLOT( upExcept())); QWhatsThis::add( tb, tr( "Click here to move the currently selected application up in the list." ) ); tb = new QToolButton ( tab ); tb-> setIconSet ( Resource::loadIconSet ( "down" )); tb-> setFocusPolicy ( QWidget::StrongFocus ); lay-> addWidget ( tb, 5, 1 ); connect ( tb, SIGNAL( clicked()), this, SLOT( downExcept())); QWhatsThis::add( tb, tr( "Click here to move the currently selected application down in the list." ) ); lay-> setRowStretch ( 6, 10 ); lay-> setColStretch ( 0, 10 ); QStringList sl = cfg. readListEntry ( "NoStyle", ';' ); QListViewItem *lvit = 0; for ( QStringList::Iterator it = sl. begin ( ); it != sl. end ( ); ++it ) { int fl = ( *it ). left ( 1 ). toInt ( 0, 32 ); lvit = new ExceptListItem ( m_except, lvit, ( *it ). mid ( 1 ), fl & 0x01, fl & 0x02, fl & 0x04 ); } vertLayout-> addSpacing ( 3 ); QFrame *f = new QFrame ( tab ); f-> setFrameStyle ( QFrame::HLine | QFrame::Sunken ); vertLayout-> addWidget ( f ); vertLayout-> addSpacing ( 3 ); QGridLayout* gridLayout = new QGridLayout ( vertLayout, 0, 0, 3, 0 ); int style = cfg. readNumEntry ( "TabStyle", 2 ) - 1; bool tabtop = ( cfg. readEntry ( "TabPosition", "Top" ) == "Top" ); QLabel* label = new QLabel( tr( "Tab style:" ), tab ); gridLayout-> addWidget ( label, 0, 0 ); QWhatsThis::add( label, tr( "Click here to select a desired style for tabbed dialogs (such as this application). The styles available are:\n\n1. Tabs - normal tabs with text labels only\n2. Tabs w/icons - tabs with icons for each tab, text label only appears on current tab\n3. Drop down list - a vertical listing of tabs\n4. Drop down list w/icons - a vertical listing of tabs with icons" ) ); QButtonGroup* btngrp = new QButtonGroup( tab, "buttongroup" ); btngrp-> hide ( ); btngrp-> setExclusive ( true ); m_tabstyle_list = new QComboBox ( false, tab, "tabstyle" ); m_tabstyle_list-> insertItem ( tr( "Tabs" )); m_tabstyle_list-> insertItem ( tr( "Tabs w/icons" )); m_tabstyle_list-> insertItem ( tr( "Drop down list" )); m_tabstyle_list-> insertItem ( tr( "Drop down list w/icons" )); m_tabstyle_list-> setCurrentItem ( style ); gridLayout-> addMultiCellWidget ( m_tabstyle_list, 0, 0, 1, 2 ); QWhatsThis::add( m_tabstyle_list, tr( "Click here to select a desired style for tabbed dialogs (such as this application). The styles available are:\n\n1. Tabs - normal tabs with text labels only\n2. Tabs w/icons - tabs with icons for each tab, text label only appears on current tab\n3. Drop down list - a vertical listing of tabs\n4. Drop down list w/icons - a vertical listing of tabs with icons" ) ); m_tabstyle_top = new QRadioButton( tr( "Top" ), tab, "tabpostop" ); btngrp-> insert ( m_tabstyle_top ); gridLayout-> addWidget( m_tabstyle_top, 1, 1 ); QWhatsThis::add( m_tabstyle_top, tr( "Click here so that tabs appear at the top of the window." ) ); m_tabstyle_bottom = new QRadioButton( tr( "Bottom" ), tab, "tabposbottom" ); btngrp-> insert ( m_tabstyle_bottom ); gridLayout-> addWidget( m_tabstyle_bottom, 1, 2 ); QWhatsThis::add( m_tabstyle_bottom, tr( "Click here so that tabs appear at the bottom of the window." ) ); m_tabstyle_top-> setChecked ( tabtop ); m_tabstyle_bottom-> setChecked ( !tabtop ); m_original_tabstyle = style; m_original_tabpos = tabtop; vertLayout-> addSpacing ( 3 ); QHBoxLayout *rotLay = new QHBoxLayout ( vertLayout, 3 ); QLabel* rotlabel = new QLabel( tr( "Rotation direction:" ), tab ); m_rotdir_cw = new QRadioButton( tab, "rotdir_cw" ); QPixmap cw1 = Resource::loadIconSet("redo"). pixmap( ); m_rotdir_ccw = new QRadioButton( tab, "rotdir_ccw" ); QImage ccwImage = cw1. convertToImage( ). mirror( 1, 0 ); QPixmap ccw1; m_rotdir_flip = new QRadioButton( tab, "rotdir_flip" ); QPixmap flip1 = Resource::loadIconSet("pass"). pixmap( ); QButtonGroup* rotbtngrp = new QButtonGroup( tab, "rotbuttongroup" ); rotbtngrp-> hide ( ); rotbtngrp-> setExclusive ( true ); rotbtngrp-> insert ( m_rotdir_cw ); rotbtngrp-> insert ( m_rotdir_ccw ); rotbtngrp-> insert ( m_rotdir_flip ); ccw1. convertFromImage( ccwImage ); m_rotdir_cw-> setPixmap( cw1 ); m_rotdir_ccw-> setPixmap( ccw1 ); m_rotdir_flip-> setPixmap( flip1 ); rotLay-> addWidget ( rotlabel, 0 ); rotLay-> addWidget ( m_rotdir_cw, 0 ); rotLay-> addWidget ( m_rotdir_ccw, 0 ); rotLay-> addWidget ( m_rotdir_flip, 0 ); int rotDirection = cfg.readNumEntry( "rotatedir" ); ODirection rot = CW; if (rotDirection == -1) { rot = ODevice::inst ( )-> direction ( ); } else { rot = (ODirection)rotDirection; } m_rotdir_cw-> setChecked ( rot == CW ); m_rotdir_ccw-> setChecked ( rot == CCW ); m_rotdir_flip-> setChecked ( rot == Flip ); return tab; } Appearance::Appearance( QWidget* parent, const char* name, WFlags ) : QDialog ( parent, name, true, WStyle_ContextHelp ) { setCaption( tr( "Appearance Settings" ) ); Config config( "qpe" ); config.setGroup( "Appearance" ); QVBoxLayout *top = new QVBoxLayout ( this, 3, 3 ); m_sample = new SampleWindow ( this ); m_sample-> setDecoration ( new DefaultWindowDecoration ( ) ); QWhatsThis::add( m_sample, tr( "This is a preview window. Look here to see your new appearance as options are changed." ) ); OTabWidget* tw = new OTabWidget ( this, "tabwidget", OTabWidget::Global, OTabWidget::Bottom ); QWidget *styletab; m_color_list = 0; tw-> addTab ( styletab = createStyleTab ( tw, config ), "appearance", tr( "Style" )); tw-> addTab ( createFontTab ( tw, config ), "font", tr( "Font" )); tw-> addTab ( createColorTab ( tw, config ), "appearance/color", tr( "Colors" ) ); tw-> addTab ( createDecoTab ( tw, config ), "appearance/deco", tr( "Windows" ) ); tw-> addTab ( m_advtab = createAdvancedTab ( tw, config ), "SettingsIcon", tr( "Advanced" ) ); top-> addWidget ( tw, 10 ); top-> addWidget ( m_sample, 1 ); tw-> setCurrentTab ( styletab ); connect ( tw, SIGNAL( currentChanged(QWidget*)), this, SLOT( tabChanged(QWidget*))); m_style_changed = m_font_changed = m_color_changed = m_deco_changed = false; } Appearance::~Appearance() {} void Appearance::tabChanged ( QWidget *w ) { if ( w == m_advtab ) { m_sample-> hide ( ); updateGeometry ( ); // shouldn't be necessary ... } else m_sample-> show ( ); } void Appearance::accept ( ) { bool newtabpos = m_tabstyle_top-> isChecked ( ); int newtabstyle = m_tabstyle_list-> currentItem ( ); Config config ( "qpe" ); config. setGroup ( "Appearance" ); if ( m_style_changed ) { StyleListItem *item = (StyleListItem *) m_style_list-> item ( m_style_list-> currentItem ( )); if ( item ) config.writeEntry( "Style", item-> key ( )); } if ( m_deco_changed ) { DecoListItem *item = (DecoListItem *) m_deco_list-> item ( m_deco_list-> currentItem ( )); if ( item ) config.writeEntry( "Decoration", item-> key ( )); } if (( newtabstyle != m_original_tabstyle ) || ( newtabpos != m_original_tabpos )) { config. writeEntry ( "TabStyle", newtabstyle + 1 ); config. writeEntry ( "TabPosition", newtabpos ? "Top" : "Bottom" ); } if ( m_font_changed ) { config. writeEntry ( "FontFamily", m_fontselect-> fontFamily ( )); config. writeEntry ( "FontStyle", m_fontselect-> fontStyle ( )); config. writeEntry ( "FontSize", m_fontselect-> fontSize ( )); } if ( m_color_changed ) { ColorListItem *item = (ColorListItem *) m_color_list-> item ( m_color_list-> currentItem ( )); if ( item ) item-> save ( config ); } ODirection rot; if (m_rotdir_ccw-> isChecked ( )) { rot = CCW; } else if (m_rotdir_cw-> isChecked ( )) { rot = CW; } else { rot = Flip; } config. writeEntry ( "rotatedir", (int)rot ); m_except-> setFocus ( ); // if the focus was on the embedded line-edit, we have to move it away first, so the contents are updated QStringList sl; QString exceptstr; for ( ExceptListItem *it = (ExceptListItem *) m_except-> firstChild ( ); it; it = (ExceptListItem *) it-> nextSibling ( )) { int fl = 0; fl |= ( it-> noStyle ( ) ? 0x01 : 0 ); fl |= ( it-> noFont ( ) ? 0x02 : 0 ); fl |= ( it-> noDeco ( ) ? 0x04 : 0 ); exceptstr = QString::number ( fl, 32 ); exceptstr.append( it-> pattern ( )); sl << exceptstr; } config. writeEntry ( "NoStyle", sl, ';' ); config. writeEntry ( "ForceStyle", m_force-> isChecked ( )); config. write ( ); // need to flush the config info first Global::applyStyle ( ); QDialog::accept ( ); } void Appearance::done ( int r ) { QDialog::done ( r ); close ( ); } void Appearance::styleClicked ( int index ) { StyleListItem *sli = (StyleListItem *) m_style_list-> item ( index ); m_style_settings-> setEnabled ( sli ? sli-> hasSettings ( ) : false ); if ( m_sample && sli && sli-> style ( )) { int ci = m_color_list ? m_color_list-> currentItem ( ) : -1; m_sample-> setStyle2 ( sli-> style ( ), ci < 0 ? palette ( ) : ((ColorListItem *) m_color_list-> item ( ci ))-> palette ( )); } m_style_changed |= ( index != m_original_style ); } void Appearance::styleSettingsClicked ( ) { StyleListItem *item = (StyleListItem *) m_style_list-> item ( m_style_list-> currentItem ( )); if ( item && item-> hasSettings ( )) { QDialog *d = new QDialog ( this, "SETTINGS-DLG", true ); QVBoxLayout *vbox = new QVBoxLayout ( d, 3, 0 ); QWidget *w = item-> settings ( d ); if ( w ) { vbox-> addWidget ( w ); d-> setCaption ( w-> caption ( )); bool accepted = ( QPEApplication::execDialog ( d ) == QDialog::Accepted ); if ( item-> setSettings ( accepted )) m_style_changed = true; } delete d; } } void Appearance::decoClicked ( int index ) { DecoListItem *dli = (DecoListItem *) m_deco_list-> item ( index ); if ( m_sample ) { if ( dli && dli-> interface ( )) m_sample-> setDecoration ( dli-> interface ( )); else m_sample-> setDecoration ( new DefaultWindowDecoration ( )); m_sample-> repaint ( ); } m_deco_changed |= ( index != m_original_deco ); } void Appearance::fontClicked ( const QFont &f ) { m_font_changed |= ( f != m_sample-> font ( )); m_sample-> setFont ( f ); } void Appearance::colorClicked ( int index ) { ColorListItem *item = (ColorListItem *) m_color_list-> item ( index ); if ( item ) m_sample-> setPalette ( item-> palette ( )); m_color_changed |= ( item-> palette ( ) != qApp-> palette ( )); } void Appearance::editSchemeClicked ( ) { ColorListItem *item = (ColorListItem *) m_color_list-> item ( m_color_list-> currentItem ( )); int cnt = 0; QString labels [QColorGroup::NColorRoles]; QColor colors [QColorGroup::NColorRoles]; for ( int role = 0; role < (int) QColorGroup::NColorRoles; ++role ) { QColor col = item->color( static_cast<QColorGroup::ColorRole>( role ) ); if ( col. isValid ( )) { labels[cnt] = item->label( static_cast<QColorGroup::ColorRole>( role ) ); colors[cnt] = col; cnt++; } } EditScheme* editdlg = new EditScheme( cnt, labels, colors, this, "editScheme", true ); if ( QPEApplication::execDialog( editdlg ) == QDialog::Accepted ) { ColorListItem *citem = (ColorListItem *) m_color_list-> item ( 0 ); cnt = 0; for ( int role = 0; role < (int) QColorGroup::NColorRoles; ++role ) { if ( item->color( static_cast<QColorGroup::ColorRole>( role ) ).isValid() ) { citem->setColor( static_cast<QColorGroup::ColorRole>( role ), colors[cnt] ); cnt++; } } m_color_list-> setCurrentItem ( 0 ); colorClicked ( 0 ); m_color_changed = true; } delete editdlg; } void Appearance::saveSchemeClicked() { ColorListItem *item = (ColorListItem *) m_color_list-> item ( m_color_list-> currentItem ( )); if ( !item ) return; QDialog *d = new QDialog ( this, 0, true ); d-> setCaption ( tr( "Save Scheme" )); QLineEdit *ed = new QLineEdit ( d ); ( new QVBoxLayout ( d, 3, 3 ))-> addWidget ( ed ); ed-> setFocus ( ); if ( d-> exec ( ) == QDialog::Accepted ) { QString schemename = ed-> text ( ); QString filestr = QPEApplication::qpeDir(); filestr.append( "/etc/colors/" ); filestr.append( schemename ); filestr.append( ".scheme" ); QFile file ( filestr ); if ( !file. exists ( )) { QPalette p = item-> palette ( ); Config config ( file.name(), Config::File ); config. setGroup( "Colors" ); item-> save ( config ); config. write ( ); // need to flush the config info first m_color_list-> insertItem ( new ColorListItem ( schemename, config )); } else { QMessageBox::information ( this, tr( "Save scheme" ), tr( "Scheme does already exist." )); } } delete d; } void Appearance::deleteSchemeClicked() { ColorListItem *item = (ColorListItem *) m_color_list-> item ( m_color_list-> currentItem ( )); if ( !item ) return; if ( m_color_list-> currentItem ( ) > 0 ) { if ( QPEMessageBox::confirmDelete ( this, tr( "Delete scheme" ), item-> text ( ) ) ) { QString filestr = QPEApplication::qpeDir ( ); filestr.append( "/etc/colors/" ); filestr.append( item-> text ( ) ); filestr.append( ".scheme" ); QFile::remove ( filestr ); delete item; } } else { QMessageBox::information( this, tr( "Delete scheme" ), tr( "Unable to delete current scheme." )); } } void Appearance::addExcept ( ) { ExceptListItem *it = new ExceptListItem ( m_except, 0, tr( "<new>" ), true, true, true ); m_except-> ensureItemVisible ( it ); m_except-> setSelected ( it, true ); } void Appearance::delExcept ( ) { if ( m_except-> selectedItem ( )) { m_except-> setFocus ( ); delete m_except-> selectedItem ( ); } } void Appearance::upExcept ( ) { ExceptListItem *it = (ExceptListItem *) m_except-> selectedItem ( ); if ( it && it-> itemAbove ( )) it-> itemAbove ( )-> moveItem ( it ); } void Appearance::downExcept ( ) { ExceptListItem *it = (ExceptListItem *) m_except-> selectedItem ( ); if ( it && it-> itemBelow ( )) it-> moveItem ( it-> itemBelow ( )); } class ExEdit : public QLineEdit { public: ExEdit ( ExceptListItem *item ) : QLineEdit ( item-> listView ( )-> viewport ( ), "exedit" ), it ( item ) { setFrame ( false ); QRect r = it-> listView ( )-> itemRect ( it ); int x = it-> listView ( )-> header ( )-> cellPos ( 3 ) - 1; int y = r. y ( ); int w = it-> listView ( )-> viewport ( )-> width ( ) - x; int h = r. height ( ); // + 2; setText ( it-> pattern ( )); setGeometry ( x, y, w, h ); odebug << "ExEdit: [" << it->text(2).latin1() << "] at " << x << "," << y << " " << w << "," << h << oendl; m_out = true; show ( ); setFocus ( ); selectAll ( ); end ( true ); } virtual void focusOutEvent ( QFocusEvent * ) { hide ( ); if ( m_out ) it-> setPattern ( text ( )); delete this; } virtual void keyPressEvent ( QKeyEvent *e ) { if ( e-> key ( ) == Key_Return ) it-> listView ( )-> setFocus ( ); else if ( e-> key ( ) == Key_Escape ) { m_out = false; it-> listView ( )-> setFocus ( ); } else QLineEdit::keyPressEvent ( e ); } private: ExceptListItem *it; bool m_out; }; void Appearance::clickedExcept ( QListViewItem *item, const QPoint &, int c ) { if ( !item || c < 0 || c > 3 ) return; ExceptListItem *it = (ExceptListItem *) item; if ( c == 0 ) it-> setNoStyle ( !it-> noStyle ( )); else if ( c == 1 ) it-> setNoFont ( !it-> noFont ( )); else if ( c == 2 ) it-> setNoDeco ( !it-> noDeco ( )); else if ( c == 3 ) { m_except-> ensureItemVisible ( it ); new ExEdit ( it ); } } diff --git a/noncore/settings/doctab/doctab.cpp b/noncore/settings/doctab/doctab.cpp index feaf538..72eda6b 100644 --- a/noncore/settings/doctab/doctab.cpp +++ b/noncore/settings/doctab/doctab.cpp @@ -1,94 +1,94 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "doctab.h" #include <qpe/global.h> #include <qpe/fontmanager.h> #include <qpe/config.h> #include <qpe/applnk.h> #include <qpe/qpedialog.h> #include <qpe/qpeapplication.h> #if defined(Q_WS_QWS) && !defined(QT_NO_COP) #include <qpe/qcopenvelope_qws.h> #endif #include <qlabel.h> #include <qcheckbox.h> #include <qradiobutton.h> #include <qtabwidget.h> #include <qslider.h> #include <qfile.h> #include <qtextstream.h> #include <qdatastream.h> #include <qmessagebox.h> #include <qcombobox.h> #include <qspinbox.h> #include <qlistbox.h> #include <qdir.h> -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 #include <qstylefactory.h> #endif #include <stdlib.h> DocTabSettings::DocTabSettings( QWidget* parent, const char* name, WFlags fl ) : DocTabSettingsBase( parent, name, TRUE, fl ) { dl = new QPEDialogListener(this); reset(); } DocTabSettings::~DocTabSettings() {} void DocTabSettings::accept() { applyDocTab(); QDialog::accept(); } void DocTabSettings::applyDocTab() { Config cfg( "Launcher" ); cfg.setGroup( "DocTab" ); cfg.writeEntry( "Enable", yes->isChecked() ); cfg.write(); } void DocTabSettings::reject() { reset(); QDialog::reject(); } void DocTabSettings::reset() { } QString DocTabSettings::actualDocTab; void DocTabSettings::done(int r) { QDialog::done(r); close(); } diff --git a/noncore/settings/language/language.cpp b/noncore/settings/language/language.cpp index 14750ac..bf90576 100644 --- a/noncore/settings/language/language.cpp +++ b/noncore/settings/language/language.cpp @@ -1,159 +1,159 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "settings.h" #include <qpe/global.h> #include <qpe/fontmanager.h> #include <qpe/config.h> #include <qpe/applnk.h> #include <qpe/qpedialog.h> #include <qpe/qpeapplication.h> #if defined(Q_WS_QWS) && !defined(QT_NO_COP) #include <qpe/qcopenvelope_qws.h> #endif #include <qlabel.h> #include <qcheckbox.h> #include <qradiobutton.h> #include <qtabwidget.h> #include <qslider.h> #include <qfile.h> #include <qtextstream.h> #include <qdatastream.h> #include <qmessagebox.h> #include <qcombobox.h> #include <qspinbox.h> #include <qlistbox.h> #include <qdir.h> -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 #include <qstylefactory.h> #endif #include <stdlib.h> LanguageSettings::LanguageSettings( QWidget* parent, const char* name, WFlags fl ) : LanguageSettingsBase( parent, name, TRUE, fl ) { if ( FontManager::hasUnicodeFont() ) languages->setFont(FontManager::unicodeFont(FontManager::Proportional)); QString tfn = QPEApplication::qpeDir() + "i18n/"; QDir langDir = tfn; QStringList list = langDir.entryList("*", QDir::Dirs ); QStringList::Iterator it; for ( it = list.begin(); it != list.end(); ++it ) { QString name = (*it); QFileInfo desktopFile( tfn + "/" + name + "/.directory" ); if ( desktopFile.exists() ) { langAvail.append(name); Config conf( desktopFile.filePath(), Config::File ); QString langName = conf.readEntry( "Name" ); QString ownName = conf.readEntryDirect( "Name[" + name + "]" ); if ( ownName.isEmpty() ) ownName = conf.readEntryDirect( "Name" ); if ( !ownName.isEmpty() && ownName != langName ) langName = langName + " [" + ownName + "]"; languages->insertItem( langName ); } } if ( langAvail. find ( "en" ) == -1 ) { langAvail. prepend ( "" ); // no tr languages-> insertItem ( QString ( "English [%1] (%2)" /* no tr (!) */ ). arg ( tr ( "English" )). arg ( tr( "default" )), 0 ); } dl = new QPEDialogListener(this); reset(); } LanguageSettings::~LanguageSettings() {} void LanguageSettings::accept() { Config c( "qpe" ); c.setGroup( "Startup" ); if ( ( c.readNumEntry( "FirstUse", 42 ) == 0 ) && ( QMessageBox::warning( this, tr("Language"), tr("<qt>Attention, all windows will be closed by changing the language\n" "without saving the Data.<br><br>Go on?</qt>"), 1, 2) ) == QMessageBox::Cancel ) return; applyLanguage(); QDialog::accept(); } void LanguageSettings::applyLanguage() { setLanguage ( langAvail. at ( languages-> currentItem ( ))); } void LanguageSettings::reject() { reset(); QDialog::reject(); } void LanguageSettings::reset() { QString l = getenv("LANG"); Config config("locale"); config.setGroup("Language"); l = config.readEntry( "Language", l ); actualLanguage = l; if (l.isEmpty()) l = "en"; int n = langAvail.find( l ); languages->setCurrentItem( n ); } QString LanguageSettings::actualLanguage; void LanguageSettings::setLanguage(const QString& lang) { if ( lang != actualLanguage ) { Config config("locale"); config.setGroup( "Language" ); if ( lang. isEmpty ( )) config. removeEntry ( "Language" ); else config.writeEntry( "Language", lang ); config.write(); #if defined(Q_WS_QWS) && !defined(QT_NO_COP) QCopEnvelope e("QPE/System", "language(QString)"); e << lang; #endif } } void LanguageSettings::done(int r) { QDialog::done(r); close(); } diff --git a/noncore/settings/networksettings/interfaces/module.h b/noncore/settings/networksettings/interfaces/module.h index 9dc913e..13189c3 100644 --- a/noncore/settings/networksettings/interfaces/module.h +++ b/noncore/settings/networksettings/interfaces/module.h @@ -1,188 +1,188 @@ #ifndef NETCONF_MODULE_H #define NETCONF_MODULE_H #include <qobject.h> -#if QT_VERSION < 300 +#if QT_VERSION < 0x030000 #include <qlist.h> #else #include <qptrlist.h> #endif #include <qmap.h> #include "interface.h" class QWidget; class QTabWidget; /** * \brief The basis of all plugins * * This is the way to extend networksettings with * extra functionality. * * * Networksettings in the 1.0 release does not use QCOM * for activation. You need to provide the following function yourself. * * A module needs to provide Name, Images, and methods for * claiming interfaces. For example you can claim physicla * interfaces like wlan0, ppp0 or virtual like a VPN * connection and hide the real ppp device or ethernet device * behind your VPN plugin. * * During start up. The main application searches for network devices * and then looks for an owner under the plugins for them. * For example the WLAN Plugin looks if there is a WLAN Extension * on that interface and then claims it by returning true from isOwner() * * \code * extern "C" * { * void* create_plugin() { * return new WLANModule(); * } * }; * \endcode * @see isOwner(Interface*) */ class Module : private QObject{ signals: /** * Emit this Signal once you change the Interface * you're operating on * * @param i The Interface */ void updateInterface(Interface *i); public: Module(){}; /** * The type of the plugin * and the name of the qcop call */ virtual const QString type() = 0; /** * The current profile has been changed and the module should do any * neccesary changes also. * As of Opie1.0 profiles are disabled. * * @param newProfile what the profile should be changed to. */ virtual void setProfile(const QString &newProfile) = 0; /** * get the icon name for this device. * @param Interface* can be used in determining the icon. * @return QString the icon name (minus .png, .gif etc) */ virtual QString getPixmapName(Interface *) = 0; /** * Check to see if the interface i is owned by this module. * See if you can handle it. And if you can claim ownership * by returning true. * For physical devices you will be asked if you want to own the * device. But you can also create new \sa Interface Implementations. * * If you want to own the Interface add it to your internal interface * list * * @param Interface* interface to check against * @return bool true if i is owned by this module, false otherwise. * * @see getInterfaces */ virtual bool isOwner(Interface *){ return false; }; /** * Create and return the Configure Module * @param Interface *i the interface to configure. * @return QWidget* pointer to this modules configure. * * @see InterfaceSetupImp */ virtual QWidget *configure(Interface *){ return NULL; } ; /** * Create, and return the Information Module. * * An default Implementation is InterfaceInformationImp * * @param Interface *i the interface to get info on. * @return QWidget* pointer to this modules info. * * @see InterfaceInformationImp * */ virtual QWidget *information(Interface *){ return NULL; }; /** * Get all active (up or down) interfaces managed by this * module. * At the end of initialisation you will be asked to return your interfaces * Return all of your interfaces even the ones you claimed by isOnwer. * Here you can also return your 'virtual' Interface Objects * * @return QList<Interface> A list of interfaces that exsist that havn't * been called by isOwner() */ virtual QList<Interface> getInterfaces() = 0; /** * Adds possible new interfaces to the list (Example: usb(ppp), ir(ppp), * modem ppp) * Both strings need to be translated. The first string is a Shortcut * like PPP and the second argument is a description. * * <code> * list.insert( * * </code> * * @param list A reference to the list of supported additionns. */ virtual void possibleNewInterfaces(QMap<QString, QString> &list) = 0; /** * Attempts to create a new interface from name you gave * possibleNewInterfaces() * @return Interface* NULL if it was unable to be created. * @param name the type of interface to create * * @see possibleNewInterfaces */ virtual Interface *addNewInterface(const QString &name) = 0; /** * Attempts to remove the interface, doesn't delete i * @return bool true if successful, false otherwise. */ virtual bool remove(Interface* i) = 0; /** * get dcop calls */ virtual void receive(const QCString &msg, const QByteArray &arg) = 0; QStringList handledInterfaceNames()const { return m_inter; } protected: /** * set which interfaceNames should not be shown cause they're handled * internally of this module.. An already running ppp link or * a tunnel... VPN an such */ void setHandledInterfaceNames( const QStringList& in) { m_inter = in; } private: QStringList m_inter; }; #endif // module.h diff --git a/noncore/settings/networksettings/mainwindow/addconnectionimp.cpp b/noncore/settings/networksettings/mainwindow/addconnectionimp.cpp index 84f1cf6..9049af4 100644 --- a/noncore/settings/networksettings/mainwindow/addconnectionimp.cpp +++ b/noncore/settings/networksettings/mainwindow/addconnectionimp.cpp @@ -1,41 +1,41 @@ #include "addconnectionimp.h" #include <qlistview.h> -#if QT_VERSION < 300 +#if QT_VERSION < 0x030000 #include <qlist.h> #else #include <qptrlist.h> #endif #include <qlabel.h> #include <qheader.h> /** * Constructor */ AddConnectionImp::AddConnectionImp(QWidget *parent, const char *name, WFlags f):AddConnection(parent, name, f){ connect(registeredServicesList, SIGNAL(selectionChanged()), this, SLOT(changed())); registeredServicesList->header()->hide(); }; /** * The current item changed, update the discription. */ void AddConnectionImp::changed(){ QListViewItem *item = registeredServicesList->currentItem(); if(item) help->setText(list[item->text(0)]); } /** * Save a copy of newList for the discriptions and append them all to the view * @param newList the new list of possible interfaces */ void AddConnectionImp::addConnections(const QMap<QString, QString> &newList){ list = newList; QMap<QString, QString>::Iterator it; for( it = list.begin(); it != list.end(); ++it ) (void)new QListViewItem(registeredServicesList, it.key()); registeredServicesList->setCurrentItem(registeredServicesList->firstChild()); } // addserviceimp.cpp diff --git a/noncore/settings/networksettings/mainwindow/mainwindowimp.cpp b/noncore/settings/networksettings/mainwindow/mainwindowimp.cpp index 5f23aea..8feb7a5 100644 --- a/noncore/settings/networksettings/mainwindow/mainwindowimp.cpp +++ b/noncore/settings/networksettings/mainwindow/mainwindowimp.cpp @@ -1,713 +1,713 @@ #include "mainwindowimp.h" #include "addconnectionimp.h" #include "interfaceinformationimp.h" #include "interfacesetupimp.h" #include "interfaces.h" #include "module.h" /* OPIE */ #include <opie2/odebug.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/qpeapplication.h> #include <qpe/config.h> #include <qpe/qlibrary.h> #include <qpe/resource.h> /* QT */ #include <qpushbutton.h> #include <qlistbox.h> #include <qlineedit.h> #include <qlistview.h> #include <qheader.h> #include <qlabel.h> #include <qtabwidget.h> // in order to disable the profiles tab #include <qmessagebox.h> -#if QT_VERSION < 300 +#if QT_VERSION < 0x030000 #include <qlist.h> #else #include <qptrlist.h> #endif #include <qdir.h> #include <qfile.h> #include <qtextstream.h> #include <qregexp.h> /* STD */ #include <net/if.h> #include <sys/ioctl.h> #include <sys/socket.h> #define DEFAULT_SCHEME "/var/lib/pcmcia/scheme" #define _PROCNETDEV "/proc/net/dev" MainWindowImp::MainWindowImp(QWidget *parent, const char *name, WFlags) : MainWindow(parent, name, Qt::WStyle_ContextHelp), advancedUserMode(true), scheme(DEFAULT_SCHEME) { connect(addConnectionButton, SIGNAL(clicked()), this, SLOT(addClicked())); connect(removeConnectionButton, SIGNAL(clicked()), this, SLOT(removeClicked())); connect(informationConnectionButton, SIGNAL(clicked()), this, SLOT(informationClicked())); connect(configureConnectionButton, SIGNAL(clicked()), this, SLOT(configureClicked())); //remove tab with no function tabWidget->removePage( tab ); // Load connections. // /usr/local/kde/lib/libinterfaces.la loadModules(QPEApplication::qpeDir() + "plugins/networksettings"); getAllInterfaces(); Interfaces i; QStringList list = i.getInterfaceList(); QMap<QString, Interface*>::Iterator it; for ( QStringList::Iterator ni = list.begin(); ni != list.end(); ++ni ) { /* * we skipped it in getAllInterfaces now * we need to ignore it as well */ if (m_handledIfaces.contains( *ni) ) { odebug << "Not up iface handled by module" << oendl; continue; } bool found = false; for( it = interfaceNames.begin(); it != interfaceNames.end(); ++it ) { if(it.key() == (*ni)) found = true; } if(!found) { if(!(*ni).contains("_")) { Interface *i = new Interface(this, *ni, false); i->setAttached(false); i->setHardwareName(tr("Disconnected")); interfaceNames.insert(i->getInterfaceName(), i); updateInterface(i); connect(i, SIGNAL(updateInterface(Interface*)), this, SLOT(updateInterface(Interface*))); } } } //getInterfaceList(); connectionList->header()->hide(); Config cfg("NetworkSetup"); profiles = QStringList::split(" ", cfg.readEntry("Profiles", "All")); for ( QStringList::Iterator it = profiles.begin(); it != profiles.end(); ++it) profilesList->insertItem((*it)); currentProfileLabel->setText(cfg.readEntry("CurrentProfile", "All")); advancedUserMode = cfg.readBoolEntry("AdvancedUserMode", false); scheme = cfg.readEntry("SchemeFile", DEFAULT_SCHEME); QFile file(scheme); if ( file.open(IO_ReadOnly) ) { // file opened successfully QTextStream stream( &file ); // use a text stream while ( !stream.eof() ) { // until end of file... QString line = stream.readLine(); // line of text excluding '\n' if(line.contains("SCHEME")) { line = line.mid(7, line.length()); currentProfileLabel->setText(line); break; } } file.close(); } makeChannel(); } /** * Deconstructor. Save profiles. Delete loaded libraries. */ MainWindowImp::~MainWindowImp() { // Save profiles. Config cfg("NetworkSetup"); cfg.setGroup("General"); cfg.writeEntry("Profiles", profiles.join(" ")); // Delete all interfaces that don't have owners. QMap<Interface*, QListViewItem*>::Iterator iIt; for( iIt = items.begin(); iIt != items.end(); ++iIt ) { if(iIt.key()->getModuleOwner() == NULL) delete iIt.key(); } // Delete Modules and Libraries QMap<Module*, QLibrary*>::Iterator it; for( it = libraries.begin(); it != libraries.end(); ++it ) { delete it.key(); // I wonder why I can't delete the libraries // What fucking shit this is. //delete it.data(); } } /** * Query the kernel for all of the interfaces. */ void MainWindowImp::getAllInterfaces() { int sockfd = socket(PF_INET, SOCK_DGRAM, 0); if(sockfd == -1) return; struct ifreq ifr; QStringList ifaces; QFile procFile(QString(_PROCNETDEV)); int result; Interface *i; if (! procFile.exists()) { struct ifreq ifrs[100]; struct ifconf ifc; ifc.ifc_len = sizeof(ifrs); ifc.ifc_req = ifrs; result = ioctl(sockfd, SIOCGIFCONF, &ifc); for (unsigned int i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++) { struct ifreq *pifr = &ifrs[i]; ifaces += pifr->ifr_name; } } else { procFile.open(IO_ReadOnly); QString line; QTextStream procTs(&procFile); int loc = -1; procTs.readLine(); // eat a line procTs.readLine(); // eat a line while((line = procTs.readLine().simplifyWhiteSpace()) != QString::null) { if((loc = line.find(":")) != -1) { ifaces += line.left(loc); } } } for (QStringList::Iterator it = ifaces.begin(); it != ifaces.end(); ++it) { int flags = 0; if ( m_handledIfaces.contains( (*it) ) ) { odebug << " " << (*it).latin1() << " is handled by a module" << oendl; continue; } // int family; i = NULL; strcpy(ifr.ifr_name, (*it).latin1()); struct ifreq ifcopy; ifcopy = ifr; result = ioctl(sockfd, SIOCGIFFLAGS, &ifcopy); flags = ifcopy.ifr_flags; i = new Interface(this, ifr.ifr_name, false); i->setAttached(true); if ((flags & IFF_UP) == IFF_UP) i->setStatus(true); else i->setStatus(false); if ((flags & IFF_BROADCAST) == IFF_BROADCAST) i->setHardwareName("Ethernet"); else if ((flags & IFF_POINTOPOINT) == IFF_POINTOPOINT) i->setHardwareName("Point to Point"); else if ((flags & IFF_MULTICAST) == IFF_MULTICAST) i->setHardwareName("Multicast"); else if ((flags & IFF_LOOPBACK) == IFF_LOOPBACK) i->setHardwareName("Loopback"); else i->setHardwareName("Unknown"); owarn << "Adding interface " << ifr.ifr_name << " to interfaceNames\n" << oendl; interfaceNames.insert(i->getInterfaceName(), i); updateInterface(i); connect(i, SIGNAL(updateInterface(Interface*)), this, SLOT(updateInterface(Interface*))); } // now lets ask the plugins too ;) QMap<Module*, QLibrary*>::Iterator it; QList<Interface> ilist; for( it = libraries.begin(); it != libraries.end(); ++it ) { if(it.key()) { ilist = it.key()->getInterfaces(); for( i = ilist.first(); i != 0; i = ilist.next() ) { owarn << "Adding interface " << i->getInterfaceName().latin1() << " to interfaceNames\n" << oendl; interfaceNames.insert(i->getInterfaceName(), i); updateInterface(i); connect(i, SIGNAL(updateInterface(Interface*)), this, SLOT(updateInterface(Interface*))); } } } } /** * Load all modules that are found in the path * @param path a directory that is scaned for any plugins that can be loaded * and attempts to load them */ void MainWindowImp::loadModules(const QString &path) { #ifdef DEBUG odebug << "MainWindowImp::loadModules: " << path.latin1() << "" << oendl; #endif QDir d(path); if(!d.exists()) return; QString lang = ::getenv("LANG"); // Don't want sym links d.setFilter( QDir::Files | QDir::NoSymLinks ); const QFileInfoList *list = d.entryInfoList(); QFileInfoListIterator it( *list ); QFileInfo *fi; while ( (fi=it.current()) ) { if(fi->fileName().contains(".so")) { /* if loaded install translation */ if( loadPlugin(path + "/" + fi->fileName()) != 0l ){ QTranslator *trans = new QTranslator(qApp); QString fn = QPEApplication::qpeDir()+"i18n/"+lang+"/"+ fi->fileName().left( fi->fileName().find(".") )+".qm"; if( trans->load( fn ) ) qApp->installTranslator( trans ); else delete trans; } odebug << "loaded plugin: >" << QString(path + "/" + fi->fileName()).latin1() << "< " << oendl; } ++it; } } /** * Attempt to load a function and resolve a function. * @param pluginFileName - the name of the file in which to attempt to load * @param resolveString - function pointer to resolve * @return pointer to the function with name resolveString or NULL */ Module* MainWindowImp::loadPlugin(const QString &pluginFileName, const QString &resolveString) { #ifdef DEBUG odebug << "MainWindowImp::loadPlugin: " << pluginFileName.latin1() << ": resolving " << resolveString.latin1() << "" << oendl; #endif QLibrary *lib = new QLibrary(pluginFileName); void *functionPointer = lib->resolve(resolveString); if( !functionPointer ) { #ifdef DEBUG odebug << "MainWindowImp::loadPlugin: Warning: " << pluginFileName.latin1() << " is not a plugin" << oendl; #endif delete lib; return 0; } // Try to get an object. Module *object = ((Module* (*)()) functionPointer)(); if(object == 0) { #ifdef DEBUG odebug << "MainWindowImp: Couldn't create object, but did load library!" << oendl; #endif delete lib; return 0; } m_handledIfaces += object->handledInterfaceNames(); // Store for deletion later libraries.insert(object, lib); return object; } /** * The Add button was clicked. Bring up the add dialog and if OK is hit * load the plugin and append it to the list */ void MainWindowImp::addClicked() { QMap<Module*, QLibrary*>::Iterator it; QMap<QString, QString> list; QMap<QString, Module*> newInterfaceOwners; for( it = libraries.begin(); it != libraries.end(); ++it ) { if(it.key()) { (it.key())->possibleNewInterfaces(list); } } // See if the list has anything that we can add. if(list.count() == 0) { QMessageBox::information(this, "Sorry", "Nothing to add.", QMessageBox::Ok); return; } AddConnectionImp addNewConnection(this, "AddConnectionImp", true); addNewConnection.addConnections(list); if( QDialog::Accepted == QPEApplication::execDialog( &addNewConnection ) ) { QListViewItem *item = addNewConnection.registeredServicesList->currentItem(); if(!item) return; for( it = libraries.begin(); it != libraries.end(); ++it ) { if(it.key()) { Interface *i = (it.key())->addNewInterface(item->text(0)); if(i) { odebug << "iface name " << i->getInterfaceName().latin1() << "" << oendl; interfaceNames.insert(i->getInterfaceName(), i); updateInterface(i); } } } } } /** * Prompt the user to see if they really want to do this. * If they do then remove from the list and unload. */ void MainWindowImp::removeClicked() { QListViewItem *item = connectionList->currentItem(); if(!item) { QMessageBox::information(this, "Sorry","Please select an interface First.", QMessageBox::Ok); return; } Interface *i = interfaceItems[item]; if(i->getModuleOwner() == NULL) { QMessageBox::information(this, "Can't remove interface.", "Interface is built in.", QMessageBox::Ok); } else { if(!i->getModuleOwner()->remove(i)) QMessageBox::information(this, tr("Error"), tr("Unable to remove."), QMessageBox::Ok); else { delete item; // QMessageBox::information(this, "Success", "Interface was removed.", QMessageBox::Ok); } } } /** * Pull up the configure about the currently selected interface. * Report an error if no interface is selected. * If the interface has a module owner then request its configure. */ void MainWindowImp::configureClicked() { QListViewItem *item = connectionList->currentItem(); if(!item) { QMessageBox::information(this, tr("Sorry"),tr("Please select an interface first."), QMessageBox::Ok); return; } QString currentProfileText = currentProfileLabel->text(); if(currentProfileText.upper() == "ALL"); currentProfileText = ""; Interface *i = interfaceItems[item]; if(i->getModuleOwner()) { QWidget *moduleConfigure = i->getModuleOwner()->configure(i); if(moduleConfigure != NULL) { i->getModuleOwner()->setProfile(currentProfileText); QPEApplication::showWidget( moduleConfigure ); return; } } InterfaceSetupImpDialog *configure = new InterfaceSetupImpDialog(this, "InterfaceSetupImp", i, true, Qt::WDestructiveClose | Qt::WStyle_ContextHelp ); configure->setProfile(currentProfileText); QPEApplication::showDialog( configure ); } /** * Pull up the information about the currently selected interface. * Report an error if no interface is selected. * If the interface has a module owner then request its configure. */ void MainWindowImp::informationClicked() { QListViewItem *item = connectionList->currentItem(); if(!item) { QMessageBox::information(this, "Sorry","Please select an interface First.", QMessageBox::Ok); return; } Interface *i = interfaceItems[item]; // if(!i->isAttached()){ // QMessageBox::information(this, "Sorry","No information about\na disconnected interface.", QMessageBox::Ok); // return; // } if(i->getModuleOwner()) { QWidget *moduleInformation = i->getModuleOwner()->information(i); if(moduleInformation != NULL) { QPEApplication::showWidget( moduleInformation ); #ifdef DEBUG odebug << "MainWindowImp::informationClicked:: Module owner has created, we showed." << oendl; #endif return; } } InterfaceInformationImp *information = new InterfaceInformationImp(this, "InterfaceSetupImp", i, Qt::WType_Modal | Qt::WDestructiveClose | Qt::WStyle_Dialog | Qt::WStyle_ContextHelp); QPEApplication::showWidget( information ); } /** * Update this interface. If no QListViewItem exists create one. * @param Interface* pointer to the interface that needs to be updated. */ void MainWindowImp::updateInterface(Interface *i) { if(!advancedUserMode) { if(i->getInterfaceName() == "lo") return; } QListViewItem *item = NULL; // Find the interface, making it if needed. if(items.find(i) == items.end()) { item = new QListViewItem(connectionList, "", "", ""); // See if you can't find a module owner for this interface QMap<Module*, QLibrary*>::Iterator it; for( it = libraries.begin(); it != libraries.end(); ++it ) { if(it.key()->isOwner(i)) i->setModuleOwner(it.key()); } items.insert(i, item); interfaceItems.insert(item, i); } else item = items[i]; // Update the icons and information #ifdef QWS item->setPixmap(0, (Resource::loadPixmap(i->getStatus() ? "up": "down"))); #else item->setPixmap(0, (SmallIcon(i->getStatus() ? "up": "down"))); #endif QString typeName = "lan"; if(i->getInterfaceName() == "lo") typeName = "lo"; if(i->getInterfaceName().contains("irda")) typeName = "irda"; if(i->getInterfaceName().contains("wlan")) typeName = "wlan"; if(i->getInterfaceName().contains("usb")) typeName = "usb"; if(!i->isAttached()) typeName = "connect_no"; // Actually try to use the Module if(i->getModuleOwner() != NULL) typeName = i->getModuleOwner()->getPixmapName(i); #ifdef QWS item->setPixmap(1, (Resource::loadPixmap(QString("networksettings/") + typeName))); #else item->setPixmap(1, (SmallIcon(typeName))); #endif item->setText(2, i->getHardwareName()); item->setText(3, QString("(%1)").arg(i->getInterfaceName())); item->setText(4, (i->getStatus()) ? i->getIp() : QString("")); } void MainWindowImp::newProfileChanged(const QString& newText) { if(newText.length() > 0) newProfileButton->setEnabled(true); else newProfileButton->setEnabled(false); } /** * Adds a new profile to the list of profiles. * Don't add profiles that already exists. * Appends to the list and QStringList */ void MainWindowImp::addProfile() { QString newProfileName = newProfile->text(); if(profiles.grep(newProfileName).count() > 0) { QMessageBox::information(this, "Can't Add","Profile already exists.", QMessageBox::Ok); return; } profiles.append(newProfileName); profilesList->insertItem(newProfileName); } /** * Removes the currently selected profile in the combo. * Doesn't delete if there are less then 2 profiles. */ void MainWindowImp::removeProfile() { if(profilesList->count() <= 1) { QMessageBox::information(this, "Can't remove.","At least one profile\nis needed.", QMessageBox::Ok); return; } QString profileToRemove = profilesList->currentText(); if(profileToRemove == "All") { QMessageBox::information(this, "Can't remove.","Can't remove default.", QMessageBox::Ok); return; } // Can't remove the curent profile if(profileToRemove == currentProfileLabel->text()) { QMessageBox::information(this, "Can't remove.",QString("%1 is the current profile.").arg(profileToRemove), QMessageBox::Ok); return; } if(QMessageBox::information(this, "Question",QString("Remove profile: %1").arg(profileToRemove), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok) { profiles = QStringList::split(" ", profiles.join(" ").replace(QRegExp(profileToRemove), "")); profilesList->clear(); for ( QStringList::Iterator it = profiles.begin(); it != profiles.end(); ++it) profilesList->insertItem((*it)); // Remove any interface settings and mappings. Interfaces interfaces; // Go through them one by one QMap<Interface*, QListViewItem*>::Iterator it; for( it = items.begin(); it != items.end(); ++it ) { QString interfaceName = it.key()->getInterfaceName(); odebug << interfaceName.latin1() << oendl; if(interfaces.setInterface(interfaceName + "_" + profileToRemove)) { interfaces.removeInterface(); if(interfaces.setMapping(interfaceName)) { if(profilesList->count() == 1) interfaces.removeMapping(); else { interfaces.removeMap("map", interfaceName + "_" + profileToRemove); } } interfaces.write(); break; } } } } /** * A new profile has been selected, change. * @param newProfile the new profile. */ void MainWindowImp::changeProfile() { if(profilesList->currentItem() == -1) { QMessageBox::information(this, "Can't Change.","Please select a profile.", QMessageBox::Ok); return; } QString newProfile = profilesList->text(profilesList->currentItem()); if(newProfile != currentProfileLabel->text()) { currentProfileLabel->setText(newProfile); QFile::remove(scheme); QFile file(scheme); if ( file.open(IO_ReadWrite) ) { QTextStream stream( &file ); stream << QString("SCHEME=%1").arg(newProfile); file.close(); } // restart all up devices? if(QMessageBox::information(this, "Question","Restart all running interfaces?", QMessageBox::Ok, QMessageBox::No) == QMessageBox::Ok) { // Go through them one by one QMap<Interface*, QListViewItem*>::Iterator it; for( it = items.begin(); it != items.end(); ++it ) { if(it.key()->getStatus() == true) it.key()->restart(); } } } // TODO change the profile in the modules } void MainWindowImp::makeChannel() { channel = new QCopChannel( "QPE/Application/networksettings", this ); connect( channel, SIGNAL(received(const QCString&,const QByteArray&)), this, SLOT(receive(const QCString&,const QByteArray&)) ); } void MainWindowImp::receive(const QCString &msg, const QByteArray &arg) { bool found = false; odebug << "MainWindowImp::receive QCop msg >"+msg+"<" << oendl; if (msg == "raise") { raise(); return; } QString dest = msg.left(msg.find("(")); QCString param = msg.right(msg.length() - msg.find("(") - 1); param = param.left( param.length() - 1 ); odebug << "dest >" << dest.latin1() << "< param >"+param+"<" << oendl; QMap<Module*, QLibrary*>::Iterator it; for( it = libraries.begin(); it != libraries.end(); ++it ) { odebug << "plugin >" << it.key()->type().latin1() << "<" << oendl; if(it.key()->type() == dest) { it.key()->receive( param, arg ); found = true; } } if (found) QPEApplication::setKeepRunning(); else odebug << "Huh what do ya want" << oendl; } diff --git a/noncore/unsupported/qpdf/QOutputDev.cpp b/noncore/unsupported/qpdf/QOutputDev.cpp index 022d938..487177c 100644 --- a/noncore/unsupported/qpdf/QOutputDev.cpp +++ b/noncore/unsupported/qpdf/QOutputDev.cpp @@ -1,1053 +1,1053 @@ ///======================================================================== // // QOutputDev.cc // // Copyright 1996 Derek B. Noonburg // CopyRight 2002 Robert Griebl // //======================================================================== #ifdef __GNUC__ #pragma implementation #endif #include <aconf.h> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <unistd.h> #include <string.h> #include <ctype.h> #include <math.h> #include <iostream> #include "GString.h" #include "Object.h" #include "Stream.h" #include "Link.h" #include "GfxState.h" #include "GfxFont.h" #include "UnicodeMap.h" #include "CharCodeToUnicode.h" #include "FontFile.h" #include "Error.h" #include "TextOutputDev.h" #include "QOutputDev.h" #include <qpixmap.h> #include <qimage.h> #include <qpainter.h> #include <qdict.h> #include <qtimer.h> #include <qapplication.h> #include <qclipboard.h> //#define QPDFDBG(x) x // special debug mode #define QPDFDBG(x) // normal compilation //------------------------------------------------------------------------ // Constants and macros //------------------------------------------------------------------------ static inline QColor q_col ( const GfxRGB &rgb ) { return QColor ( lrint ( rgb. r * 255 ), lrint ( rgb. g * 255 ), lrint ( rgb. b * 255 )); } //------------------------------------------------------------------------ // Font substitutions //------------------------------------------------------------------------ struct QOutFontSubst { char * m_name; char * m_sname; bool m_bold; bool m_italic; QFont::StyleHint m_hint; }; static QOutFontSubst qStdFonts [] = { { "Helvetica", "Helvetica", false, false, QFont::Helvetica }, { "Helvetica-Oblique", "Helvetica", false, true, QFont::Helvetica }, { "Helvetica-Bold", "Helvetica", true, false, QFont::Helvetica }, { "Helvetica-BoldOblique", "Helvetica", true, true, QFont::Helvetica }, { "Times-Roman", "Times", false, false, QFont::Times }, { "Times-Italic", "Times", false, true, QFont::Times }, { "Times-Bold", "Times", true, false, QFont::Times }, { "Times-BoldItalic", "Times", true, true, QFont::Times }, { "Courier", "Courier", false, false, QFont::Courier }, { "Courier-Oblique", "Courier", false, true, QFont::Courier }, { "Courier-Bold", "Courier", true, false, QFont::Courier }, { "Courier-BoldOblique", "Courier", true, true, QFont::Courier }, { "Symbol", 0, false, false, QFont::AnyStyle }, { "Zapf-Dingbats", 0, false, false, QFont::AnyStyle }, { 0, 0, false, false, QFont::AnyStyle } }; QFont QOutputDev::matchFont ( GfxFont *gfxFont, fp_t m11, fp_t m12, fp_t m21, fp_t m22 ) { static QDict<QOutFontSubst> stdfonts; // build dict for std. fonts on first invocation if ( stdfonts. isEmpty ( )) { for ( QOutFontSubst *ptr = qStdFonts; ptr-> m_name; ptr++ ) { stdfonts. insert ( QString ( ptr-> m_name ), ptr ); } } // compute size and normalized transform matrix int size = lrint ( sqrt ( m21 * m21 + m22 * m22 )); QPDFDBG( printf ( "SET FONT: Name=%s, Size=%d, Bold=%d, Italic=%d, Mono=%d, Serif=%d, Symbol=%d, CID=%d, EmbFN=%s, M=(%f,%f,%f,%f)\n", (( gfxFont-> getName ( )) ? gfxFont-> getName ( )-> getCString ( ) : "<n/a>" ), size, gfxFont-> isBold ( ), gfxFont-> isItalic ( ), gfxFont-> isFixedWidth ( ), gfxFont-> isSerif ( ), gfxFont-> isSymbolic ( ), gfxFont-> isCIDFont ( ), ( gfxFont-> getEmbeddedFontName ( ) ? gfxFont-> getEmbeddedFontName()-> getCString ( ) : "<n/a>" ), (double) m11, (double) m12, (double) m21, (double) m22 ) ); QString fname (( gfxFont-> getName ( )) ? gfxFont-> getName ( )-> getCString ( ) : "<n/a>" ); QFont f; f. setPixelSize ( size > 0 ? size : 8 ); // type3 fonts misbehave sometimes // fast lookup for std. fonts QOutFontSubst *subst = stdfonts [fname]; if ( subst ) { if ( subst-> m_sname ) f. setFamily ( subst-> m_sname ); f. setStyleHint ( subst-> m_hint, (QFont::StyleStrategy) ( QFont::PreferOutline | QFont::PreferQuality )); f. setBold ( subst-> m_bold ); f. setItalic ( subst-> m_italic ); } else { QFont::StyleHint sty; if ( gfxFont-> isSerif ( )) sty = QFont::Serif; else if ( gfxFont-> isFixedWidth ( )) sty = QFont::TypeWriter; else sty = QFont::Helvetica; f. setStyleHint ( sty, (QFont::StyleStrategy) ( QFont::PreferOutline | QFont::PreferQuality )); f. setBold ( gfxFont-> isBold ( ) > 0 ); f. setItalic ( gfxFont-> isItalic ( ) > 0 ); f. setFixedPitch ( gfxFont-> isFixedWidth ( ) > 0 ); // common specifiers in font names if ( fname. contains ( "Oblique" ) || fname. contains ( "Italic" )) f. setItalic ( true ); if ( fname. contains ( "Bold" )) f. setWeight ( QFont::Bold ); if ( fname. contains ( "Demi" )) f. setWeight ( QFont::DemiBold ); if ( fname. contains ( "Light" )) f. setWeight ( QFont::Light ); if ( fname. contains ( "Black" )) f. setWeight ( QFont::Black ); } // Treat x-sheared fonts as italic if (( m12 > -0.1 ) && ( m12 < 0.1 ) && ((( m21 > -5.0 ) && ( m21 < -0.1 )) || (( m21 > 0.1 ) && ( m21 < 5.0 )))) { f. setItalic ( true ); } return f; } //------------------------------------------------------------------------ // QOutputDev //------------------------------------------------------------------------ QOutputDev::QOutputDev ( QWidget *parent, const char *name, int flags ) : QScrollView ( parent, name, WRepaintNoErase | WResizeNoErase | flags ) { m_pixmap = 0; m_painter = 0; // create text object m_text = new TextPage ( gFalse ); } QOutputDev::~QOutputDev ( ) { delete m_painter; delete m_pixmap; delete m_text; } void QOutputDev::startPage ( int /*pageNum*/, GfxState *state ) { delete m_pixmap; delete m_painter; m_pixmap = new QPixmap ( lrint ( state-> getPageWidth ( )), lrint ( state-> getPageHeight ( ))); m_painter = new QPainter ( m_pixmap ); QPDFDBG( printf ( "NEW PIXMAP (%ld x %ld)\n", lrint ( state-> getPageWidth ( )), lrint ( state-> getPageHeight ( )))); resizeContents ( m_pixmap-> width ( ), m_pixmap-> height ( )); setContentsPos ( 0, 0 ); m_pixmap-> fill ( white ); // clear window m_text-> clear ( ); // cleat text object viewport ( )-> repaint ( ); } void QOutputDev::endPage ( ) { QPDFDBG( printf("End page\n") ); m_text-> coalesce ( ); /* * I get stupid crashes after endPage is called and then we do clipping * and other stuff..... */ #if 0 delete m_painter; m_painter = 0; #endif updateContents ( 0, 0, contentsWidth ( ), contentsHeight ( )); } void QOutputDev::drawLink ( Link *link, Catalog */*catalog*/ ) { fp_t x1, y1, x2, y2, w; link-> getBorder ( &x1, &y1, &x2, &y2, &w ); if ( w > 0 ) { int x, y, dx, dy; cvtUserToDev ( x1, y1, &x, &y ); cvtUserToDev ( x2, y2, &dx, &dy ); QPen oldpen = m_painter-> pen ( ); m_painter-> setPen ( blue ); m_painter-> drawRect ( x, y, dx, dy ); m_painter-> setPen ( oldpen ); } } void QOutputDev::saveState ( GfxState */*state*/ ) { if ( ! m_painter ) return; QPDFDBG( printf ( "SAVE (CLIP=%d/%d)\n", m_painter-> hasClipping ( ), !m_painter-> clipRegion ( ). isEmpty ( ))); m_painter-> save ( ); } void QOutputDev::restoreState ( GfxState */*state*/ ) { if( ! m_painter ) return; m_painter-> restore ( ); // m_painter-> setClipRegion ( QRect ( 0, 0, m_pixmap-> width ( ), m_pixmap-> height ( ))); // m_painter-> setClipping ( false ); QPDFDBG ( printf ( "RESTORE (CLIP=%d/%d)\n", m_painter-> hasClipping ( ), !m_painter-> clipRegion ( ). isEmpty ( ))); } void QOutputDev::updateAll ( GfxState *state ) { updateLineAttrs ( state, gTrue ); // updateFlatness ( state ); // updateMiterLimit ( state ); updateFillColor ( state ); updateStrokeColor ( state ); updateFont ( state ); } void QOutputDev::updateCTM ( GfxState *state, fp_t /*m11*/, fp_t /*m12*/, fp_t /*m21*/, fp_t /*m22*/, fp_t /*m31*/, fp_t /*m32*/ ) { updateLineAttrs ( state, gTrue ); } void QOutputDev::updateLineDash ( GfxState *state ) { updateLineAttrs ( state, gTrue ); } void QOutputDev::updateFlatness ( GfxState */*state*/ ) { // not supported QPDFDBG( printf ( "updateFlatness not supported !\n" )); } void QOutputDev::updateLineJoin ( GfxState *state ) { updateLineAttrs ( state, gFalse ); } void QOutputDev::updateLineCap ( GfxState *state ) { updateLineAttrs ( state, gFalse ); } // unimplemented void QOutputDev::updateMiterLimit ( GfxState */*state*/ ) { QPDFDBG( printf ( "updateMiterLimit not supported !\n" )); } void QOutputDev::updateLineWidth ( GfxState *state ) { updateLineAttrs ( state, gFalse ); } void QOutputDev::updateLineAttrs ( GfxState *state, GBool updateDash ) { fp_t *dashPattern; int dashLength; fp_t dashStart; Qt::PenCapStyle cap; Qt::PenJoinStyle join; int width; width = lrint ( state-> getTransformedLineWidth ( )); switch ( state-> getLineCap ( )) { case 0: cap = FlatCap; break; case 1: cap = RoundCap; break; case 2: cap = SquareCap; break; default: qWarning ( "Bad line cap style (%d)\n", state-> getLineCap ( )); cap = FlatCap; break; } switch (state->getLineJoin()) { case 0: join = MiterJoin; break; case 1: join = RoundJoin; break; case 2: join = BevelJoin; break; default: qWarning ( "Bad line join style (%d)\n", state->getLineJoin ( )); join = MiterJoin; break; } state-> getLineDash ( &dashPattern, &dashLength, &dashStart ); QColor oldcol = m_painter-> pen ( ). color ( ); GfxRGB rgb; state-> getStrokeRGB ( &rgb ); oldcol = q_col ( rgb ); m_painter-> setPen ( QPen ( oldcol, width, dashLength > 0 ? DashLine : SolidLine, cap, join )); if ( updateDash && ( dashLength > 0 )) { // Not supported by QT /* char dashList[20]; if (dashLength > 20) dashLength = 20; for ( int i = 0; i < dashLength; ++i ) { dashList[i] = xoutRound(state->transformWidth(dashPattern[i])); if (dashList[i] == 0) dashList[i] = 1; } XSetDashes(display, strokeGC, xoutRound(dashStart), dashList, dashLength); */ } } void QOutputDev::updateFillColor ( GfxState *state ) { GfxRGB rgb; state-> getFillRGB ( &rgb ); m_painter-> setBrush ( q_col ( rgb )); } void QOutputDev::updateStrokeColor ( GfxState *state ) { GfxRGB rgb; state-> getStrokeRGB ( &rgb ); QPen pen = m_painter-> pen ( ); pen. setColor ( q_col ( rgb )); m_painter-> setPen ( pen ); } void QOutputDev::updateFont ( GfxState *state ) { fp_t m11, m12, m21, m22; GfxFont *gfxFont = state-> getFont ( ); if ( !gfxFont ) return; state-> getFontTransMat ( &m11, &m12, &m21, &m22 ); m11 *= state-> getHorizScaling ( ); m12 *= state-> getHorizScaling ( ); QFont font = matchFont ( gfxFont, m11, m12, m21, m22 ); m_painter-> setFont ( font ); m_text-> updateFont ( state ); } void QOutputDev::stroke ( GfxState *state ) { QPointArray points; QArray<int> lengths; // transform points int n = convertPath ( state, points, lengths ); QPDFDBG( printf ( "DRAWING: %d POLYS\n", n )); // draw each subpath int j = 0; for ( int i = 0; i < n; i++ ) { int len = lengths [i]; if ( len >= 2 ) { QPDFDBG( printf ( " - POLY %d: ", i )); QPDFDBG( for ( int ii = 0; ii < len; ii++ )) QPDFDBG( printf ( "(%d/%d) ", points [j+ii]. x ( ), points [j+ii]. y ( ))); QPDFDBG( printf ( "\n" )); m_painter-> drawPolyline ( points, j, len ); } j += len; } qApp-> processEvents ( ); } void QOutputDev::fill ( GfxState *state ) { doFill ( state, true ); } void QOutputDev::eoFill ( GfxState *state ) { doFill ( state, false ); } // // X doesn't color the pixels on the right-most and bottom-most // borders of a polygon. This means that one-pixel-thick polygons // are not colored at all. I think this is supposed to be a // feature, but I can't figure out why. So after it fills a // polygon, it also draws lines around the border. This is done // only for single-component polygons, since it's not very // compatible with the compound polygon kludge (see convertPath()). // void QOutputDev::doFill ( GfxState *state, bool winding ) { QPointArray points; QArray<int> lengths; // transform points int n = convertPath ( state, points, lengths ); QPDFDBG( printf ( "FILLING: %d POLYS\n", n )); QPen oldpen = m_painter-> pen ( ); m_painter-> setPen ( QPen ( NoPen )); // draw each subpath int j = 0; for ( int i = 0; i < n; i++ ) { int len = lengths [i]; if ( len >= 3 ) { QPDFDBG( printf ( " - POLY %d: ", i )); QPDFDBG( for ( int ii = 0; ii < len; ii++ )) QPDFDBG( printf ( "(%d/%d) ", points [j+ii]. x ( ), points [j+ii]. y ( ))); QPDFDBG( printf ( "\n" )); m_painter-> drawPolygon ( points, winding, j, len ); } j += len; } m_painter-> setPen ( oldpen ); qApp-> processEvents ( ); } void QOutputDev::clip ( GfxState *state ) { doClip ( state, true ); } void QOutputDev::eoClip ( GfxState *state ) { doClip ( state, false ); } void QOutputDev::doClip ( GfxState *state, bool winding ) { QPointArray points; QArray<int> lengths; // transform points int n = convertPath ( state, points, lengths ); QRegion region; QPDFDBG( printf ( "CLIPPING: %d POLYS\n", n )); // draw each subpath int j = 0; for ( int i = 0; i < n; i++ ) { int len = lengths [i]; if ( len >= 3 ) { QPointArray dummy; dummy. setRawData ( points. data ( ) + j, len ); QPDFDBG( printf ( " - POLY %d: ", i )); QPDFDBG( for ( int ii = 0; ii < len; ii++ ) printf ( "(%d/%d) ", points [j+ii]. x ( ), points [j+ii]. y ( ))); QPDFDBG( printf ( "\n" )); region |= QRegion ( dummy, winding ); dummy. resetRawData ( points. data ( ) + j, len ); } j += len; } if ( m_painter && m_painter-> hasClipping ( )) region &= m_painter-> clipRegion ( ); // m_painter-> setClipRegion ( region ); // m_painter-> setClipping ( true ); // m_painter-> fillRect ( 0, 0, m_pixmap-> width ( ), m_pixmap-> height ( ), red ); // m_painter-> drawText ( points [0]. x ( ) + 10, points [0]. y ( ) + 10, "Bla bla" ); qApp-> processEvents ( ); } // // Transform points in the path and convert curves to line segments. // Builds a set of subpaths and returns the number of subpaths. // If <fillHack> is set, close any unclosed subpaths and activate a // kludge for polygon fills: First, it divides up the subpaths into // non-overlapping polygons by simply comparing bounding rectangles. // Then it connects subaths within a single compound polygon to a single // point so that X can fill the polygon (sort of). // int QOutputDev::convertPath ( GfxState *state, QPointArray &points, QArray<int> &lengths ) { GfxPath *path = state-> getPath ( ); int n = path-> getNumSubpaths ( ); lengths. resize ( n ); // do each subpath for ( int i = 0; i < n; i++ ) { // transform the points lengths [i] = convertSubpath ( state, path-> getSubpath ( i ), points ); } return n; } // // Transform points in a single subpath and convert curves to line // segments. // int QOutputDev::convertSubpath ( GfxState *state, GfxSubpath *subpath, QPointArray &points ) { int oldcnt = points. count ( ); fp_t x0, y0, x1, y1, x2, y2, x3, y3; int m = subpath-> getNumPoints ( ); int i = 0; while ( i < m ) { if ( i >= 1 && subpath-> getCurve ( i )) { state-> transform ( subpath-> getX ( i - 1 ), subpath-> getY ( i - 1 ), &x0, &y0 ); state-> transform ( subpath-> getX ( i ), subpath-> getY ( i ), &x1, &y1 ); state-> transform ( subpath-> getX ( i + 1 ), subpath-> getY ( i + 1 ), &x2, &y2 ); state-> transform ( subpath-> getX ( i + 2 ), subpath-> getY ( i + 2 ), &x3, &y3 ); QPointArray tmp; tmp. setPoints ( 4, lrint ( x0 ), lrint ( y0 ), lrint ( x1 ), lrint ( y1 ), lrint ( x2 ), lrint ( y2 ), lrint ( x3 ), lrint ( y3 )); -#if QT_VERSION < 300 +#if QT_VERSION < 0x030000 tmp = tmp. quadBezier ( ); for ( uint loop = 0; loop < tmp. count ( ); loop++ ) { QPoint p = tmp. point ( loop ); points. putPoints ( points. count ( ), 1, p. x ( ), p. y ( )); } #else tmp = tmp. cubicBezier ( ); points. putPoints ( points. count ( ), tmp. count ( ), tmp ); #endif i += 3; } else { state-> transform ( subpath-> getX ( i ), subpath-> getY ( i ), &x1, &y1 ); points. putPoints ( points. count ( ), 1, lrint ( x1 ), lrint ( y1 )); ++i; } } return points. count ( ) - oldcnt; } void QOutputDev::beginString ( GfxState *state, GString */*s*/ ) { m_text-> beginString ( state ); } void QOutputDev::endString ( GfxState */*state*/ ) { m_text-> endString ( ); } void QOutputDev::drawChar ( GfxState *state, fp_t x, fp_t y, fp_t dx, fp_t dy, fp_t originX, fp_t originY, CharCode code, Unicode *u, int uLen ) { fp_t x1, y1, dx1, dy1; if ( uLen > 0 ) m_text-> addChar ( state, x, y, dx, dy, u, uLen ); // check for invisible text -- this is used by Acrobat Capture if (( state-> getRender ( ) & 3 ) == 3 ) { return; } x -= originX; y -= originY; state-> transform ( x, y, &x1, &y1 ); state-> transformDelta ( dx, dy, &dx1, &dy1 ); if ( uLen > 0 ) { QString str; QFontMetrics fm = m_painter-> fontMetrics ( ); for ( int i = 0; i < uLen; i++ ) { QChar c = QChar ( u [i] ); if ( fm. inFont ( c )) { str [i] = QChar ( u [i] ); } else { str [i] = ' '; QPDFDBG( printf ( "CHARACTER NOT IN FONT: %hx\n", c. unicode ( ))); } } if (( uLen == 1 ) && ( str [0] == ' ' )) return; fp_t m11, m12, m21, m22; state-> getFontTransMat ( &m11, &m12, &m21, &m22 ); m11 *= state-> getHorizScaling ( ); m12 *= state-> getHorizScaling ( ); fp_t fsize = m_painter-> font ( ). pixelSize ( ); #ifndef QT_NO_TRANSFORMATIONS QWMatrix oldmat; bool dorot = (( m12 < -0.1 ) || ( m12 > 0.1 )) && (( m21 < -0.1 ) || ( m21 > 0.1 )); if ( dorot ) { oldmat = m_painter-> worldMatrix ( ); std::cerr << std::endl << "ROTATED: " << m11 << ", " << m12 << ", " << m21 << ", " << m22 << " / SIZE: " << fsize << " / TEXT: " << str. local8Bit ( ) << endl << endl; QWMatrix mat ( lrint ( m11 / fsize ), lrint ( m12 / fsize ), -lrint ( m21 / fsize ), -lrint ( m22 / fsize ), lrint ( x1 ), lrint ( y1 )); m_painter-> setWorldMatrix ( mat ); x1 = 0; y1 = 0; } #endif QPen oldpen = m_painter-> pen ( ); if (!( state-> getRender ( ) & 1 )) { QPen fillpen = oldpen; fillpen. setColor ( m_painter-> brush ( ). color ( )); m_painter-> setPen ( fillpen ); } if ( fsize > 5 ) m_painter-> drawText ( lrint ( x1 ), lrint ( y1 ), str ); else m_painter-> fillRect ( lrint ( x1 ), lrint ( y1 ), lrint ( QMAX( fp_t(1), dx1 )), lrint ( QMAX( fsize, dy1 )), m_painter-> pen ( ). color ( )); m_painter-> setPen ( oldpen ); #ifndef QT_NO_TRANSFORMATIONS if ( dorot ) m_painter-> setWorldMatrix ( oldmat ); #endif QPDFDBG( printf ( "DRAW TEXT: \"%s\" at (%ld/%ld)\n", str. local8Bit ( ). data ( ), lrint ( x1 ), lrint ( y1 ))); } else if ( code != 0 ) { // some PDF files use CID 0, which is .notdef, so just ignore it qWarning ( "Unknown character (CID=%d Unicode=%hx)\n", code, (unsigned short) ( uLen > 0 ? u [0] : (Unicode) 0 )); } qApp-> processEvents ( ); } void QOutputDev::drawImageMask ( GfxState *state, Object */*ref*/, Stream *str, int width, int height, GBool invert, GBool inlineImg ) { // get CTM, check for singular matrix fp_t *ctm = state-> getCTM ( ); if ( fabs ( ctm [0] * ctm [3] - ctm [1] * ctm [2] ) < 0.000001 ) { qWarning ( "Singular CTM in drawImage\n" ); if ( inlineImg ) { str-> reset ( ); int j = height * (( width + 7 ) / 8 ); for ( int i = 0; i < j; i++ ) str->getChar(); str->close(); } return; } GfxRGB rgb; state-> getFillRGB ( &rgb ); uint val = ( lrint ( rgb. r * 255 ) & 0xff ) << 16 | ( lrint ( rgb. g * 255 ) & 0xff ) << 8 | ( lrint ( rgb. b * 255 ) & 0xff ); QImage img ( width, height, 32 ); img. setAlphaBuffer ( true ); QPDFDBG( printf ( "IMAGE MASK (%dx%d)\n", width, height )); // initialize the image stream ImageStream *imgStr = new ImageStream ( str, width, 1, 1 ); imgStr-> reset ( ); uchar **scanlines = img. jumpTable ( ); if ( ctm [3] > 0 ) scanlines += ( height - 1 ); for ( int y = 0; y < height; y++ ) { QRgb *scanline = (QRgb *) *scanlines; if ( ctm [0] < 0 ) scanline += ( width - 1 ); for ( int x = 0; x < width; x++ ) { Guchar alpha; imgStr-> getPixel ( &alpha ); if ( invert ) alpha ^= 1; *scanline = ( alpha == 0 ) ? 0xff000000 | val : val; ctm [0] < 0 ? scanline-- : scanline++; } ctm [3] > 0 ? scanlines-- : scanlines++; qApp-> processEvents ( ); } #ifndef QT_NO_TRANSFORMATIONS QWMatrix mat ( ctm [0] / width, ctm [1], ctm [2], ctm [3] / height, ctm [4], ctm [5] ); std::cerr << "MATRIX T=" << mat. dx ( ) << "/" << mat. dy ( ) << std::endl << " - M=" << mat. m11 ( ) << "/" << mat. m12 ( ) << "/" << mat. m21 ( ) << "/" << mat. m22 ( ) << std::endl; QWMatrix oldmat = m_painter-> worldMatrix ( ); m_painter-> setWorldMatrix ( mat, true ); #ifdef QWS QPixmap pm; pm. convertFromImage ( img ); m_painter-> drawPixmap ( 0, 0, pm ); #else m_painter-> drawImage ( QPoint ( 0, 0 ), img ); #endif m_painter-> setWorldMatrix ( oldmat ); #else if (( ctm [1] < -0.1 ) || ( ctm [1] > 0.1 ) || ( ctm [2] < -0.1 ) || ( ctm [2] > 0.1 )) { QPDFDBG( printf ( "### ROTATED / SHEARED / ETC -- CANNOT DISPLAY THIS IMAGE\n" )); } else { int x = lrint ( ctm [4] ); int y = lrint ( ctm [5] ); int w = lrint ( ctm [0] ); int h = lrint ( ctm [3] ); if ( w < 0 ) { x += w; w = -w; } if ( h < 0 ) { y += h; h = -h; } QPDFDBG( printf ( "DRAWING IMAGE MASKED: %d/%d - %dx%d\n", x, y, w, h )); img = img. smoothScale ( w, h ); qApp-> processEvents ( ); m_painter-> drawImage ( x, y, img ); } #endif delete imgStr; qApp-> processEvents ( ); } void QOutputDev::drawImage(GfxState *state, Object */*ref*/, Stream *str, int width, int height, GfxImageColorMap *colorMap, int *maskColors, GBool inlineImg ) { int nComps, nVals, nBits; // image parameters nComps = colorMap->getNumPixelComps ( ); nVals = width * nComps; nBits = colorMap-> getBits ( ); // get CTM, check for singular matrix fp_t *ctm = state-> getCTM ( ); if ( fabs ( ctm [0] * ctm [3] - ctm [1] * ctm [2] ) < 0.000001 ) { qWarning ( "Singular CTM in drawImage\n" ); if ( inlineImg ) { str-> reset ( ); int j = height * (( nVals * nBits + 7 ) / 8 ); for ( int i = 0; i < j; i++ ) str->getChar(); str->close(); } return; } QImage img ( width, height, 32 ); if ( maskColors ) img. setAlphaBuffer ( true ); QPDFDBG( printf ( "IMAGE (%dx%d)\n", width, height )); // initialize the image stream ImageStream *imgStr = new ImageStream ( str, width, nComps, nBits ); imgStr-> reset ( ); Guchar pixBuf [gfxColorMaxComps]; GfxRGB rgb; uchar **scanlines = img. jumpTable ( ); if ( ctm [3] > 0 ) scanlines += ( height - 1 ); for ( int y = 0; y < height; y++ ) { QRgb *scanline = (QRgb *) *scanlines; if ( ctm [0] < 0 ) scanline += ( width - 1 ); for ( int x = 0; x < width; x++ ) { imgStr-> getPixel ( pixBuf ); colorMap-> getRGB ( pixBuf, &rgb ); uint val = ( lrint ( rgb. r * 255 ) & 0xff ) << 16 | ( lrint ( rgb. g * 255 ) & 0xff ) << 8 | ( lrint ( rgb. b * 255 ) & 0xff ); if ( maskColors ) { for ( int k = 0; k < nComps; ++k ) { if (( pixBuf [k] < maskColors [2 * k] ) || ( pixBuf [k] > maskColors [2 * k] )) { val |= 0xff000000; break; } } } *scanline = val; ctm [0] < 0 ? scanline-- : scanline++; } ctm [3] > 0 ? scanlines-- : scanlines++; qApp-> processEvents ( ); } #ifndef QT_NO_TRANSFORMATIONS QWMatrix mat ( ctm [0] / width, ctm [1], ctm [2], ctm [3] / height, ctm [4], ctm [5] ); std::cerr << "MATRIX T=" << mat. dx ( ) << "/" << mat. dy ( ) << std::endl << " - M=" << mat. m11 ( ) << "/" << mat. m12 ( ) << "/" << mat. m21 ( ) << "/" << mat. m22 ( ) << std::endl; QWMatrix oldmat = m_painter-> worldMatrix ( ); m_painter-> setWorldMatrix ( mat, true ); #ifdef QWS QPixmap pm; pm. convertFromImage ( img ); m_painter-> drawPixmap ( 0, 0, pm ); #else m_painter-> drawImage ( QPoint ( 0, 0 ), img ); #endif m_painter-> setWorldMatrix ( oldmat ); #else // QT_NO_TRANSFORMATIONS if (( ctm [1] < -0.1 ) || ( ctm [1] > 0.1 ) || ( ctm [2] < -0.1 ) || ( ctm [2] > 0.1 )) { QPDFDBG( printf ( "### ROTATED / SHEARED / ETC -- CANNOT DISPLAY THIS IMAGE\n" )); } else { int x = lrint ( ctm [4] ); int y = lrint ( ctm [5] ); int w = lrint ( ctm [0] ); int h = lrint ( ctm [3] ); if ( w < 0 ) { x += w; w = -w; } if ( h < 0 ) { y += h; h = -h; } QPDFDBG( printf ( "DRAWING IMAGE: %d/%d - %dx%d\n", x, y, w, h )); img = img. smoothScale ( w, h ); qApp-> processEvents ( ); m_painter-> drawImage ( x, y, img ); } #endif delete imgStr; qApp-> processEvents ( ); } bool QOutputDev::findText ( const QString &str, QRect &r, bool top, bool bottom ) { int l, t, w, h; r. rect ( &l, &t, &w, &h ); bool res = findText ( str, l, t, w, h, top, bottom ); r. setRect ( l, t, w, h ); return res; } bool QOutputDev::findText ( const QString &str, int &l, int &t, int &w, int &h, bool top, bool bottom ) { bool found = false; uint len = str. length ( ); Unicode *s = new Unicode [len]; for ( uint i = 0; i < len; i++ ) s [i] = str [i]. unicode ( ); fp_t x1 = (fp_t) l; fp_t y1 = (fp_t) t; fp_t x2 = (fp_t) l + w - 1; fp_t y2 = (fp_t) t + h - 1; if ( m_text-> findText ( s, len, top, bottom, &x1, &y1, &x2, &y2 )) { l = lrint ( x1 ); t = lrint ( y1 ); w = lrint ( x2 ) - l + 1; h = lrint ( y2 ) - t + 1; found = true; } delete [] s; return found; } GBool QOutputDev::findText ( Unicode *s, int len, GBool top, GBool bottom, int *xMin, int *yMin, int *xMax, int *yMax ) { bool found = false; fp_t xMin1 = (double) *xMin; fp_t yMin1 = (double) *yMin; fp_t xMax1 = (double) *xMax; fp_t yMax1 = (double) *yMax; if ( m_text-> findText ( s, len, top, bottom, &xMin1, &yMin1, &xMax1, &yMax1 )) { *xMin = lrint ( xMin1 ); *xMax = lrint ( xMax1 ); *yMin = lrint ( yMin1 ); *yMax = lrint ( yMax1 ); found = true; } return found; } QString QOutputDev::getText ( int l, int t, int w, int h ) { GString *gstr = m_text-> getText ( l, t, l + w - 1, t + h - 1 ); QString str = gstr-> getCString ( ); delete gstr; return str; } QString QOutputDev::getText ( const QRect &r ) { return getText ( r. left ( ), r. top ( ), r. width ( ), r. height ( )); } void QOutputDev::drawContents ( QPainter *p, int clipx, int clipy, int clipw, int cliph ) { if ( m_pixmap ) p-> drawPixmap ( clipx, clipy, *m_pixmap, clipx, clipy, clipw, cliph ); else p-> fillRect ( clipx, clipy, clipw, cliph, white ); } diff --git a/scripts/kconfig/qconf.cc b/scripts/kconfig/qconf.cc index 52419ad..0459caf 100644 --- a/scripts/kconfig/qconf.cc +++ b/scripts/kconfig/qconf.cc @@ -1,1304 +1,1304 @@ /* * Copyright (C) 2002 Roman Zippel <zippel@linux-m68k.org> * Released under the terms of the GNU GPL v2.0. */ #include <qapplication.h> #include <qmainwindow.h> #include <qtoolbar.h> #include <qvbox.h> #include <qsplitter.h> #include <qlistview.h> #include <qtextview.h> #include <qlineedit.h> #include <qmenubar.h> #include <qmessagebox.h> #include <qaction.h> #include <qheader.h> #include <qfiledialog.h> #include <qregexp.h> -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 #include <qsettings.h> #endif #include <stdlib.h> #include "lkc.h" #include "qconf.h" #include "qconf.moc" #include "images.c" static QApplication *configApp; -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 static QSettings *configSettings; #endif /* * update all the children of a menu entry * removes/adds the entries from the parent widget as necessary * * parent: either the menu list widget or a menu entry widget * menu: entry to be updated */ template <class P> void ConfigList::updateMenuList(P* parent, struct menu* menu) { struct menu* child; ConfigItem* item; ConfigItem* last; bool visible; enum prop_type type; if (!menu) { while ((item = parent->firstChild())) delete item; return; } last = parent->firstChild(); if (last && !last->goParent) last = 0; for (child = menu->list; child; child = child->next) { item = last ? last->nextSibling() : parent->firstChild(); type = child->prompt ? child->prompt->type : P_UNKNOWN; switch (mode) { case menuMode: if (!(child->flags & MENU_ROOT)) goto hide; break; case symbolMode: if (child->flags & MENU_ROOT) goto hide; break; default: break; } visible = menu_is_visible(child); if (showAll || visible) { if (!item || item->menu != child) item = new ConfigItem(parent, last, child, visible); else item->testUpdateMenu(visible); if (mode == fullMode || mode == menuMode || type != P_MENU) updateMenuList(item, child); else updateMenuList(item, 0); last = item; continue; } hide: if (item && item->menu == child) { last = parent->firstChild(); if (last == item) last = 0; else while (last->nextSibling() != item) last = last->nextSibling(); delete item; } } } -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 /* * set the new data * TODO check the value */ void ConfigItem::okRename(int col) { Parent::okRename(col); sym_set_string_value(menu->sym, text(dataColIdx).latin1()); } #endif /* * update the displayed of a menu entry */ void ConfigItem::updateMenu(void) { ConfigList* list; struct symbol* sym; struct property *prop; QString prompt; int type; tristate expr; list = listView(); if (goParent) { setPixmap(promptColIdx, list->menuBackPix); prompt = ".."; goto set_prompt; } sym = menu->sym; prop = menu->prompt; prompt = menu_get_prompt(menu); if (prop) switch (prop->type) { case P_MENU: if (list->mode == singleMode || list->mode == symbolMode) { /* a menuconfig entry is displayed differently * depending whether it's at the view root or a child. */ if (sym && list->rootEntry == menu) break; setPixmap(promptColIdx, list->menuPix); } else { if (sym) break; setPixmap(promptColIdx, 0); } goto set_prompt; case P_COMMENT: setPixmap(promptColIdx, 0); goto set_prompt; default: ; } if (!sym) goto set_prompt; setText(nameColIdx, sym->name); type = sym_get_type(sym); switch (type) { case S_BOOLEAN: case S_TRISTATE: char ch; if (!sym_is_changable(sym) && !list->showAll) { setPixmap(promptColIdx, 0); setText(noColIdx, 0); setText(modColIdx, 0); setText(yesColIdx, 0); break; } expr = sym_get_tristate_value(sym); switch (expr) { case yes: if (sym_is_choice_value(sym) && type == S_BOOLEAN) setPixmap(promptColIdx, list->choiceYesPix); else setPixmap(promptColIdx, list->symbolYesPix); setText(yesColIdx, "Y"); ch = 'Y'; break; case mod: setPixmap(promptColIdx, list->symbolModPix); setText(modColIdx, "M"); ch = 'M'; break; default: if (sym_is_choice_value(sym) && type == S_BOOLEAN) setPixmap(promptColIdx, list->choiceNoPix); else setPixmap(promptColIdx, list->symbolNoPix); setText(noColIdx, "N"); ch = 'N'; break; } if (expr != no) setText(noColIdx, sym_tristate_within_range(sym, no) ? "_" : 0); if (expr != mod) setText(modColIdx, sym_tristate_within_range(sym, mod) ? "_" : 0); if (expr != yes) setText(yesColIdx, sym_tristate_within_range(sym, yes) ? "_" : 0); setText(dataColIdx, QChar(ch)); break; case S_INT: case S_HEX: case S_STRING: const char* data; data = sym_get_string_value(sym); -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 int i = list->mapIdx(dataColIdx); if (i >= 0) setRenameEnabled(i, TRUE); #endif setText(dataColIdx, data); if (type == S_STRING) prompt.sprintf("%s: %s", prompt.latin1(), data); else prompt.sprintf("(%s) %s", data, prompt.latin1()); break; } if (!sym_has_value(sym) && visible) prompt += " (NEW)"; set_prompt: setText(promptColIdx, prompt); } void ConfigItem::testUpdateMenu(bool v) { ConfigItem* i; visible = v; if (!menu) return; sym_calc_value(menu->sym); if (menu->flags & MENU_CHANGED) { /* the menu entry changed, so update all list items */ menu->flags &= ~MENU_CHANGED; for (i = (ConfigItem*)menu->data; i; i = i->nextItem) i->updateMenu(); } else if (listView()->updateAll) updateMenu(); } void ConfigItem::paintCell(QPainter* p, const QColorGroup& cg, int column, int width, int align) { ConfigList* list = listView(); if (visible) { if (isSelected() && !list->hasFocus() && list->mode == menuMode) Parent::paintCell(p, list->inactivedColorGroup, column, width, align); else Parent::paintCell(p, cg, column, width, align); } else Parent::paintCell(p, list->disabledColorGroup, column, width, align); } /* * construct a menu entry */ void ConfigItem::init(void) { if (menu) { ConfigList* list = listView(); nextItem = (ConfigItem*)menu->data; menu->data = this; if (list->mode != fullMode) setOpen(TRUE); sym_calc_value(menu->sym); } updateMenu(); } /* * destruct a menu entry */ ConfigItem::~ConfigItem(void) { if (menu) { ConfigItem** ip = (ConfigItem**)&menu->data; for (; *ip; ip = &(*ip)->nextItem) { if (*ip == this) { *ip = nextItem; break; } } } } void ConfigLineEdit::show(ConfigItem* i) { item = i; if (sym_get_string_value(item->menu->sym)) setText(sym_get_string_value(item->menu->sym)); else setText(0); Parent::show(); setFocus(); } void ConfigLineEdit::keyPressEvent(QKeyEvent* e) { switch (e->key()) { case Key_Escape: break; case Key_Return: case Key_Enter: sym_set_string_value(item->menu->sym, text().latin1()); parent()->updateList(item); break; default: Parent::keyPressEvent(e); return; } e->accept(); parent()->list->setFocus(); hide(); } ConfigList::ConfigList(ConfigView* p, ConfigMainWindow* cv) : Parent(p), cview(cv), updateAll(false), symbolYesPix(xpm_symbol_yes), symbolModPix(xpm_symbol_mod), symbolNoPix(xpm_symbol_no), choiceYesPix(xpm_choice_yes), choiceNoPix(xpm_choice_no), menuPix(xpm_menu), menuInvPix(xpm_menu_inv), menuBackPix(xpm_menuback), voidPix(xpm_void), showAll(false), showName(false), showRange(false), showData(false), rootEntry(0) { int i; setSorting(-1); setRootIsDecorated(TRUE); disabledColorGroup = palette().active(); disabledColorGroup.setColor(QColorGroup::Text, palette().disabled().text()); inactivedColorGroup = palette().active(); inactivedColorGroup.setColor(QColorGroup::Highlight, palette().disabled().highlight()); connect(this, SIGNAL(selectionChanged(void)), SLOT(updateSelection(void))); for (i = 0; i < colNr; i++) colMap[i] = colRevMap[i] = -1; addColumn(promptColIdx, "Option"); reinit(); } void ConfigList::reinit(void) { removeColumn(dataColIdx); removeColumn(yesColIdx); removeColumn(modColIdx); removeColumn(noColIdx); removeColumn(nameColIdx); if (showName) addColumn(nameColIdx, "Name"); if (showRange) { addColumn(noColIdx, "N"); addColumn(modColIdx, "M"); addColumn(yesColIdx, "Y"); } if (showData) addColumn(dataColIdx, "Value"); updateListAll(); } void ConfigList::updateSelection(void) { struct menu *menu; enum prop_type type; ConfigItem* item = (ConfigItem*)selectedItem(); if (!item) return; cview->setHelp(item); menu = item->menu; if (!menu) return; type = menu->prompt ? menu->prompt->type : P_UNKNOWN; if (mode == menuMode && type == P_MENU) emit menuSelected(menu); } void ConfigList::updateList(ConfigItem* item) { ConfigItem* last = 0; if (!rootEntry) goto update; if (rootEntry != &rootmenu && (mode == singleMode || (mode == symbolMode && rootEntry->parent != &rootmenu))) { item = firstChild(); if (!item) item = new ConfigItem(this, 0, true); last = item; } if (mode == singleMode && rootEntry->sym && rootEntry->prompt) { item = last ? last->nextSibling() : firstChild(); if (!item) item = new ConfigItem(this, last, rootEntry, true); updateMenuList(item, rootEntry); triggerUpdate(); return; } update: updateMenuList(this, rootEntry); triggerUpdate(); } void ConfigList::setAllOpen(bool open) { QListViewItemIterator it(this); for (; it.current(); it++) it.current()->setOpen(open); } void ConfigList::setValue(ConfigItem* item, tristate val) { struct symbol* sym; int type; tristate oldval; sym = item->menu ? item->menu->sym : 0; if (!sym) return; type = sym_get_type(sym); switch (type) { case S_BOOLEAN: case S_TRISTATE: oldval = sym_get_tristate_value(sym); if (!sym_set_tristate_value(sym, val)) return; if (oldval == no && item->menu->list) item->setOpen(TRUE); parent()->updateList(item); break; } } void ConfigList::changeValue(ConfigItem* item) { struct symbol* sym; struct menu* menu; int type, oldexpr, newexpr; menu = item->menu; if (!menu) return; sym = menu->sym; if (!sym) { if (item->menu->list) item->setOpen(!item->isOpen()); return; } type = sym_get_type(sym); switch (type) { case S_BOOLEAN: case S_TRISTATE: oldexpr = sym_get_tristate_value(sym); newexpr = sym_toggle_tristate_value(sym); if (item->menu->list) { if (oldexpr == newexpr) item->setOpen(!item->isOpen()); else if (oldexpr == no) item->setOpen(TRUE); } if (oldexpr != newexpr) parent()->updateList(item); break; case S_INT: case S_HEX: case S_STRING: -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 if (colMap[dataColIdx] >= 0) item->startRename(colMap[dataColIdx]); else #endif parent()->lineEdit->show(item); break; } } void ConfigList::setRootMenu(struct menu *menu) { enum prop_type type; if (rootEntry == menu) return; type = menu && menu->prompt ? menu->prompt->type : P_UNKNOWN; if (type != P_MENU) return; updateMenuList(this, 0); rootEntry = menu; updateListAll(); setSelected(currentItem(), hasFocus()); } void ConfigList::setParentMenu(void) { ConfigItem* item; struct menu *oldroot; oldroot = rootEntry; if (rootEntry == &rootmenu) return; setRootMenu(menu_get_parent_menu(rootEntry->parent)); QListViewItemIterator it(this); for (; (item = (ConfigItem*)it.current()); it++) { if (item->menu == oldroot) { setCurrentItem(item); ensureItemVisible(item); break; } } } void ConfigList::keyPressEvent(QKeyEvent* ev) { QListViewItem* i = currentItem(); ConfigItem* item; struct menu *menu; enum prop_type type; if (ev->key() == Key_Escape && mode != fullMode) { emit parentSelected(); ev->accept(); return; } if (!i) { Parent::keyPressEvent(ev); return; } item = (ConfigItem*)i; switch (ev->key()) { case Key_Return: case Key_Enter: if (item->goParent) { emit parentSelected(); break; } menu = item->menu; if (!menu) break; type = menu->prompt ? menu->prompt->type : P_UNKNOWN; if (type == P_MENU && rootEntry != menu && mode != fullMode && mode != menuMode) { emit menuSelected(menu); break; } case Key_Space: changeValue(item); break; case Key_N: setValue(item, no); break; case Key_M: setValue(item, mod); break; case Key_Y: setValue(item, yes); break; default: Parent::keyPressEvent(ev); return; } ev->accept(); } void ConfigList::contentsMousePressEvent(QMouseEvent* e) { //QPoint p(contentsToViewport(e->pos())); //printf("contentsMousePressEvent: %d,%d\n", p.x(), p.y()); Parent::contentsMousePressEvent(e); } void ConfigList::contentsMouseReleaseEvent(QMouseEvent* e) { QPoint p(contentsToViewport(e->pos())); ConfigItem* item = (ConfigItem*)itemAt(p); struct menu *menu; enum prop_type ptype; const QPixmap* pm; int idx, x; if (!item) goto skip; menu = item->menu; x = header()->offset() + p.x(); idx = colRevMap[header()->sectionAt(x)]; switch (idx) { case promptColIdx: pm = item->pixmap(promptColIdx); if (pm) { int off = header()->sectionPos(0) + itemMargin() + treeStepSize() * (item->depth() + (rootIsDecorated() ? 1 : 0)); if (x >= off && x < off + pm->width()) { if (item->goParent) { emit parentSelected(); break; } else if (!menu) break; ptype = menu->prompt ? menu->prompt->type : P_UNKNOWN; if (ptype == P_MENU && rootEntry != menu && mode != fullMode && mode != menuMode) emit menuSelected(menu); else changeValue(item); } } break; case noColIdx: setValue(item, no); break; case modColIdx: setValue(item, mod); break; case yesColIdx: setValue(item, yes); break; case dataColIdx: changeValue(item); break; } skip: //printf("contentsMouseReleaseEvent: %d,%d\n", p.x(), p.y()); Parent::contentsMouseReleaseEvent(e); } void ConfigList::contentsMouseMoveEvent(QMouseEvent* e) { //QPoint p(contentsToViewport(e->pos())); //printf("contentsMouseMoveEvent: %d,%d\n", p.x(), p.y()); Parent::contentsMouseMoveEvent(e); } void ConfigList::contentsMouseDoubleClickEvent(QMouseEvent* e) { QPoint p(contentsToViewport(e->pos())); ConfigItem* item = (ConfigItem*)itemAt(p); struct menu *menu; enum prop_type ptype; if (!item) goto skip; if (item->goParent) { emit parentSelected(); goto skip; } menu = item->menu; if (!menu) goto skip; ptype = menu->prompt ? menu->prompt->type : P_UNKNOWN; if (ptype == P_MENU && (mode == singleMode || mode == symbolMode)) emit menuSelected(menu); else if (menu->sym) changeValue(item); skip: //printf("contentsMouseDoubleClickEvent: %d,%d\n", p.x(), p.y()); Parent::contentsMouseDoubleClickEvent(e); } void ConfigList::focusInEvent(QFocusEvent *e) { Parent::focusInEvent(e); QListViewItem* item = currentItem(); if (!item) return; setSelected(item, TRUE); emit gotFocus(); } ConfigView* ConfigView::viewList; ConfigView::ConfigView(QWidget* parent, ConfigMainWindow* cview) : Parent(parent) { list = new ConfigList(this, cview); lineEdit = new ConfigLineEdit(this); lineEdit->hide(); this->nextView = viewList; viewList = this; } ConfigView::~ConfigView(void) { ConfigView** vp; for (vp = &viewList; *vp; vp = &(*vp)->nextView) { if (*vp == this) { *vp = nextView; break; } } } void ConfigView::updateList(ConfigItem* item) { ConfigView* v; for (v = viewList; v; v = v->nextView) v->list->updateList(item); } void ConfigView::updateListAll(void) { ConfigView* v; for (v = viewList; v; v = v->nextView) v->list->updateListAll(); } /* * Construct the complete config widget */ ConfigMainWindow::ConfigMainWindow(void) { QMenuBar* menu; QSplitter* split1; QSplitter* split2; bool ok; int x, y, width, height; QWidget *d = configApp->desktop(); -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 width = configSettings->readNumEntry("/kconfig/qconf/window width", d->width() - 64); height = configSettings->readNumEntry("/kconfig/qconf/window height", d->height() - 64); resize(width, height); x = configSettings->readNumEntry("/kconfig/qconf/window x", 0, &ok); if (ok) y = configSettings->readNumEntry("/kconfig/qconf/window y", 0, &ok); if (ok) move(x, y); #else width = d->width() - 64; height = d->height() - 64; resize(width, height); #endif showDebug = false; split1 = new QSplitter(this); split1->setOrientation(QSplitter::Horizontal); setCentralWidget(split1); menuView = new ConfigView(split1, this); menuList = menuView->list; split2 = new QSplitter(split1); split2->setOrientation(QSplitter::Vertical); // create config tree configView = new ConfigView(split2, this); configList = configView->list; helpText = new QTextView(split2); helpText->setTextFormat(Qt::RichText); setTabOrder(configList, helpText); configList->setFocus(); menu = menuBar(); toolBar = new QToolBar("Tools", this); backAction = new QAction("Back", QPixmap(xpm_back), "Back", 0, this); connect(backAction, SIGNAL(activated()), SLOT(goBack())); backAction->setEnabled(FALSE); QAction *quitAction = new QAction("Quit", "&Quit", CTRL+Key_Q, this); connect(quitAction, SIGNAL(activated()), SLOT(close())); QAction *loadAction = new QAction("Load", QPixmap(xpm_load), "&Load", CTRL+Key_L, this); connect(loadAction, SIGNAL(activated()), SLOT(loadConfig())); QAction *saveAction = new QAction("Save", QPixmap(xpm_save), "&Save", CTRL+Key_S, this); connect(saveAction, SIGNAL(activated()), SLOT(saveConfig())); QAction *saveAsAction = new QAction("Save As...", "Save &As...", 0, this); connect(saveAsAction, SIGNAL(activated()), SLOT(saveConfigAs())); QAction *singleViewAction = new QAction("Single View", QPixmap(xpm_single_view), "Split View", 0, this); connect(singleViewAction, SIGNAL(activated()), SLOT(showSingleView())); QAction *splitViewAction = new QAction("Split View", QPixmap(xpm_split_view), "Split View", 0, this); connect(splitViewAction, SIGNAL(activated()), SLOT(showSplitView())); QAction *fullViewAction = new QAction("Full View", QPixmap(xpm_tree_view), "Full View", 0, this); connect(fullViewAction, SIGNAL(activated()), SLOT(showFullView())); QAction *showNameAction = new QAction(NULL, "Show Name", 0, this); showNameAction->setToggleAction(TRUE); showNameAction->setOn(configList->showName); connect(showNameAction, SIGNAL(toggled(bool)), SLOT(setShowName(bool))); QAction *showRangeAction = new QAction(NULL, "Show Range", 0, this); showRangeAction->setToggleAction(TRUE); showRangeAction->setOn(configList->showRange); connect(showRangeAction, SIGNAL(toggled(bool)), SLOT(setShowRange(bool))); QAction *showDataAction = new QAction(NULL, "Show Data", 0, this); showDataAction->setToggleAction(TRUE); showDataAction->setOn(configList->showData); connect(showDataAction, SIGNAL(toggled(bool)), SLOT(setShowData(bool))); QAction *showAllAction = new QAction(NULL, "Show All Options", 0, this); showAllAction->setToggleAction(TRUE); showAllAction->setOn(configList->showAll); connect(showAllAction, SIGNAL(toggled(bool)), SLOT(setShowAll(bool))); QAction *showDebugAction = new QAction(NULL, "Show Debug Info", 0, this); showDebugAction->setToggleAction(TRUE); showDebugAction->setOn(showDebug); connect(showDebugAction, SIGNAL(toggled(bool)), SLOT(setShowDebug(bool))); QAction *showIntroAction = new QAction(NULL, "Introduction", 0, this); connect(showIntroAction, SIGNAL(activated()), SLOT(showIntro())); QAction *showAboutAction = new QAction(NULL, "About", 0, this); connect(showAboutAction, SIGNAL(activated()), SLOT(showAbout())); // init tool bar backAction->addTo(toolBar); toolBar->addSeparator(); loadAction->addTo(toolBar); saveAction->addTo(toolBar); toolBar->addSeparator(); singleViewAction->addTo(toolBar); splitViewAction->addTo(toolBar); fullViewAction->addTo(toolBar); // create config menu QPopupMenu* config = new QPopupMenu(this); menu->insertItem("&File", config); loadAction->addTo(config); saveAction->addTo(config); saveAsAction->addTo(config); config->insertSeparator(); quitAction->addTo(config); // create options menu QPopupMenu* optionMenu = new QPopupMenu(this); menu->insertItem("&Option", optionMenu); showNameAction->addTo(optionMenu); showRangeAction->addTo(optionMenu); showDataAction->addTo(optionMenu); optionMenu->insertSeparator(); showAllAction->addTo(optionMenu); showDebugAction->addTo(optionMenu); // create help menu QPopupMenu* helpMenu = new QPopupMenu(this); menu->insertSeparator(); menu->insertItem("&Help", helpMenu); showIntroAction->addTo(helpMenu); showAboutAction->addTo(helpMenu); connect(configList, SIGNAL(menuSelected(struct menu *)), SLOT(changeMenu(struct menu *))); connect(configList, SIGNAL(parentSelected()), SLOT(goBack())); connect(menuList, SIGNAL(menuSelected(struct menu *)), SLOT(changeMenu(struct menu *))); connect(configList, SIGNAL(gotFocus(void)), SLOT(listFocusChanged(void))); connect(menuList, SIGNAL(gotFocus(void)), SLOT(listFocusChanged(void))); showSplitView(); } static QString print_filter(const char *str) { QRegExp re("[<>&\"\\n]"); QString res = str; for (int i = 0; (i = res.find(re, i)) >= 0;) { switch (res[i].latin1()) { case '<': res.replace(i, 1, "<"); i += 4; break; case '>': res.replace(i, 1, ">"); i += 4; break; case '&': res.replace(i, 1, "&"); i += 5; break; case '"': res.replace(i, 1, """); i += 6; break; case '\n': res.replace(i, 1, "<br>"); i += 4; break; } } return res; } static void expr_print_help(void *data, const char *str) { ((QString*)data)->append(print_filter(str)); } /* * display a new help entry as soon as a new menu entry is selected */ void ConfigMainWindow::setHelp(QListViewItem* item) { struct symbol* sym; struct menu* menu = 0; configList->parent()->lineEdit->hide(); if (item) menu = ((ConfigItem*)item)->menu; if (!menu) { helpText->setText(NULL); return; } QString head, debug, help; menu = ((ConfigItem*)item)->menu; sym = menu->sym; if (sym) { if (menu->prompt) { head += "<big><b>"; head += print_filter(menu->prompt->text); head += "</b></big>"; if (sym->name) { head += " ("; head += print_filter(sym->name); head += ")"; } } else if (sym->name) { head += "<big><b>"; head += print_filter(sym->name); head += "</b></big>"; } head += "<br><br>"; if (showDebug) { debug += "type: "; debug += print_filter(sym_type_name(sym->type)); if (sym_is_choice(sym)) debug += " (choice)"; debug += "<br>"; if (sym->rev_dep.expr) { debug += "reverse dep: "; expr_print(sym->rev_dep.expr, expr_print_help, &debug, E_NONE); debug += "<br>"; } for (struct property *prop = sym->prop; prop; prop = prop->next) { switch (prop->type) { case P_PROMPT: case P_MENU: debug += "prompt: "; debug += print_filter(prop->text); debug += "<br>"; break; case P_DEFAULT: debug += "default: "; expr_print(prop->expr, expr_print_help, &debug, E_NONE); debug += "<br>"; break; case P_CHOICE: if (sym_is_choice(sym)) { debug += "choice: "; expr_print(prop->expr, expr_print_help, &debug, E_NONE); debug += "<br>"; } break; case P_SELECT: debug += "select: "; expr_print(prop->expr, expr_print_help, &debug, E_NONE); debug += "<br>"; break; case P_RANGE: debug += "range: "; expr_print(prop->expr, expr_print_help, &debug, E_NONE); debug += "<br>"; break; default: debug += "unknown property: "; debug += prop_get_type_name(prop->type); debug += "<br>"; } if (prop->visible.expr) { debug += " dep: "; expr_print(prop->visible.expr, expr_print_help, &debug, E_NONE); debug += "<br>"; } } debug += "<br>"; } help = print_filter(sym->help); } else if (menu->prompt) { head += "<big><b>"; head += print_filter(menu->prompt->text); head += "</b></big><br><br>"; if (showDebug) { if (menu->prompt->visible.expr) { debug += " dep: "; expr_print(menu->prompt->visible.expr, expr_print_help, &debug, E_NONE); debug += "<br><br>"; } } } if (showDebug) debug += QString().sprintf("defined at %s:%d<br><br>", menu->file->name, menu->lineno); helpText->setText(head + debug + help); } void ConfigMainWindow::loadConfig(void) { QString s = QFileDialog::getOpenFileName(".config", NULL, this); if (s.isNull()) return; if (conf_read(s.latin1())) QMessageBox::information(this, "qconf", "Unable to load configuration!"); ConfigView::updateListAll(); } void ConfigMainWindow::saveConfig(void) { if (conf_write(NULL)) QMessageBox::information(this, "qconf", "Unable to save configuration!"); } void ConfigMainWindow::saveConfigAs(void) { QString s = QFileDialog::getSaveFileName(".config", NULL, this); if (s.isNull()) return; if (conf_write(s.latin1())) QMessageBox::information(this, "qconf", "Unable to save configuration!"); } void ConfigMainWindow::changeMenu(struct menu *menu) { configList->setRootMenu(menu); backAction->setEnabled(TRUE); } void ConfigMainWindow::listFocusChanged(void) { if (menuList->hasFocus()) { if (menuList->mode == menuMode) configList->clearSelection(); setHelp(menuList->selectedItem()); } else if (configList->hasFocus()) { setHelp(configList->selectedItem()); } } void ConfigMainWindow::goBack(void) { ConfigItem* item; configList->setParentMenu(); if (configList->rootEntry == &rootmenu) backAction->setEnabled(FALSE); item = (ConfigItem*)menuList->selectedItem(); while (item) { if (item->menu == configList->rootEntry) { menuList->setSelected(item, TRUE); break; } item = (ConfigItem*)item->parent(); } } void ConfigMainWindow::showSingleView(void) { menuView->hide(); menuList->setRootMenu(0); configList->mode = singleMode; if (configList->rootEntry == &rootmenu) configList->updateListAll(); else configList->setRootMenu(&rootmenu); configList->setAllOpen(TRUE); configList->setFocus(); } void ConfigMainWindow::showSplitView(void) { configList->mode = symbolMode; if (configList->rootEntry == &rootmenu) configList->updateListAll(); else configList->setRootMenu(&rootmenu); configList->setAllOpen(TRUE); configApp->processEvents(); menuList->mode = menuMode; menuList->setRootMenu(&rootmenu); menuList->setAllOpen(TRUE); menuView->show(); menuList->setFocus(); } void ConfigMainWindow::showFullView(void) { menuView->hide(); menuList->setRootMenu(0); configList->mode = fullMode; if (configList->rootEntry == &rootmenu) configList->updateListAll(); else configList->setRootMenu(&rootmenu); configList->setAllOpen(FALSE); configList->setFocus(); } void ConfigMainWindow::setShowAll(bool b) { if (configList->showAll == b) return; configList->showAll = b; configList->updateListAll(); menuList->showAll = b; menuList->updateListAll(); } void ConfigMainWindow::setShowDebug(bool b) { if (showDebug == b) return; showDebug = b; } void ConfigMainWindow::setShowName(bool b) { if (configList->showName == b) return; configList->showName = b; configList->reinit(); menuList->showName = b; menuList->reinit(); } void ConfigMainWindow::setShowRange(bool b) { if (configList->showRange == b) return; configList->showRange = b; configList->reinit(); menuList->showRange = b; menuList->reinit(); } void ConfigMainWindow::setShowData(bool b) { if (configList->showData == b) return; configList->showData = b; configList->reinit(); menuList->showData = b; menuList->reinit(); } /* * ask for saving configuration before quitting * TODO ask only when something changed */ void ConfigMainWindow::closeEvent(QCloseEvent* e) { if (!sym_change_count) { e->accept(); return; } QMessageBox mb("qconf", "Save configuration?", QMessageBox::Warning, QMessageBox::Yes | QMessageBox::Default, QMessageBox::No, QMessageBox::Cancel | QMessageBox::Escape); mb.setButtonText(QMessageBox::Yes, "&Save Changes"); mb.setButtonText(QMessageBox::No, "&Discard Changes"); mb.setButtonText(QMessageBox::Cancel, "Cancel Exit"); switch (mb.exec()) { case QMessageBox::Yes: conf_write(NULL); case QMessageBox::No: e->accept(); break; case QMessageBox::Cancel: e->ignore(); break; } } void ConfigMainWindow::showIntro(void) { static char str[] = "Welcome to the qconf graphical kernel configuration tool for Linux.\n\n" "For each option, a blank box indicates the feature is disabled, a check\n" "indicates it is enabled, and a dot indicates that it is to be compiled\n" "as a module. Clicking on the box will cycle through the three states.\n\n" "If you do not see an option (e.g., a device driver) that you believe\n" "should be present, try turning on Show All Options under the Options menu.\n" "Although there is no cross reference yet to help you figure out what other\n" "options must be enabled to support the option you are interested in, you can\n" "still view the help of a grayed-out option.\n\n" "Toggling Show Debug Info under the Options menu will show the dependencies,\n" "which you can then match by examining other options.\n\n"; QMessageBox::information(this, "qconf", str); } void ConfigMainWindow::showAbout(void) { static char str[] = "qconf is Copyright (C) 2002 Roman Zippel <zippel@linux-m68k.org>.\n\n" "Bug reports and feature request can also be entered at http://bugzilla.kernel.org/\n"; QMessageBox::information(this, "qconf", str); } void fixup_rootmenu(struct menu *menu) { struct menu *child; static int menu_cnt = 0; menu->flags |= MENU_ROOT; for (child = menu->list; child; child = child->next) { if (child->prompt && child->prompt->type == P_MENU) { menu_cnt++; fixup_rootmenu(child); menu_cnt--; } else if (!menu_cnt) fixup_rootmenu(child); } } static const char *progname; static void usage(void) { printf("%s <config>\n", progname); exit(0); } int main(int ac, char** av) { ConfigMainWindow* v; const char *name; #ifndef LKC_DIRECT_LINK kconfig_load(); #endif progname = av[0]; configApp = new QApplication(ac, av); -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 configSettings = new QSettings; #endif if (ac > 1 && av[1][0] == '-') { switch (av[1][1]) { case 'h': case '?': usage(); } name = av[2]; } else name = av[1]; if (!name) usage(); conf_parse(name); fixup_rootmenu(&rootmenu); conf_read(NULL); //zconfdump(stdout); v = new ConfigMainWindow(); //zconfdump(stdout); v->show(); configApp->connect(configApp, SIGNAL(lastWindowClosed()), SLOT(quit())); configApp->exec(); -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 configSettings->writeEntry("/kconfig/qconf/window x", v->pos().x()); configSettings->writeEntry("/kconfig/qconf/window y", v->pos().y()); configSettings->writeEntry("/kconfig/qconf/window width", v->size().width()); configSettings->writeEntry("/kconfig/qconf/window height", v->size().height()); delete configSettings; #endif return 0; } diff --git a/scripts/kconfig/qconf.h b/scripts/kconfig/qconf.h index c548884..dee5254 100644 --- a/scripts/kconfig/qconf.h +++ b/scripts/kconfig/qconf.h @@ -1,238 +1,238 @@ /* * Copyright (C) 2002 Roman Zippel <zippel@linux-m68k.org> * Released under the terms of the GNU GPL v2.0. */ #include <qlistview.h> class ConfigList; class ConfigItem; class ConfigLineEdit; class ConfigMainWindow; class ConfigView : public QVBox { Q_OBJECT typedef class QVBox Parent; public: ConfigView(QWidget* parent, ConfigMainWindow* cview); ~ConfigView(void); static void updateList(ConfigItem* item); static void updateListAll(void); public: ConfigList* list; ConfigLineEdit* lineEdit; static ConfigView* viewList; ConfigView* nextView; }; enum colIdx { promptColIdx, nameColIdx, noColIdx, modColIdx, yesColIdx, dataColIdx, colNr }; enum listMode { singleMode, menuMode, symbolMode, fullMode }; class ConfigList : public QListView { Q_OBJECT typedef class QListView Parent; public: ConfigList(ConfigView* p, ConfigMainWindow* cview); void reinit(void); ConfigView* parent(void) const { return (ConfigView*)Parent::parent(); } protected: ConfigMainWindow* cview; void keyPressEvent(QKeyEvent *e); void contentsMousePressEvent(QMouseEvent *e); void contentsMouseReleaseEvent(QMouseEvent *e); void contentsMouseMoveEvent(QMouseEvent *e); void contentsMouseDoubleClickEvent(QMouseEvent *e); void focusInEvent(QFocusEvent *e); public slots: void setRootMenu(struct menu *menu); void updateList(ConfigItem *item); void setValue(ConfigItem* item, tristate val); void changeValue(ConfigItem* item); void updateSelection(void); signals: void menuSelected(struct menu *menu); void parentSelected(void); void gotFocus(void); public: void updateListAll(void) { updateAll = true; updateList(NULL); updateAll = false; } ConfigList* listView() { return this; } ConfigItem* firstChild() const { return (ConfigItem *)Parent::firstChild(); } int mapIdx(colIdx idx) { return colMap[idx]; } void addColumn(colIdx idx, const QString& label) { colMap[idx] = Parent::addColumn(label); colRevMap[colMap[idx]] = idx; } void removeColumn(colIdx idx) { int col = colMap[idx]; if (col >= 0) { Parent::removeColumn(col); colRevMap[col] = colMap[idx] = -1; } } void setAllOpen(bool open); void setParentMenu(void); template <class P> void ConfigList::updateMenuList(P*, struct menu*); bool updateAll; QPixmap symbolYesPix, symbolModPix, symbolNoPix; QPixmap choiceYesPix, choiceNoPix; QPixmap menuPix, menuInvPix, menuBackPix, voidPix; bool showAll, showName, showRange, showData; enum listMode mode; struct menu *rootEntry; QColorGroup disabledColorGroup; QColorGroup inactivedColorGroup; private: int colMap[colNr]; int colRevMap[colNr]; }; class ConfigItem : public QListViewItem { typedef class QListViewItem Parent; public: ConfigItem(QListView *parent, ConfigItem *after, struct menu *m, bool v) : Parent(parent, after), menu(m), visible(v), goParent(false) { init(); } ConfigItem(ConfigItem *parent, ConfigItem *after, struct menu *m, bool v) : Parent(parent, after), menu(m), visible(v), goParent(false) { init(); } ConfigItem(QListView *parent, ConfigItem *after, bool v) : Parent(parent, after), menu(0), visible(v), goParent(true) { init(); } ~ConfigItem(void); void init(void); -#if QT_VERSION >= 300 +#if QT_VERSION >= 0x030000 void okRename(int col); #endif void updateMenu(void); void testUpdateMenu(bool v); ConfigList* listView() const { return (ConfigList*)Parent::listView(); } ConfigItem* firstChild() const { return (ConfigItem *)Parent::firstChild(); } ConfigItem* nextSibling() const { return (ConfigItem *)Parent::nextSibling(); } void setText(colIdx idx, const QString& text) { Parent::setText(listView()->mapIdx(idx), text); } QString text(colIdx idx) const { return Parent::text(listView()->mapIdx(idx)); } void setPixmap(colIdx idx, const QPixmap& pm) { Parent::setPixmap(listView()->mapIdx(idx), pm); } const QPixmap* pixmap(colIdx idx) const { return Parent::pixmap(listView()->mapIdx(idx)); } void paintCell(QPainter* p, const QColorGroup& cg, int column, int width, int align); ConfigItem* nextItem; struct menu *menu; bool visible; bool goParent; }; class ConfigLineEdit : public QLineEdit { Q_OBJECT typedef class QLineEdit Parent; public: ConfigLineEdit(ConfigView* parent) : Parent(parent) { } ConfigView* parent(void) const { return (ConfigView*)Parent::parent(); } void show(ConfigItem *i); void keyPressEvent(QKeyEvent *e); public: ConfigItem *item; }; class ConfigMainWindow : public QMainWindow { Q_OBJECT public: ConfigMainWindow(void); public slots: void setHelp(QListViewItem* item); void changeMenu(struct menu *); void listFocusChanged(void); void goBack(void); void loadConfig(void); void saveConfig(void); void saveConfigAs(void); void showSingleView(void); void showSplitView(void); void showFullView(void); void setShowAll(bool); void setShowDebug(bool); void setShowRange(bool); void setShowName(bool); void setShowData(bool); void showIntro(void); void showAbout(void); protected: void closeEvent(QCloseEvent *e); ConfigView *menuView; ConfigList *menuList; ConfigView *configView; ConfigList *configList; QTextView *helpText; QToolBar *toolBar; QAction *backAction; bool showDebug; }; |