43 files changed, 76 insertions, 67 deletions
diff --git a/core/apps/embeddedkonsole/commandeditdialog.cpp b/core/apps/embeddedkonsole/commandeditdialog.cpp index 8b2abfa..97b0a9e 100644 --- a/core/apps/embeddedkonsole/commandeditdialog.cpp +++ b/core/apps/embeddedkonsole/commandeditdialog.cpp @@ -1,199 +1,199 @@ //comandeditdialog.cpp #include "commandeditdialog.h" #include "playlistselection.h" #include <qstring.h> #include <qpe/config.h> #include <qpe/qpetoolbar.h> #include <qwidget.h> -#include <qpe/qpemenubar.h> +#include <qmenubar.h> #include <qpe/resource.h> #include <qlist.h> #include <qtoolbutton.h> #include <qvbox.h> #include <qlistview.h> #include <qlineedit.h> #include <qheader.h> #include <qlabel.h> #include <qmessagebox.h> #include "smallcommandeditdialogbase.h" CommandEditDialog::CommandEditDialog(QWidget *parent, const char* name, WFlags fl ) : CommandEditDialogBase(parent, name, TRUE, fl) { m_SuggestedCommandList->addColumn( tr("Command Selection") ); m_SuggestedCommandList->header()->hide(); m_SuggestedCommandList->setSorting(-1,FALSE); m_SuggestedCommandList->clearSelection(); m_SuggestedCommandList->setSorting(0,TRUE); QListViewItem *item; item = new QListViewItem( m_SuggestedCommandList,"export "); item = new QListViewItem( m_SuggestedCommandList,"ifconfig "); item = new QListViewItem( m_SuggestedCommandList,"ipkg "); item = new QListViewItem( m_SuggestedCommandList,"gzip "); item = new QListViewItem( m_SuggestedCommandList,"gunzip "); item = new QListViewItem( m_SuggestedCommandList,"chgrp "); item = new QListViewItem( m_SuggestedCommandList,"chown "); item = new QListViewItem( m_SuggestedCommandList,"date "); item = new QListViewItem( m_SuggestedCommandList,"dd "); item = new QListViewItem( m_SuggestedCommandList,"dmesg "); item = new QListViewItem( m_SuggestedCommandList,"fuser "); item = new QListViewItem( m_SuggestedCommandList,"hostname "); item = new QListViewItem( m_SuggestedCommandList,"kill "); item = new QListViewItem( m_SuggestedCommandList,"killall "); item = new QListViewItem( m_SuggestedCommandList,"ln "); item = new QListViewItem( m_SuggestedCommandList,"ln -s "); item = new QListViewItem( m_SuggestedCommandList,"lsmod"); item = new QListViewItem( m_SuggestedCommandList,"depmod -a"); item = new QListViewItem( m_SuggestedCommandList,"modprobe "); item = new QListViewItem( m_SuggestedCommandList,"mount "); item = new QListViewItem( m_SuggestedCommandList,"more "); item = new QListViewItem( m_SuggestedCommandList,"sort "); item = new QListViewItem( m_SuggestedCommandList,"touch "); item = new QListViewItem( m_SuggestedCommandList,"umount "); item = new QListViewItem( m_SuggestedCommandList,"mknod "); item = new QListViewItem( m_SuggestedCommandList,"netstat "); item = new QListViewItem( m_SuggestedCommandList,"route "); item = new QListViewItem( m_SuggestedCommandList,"cardctl eject "); m_SuggestedCommandList->setSelected(m_SuggestedCommandList->firstChild(),TRUE); m_SuggestedCommandList->sort(); connect( m_SuggestedCommandList, SIGNAL( clicked( QListViewItem * ) ), m_PlayListSelection, SLOT( addToSelection( QListViewItem *) ) ); ToolButton1->setTextLabel("new"); ToolButton1->setPixmap(Resource::loadPixmap("new")); ToolButton1->setAutoRaise(TRUE); ToolButton1->setFocusPolicy(QWidget::NoFocus); connect(ToolButton1,SIGNAL(clicked()),this,SLOT(showAddDialog())); ToolButton2->setTextLabel("edit"); ToolButton2->setPixmap(Resource::loadPixmap("edit")); ToolButton2->setAutoRaise(TRUE); ToolButton2->setFocusPolicy(QWidget::NoFocus); connect(ToolButton2,SIGNAL(clicked()),this,SLOT(showEditDialog())); ToolButton3->setTextLabel("delete"); ToolButton3->setPixmap(Resource::loadPixmap("editdelete")); ToolButton3->setAutoRaise(TRUE); ToolButton3->setFocusPolicy(QWidget::NoFocus); connect(ToolButton3,SIGNAL(clicked()),m_PlayListSelection,SLOT(removeSelected())); ToolButton4->setTextLabel("up"); ToolButton4->setPixmap(Resource::loadPixmap("up")); ToolButton4->setAutoRaise(TRUE); ToolButton4->setFocusPolicy(QWidget::NoFocus); connect(ToolButton4,SIGNAL(clicked()),m_PlayListSelection,SLOT(moveSelectedUp())); ToolButton5->setTextLabel("down"); ToolButton5->setPixmap(Resource::loadPixmap("down")); ToolButton5->setAutoRaise(TRUE); ToolButton5->setFocusPolicy(QWidget::NoFocus); connect(ToolButton5,SIGNAL(clicked()),m_PlayListSelection,SLOT(moveSelectedDown())); QListViewItem *current = m_SuggestedCommandList->selectedItem(); if ( current ) item->moveItem( current ); m_SuggestedCommandList->setSelected( item, TRUE ); m_SuggestedCommandList->ensureItemVisible( m_SuggestedCommandList->selectedItem() ); Config cfg("Konsole"); cfg.setGroup("Commands"); if (cfg.readEntry("Commands Set","FALSE") == "TRUE") { for (int i = 0; i < 100; i++) { QString tmp; tmp = cfg.readEntry( QString::number(i),""); if (!tmp.isEmpty()) m_PlayListSelection->addStringToSelection(tmp); } } else { m_PlayListSelection->addStringToSelection("ls "); m_PlayListSelection->addStringToSelection("cardctl eject"); m_PlayListSelection->addStringToSelection("cat "); m_PlayListSelection->addStringToSelection("cd "); m_PlayListSelection->addStringToSelection("chmod "); m_PlayListSelection->addStringToSelection("cp "); m_PlayListSelection->addStringToSelection("dc "); m_PlayListSelection->addStringToSelection("df "); m_PlayListSelection->addStringToSelection("dmesg"); m_PlayListSelection->addStringToSelection("echo "); m_PlayListSelection->addStringToSelection("env"); m_PlayListSelection->addStringToSelection("find "); m_PlayListSelection->addStringToSelection("free"); m_PlayListSelection->addStringToSelection("grep "); m_PlayListSelection->addStringToSelection("ifconfig "); m_PlayListSelection->addStringToSelection("ipkg "); m_PlayListSelection->addStringToSelection("mkdir "); m_PlayListSelection->addStringToSelection("mv "); m_PlayListSelection->addStringToSelection("nc localhost 7776"); m_PlayListSelection->addStringToSelection("nc localhost 7777"); m_PlayListSelection->addStringToSelection("nslookup "); m_PlayListSelection->addStringToSelection("ping "); m_PlayListSelection->addStringToSelection("ps aux"); m_PlayListSelection->addStringToSelection("pwd "); m_PlayListSelection->addStringToSelection("rm "); m_PlayListSelection->addStringToSelection("rmdir "); m_PlayListSelection->addStringToSelection("route "); m_PlayListSelection->addStringToSelection("set "); m_PlayListSelection->addStringToSelection("traceroute"); } } CommandEditDialog::~CommandEditDialog() { } void CommandEditDialog::accept() { int i = 0; Config *cfg = new Config("Konsole"); cfg->setGroup("Commands"); cfg->clearGroup(); QListViewItemIterator it( m_PlayListSelection ); for ( ; it.current(); ++it ) { // qDebug(it.current()->text(0)); cfg->writeEntry(QString::number(i),it.current()->text(0)); i++; } cfg->writeEntry("Commands Set","TRUE"); // qDebug("CommandEditDialog::accept() - written"); delete cfg; emit commandsEdited(); close(); } void CommandEditDialog::showEditDialog() { editCommandBase *d = new editCommandBase(this,"smalleditdialog", TRUE); d->setCaption("Edit command"); d->TextLabel->setText("Edit command:"); d->commandEdit->setText(m_PlayListSelection->currentItem()->text(0)); int i = d->exec(); if ((i==1) && (!(d->commandEdit->text()).isEmpty())) m_PlayListSelection->currentItem()->setText(0,(d->commandEdit->text())); } void CommandEditDialog::showAddDialog() { editCommandBase *d = new editCommandBase(this,"smalleditdialog", TRUE); int i = d->exec(); if ((i==1) && (!(d->commandEdit->text()).isEmpty())) m_PlayListSelection->addStringToSelection(d->commandEdit->text()); } diff --git a/core/apps/embeddedkonsole/konsole.cpp b/core/apps/embeddedkonsole/konsole.cpp index ec438c3..d855d90 100644 --- a/core/apps/embeddedkonsole/konsole.cpp +++ b/core/apps/embeddedkonsole/konsole.cpp @@ -1,1102 +1,1102 @@ /* ---------------------------------------------------------------------- */ /* */ /* [main.C] Konsole */ /* */ /* ---------------------------------------------------------------------- */ /* */ /* Copyright (c) 1997,1998 by Lars Doelle <lars.doelle@on-line.de> */ /* */ /* This file is part of Konsole, an X terminal. */ /* */ /* The material contained in here more or less directly orginates from */ /* kvt, which is copyright (c) 1996 by Matthias Ettrich <ettrich@kde.org> */ /* */ /* ---------------------------------------------------------------------- */ /* */ /* Ported Konsole to Qt/Embedded */ /* */ /* Copyright (C) 2000 by John Ryland <jryland@trolltech.com> */ /* */ /* -------------------------------------------------------------------------- */ // enhancements added by L.J. Potter <ljp@llornkcor.com> #define QT_QWS_OPIE #include <qpe/resource.h> #include <qdir.h> #include <qevent.h> #include <qdragobject.h> #include <qobjectlist.h> #include <qtoolbutton.h> #include <qpe/qpetoolbar.h> #include <qpushbutton.h> #include <qfontdialog.h> #include <qglobal.h> #include <qpainter.h> -#include <qpe/qpemenubar.h> +#include <qmenubar.h> #include <qmessagebox.h> #include <qaction.h> #include <qapplication.h> #include <qfontmetrics.h> #include <qcombobox.h> #include <qevent.h> #include <qtabwidget.h> #include <qtabbar.h> #include <qpe/config.h> #include <qstringlist.h> #include <qpalette.h> #include <unistd.h> #include <pwd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "konsole.h" #include "keytrans.h" #include "commandeditdialog.h" #ifdef QT_QWS_OPIE #include <opie/colorpopupmenu.h> #endif class EKNumTabBar : public QTabBar { public: void numberTabs() { // Yes, it really is this messy. QTabWidget needs functions // that provide acces to tabs in a sequential way. int m=INT_MIN; for (int i=0; i<count(); i++) { QTab* left=0; QListIterator<QTab> it(*tabList()); int x=INT_MAX; for( QTab* t; (t=it.current()); ++it ) { int tx = t->rect().x(); if ( tx<x && tx>m ) { x = tx; left = t; } } if ( left ) { left->setText(QString::number(i+1)); m = left->rect().x(); } } } }; class EKNumTabWidget : public QTabWidget { public: EKNumTabWidget(QWidget* parent) : QTabWidget(parent) { } void addTab(QWidget* w) { QTab* t = new QTab(QString::number(tabBar()->count()+1)); QTabWidget::addTab(w,t); } void removeTab(QWidget* w) { removePage(w); ((EKNumTabBar*)tabBar())->numberTabs(); } }; // This could be configurable or dynamicly generated from the bash history // file of the user static const char *commonCmds[] = { "ls ", // I left this here, cause it looks better than the first alpha "cardctl eject", "cat ", "cd ", "chmod ", "clear", "cp ", "dc ", "df ", "dmesg", "echo ", "env", "find ", "free", "grep ", "ifconfig ", "ipkg ", "mkdir ", "mv ", "nc localhost 7776", "nc localhost 7777", "netstat ", "nslookup ", "ping ", "ps aux", "pwd ", "qcop QPE/System 'linkChanged(QString)' ''", "qcop QPE/System 'restart()'", "qcop QPE/System 'quit()'", "rm ", "rmdir ", "route ", "set ", "traceroute", /* "gzip", "gunzip", "chgrp", "chown", "date", "dd", "df", "dmesg", "fuser", "hostname", "kill", "killall", "ln", "ping", "mount", "more", "sort", "touch", "umount", "mknod", "netstat", */ "exit", NULL }; static void konsoleInit(const char** shell) { if(setuid(getuid()) !=0) qDebug("setuid failed"); if(setgid(getgid()) != 0) qDebug("setgid failed"); // drop privileges // QPEApplication::grabKeyboard(); // for CTRL and ALT qDebug("keyboard grabbed"); #ifdef FAKE_CTRL_AND_ALT qDebug("Fake Ctrl and Alt defined"); QPEApplication::grabKeyboard(); // for CTRL and ALT #endif *shell = getenv("SHELL"); qWarning("SHell initially is %s", *shell ); if (shell == NULL || *shell == '\0') { struct passwd *ent = 0; uid_t me = getuid(); *shell = "/bin/sh"; while ( (ent = getpwent()) != 0 ) { if (ent->pw_uid == me) { if (ent->pw_shell != "") *shell = ent->pw_shell; break; } } endpwent(); } qWarning("SHELL now is %s", *shell ); if( putenv((char*)"COLORTERM=") !=0) qDebug("putenv failed"); // to trigger mc's color detection } Konsole::Konsole(QWidget* parent, const char* name, WFlags fl) : QMainWindow(parent, name, fl) { QStrList tmp; const char* shell; setCaption( tr("Terminal") ); konsoleInit( &shell); qWarning("Using shell %s", shell); init(shell,tmp); } void Konsole::initCommandList() { // qDebug("Konsole::initCommandList"); Config cfg("Konsole"); cfg.setGroup("Commands"); commonCombo->setInsertionPolicy(QComboBox::AtCurrent); commonCombo->clear(); if (cfg.readEntry("Commands Set","FALSE") == "FALSE") { for (int i = 0; commonCmds[i] != NULL; i++) { commonCombo->insertItem(commonCmds[i],i); } } else { for (int i = 0; i < 100; i++) { if (!(cfg.readEntry( QString::number(i),"")).isEmpty()) commonCombo->insertItem((cfg.readEntry( QString::number(i),""))); } } } void Konsole::init(const char* _pgm, QStrList & _args) { b_scroll = TRUE; // histon; n_keytab = 0; n_render = 0; startUp=0; fromMenu = FALSE; setCaption( tr("Terminal") ); setIcon( Resource::loadPixmap( "konsole" ) ); Config cfg("Konsole"); cfg.setGroup("Konsole"); QString tmp; // initialize the list of allowed fonts /////////////////////////////////// cfont = cfg.readNumEntry("FontID", 1); QFont f = QFont("Micro", 4, QFont::Normal); f.setFixedPitch(TRUE); fonts.append(new VTFont(tr("Micro"), f)); f = QFont("Fixed", 7, QFont::Normal); f.setFixedPitch(TRUE); fonts.append(new VTFont(tr("Small Fixed"), f)); f = QFont("Fixed", 12, QFont::Normal); f.setFixedPitch(TRUE); fonts.append(new VTFont(tr("Medium Fixed"), f)); // create terminal emulation framework //////////////////////////////////// nsessions = 0; tab = new EKNumTabWidget(this); connect(tab, SIGNAL(currentChanged(QWidget*)), this, SLOT(switchSession(QWidget*))); // create terminal toolbar //////////////////////////////////////////////// setToolBarsMovable( FALSE ); QPEToolBar *menuToolBar = new QPEToolBar( this ); menuToolBar->setHorizontalStretchable( TRUE ); - QPEMenuBar *menuBar = new QPEMenuBar( menuToolBar ); + QMenuBar *menuBar = new QMenuBar( menuToolBar ); fontList = new QPopupMenu( this ); for(uint i = 0; i < fonts.count(); i++) { VTFont *fnt = fonts.at(i); fontList->insertItem(fnt->getName(), i); } fontChanged(cfont); configMenu = new QPopupMenu( this); colorMenu = new QPopupMenu( this); scrollMenu = new QPopupMenu( this); editCommandListMenu = new QPopupMenu( this); configMenu->insertItem(tr("Command List"), editCommandListMenu); bool listHidden; cfg.setGroup("Menubar"); if( cfg.readEntry("Hidden","FALSE") == "TRUE") { editCommandListMenu->insertItem( tr( "Show command list" )); listHidden=TRUE; } else { editCommandListMenu->insertItem( tr( "Hide command list" )); listHidden=FALSE; } cfg.setGroup("Tabs"); tmp=cfg.readEntry("Position","Bottom"); if(tmp=="Top") { tab->setTabPosition(QTabWidget::Top); configMenu->insertItem( tr( "Tabs on Bottom" ) ); } else { tab->setTabPosition(QTabWidget::Bottom); configMenu->insertItem(tr("Tabs on Top")); } configMenu->insertSeparator(2); colorMenu->insertItem(tr( "Green on Black")); colorMenu->insertItem(tr( "Black on White")); colorMenu->insertItem(tr( "White on Black")); colorMenu->insertItem(tr( "Black on Transparent")); colorMenu->insertItem(tr( "Black on Red")); colorMenu->insertItem(tr( "Red on Black")); colorMenu->insertItem(tr( "Green on Yellow")); colorMenu->insertItem(tr( "Blue on Magenta")); colorMenu->insertItem(tr( "Magenta on Blue")); colorMenu->insertItem(tr( "Cyan on White")); colorMenu->insertItem(tr( "White on Cyan")); colorMenu->insertItem(tr( "Blue on Black")); colorMenu->insertItem(tr( "Amber on Black")); #ifdef QT_QWS_OPIE colorMenu->insertItem(tr( "Custom")); #endif configMenu->insertItem( tr("Font"), fontList ); configMenu->insertItem(tr( "Colors") ,colorMenu); connect( fontList, SIGNAL( activated(int) ), this, SLOT( fontChanged(int) )); connect( configMenu, SIGNAL( activated(int) ), this, SLOT( configMenuSelected(int) )); connect( colorMenu, SIGNAL( activated(int) ), this, SLOT( colorMenuIsSelected(int) )); connect( scrollMenu, SIGNAL(activated(int)),this,SLOT(scrollMenuSelected(int))); connect(editCommandListMenu,SIGNAL(activated(int)),this,SLOT(editCommandListMenuSelected(int))); menuBar->insertItem( tr("Options"), configMenu ); QPEToolBar *toolbar = new QPEToolBar( this ); QAction *a; // Button Commands a = new QAction( tr("New"), Resource::loadPixmap( "konsole" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( newSession() ) ); a->addTo( toolbar ); a = new QAction( tr("Enter"), Resource::loadPixmap( "konsole/enter" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( hitEnter() ) ); a->addTo( toolbar ); a = new QAction( tr("Space"), Resource::loadPixmap( "konsole/space" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( hitSpace() ) ); a->addTo( toolbar ); a = new QAction( tr("Tab"), Resource::loadPixmap( "konsole/tab" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( hitTab() ) ); a->addTo( toolbar ); a = new QAction( tr("Up"), Resource::loadPixmap( "konsole/up" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( hitUp() ) ); a->addTo( toolbar ); a = new QAction( tr("Down"), Resource::loadPixmap( "konsole/down" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( hitDown() ) ); a->addTo( toolbar ); a = new QAction( tr("Paste"), Resource::loadPixmap( "paste" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( hitPaste() ) ); a->addTo( toolbar ); /* a = new QAction( tr("Up"), Resource::loadPixmap( "up" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( hitUp() ) ); a->addTo( toolbar ); a = new QAction( tr("Down"), Resource::loadPixmap( "down" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( hitDown() ) ); a->addTo( toolbar ); */ secondToolBar = new QPEToolBar( this ); secondToolBar->setHorizontalStretchable( TRUE ); commonCombo = new QComboBox( secondToolBar ); commonCombo->setMaximumWidth(236); editCommandListMenu->insertItem( tr( "Quick Edit" ) ); if( listHidden) { secondToolBar->hide(); editCommandListMenu->setItemEnabled(-23 ,FALSE); } editCommandListMenu->insertItem(tr( "Edit" ) ); cfg.setGroup("Commands"); commonCombo->setInsertionPolicy(QComboBox::AtCurrent); initCommandList(); // for (int i = 0; commonCmds[i] != NULL; i++) { // commonCombo->insertItem( commonCmds[i], i ); // tmp = cfg.readEntry( QString::number(i),""); // if(tmp != "") // commonCombo->changeItem( tmp,i ); // } connect( commonCombo, SIGNAL( activated(int) ), this, SLOT( enterCommand(int) )); scrollMenu->insertItem(tr( "None" )); scrollMenu->insertItem(tr( "Left" )); scrollMenu->insertItem(tr( "Right" )); // scrollMenu->insertSeparator(4); // scrollMenu->insertItem(tr( "Horizontal" )); configMenu->insertItem(tr( "ScrollBar" ),scrollMenu); int jut = configMenu->insertItem(tr( "Wrap" )); cfg.setGroup("ScrollBar"); configMenu->setItemChecked(jut, cfg.readBoolEntry("HorzScroll",0)); jut = configMenu->insertItem(tr( "Use Beep" )); cfg.setGroup("Menubar"); configMenu->setItemChecked(jut, cfg.readBoolEntry("useBeep",0)); //scrollMenuSelected(-29); // cfg.setGroup("ScrollBar"); // if(cfg.readBoolEntry("HorzScroll",0)) { // if(cfg.readNumEntry("Position",2) == 0) // te->setScrollbarLocation(1); // else // te->setScrollbarLocation(0); // te->setScrollbarLocation( cfg.readNumEntry("Position",2)); // te->setWrapAt(120); // } // create applications ///////////////////////////////////////////////////// setCentralWidget(tab); // load keymaps //////////////////////////////////////////////////////////// KeyTrans::loadAll(); for (int i = 0; i < KeyTrans::count(); i++) { KeyTrans* s = KeyTrans::find(i); assert( s ); } se_pgm = _pgm; se_args = _args; se_args.prepend("--login"); parseCommandLine(); // read and apply default values /////////////////////////////////////////// resize(321, 321); // Dummy. QSize currentSize = size(); if (currentSize != size()) defaultSize = size(); } void Konsole::show() { if ( !nsessions ) { newSession(); } QMainWindow::show(); } void Konsole::initSession(const char*, QStrList &) { QMainWindow::show(); } Konsole::~Konsole() { while (nsessions > 0) { doneSession(getTe()->currentSession, 0); } Config cfg("Konsole"); cfg.setGroup("Konsole"); cfg.writeEntry("FontID", cfont); } void Konsole::fontChanged(int f) { VTFont* font = fonts.at(f); if (font != 0) { for(uint i = 0; i < fonts.count(); i++) { fontList->setItemChecked(i, (i == (uint) f) ? TRUE : FALSE); } cfont = f; TEWidget* te = getTe(); if (te != 0) { te->setVTFont(font->getFont()); } } } void Konsole::enterCommand(int c) { TEWidget* te = getTe(); if (te != 0) { if(!commonCombo->editable()) { QString text = commonCombo->text(c); //commonCmds[c]; te->emitText(text); } else { changeCommand( commonCombo->text(c), c); } } } void Konsole::hitEnter() { TEWidget* te = getTe(); if (te != 0) { te->emitText(QString("\r")); } } void Konsole::hitSpace() { TEWidget* te = getTe(); if (te != 0) { te->emitText(QString(" ")); } } void Konsole::hitTab() { TEWidget* te = getTe(); if (te != 0) { te->emitText(QString("\t")); } } void Konsole::hitPaste() { TEWidget* te = getTe(); if (te != 0) { te->pasteClipboard(); } } void Konsole::hitUp() { TEWidget* te = getTe(); if (te != 0) { QKeyEvent ke( QKeyEvent::KeyPress, Qt::Key_Up, 0, 0); QApplication::sendEvent( te, &ke ); } } void Konsole::hitDown() { TEWidget* te = getTe(); if (te != 0) { QKeyEvent ke( QKeyEvent::KeyPress, Qt::Key_Down, 0, 0); QApplication::sendEvent( te, &ke ); } } /** This function calculates the size of the external widget needed for the internal widget to be */ QSize Konsole::calcSize(int columns, int lines) { TEWidget* te = getTe(); if (te != 0) { QSize size = te->calcSize(columns, lines); return size; } else { QSize size; return size; } } /** sets application window to a size based on columns X lines of the te guest widget. Call with (0,0) for setting default size. */ void Konsole::setColLin(int columns, int lines) { qDebug("konsole::setColLin:: Columns %d", columns); if ((columns==0) || (lines==0)) { if (defaultSize.isEmpty()) // not in config file : set default value { defaultSize = calcSize(80,24); // notifySize(24,80); // set menu items (strange arg order !) } resize(defaultSize); } else { resize(calcSize(columns, lines)); // notifySize(lines,columns); // set menu items (strange arg order !) } } /* void Konsole::setFont(int fontno) { QFont f; if (fontno == 0) f = defaultFont = QFont( "Helvetica", 12 ); else if (fonts[fontno][0] == '-') f.setRawName( fonts[fontno] ); else { f.setFamily(fonts[fontno]); f.setRawMode( TRUE ); } if ( !f.exactMatch() && fontno != 0) { QString msg = i18n("Font `%1' not found.\nCheck README.linux.console for help.").arg(fonts[fontno]); QMessageBox(this, msg); return; } if (se) se->setFontNo(fontno); te->setVTFont(f); n_font = fontno; } */ // --| color selection |------------------------------------------------------- void Konsole::changeColumns(int columns) { //FIXME this seems to cause silliness when reset command is executed // qDebug("change columns"); // TEWidget* te = getTe(); // if (te != 0) { // setColLin(columns,te->Lines()); // te->update(); // } } //FIXME: If a child dies during session swap, // this routine might be called before // session swap is completed. void Konsole::doneSession(TESession*, int ) { TEWidget *te = getTe(); if (te != 0) { te->currentSession->setConnect(FALSE); tab->removeTab(te); delete te->currentSession; delete te; nsessions--; } if (nsessions == 0) { close(); } } void Konsole::newSession() { if(nsessions < 15) { // seems to be something weird about 16 tabs on the Zaurus.... memory? TEWidget* te = new TEWidget(tab); Config c("Konsole"); c.setGroup("Menubar"); te->useBeep=c.readBoolEntry("useBeep",0); // te->setBackgroundMode(PaletteBase); //we want transparent!! te->setVTFont(fonts.at(cfont)->getFont()); tab->addTab(te); TESession* se = new TESession(this, te, se_pgm, se_args, "xterm"); te->currentSession = se; connect( se, SIGNAL(done(TESession*,int)), this, SLOT(doneSession(TESession*,int)) ); se->run(); se->setConnect(TRUE); se->setHistory(b_scroll); tab->setCurrentPage(nsessions); nsessions++; doWrap(); setColor(); } } TEWidget* Konsole::getTe() { if (nsessions) { return (TEWidget *) tab->currentPage(); } else { return 0; } } void Konsole::switchSession(QWidget* w) { TEWidget* te = (TEWidget *) w; QFont teFnt = te->getVTFont(); for(uint i = 0; i < fonts.count(); i++) { VTFont *fnt = fonts.at(i); bool cf = fnt->getFont() == teFnt; fontList->setItemChecked(i, cf); if (cf) { cfont = i; } } } void Konsole::colorMenuIsSelected(int iD) { fromMenu = TRUE; colorMenuSelected(iD); } /// ------------------------------- some new stuff by L.J. Potter void Konsole::colorMenuSelected(int iD) { // this is NOT pretty, elegant or anything else besides functional // QString temp; // qDebug( temp.sprintf("colormenu %d", iD)); TEWidget* te = getTe(); Config cfg("Konsole"); cfg.setGroup("Colors"); // QColor foreground; // QColor background; colorMenu->setItemChecked(lastSelectedMenu,FALSE); ColorEntry m_table[TABLE_COLORS]; const ColorEntry * defaultCt=te->getdefaultColorTable(); /////////// fore back int i; if(iD==-9) { // default default for (i = 0; i < TABLE_COLORS; i++) { m_table[i].color = defaultCt[i].color; if(i==1 || i == 11) m_table[i].transparent=1; cfg.writeEntry("Schema","9"); colorMenu->setItemChecked(-9,TRUE); } } else { if(iD==-6) { // green black foreground.setRgb(0x18,255,0x18); background.setRgb(0x00,0x00,0x00); cfg.writeEntry("Schema","6"); colorMenu->setItemChecked(-6,TRUE); } if(iD==-7) { // black white foreground.setRgb(0x00,0x00,0x00); background.setRgb(0xFF,0xFF,0xFF); cfg.writeEntry("Schema","7"); colorMenu->setItemChecked(-7,TRUE); } if(iD==-8) { // white black foreground.setRgb(0xFF,0xFF,0xFF); background.setRgb(0x00,0x00,0x00); cfg.writeEntry("Schema","8"); colorMenu->setItemChecked(-8,TRUE); } if(iD==-10) {// Black, Red foreground.setRgb(0x00,0x00,0x00); background.setRgb(0xB2,0x18,0x18); cfg.writeEntry("Schema","10"); colorMenu->setItemChecked(-10,TRUE); } if(iD==-11) {// Red, Black foreground.setRgb(230,31,31); //0xB2,0x18,0x18 background.setRgb(0x00,0x00,0x00); cfg.writeEntry("Schema","11"); colorMenu->setItemChecked(-11,TRUE); } if(iD==-12) {// Green, Yellow - is ugly // foreground.setRgb(0x18,0xB2,0x18); foreground.setRgb(36,139,10); // background.setRgb(0xB2,0x68,0x18); background.setRgb(255,255,0); cfg.writeEntry("Schema","12"); colorMenu->setItemChecked(-12,TRUE); } if(iD==-13) {// Blue, Magenta foreground.setRgb(0x18,0xB2,0xB2); background.setRgb(0x18,0x18,0xB2); cfg.writeEntry("Schema","13"); colorMenu->setItemChecked(-13,TRUE); } if(iD==-14) {// Magenta, Blue foreground.setRgb(0x18,0x18,0xB2); background.setRgb(0x18,0xB2,0xB2); cfg.writeEntry("Schema","14"); colorMenu->setItemChecked(-14,TRUE); } if(iD==-15) {// Cyan, White foreground.setRgb(0x18,0xB2,0xB2); background.setRgb(0xFF,0xFF,0xFF); cfg.writeEntry("Schema","15"); colorMenu->setItemChecked(-15,TRUE); } if(iD==-16) {// White, Cyan background.setRgb(0x18,0xB2,0xB2); foreground.setRgb(0xFF,0xFF,0xFF); cfg.writeEntry("Schema","16"); colorMenu->setItemChecked(-16,TRUE); } if(iD==-17) {// Black, Blue background.setRgb(0x00,0x00,0x00); foreground.setRgb(0x18,0xB2,0xB2); cfg.writeEntry("Schema","17"); colorMenu->setItemChecked(-17,TRUE); } if(iD==-18) {// Black, Gold background.setRgb(0x00,0x00,0x00); foreground.setRgb(255,215,0); cfg.writeEntry("Schema","18"); colorMenu->setItemChecked(-18,TRUE); } #ifdef QT_QWS_OPIE if(iD==-19) { // Custom qDebug("do custom"); if(fromMenu) { OColorPopupMenu* penColorPopupMenu = new OColorPopupMenu(Qt::black, this, "foreground color"); connect(penColorPopupMenu, SIGNAL(colorSelected(const QColor&)), this, SLOT(changeForegroundColor(const QColor&))); penColorPopupMenu->exec(); } cfg.writeEntry("Schema","19"); if(!fromMenu) { foreground.setNamedColor(cfg.readEntry("foreground","")); background.setNamedColor(cfg.readEntry("background","")); } fromMenu=FALSE; colorMenu->setItemChecked(-19,TRUE); } #endif for (i = 0; i < TABLE_COLORS; i++) { if(i==0 || i == 10) { m_table[i].color = foreground; } else if(i==1 || i == 11) { m_table[i].color = background; m_table[i].transparent=0; } else m_table[i].color = defaultCt[i].color; } } lastSelectedMenu = iD; te->setColorTable(m_table); update(); } void Konsole::configMenuSelected(int iD) { // QString temp; // qDebug( temp.sprintf("configmenu %d",iD)); TEWidget* te = getTe(); Config cfg("Konsole"); cfg.setGroup("Menubar"); int i,j; #ifdef QT_QWS_OPIE i=-29;j=-30; #else i=-28;j=-29; #endif if(iD == -4) { cfg.setGroup("Tabs"); QString tmp=cfg.readEntry("Position","Bottom"); if(tmp=="Top") { tab->setTabPosition(QTabWidget::Bottom); configMenu->changeItem( iD, tr("Tabs on Top")); cfg.writeEntry("Position","Bottom"); } else { tab->setTabPosition(QTabWidget::Top); configMenu->changeItem( iD, tr("Tabs on Bottom")); cfg.writeEntry("Position","Top"); } } if(iD == i) { cfg.setGroup("ScrollBar"); bool b=cfg.readBoolEntry("HorzScroll",0); b=!b; cfg.writeEntry("HorzScroll", b ); cfg.write(); doWrap(); if(cfg.readNumEntry("Position",2) == 0) { te->setScrollbarLocation(1); } else { te->setScrollbarLocation(0); } te->setScrollbarLocation( cfg.readNumEntry("Position",2)); } if(iD == j) { cfg.setGroup("Menubar"); bool b=cfg.readBoolEntry("useBeep",0); b=!b; cfg.writeEntry("useBeep", b ); cfg.write(); configMenu->setItemChecked(j,b); te->useBeep=b; } } void Konsole::changeCommand(const QString &text, int c) { Config cfg("Konsole"); cfg.setGroup("Commands"); if(commonCmds[c] != text) { cfg.writeEntry(QString::number(c),text); commonCombo->clearEdit(); commonCombo->setCurrentItem(c); } } void Konsole::setColor() { Config cfg("Konsole"); cfg.setGroup("Colors"); int scheme = cfg.readNumEntry("Schema",1); if(scheme != 1) colorMenuSelected( -scheme); } void Konsole::scrollMenuSelected(int index) { // qDebug( "scrollbar menu %d",index); TEWidget* te = getTe(); Config cfg("Konsole"); cfg.setGroup("ScrollBar"); int i,j,k; #ifdef QT_QWS_OPIE i=-25;j=-26;k=-27; #else i=-24;j=-25;k=-26; #endif if(index == i) { te->setScrollbarLocation(0); cfg.writeEntry("Position",0); } else if(index == j) { te->setScrollbarLocation(1); cfg.writeEntry("Position",1); } else if(index == k) { te->setScrollbarLocation(2); cfg.writeEntry("Position",2); } // case -29: { // bool b=cfg.readBoolEntry("HorzScroll",0); // cfg.writeEntry("HorzScroll", !b ); // cfg.write(); // if(cfg.readNumEntry("Position",2) == 0) { // te->setScrollbarLocation(1); // te->setWrapAt(0); // } else { // te->setScrollbarLocation(0); // te->setWrapAt(120); // } // te->setScrollbarLocation( cfg.readNumEntry("Position",2)); // } // break; } void Konsole::editCommandListMenuSelected(int iD) { // QString temp; // qDebug( temp.sprintf("edit command list %d",iD)); TEWidget* te = getTe(); Config cfg("Konsole"); cfg.setGroup("Menubar"); if( iD == -3) { if(!secondToolBar->isHidden()) { secondToolBar->hide(); configMenu->changeItem( iD,tr( "Show Command List" )); cfg.writeEntry("Hidden","TRUE"); configMenu->setItemEnabled(-23 ,FALSE); } else { secondToolBar->show(); configMenu->changeItem( iD,tr( "Hide Command List" )); cfg.writeEntry("Hidden","FALSE"); configMenu->setItemEnabled(-23 ,TRUE); if(cfg.readEntry("EditEnabled","FALSE")=="TRUE") { configMenu->setItemChecked(-23,TRUE); commonCombo->setEditable( TRUE ); } else { configMenu->setItemChecked(-23,FALSE); commonCombo->setEditable( FALSE ); } } } if( iD == -23) { cfg.setGroup("Commands"); // qDebug("enableCommandEdit"); if( !configMenu->isItemChecked(iD) ) { commonCombo->setEditable( TRUE ); configMenu->setItemChecked(iD,TRUE); commonCombo->setCurrentItem(0); cfg.writeEntry("EditEnabled","TRUE"); } else { commonCombo->setEditable( FALSE ); configMenu->setItemChecked(iD,FALSE); cfg.writeEntry("EditEnabled","FALSE"); commonCombo->setFocusPolicy(QWidget::NoFocus); te->setFocus(); } } if(iD == -24) { // "edit commands" CommandEditDialog *m = new CommandEditDialog(this); connect(m,SIGNAL(commandsEdited()),this,SLOT(initCommandList())); m->showMaximized(); } } // $QPEDIR/bin/qcop QPE/Application/embeddedkonsole 'setDocument(QString)' 'ssh -V' void Konsole::setDocument( const QString &cmd) { newSession(); TEWidget* te = getTe(); if(cmd.find("-e", 0, TRUE) != -1) { QString cmd2; cmd2=cmd.right(cmd.length()-3)+" &"; system(cmd2.latin1()); if(startUp <= 1 && nsessions < 2) { doneSession(getTe()->currentSession, 0); exit(0); } else doneSession(getTe()->currentSession, 0); } else { if (te != 0) { te->emitText(cmd+"\r"); } } startUp++; } void Konsole::parseCommandLine() { QString cmd; // newSession(); for (int i=1;i< qApp->argc();i++) { if( QString(qApp->argv()[i]) == "-e") { i++; for ( int j=i;j< qApp->argc();j++) { cmd+=QString(qApp->argv()[j])+" "; } cmd.stripWhiteSpace(); system(cmd.latin1()); exit(0);//close(); } // end -e switch } startUp++; } void Konsole::changeForegroundColor(const QColor &color) { Config cfg("Konsole"); cfg.setGroup("Colors"); int r, g, b; color.rgb(&r,&g,&b); foreground.setRgb(r,g,b); cfg.writeEntry("foreground",color.name()); qDebug("foreground "+color.name()); cfg.write(); qDebug("do other dialog"); #ifdef QT_QWS_OPIE OColorPopupMenu* penColorPopupMenu2 = new OColorPopupMenu(Qt::black, this,"background color"); connect(penColorPopupMenu2, SIGNAL(colorSelected(const QColor&)), this, SLOT(changeBackgroundColor(const QColor&))); penColorPopupMenu2->exec(); #endif } void Konsole::changeBackgroundColor(const QColor &color) { qDebug("Change background"); Config cfg("Konsole"); cfg.setGroup("Colors"); int r, g, b; color.rgb(&r,&g,&b); background.setRgb(r,g,b); cfg.writeEntry("background",color.name()); qDebug("background "+color.name()); cfg.write(); } void Konsole::doWrap() { int i; #ifdef QT_QWS_OPIE i=-29; #else i=-28; #endif Config cfg("Konsole"); cfg.setGroup("ScrollBar"); TEWidget* te = getTe(); if( !cfg.readBoolEntry("HorzScroll",0)) { te->setWrapAt(0); configMenu->setItemChecked( i,TRUE); } else { // te->setWrapAt(90); te->setWrapAt(120); configMenu->setItemChecked( i,FALSE); } } diff --git a/core/apps/helpbrowser/helpbrowser.cpp b/core/apps/helpbrowser/helpbrowser.cpp index 531dbff..ed1c165 100644 --- a/core/apps/helpbrowser/helpbrowser.cpp +++ b/core/apps/helpbrowser/helpbrowser.cpp @@ -1,250 +1,250 @@ /********************************************************************** ** 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 "helpbrowser.h" #include <qpe/qpeapplication.h> #include <qpe/resource.h> #include <qpe/mimetype.h> #include <qpe/applnk.h> #include <qpe/global.h> #include <qstatusbar.h> #include <qdragobject.h> #include <qpixmap.h> #include <qpopupmenu.h> -#include <qpe/qpemenubar.h> +#include <qmenubar.h> #include <qpe/qpetoolbar.h> #include <qpe/qcopenvelope_qws.h> #include <qtoolbutton.h> #include <qiconset.h> #include <qfile.h> #include <qtextstream.h> #include <qstylesheet.h> #include <qmessagebox.h> #include <qfiledialog.h> #include <qevent.h> #include <qlineedit.h> #include <qobjectlist.h> #include <qfileinfo.h> #include <qfile.h> #include <qdatastream.h> #include <qprinter.h> #include <qsimplerichtext.h> #include <qpaintdevicemetrics.h> #include <qaction.h> #include <cctype> #include "magictextbrowser.h" HelpBrowser::HelpBrowser( QWidget* parent, const char *name, WFlags f ) : QMainWindow( parent, name, f ), selectedURL() { init( "index.html" ); } void HelpBrowser::init( const QString& _home ) { setIcon( Resource::loadPixmap( "HelpBrowser" ) ); setBackgroundMode( PaletteButton ); browser = new MagicTextBrowser( this ); browser->setFrameStyle( QFrame::Panel | QFrame::Sunken ); connect( browser, SIGNAL( textChanged() ), this, SLOT( textChanged() ) ); setCentralWidget( browser ); setToolBarsMovable( FALSE ); if ( !_home.isEmpty() ) browser->setSource( _home ); QPEToolBar* toolbar = new QPEToolBar( this ); toolbar->setHorizontalStretchable( TRUE ); - QPEMenuBar *menu = new QPEMenuBar( toolbar ); + QMenuBar *menu = new QMenuBar( toolbar ); toolbar = new QPEToolBar( this ); // addToolBar( toolbar, "Toolbar"); QPopupMenu* go = new QPopupMenu( this ); backAction = new QAction( tr( "Backward" ), Resource::loadIconSet( "back" ), QString::null, 0, this, 0 ); connect( backAction, SIGNAL( activated() ), browser, SLOT( backward() ) ); connect( browser, SIGNAL( backwardAvailable( bool ) ), backAction, SLOT( setEnabled( bool ) ) ); backAction->addTo( go ); backAction->addTo( toolbar ); backAction->setEnabled( FALSE ); forwardAction = new QAction( tr( "Forward" ), Resource::loadIconSet( "forward" ), QString::null, 0, this, 0 ); connect( forwardAction, SIGNAL( activated() ), browser, SLOT( forward() ) ); connect( browser, SIGNAL( forwardAvailable( bool ) ), forwardAction, SLOT( setEnabled( bool ) ) ); forwardAction->addTo( go ); forwardAction->addTo( toolbar ); forwardAction->setEnabled( FALSE ); QAction *a = new QAction( tr( "Home" ), Resource::loadIconSet( "home" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), browser, SLOT( home() ) ); a->addTo( go ); a->addTo( toolbar ); bookm = new QPopupMenu( this ); bookm->insertItem( tr( "Add Bookmark" ), this, SLOT( addBookmark() ) ); bookm->insertItem( tr( "Remove from Bookmarks" ), this, SLOT( removeBookmark() ) ); bookm->insertSeparator(); connect( bookm, SIGNAL( activated( int ) ), this, SLOT( bookmChosen( int ) ) ); readBookmarks(); menu->insertItem( tr("Go"), go ); menu->insertItem( tr( "Bookmarks" ), bookm ); resize( 240, 300 ); browser->setFocus(); browser->setFrameStyle( QFrame::NoFrame ); #if !defined(QT_NO_COP) QCopChannel *addressChannel = new QCopChannel("QPE/HelpBrowser" , this ); connect (addressChannel, SIGNAL( received(const QCString &, const QByteArray &)), this, SLOT ( appMessage(const QCString &, const QByteArray &) ) ); #endif connect( qApp, SIGNAL(appMessage(const QCString&, const QByteArray&)), this, SLOT(appMessage(const QCString&, const QByteArray&)) ); } void HelpBrowser::appMessage(const QCString& msg, const QByteArray& data) { qDebug("reached appMessage"); if ( msg == "showFile(QString)" ) { QDataStream ds(data,IO_ReadOnly); QString fn; ds >> fn; setDocument( fn ); QPEApplication::setKeepRunning(); showMaximized(); setActiveWindow(); raise(); } } void HelpBrowser::setDocument( const QString &doc ) { if ( !doc.isEmpty() ) browser->setSource( doc ); raise(); } void HelpBrowser::textChanged() { if ( browser->documentTitle().isNull() ) setCaption( tr("Help Browser") ); else setCaption( browser->documentTitle() ) ; selectedURL = caption(); } HelpBrowser::~HelpBrowser() { QStringList bookmarks; QMap<int, Bookmark>::Iterator it2 = mBookmarks.begin(); for ( ; it2 != mBookmarks.end(); ++it2 ) bookmarks.append( (*it2).name + "=" + (*it2).file ); QFile f2( Global::applicationFileName("helpbrowser", "bookmarks") ); if ( f2.open( IO_WriteOnly ) ) { QDataStream s2( &f2 ); s2 << bookmarks; f2.close(); } } void HelpBrowser::pathSelected( const QString &_path ) { browser->setSource( _path ); } void HelpBrowser::readBookmarks() { QString file = Global::applicationFileName("helpbrowser", "bookmarks"); if ( QFile::exists( file ) ) { QStringList bookmarks; QFile f( file ); if ( f.open( IO_ReadOnly ) ) { QDataStream s( &f ); s >> bookmarks; f.close(); } QStringList::Iterator it = bookmarks.begin(); for ( ; it != bookmarks.end(); ++it ) { Bookmark b; QString current = *it; int equal = current.find( "=" ); if ( equal < 1 || equal == (int)current.length() - 1 ) continue; b.name = current.left( equal ); b.file = current.mid( equal + 1 ); mBookmarks[ bookm->insertItem( b.name ) ] = b; } } } void HelpBrowser::bookmChosen( int i ) { if ( mBookmarks.contains( i ) ) browser->setSource( mBookmarks[ i ].file ); } void HelpBrowser::addBookmark() { Bookmark b; b.name = browser->documentTitle(); b.file = browser->source(); if (b.name.isEmpty() ) { b.name = b.file.left( b.file.length() - 5 ); // remove .html } QMap<int, Bookmark>::Iterator it; for( it = mBookmarks.begin(); it != mBookmarks.end(); ++it ) if ( (*it).file == b.file ) return; mBookmarks[ bookm->insertItem( b.name ) ] = b; } void HelpBrowser::removeBookmark() { QString file = browser->source(); QMap<int, Bookmark>::Iterator it = mBookmarks.begin(); for( ; it != mBookmarks.end(); ++it ) if ( (*it).file == file ) { bookm->removeItem( it.key() ); mBookmarks.remove( it ); break; } } diff --git a/core/apps/textedit/textedit.cpp b/core/apps/textedit/textedit.cpp index b875228..0e3254f 100644 --- a/core/apps/textedit/textedit.cpp +++ b/core/apps/textedit/textedit.cpp @@ -1,1212 +1,1212 @@ /********************************************************************** // 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" #include <opie/ofileselector.h> #include <opie/ofiledialog.h> #include <opie/ofontselector.h> #include <qpe/fontdatabase.h> #include <qpe/global.h> #include <qpe/fileselector.h> #include <qpe/applnk.h> #include <qpe/resource.h> #include <qpe/config.h> #include <qpe/qpeapplication.h> -#include <qpe/qpemenubar.h> +#include <qmenubar.h> #include <qpe/qpetoolbar.h> #include <qpe/qcopenvelope_qws.h> #include <qpoint.h> #include <qtextstream.h> #include <qdatetime.h> #include <qclipboard.h> #include <qstringlist.h> #include <qaction.h> #include <qcolordialog.h> #include <qfileinfo.h> #include <qlineedit.h> #include <qmessagebox.h> #include <qobjectlist.h> #include <qpopupmenu.h> #include <qspinbox.h> #include <qtoolbutton.h> #include <qwidgetstack.h> #include <qcheckbox.h> #include <qcombo.h> #include <qlayout.h> #include <qapplication.h> #include <qtimer.h> #include <qdir.h> #include <unistd.h> #include <sys/stat.h> #include <stdlib.h> //getenv #if QT_VERSION < 300 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" ) ); QPEToolBar *bar = new QPEToolBar( this ); bar->setHorizontalStretchable( true ); menu = bar; - QPEMenuBar *mb = new QPEMenuBar( 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 QPEToolBar( 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 QPEToolBar(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() { qWarning("textedit d'tor"); 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"; qDebug("newFile "+currentFileName); updateCaption( currentFileName); // editor->setEdited( false); } void TextEdit::openDotFile( const QString &f ) { if(!currentFileName.isEmpty()) { currentFileName=f; qDebug("openFile dotfile " + currentFileName); 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 ) { qDebug("filename is "+ f); 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) == "") { qDebug("opening dotfile"); 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); qDebug("openFile string "+currentFileName); 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(); qDebug("openFile doclnk " + currentFileName); if ( !fm.loadFile( f, txt ) ) { // ####### could be a new file qDebug( "Cannot open file" ); } // 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() { qDebug("saveAsFile " + currentFileName); if(currentFileName.isEmpty()) { saveAs(); return false; } QString file = doc->file(); qDebug("saver file "+file); QString name= doc->name(); qDebug("File named "+name); QString rt = editor->text(); if( !rt.isEmpty() ) { if(name.isEmpty()) { saveAs(); } else { currentFileName= name ; qDebug("saveFile "+currentFileName); 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 ) ) { return false; } } else { qDebug("regular save file"); 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; qDebug("saveAsFile " + currentFileName); // case of nothing to save... // if ( !doc && !currentFileName.isEmpty()) { // //|| !bFromDocView) // qDebug("no doc"); // return true; // } // if ( !editor->edited() ) { // delete doc; // doc = 0; // return true; // } QString rt = editor->text(); qDebug(currentFileName); if( currentFileName.isEmpty() || currentFileName == tr("Unnamed") || currentFileName == tr("Text Editor")) { qDebug("do silly TT filename thing"); // 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 // qDebug("hmmmmmm"); } 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; qDebug("saving filename "+fileNm); 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); qDebug("Saving file as "+currentFileName); doc->setName( currentFileName); updateCaption( currentFileName); FileManager fm; if ( !fm.saveFile( *doc, rt ) ) { return false; } if( filePerms ) { filePermissions *filePerm; filePerm = new filePermissions(this, tr("Permissions"),true, 0,(const QString &)fileNm); filePerm->showMaximized(); filePerm->exec(); if( filePerm) delete filePerm; } // } editor->setEdited( false); edited1 = false; edited = false; if(caption().left(1)=="*") setCaption(caption().right(caption().length()-1)); return true; } qDebug("returning false"); 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; qDebug("setDocument"); QFileInfo fi(currentFileName); qDebug("basename:"+fi.baseName()+": current filenmame "+currentFileName); if( (fi.baseName().left(1)).isEmpty() ) { openDotFile(currentFileName); } else { qDebug("setDoc open"); 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 ( )); d-> showMaximized ( ); if ( d-> exec ( ) == 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() { // qDebug("editor changed"); if( /*editor->edited() &&*/ /*edited && */!edited1) { setCaption( "*"+caption()); edited1=true; } edited=true; } void TextEdit::receive(const QCString&msg, const QByteArray &) { qDebug("QCop "+msg); if ( msg == "setDocument(QString)" ) { qDebug("bugger all"); } } 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 { // qDebug("autosave"); save(); } setTimer(); } } void TextEdit::doTimer(bool b) { Config cfg("TextEdit"); cfg.setGroup ( "View" ); cfg.writeEntry ( "autosave", b); featureAutoSave = b; nAutoSave->setOn(b); if(b) { // qDebug("doTimer true"); setTimer(); } // else // qDebug("doTimer false"); } void TextEdit::setTimer() { if(featureAutoSave) { // qDebug("setting autosave"); 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/multimedia/opieplayer/playlistwidget.cpp b/core/multimedia/opieplayer/playlistwidget.cpp index 8016d8e..cfcfd41 100644 --- a/core/multimedia/opieplayer/playlistwidget.cpp +++ b/core/multimedia/opieplayer/playlistwidget.cpp @@ -1,1185 +1,1185 @@ /********************************************************************** ** 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. ** **********************************************************************/ // code added by L. J. Potter Sat 03-02-2002 06:17:54 #define QTOPIA_INTERNAL_FSLP #include <qpe/qcopenvelope_qws.h> -#include <qpe/qpemenubar.h> +#include <qmenubar.h> #include <qpe/qpetoolbar.h> #include <qpe/fileselector.h> #include <qpe/qpeapplication.h> #include <qpe/lnkproperties.h> #include <qpe/storage.h> #include <qpe/applnk.h> #include <qpe/config.h> #include <qpe/global.h> #include <qpe/resource.h> #include <qaction.h> #include <qcursor.h> #include <qimage.h> #include <qfile.h> #include <qdir.h> #include <qlayout.h> #include <qlabel.h> #include <qlist.h> #include <qlistbox.h> #include <qmainwindow.h> #include <qmessagebox.h> #include <qtoolbutton.h> #include <qtabwidget.h> #include <qlistview.h> #include <qpoint.h> #include <qlineedit.h> #include <qpushbutton.h> #include <qregexp.h> #include <qtextstream.h> //#include <qtimer.h> #include "playlistselection.h" #include "playlistwidget.h" #include "mediaplayerstate.h" #include "inputDialog.h" #include <stdlib.h> #include "audiowidget.h" #include "videowidget.h" #include <unistd.h> #include <sys/file.h> #include <sys/ioctl.h> #include <sys/soundcard.h> // for setBacklight() #include <linux/fb.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #define BUTTONS_ON_TOOLBAR #define SIDE_BUTTONS #define CAN_SAVE_LOAD_PLAYLISTS extern AudioWidget *audioUI; extern VideoWidget *videoUI; extern MediaPlayerState *mediaPlayerState; static inline QString fullBaseName ( const QFileInfo &fi ) { QString str = fi. fileName ( ); return str. left ( str. findRev ( '.' )); } QString audioMimes ="audio/mpeg;audio/x-wav;application/ogg;audio/x-mod"; // class myFileSelector { // }; class PlayListWidgetPrivate { public: QToolButton *tbPlay, *tbFull, *tbLoop, *tbScale, *tbShuffle, *tbAddToList, *tbRemoveFromList, *tbMoveUp, *tbMoveDown, *tbRemove; QFrame *playListFrame; FileSelector *files; PlayListSelection *selectedFiles; bool setDocumentUsed; DocLnk *current; }; class ToolButton : public QToolButton { public: ToolButton( QWidget *parent, const char *name, const QString& icon, QObject *handler, const QString& slot, bool t = FALSE ) : QToolButton( parent, name ) { setTextLabel( name ); setPixmap( Resource::loadPixmap( icon ) ); setAutoRaise( TRUE ); setFocusPolicy( QWidget::NoFocus ); setToggleButton( t ); connect( this, t ? SIGNAL( toggled(bool) ) : SIGNAL( clicked() ), handler, slot ); QPEMenuToolFocusManager::manager()->addWidget( this ); } }; class MenuItem : public QAction { public: MenuItem( QWidget *parent, const QString& text, QObject *handler, const QString& slot ) : QAction( text, QString::null, 0, 0 ) { connect( this, SIGNAL( activated() ), handler, slot ); addTo( parent ); } }; PlayListWidget::PlayListWidget( QWidget* parent, const char* name, WFlags fl ) : QMainWindow( parent, name, fl ) { d = new PlayListWidgetPrivate; d->setDocumentUsed = FALSE; d->current = NULL; fromSetDocument = FALSE; insanityBool=FALSE; audioScan = FALSE; videoScan = FALSE; // menuTimer = new QTimer( this ,"menu timer"), // connect( menuTimer, SIGNAL( timeout() ), SLOT( addSelected() ) ); channel = new QCopChannel( "QPE/Application/opieplayer", this ); connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), this, SLOT( qcopReceive(const QCString&, const QByteArray&)) ); setBackgroundMode( PaletteButton ); setCaption( tr("OpiePlayer") ); setIcon( Resource::loadPixmap( "opieplayer/MPEGPlayer" ) ); setToolBarsMovable( FALSE ); // Create Toolbar QPEToolBar *toolbar = new QPEToolBar( this ); toolbar->setHorizontalStretchable( TRUE ); // Create Menubar - QPEMenuBar *menu = new QPEMenuBar( toolbar ); + QMenuBar *menu = new QMenuBar( toolbar ); menu->setMargin( 0 ); QPEToolBar *bar = new QPEToolBar( this ); bar->setLabel( tr( "Play Operations" ) ); // d->tbPlayCurList = new ToolButton( bar, tr( "play List" ), "opieplayer/play_current_list", // this , SLOT( addSelected()) ); tbDeletePlaylist = new QPushButton( Resource::loadIconSet("trash"),"",bar,"close"); tbDeletePlaylist->setFlat(TRUE); tbDeletePlaylist->setFixedSize(20,20); d->tbAddToList = new ToolButton( bar, tr( "Add to Playlist" ), "opieplayer/add_to_playlist", this , SLOT(addSelected()) ); d->tbRemoveFromList = new ToolButton( bar, tr( "Remove from Playlist" ), "opieplayer/remove_from_playlist", this , SLOT(removeSelected()) ); // d->tbPlay = new ToolButton( bar, tr( "Play" ), "opieplayer/play", /*this */mediaPlayerState , SLOT(setPlaying(bool) /* btnPlay() */), TRUE ); d->tbPlay = new ToolButton( bar, tr( "Play" ), "opieplayer/play", this , SLOT( btnPlay(bool) ), TRUE ); d->tbShuffle = new ToolButton( bar, tr( "Randomize" ),"opieplayer/shuffle", mediaPlayerState, SLOT(setShuffled(bool)), TRUE ); d->tbLoop = new ToolButton( bar, tr( "Loop" ),"opieplayer/loop", mediaPlayerState, SLOT(setLooping(bool)), TRUE ); tbDeletePlaylist->hide(); QPopupMenu *pmPlayList = new QPopupMenu( this ); menu->insertItem( tr( "File" ), pmPlayList ); new MenuItem( pmPlayList, tr( "Clear List" ), this, SLOT( clearList() ) ); new MenuItem( pmPlayList, tr( "Add all audio files" ), this, SLOT( addAllMusicToList() ) ); new MenuItem( pmPlayList, tr( "Add all video files" ), this, SLOT( addAllVideoToList() ) ); new MenuItem( pmPlayList, tr( "Add all files" ), this, SLOT( addAllToList() ) ); pmPlayList->insertSeparator(-1); new MenuItem( pmPlayList, tr( "Save PlayList" ), this, SLOT( saveList() ) ); new MenuItem( pmPlayList, tr( "Open File or URL" ), this,SLOT( openFile() ) ); pmPlayList->insertSeparator(-1); new MenuItem( pmPlayList, tr( "Rescan for Audio Files" ), this,SLOT( scanForAudio() ) ); new MenuItem( pmPlayList, tr( "Rescan for Video Files" ), this,SLOT( scanForVideo() ) ); QPopupMenu *pmView = new QPopupMenu( this ); menu->insertItem( tr( "View" ), pmView ); fullScreenButton = new QAction(tr("Full Screen"), Resource::loadPixmap("fullscreen"), QString::null, 0, this, 0); fullScreenButton->addTo(pmView); scaleButton = new QAction(tr("Scale"), Resource::loadPixmap("opieplayer/scale"), QString::null, 0, this, 0); scaleButton->addTo(pmView); skinsMenu = new QPopupMenu( this ); menu->insertItem( tr( "Skins" ), skinsMenu ); skinsMenu->isCheckable(); connect( skinsMenu, SIGNAL( activated( int ) ) , this, SLOT( skinsMenuActivated( int ) ) ); populateSkinsMenu(); QVBox *vbox5 = new QVBox( this ); vbox5->setBackgroundMode( PaletteButton ); QVBox *vbox4 = new QVBox( vbox5 ); vbox4->setBackgroundMode( PaletteButton ); QHBox *hbox6 = new QHBox( vbox4 ); hbox6->setBackgroundMode( PaletteButton ); tabWidget = new QTabWidget( hbox6, "tabWidget" ); // tabWidget->setTabShape(QTabWidget::Triangular); QWidget *pTab; pTab = new QWidget( tabWidget, "pTab" ); // playlistView = new QListView( pTab, "playlistview" ); // playlistView->setMinimumSize(236,260); tabWidget->insertTab( pTab,"Playlist"); // Add the playlist area QVBox *vbox3 = new QVBox( pTab ); vbox3->setBackgroundMode( PaletteButton ); d->playListFrame = vbox3; QGridLayout *layoutF = new QGridLayout( pTab ); layoutF->setSpacing( 2); layoutF->setMargin( 2); layoutF->addMultiCellWidget( d->playListFrame , 0, 0, 0, 1 ); QHBox *hbox2 = new QHBox( vbox3 ); hbox2->setBackgroundMode( PaletteButton ); d->selectedFiles = new PlayListSelection( hbox2); QVBox *vbox1 = new QVBox( hbox2 ); vbox1->setBackgroundMode( PaletteButton ); QPEApplication::setStylusOperation( d->selectedFiles->viewport(),QPEApplication::RightOnHold); QVBox *stretch1 = new QVBox( vbox1 ); stretch1->setBackgroundMode( PaletteButton ); // add stretch new ToolButton( vbox1, tr( "Move Up" ), "opieplayer/up", d->selectedFiles, SLOT(moveSelectedUp()) ); new ToolButton( vbox1, tr( "Remove" ), "opieplayer/cut", d->selectedFiles, SLOT(removeSelected()) ); new ToolButton( vbox1, tr( "Move Down" ), "opieplayer/down", d->selectedFiles, SLOT(moveSelectedDown()) ); QVBox *stretch2 = new QVBox( vbox1 ); stretch2->setBackgroundMode( PaletteButton ); // add stretch QWidget *aTab; aTab = new QWidget( tabWidget, "aTab" ); audioView = new QListView( aTab, "Audioview" ); QGridLayout *layoutA = new QGridLayout( aTab ); layoutA->setSpacing( 2); layoutA->setMargin( 2); layoutA->addMultiCellWidget( audioView, 0, 0, 0, 1 ); audioView->addColumn( tr("Title"),-1); audioView->addColumn(tr("Size"), -1); audioView->addColumn(tr("Media"),-1); audioView->addColumn( tr( "Path" ), -1 ); audioView->setColumnAlignment(1, Qt::AlignRight); audioView->setColumnAlignment(2, Qt::AlignRight); audioView->setAllColumnsShowFocus(TRUE); audioView->setMultiSelection( TRUE ); audioView->setSelectionMode( QListView::Extended); audioView->setSorting( 3, TRUE ); tabWidget->insertTab(aTab,tr("Audio")); QPEApplication::setStylusOperation( audioView->viewport(),QPEApplication::RightOnHold); // audioView // populateAudioView(); // videowidget QWidget *vTab; vTab = new QWidget( tabWidget, "vTab" ); videoView = new QListView( vTab, "Videoview" ); QGridLayout *layoutV = new QGridLayout( vTab ); layoutV->setSpacing( 2); layoutV->setMargin( 2); layoutV->addMultiCellWidget( videoView, 0, 0, 0, 1 ); videoView->addColumn(tr("Title"),-1); videoView->addColumn(tr("Size"),-1); videoView->addColumn(tr("Media"),-1); videoView->addColumn(tr( "Path" ), -1 ); videoView->setColumnAlignment(1, Qt::AlignRight); videoView->setColumnAlignment(2, Qt::AlignRight); videoView->setAllColumnsShowFocus(TRUE); videoView->setMultiSelection( TRUE ); videoView->setSelectionMode( QListView::Extended); QPEApplication::setStylusOperation( videoView->viewport(),QPEApplication::RightOnHold); tabWidget->insertTab( vTab,tr("Video")); QWidget *LTab; LTab = new QWidget( tabWidget, "LTab" ); playLists = new FileSelector( "playlist/plain;audio/x-mpegurl", LTab, "fileselector" , FALSE, FALSE); QGridLayout *layoutL = new QGridLayout( LTab ); layoutL->setSpacing( 2); layoutL->setMargin( 2); layoutL->addMultiCellWidget( playLists, 0, 0, 0, 1 ); tabWidget->insertTab(LTab,tr("Lists")); connect(tbDeletePlaylist,(SIGNAL(released())),SLOT( deletePlaylist())); connect( fullScreenButton, SIGNAL(activated()), mediaPlayerState, SLOT(toggleFullscreen()) ); connect( scaleButton, SIGNAL(activated()), mediaPlayerState, SLOT(toggleScaled()) ); connect( d->selectedFiles, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int)), this,SLOT( playlistViewPressed(int, QListViewItem *, const QPoint&, int)) ); ///audioView connect( audioView, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int)), this,SLOT( viewPressed(int, QListViewItem *, const QPoint&, int)) ); connect( audioView, SIGNAL( returnPressed( QListViewItem *)), this,SLOT( playIt( QListViewItem *)) ); connect( audioView, SIGNAL( doubleClicked( QListViewItem *) ), this, SLOT( addToSelection( QListViewItem *) ) ); //videoView connect( videoView, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int)), this,SLOT( viewPressed(int, QListViewItem *, const QPoint&, int)) ); connect( videoView, SIGNAL( returnPressed( QListViewItem *)), this,SLOT( playIt( QListViewItem *)) ); connect( videoView, SIGNAL( doubleClicked( QListViewItem *) ), this, SLOT( addToSelection( QListViewItem *) ) ); //playlists connect( playLists, SIGNAL( fileSelected( const DocLnk &) ), this, SLOT( loadList( const DocLnk & ) ) ); connect( tabWidget, SIGNAL (currentChanged(QWidget*)),this,SLOT(tabChanged(QWidget*))); connect( mediaPlayerState, SIGNAL( playingToggled( bool ) ), d->tbPlay, SLOT( setOn( bool ) ) ); connect( mediaPlayerState, SIGNAL( loopingToggled( bool ) ), d->tbLoop, SLOT( setOn( bool ) ) ); connect( mediaPlayerState, SIGNAL( shuffledToggled( bool ) ), d->tbShuffle, SLOT( setOn( bool ) ) ); connect( mediaPlayerState, SIGNAL( playlistToggled( bool ) ), this, SLOT( setPlaylist( bool ) ) ); connect( d->selectedFiles, SIGNAL( doubleClicked( QListViewItem *) ), this, SLOT( playIt( QListViewItem *) ) ); setCentralWidget( vbox5 ); Config cfg( "OpiePlayer" ); readConfig( cfg ); currentPlayList = cfg.readEntry("CurrentPlaylist","default"); loadList(DocLnk( currentPlayList)); setCaption(tr("OpiePlayer: ")+ fullBaseName ( QFileInfo(currentPlayList))); initializeStates(); } PlayListWidget::~PlayListWidget() { Config cfg( "OpiePlayer" ); writeConfig( cfg ); if ( d->current ) delete d->current; if(d) delete d; } void PlayListWidget::initializeStates() { d->tbPlay->setOn( mediaPlayerState->playing() ); d->tbLoop->setOn( mediaPlayerState->looping() ); d->tbShuffle->setOn( mediaPlayerState->shuffled() ); setPlaylist( true); } void PlayListWidget::readConfig( Config& cfg ) { cfg.setGroup("PlayList"); QString currentString = cfg.readEntry("current", "" ); int noOfFiles = cfg.readNumEntry("NumberOfFiles", 0 ); for ( int i = 0; i < noOfFiles; i++ ) { QString entryName; entryName.sprintf( "File%i", i + 1 ); QString linkFile = cfg.readEntry( entryName ); DocLnk lnk( linkFile ); if ( lnk.isValid() ) { d->selectedFiles->addToSelection( lnk ); } } d->selectedFiles->setSelectedItem( currentString); } void PlayListWidget::writeConfig( Config& cfg ) const { d->selectedFiles->writeCurrent( cfg); cfg.setGroup("PlayList"); int noOfFiles = 0; d->selectedFiles->first(); do { const DocLnk *lnk = d->selectedFiles->current(); if ( lnk ) { QString entryName; entryName.sprintf( "File%i", noOfFiles + 1 ); // qDebug(entryName); cfg.writeEntry( entryName, lnk->linkFile() ); // if this link does exist, add it so we have the file // next time... if ( !QFile::exists( lnk->linkFile() ) ) { // the way writing lnks doesn't really check for out // of disk space, but check it anyway. // if ( !lnk->writeLink() ) { // QMessageBox::critical( 0, tr("Out of space"), // tr( "There was a problem saving " // "the playlist.\n" // "Your playlist " // "may be missing some entries\n" // "the next time you start it." ) // ); // } } noOfFiles++; } } while ( d->selectedFiles->next() ); cfg.writeEntry("NumberOfFiles", noOfFiles ); } void PlayListWidget::addToSelection( const DocLnk& lnk ) { d->setDocumentUsed = false; if ( mediaPlayerState->playlist() ) { if(QFileInfo(lnk.file()).exists() || lnk.file().left(4) == "http" ) d->selectedFiles->addToSelection( lnk ); } else mediaPlayerState->setPlaying( true); } void PlayListWidget::clearList() { while ( first() ) d->selectedFiles->removeSelected(); Config cfg( "OpiePlayer" ); cfg.setGroup("PlayList"); cfg.writeEntry("CurrentPlaylist",""); currentPlayList=""; } void PlayListWidget::addAllToList() { DocLnkSet filesAll; Global::findDocuments(&filesAll, "video/*;audio/*"); QListIterator<DocLnk> Adit( filesAll.children() ); for ( ; Adit.current(); ++Adit ) if(QFileInfo(Adit.current()->file()).exists()) d->selectedFiles->addToSelection( **Adit ); tabWidget->setCurrentPage(0); writeCurrentM3u(); d->selectedFiles->first(); } void PlayListWidget::addAllMusicToList() { QListIterator<DocLnk> dit( files.children() ); for ( ; dit.current(); ++dit ) if(QFileInfo(dit.current()->file()).exists()) d->selectedFiles->addToSelection( **dit ); tabWidget->setCurrentPage(0); writeCurrentM3u(); d->selectedFiles->first(); } void PlayListWidget::addAllVideoToList() { QListIterator<DocLnk> dit( vFiles.children() ); for ( ; dit.current(); ++dit ) if(QFileInfo( dit.current()->file()).exists()) d->selectedFiles->addToSelection( **dit ); tabWidget->setCurrentPage(0); writeCurrentM3u(); d->selectedFiles->first(); } void PlayListWidget::setDocument(const QString& fileref) { fromSetDocument = true; d->setDocumentUsed = TRUE; setDocumentEx(fileref); } void PlayListWidget::setDocumentEx(const QString& fileref) { qDebug("opieplayer receive "+fileref); clearList(); DocLnk lnk; QFileInfo fileInfo(fileref); if ( !fileInfo.exists() ) { QMessageBox::critical( 0, tr( "Invalid File" ), tr( "There was a problem in getting the file." ) ); return; } // qDebug("<<<<<<<<<<<<<<<<<<<<<<setDocument "+fileref); QString extension = fileInfo.extension(false); if( extension.find( "m3u", 0, false) != -1) { //is m3u readm3u( fileref); } else if( extension.find( "pls", 0, false) != -1 ) { //is pls readPls( fileref); } else if( fileref.find("playlist",0,TRUE) != -1) {//is playlist clearList(); lnk.setName( fileInfo.baseName() ); //sets name lnk.setFile( fileref ); //sets file name lnk.setIcon("Sound"); //addToSelection( lnk ); loadList( lnk); d->selectedFiles->first(); } else { if( fileref.find(".desktop",0,TRUE) != -1) { lnk = DocLnk(fileref); } else { lnk.setName( fileInfo.baseName() ); //sets name lnk.setFile( fileref ); //sets file name lnk.setIcon("Sound"); } addToSelection( lnk ); // addToSelection( DocLnk( fileref ) ); lnk.removeLinkFile(); // qApp->processEvents(); } setCaption(tr("OpiePlayer")); d->setDocumentUsed = TRUE; d->selectedFiles->setSelected(d->selectedFiles->firstChild(),true ); mediaPlayerState->setPlaying( FALSE ); qApp->processEvents(); mediaPlayerState->setPlaying( TRUE ); } void PlayListWidget::setActiveWindow() { // qDebug("SETTING active window"); // When we get raised we need to ensure that it switches views char origView = mediaPlayerState->view(); mediaPlayerState->setView( 'l' ); // invalidate mediaPlayerState->setView( origView ); // now switch back } void PlayListWidget::useSelectedDocument() { d->setDocumentUsed = FALSE; } const DocLnk *PlayListWidget::current() { // this is fugly switch (tabWidget->currentPageIndex()) { case 0: //playlist { // qDebug("playlist"); if ( mediaPlayerState->playlist() ) { return d->selectedFiles->current(); } else if ( d->setDocumentUsed && d->current ) { return d->current; } else { return &(d->files->selectedDocument()); } } break; case 1://audio { // qDebug("audioView"); QListIterator<DocLnk> dit( files.children() ); for ( ; dit.current(); ++dit ) { if( dit.current()->name() == audioView->currentItem()->text(0) && !insanityBool) { insanityBool=TRUE; return dit; } } } break; case 2: // video { QListIterator<DocLnk> Vdit( vFiles.children() ); for ( ; Vdit.current(); ++Vdit ) { if( Vdit.current()->name() == videoView->currentItem()->text(0) && !insanityBool) { insanityBool=TRUE; return Vdit; } } } break; }; return 0; } bool PlayListWidget::prev() { if ( mediaPlayerState->playlist() ) { if ( mediaPlayerState->shuffled() ) { const DocLnk *cur = current(); int j = 1 + (int)(97.0 * rand() / (RAND_MAX + 1.0)); for ( int i = 0; i < j; i++ ) { if ( !d->selectedFiles->next() ) d->selectedFiles->first(); } if ( cur == current() ) if ( !d->selectedFiles->next() ) d->selectedFiles->first(); return TRUE; } else { if ( !d->selectedFiles->prev() ) { if ( mediaPlayerState->looping() ) { return d->selectedFiles->last(); } else { return FALSE; } } return TRUE; } } else { return mediaPlayerState->looping(); } } bool PlayListWidget::next() { if ( mediaPlayerState->playlist() ) { if ( mediaPlayerState->shuffled() ) { return prev(); } else { if ( !d->selectedFiles->next() ) { if ( mediaPlayerState->looping() ) { return d->selectedFiles->first(); } else { return FALSE; } } return TRUE; } } else { return mediaPlayerState->looping(); } } bool PlayListWidget::first() { if ( mediaPlayerState->playlist() ) return d->selectedFiles->first(); else return mediaPlayerState->looping(); } bool PlayListWidget::last() { if ( mediaPlayerState->playlist() ) return d->selectedFiles->last(); else return mediaPlayerState->looping(); } void PlayListWidget::saveList() { writem3u(); } void PlayListWidget::loadList( const DocLnk & lnk) { QString name = lnk.name(); // qDebug("<<<<<<<<<<<<<<<<<<<<<<<<currentList is "+name); if( name.length()>0) { setCaption("OpiePlayer: "+name); // qDebug("<<<<<<<<<<<<load list "+ lnk.file()); clearList(); readm3u(lnk.file()); tabWidget->setCurrentPage(0); } } void PlayListWidget::setPlaylist( bool shown ) { if ( shown ) d->playListFrame->show(); else d->playListFrame->hide(); } void PlayListWidget::setView( char view ) { if ( view == 'l' ) showMaximized(); else hide(); } void PlayListWidget::addSelected() { DocLnk lnk; QString filename; switch (tabWidget->currentPageIndex()) { case 0: //playlist return; break; case 1: { //audio QListViewItemIterator it( audioView ); for ( ; it.current(); ++it ) { if ( it.current()->isSelected() ) { filename = it.current()->text(3); lnk.setName( QFileInfo(filename).baseName() ); //sets name lnk.setFile( filename ); //sets file name d->selectedFiles->addToSelection( lnk); } } audioView->clearSelection(); // d->selectedFiles->next(); } break; case 2: { // video QListViewItemIterator it( videoView ); for ( ; it.current(); ++it ) { if ( it.current()->isSelected() ) { filename = it.current()->text(3); lnk.setName( QFileInfo(filename).baseName() ); //sets name lnk.setFile( filename ); //sets file name d->selectedFiles->addToSelection( lnk); } } videoView->clearSelection(); } break; }; // tabWidget->setCurrentPage(0); writeCurrentM3u(); } void PlayListWidget::removeSelected() { d->selectedFiles->removeSelected( ); } void PlayListWidget::playIt( QListViewItem *) { // d->setDocumentUsed = FALSE; // mediaPlayerState->curPosition =0; // mediaPlayerState->setPlaying(FALSE); mediaPlayerState->setPlaying(TRUE); d->selectedFiles->unSelect(); } void PlayListWidget::addToSelection( QListViewItem *it) { d->setDocumentUsed = FALSE; if(it) { switch ( tabWidget->currentPageIndex()) { case 0: //playlist return; break; }; // case 1: { DocLnk lnk; QString filename; filename=it->text(3); lnk.setName( fullBaseName ( QFileInfo(filename)) ); //sets name lnk.setFile( filename ); //sets file name d->selectedFiles->addToSelection( lnk); if(tabWidget->currentPageIndex() == 0) writeCurrentM3u(); // tabWidget->setCurrentPage(0); } } void PlayListWidget::tabChanged(QWidget *) { switch ( tabWidget->currentPageIndex()) { case 0: { if( !tbDeletePlaylist->isHidden()) tbDeletePlaylist->hide(); d->tbRemoveFromList->setEnabled(TRUE); d->tbAddToList->setEnabled(FALSE); } break; case 1: { audioView->clear(); populateAudioView(); if( !tbDeletePlaylist->isHidden()) tbDeletePlaylist->hide(); d->tbRemoveFromList->setEnabled(FALSE); d->tbAddToList->setEnabled(TRUE); } break; case 2: { videoView->clear(); populateVideoView(); if( !tbDeletePlaylist->isHidden()) tbDeletePlaylist->hide(); d->tbRemoveFromList->setEnabled(FALSE); d->tbAddToList->setEnabled(TRUE); } break; case 3: { if( tbDeletePlaylist->isHidden()) tbDeletePlaylist->show(); playLists->reread(); } break; }; } void PlayListWidget::btnPlay(bool b) { // mediaPlayerState->setPlaying(b); switch ( tabWidget->currentPageIndex()) { case 0: { // if( d->selectedFiles->current()->file().find(" ",0,TRUE) != -1 // if( d->selectedFiles->current()->file().find("%20",0,TRUE) != -1) { // QMessageBox::message("Note","You are trying to play\na malformed url."); // } else { mediaPlayerState->setPlaying(b); insanityBool=FALSE; qDebug("insanity"); // } } break; case 1: { // d->selectedFiles->unSelect(); addToSelection( audioView->currentItem() ); mediaPlayerState->setPlaying( b); d->selectedFiles->removeSelected( ); d->selectedFiles->unSelect(); tabWidget->setCurrentPage(1); insanityBool=FALSE; }// audioView->clearSelection(); break; case 2: { addToSelection( videoView->currentItem() ); mediaPlayerState->setPlaying( b); // qApp->processEvents(); d->selectedFiles->removeSelected( ); d->selectedFiles->unSelect(); tabWidget->setCurrentPage(2); insanityBool=FALSE; }// videoView->clearSelection(); break; }; } void PlayListWidget::deletePlaylist() { switch( QMessageBox::information( this, (tr("Remove Playlist?")), (tr("You really want to delete\nthis playlist?")), (tr("Yes")), (tr("No")), 0 )){ case 0: // Yes clicked, QFile().remove(playLists->selectedDocument().file()); QFile().remove(playLists->selectedDocument().linkFile()); playLists->reread(); break; case 1: // Cancel break; }; } void PlayListWidget::viewPressed( int mouse, QListViewItem *, const QPoint&, int ) { switch (mouse) { case 1: break; case 2:{ QPopupMenu m; m.insertItem( tr( "Play" ), this, SLOT( playSelected() )); m.insertItem( tr( "Add to Playlist" ), this, SLOT( addSelected() )); m.insertSeparator(); if( QFile(QPEApplication::qpeDir()+"lib/libopie.so").exists() ) m.insertItem( tr( "Properties" ), this, SLOT( listDelete() )); m.exec( QCursor::pos() ); } break; }; } void PlayListWidget::playSelected() { btnPlay( true); // d->selectedFiles->unSelect(); } void PlayListWidget::playlistViewPressed( int mouse, QListViewItem *, const QPoint&, int) { switch (mouse) { case 1: break; case 2:{ QPopupMenu m; m.insertItem( tr( "Play Selected" ), this, SLOT( playSelected() )); m.insertItem( tr( "Remove" ), this, SLOT( removeSelected() )); // m.insertSeparator(); // m.insertItem( tr( "Properties" ), this, SLOT( listDelete() )); m.exec( QCursor::pos() ); } break; }; } void PlayListWidget::listDelete() { Config cfg( "OpiePlayer" ); cfg.setGroup("PlayList"); currentPlayList = cfg.readEntry("CurrentPlaylist",""); QString file; // int noOfFiles = cfg.readNumEntry("NumberOfFiles", 0 ); switch ( tabWidget->currentPageIndex()) { case 0: break; case 1: { file = audioView->currentItem()->text(0); QListIterator<DocLnk> Pdit( files.children() ); for ( ; Pdit.current(); ++Pdit ) { if( Pdit.current()->name() == file) { LnkProperties prop( Pdit.current() ); prop.showMaximized(); prop.exec(); } } populateAudioView(); } break; case 2: { // file = videoView->selectedItem()->text(0); // for ( int i = 0; i < noOfFiles; i++ ) { // QString entryName; // entryName.sprintf( "File%i", i + 1 ); // QString linkFile = cfg.readEntry( entryName ); // AppLnk lnk( AppLnk(linkFile)); // if( lnk.name() == file ) { // LnkProperties prop( &lnk); // // connect(&prop, SIGNAL(select(const AppLnk *)), this, SLOT(externalSelected(const AppLnk *))); // prop.showMaximized(); // prop.exec(); // } // } } break; }; } void PlayListWidget::scanForAudio() { // qDebug("scan for audio"); files.detachChildren(); QListIterator<DocLnk> sdit( files.children() ); for ( ; sdit.current(); ++sdit ) { delete sdit.current(); } Global::findDocuments( &files, audioMimes); audioScan = true; } void PlayListWidget::scanForVideo() { // qDebug("scan for video"); vFiles.detachChildren(); QListIterator<DocLnk> sdit( vFiles.children() ); for ( ; sdit.current(); ++sdit ) { delete sdit.current(); } Global::findDocuments(&vFiles, "video/*"); videoScan = true; } void PlayListWidget::populateAudioView() { audioView->clear(); StorageInfo storageInfo; const QList<FileSystem> &fs = storageInfo.fileSystems(); if(!audioScan) scanForAudio(); QListIterator<DocLnk> dit( files.children() ); QListIterator<FileSystem> it ( fs ); QString storage; for ( ; dit.current(); ++dit ) { for( ; it.current(); ++it ){ const QString name = (*it)->name(); const QString path = (*it)->path(); if(dit.current()->file().find(path) != -1 ) storage=name; } QListViewItem * newItem; if ( QFile( dit.current()->file()).exists() || dit.current()->file().left(4) == "http" ) { long size; if( dit.current()->file().left(4) == "http" ) size=0; else size = QFile( dit.current()->file() ).size(); // qDebug(dit.current()->name()); newItem= /*(void)*/ new QListViewItem( audioView, dit.current()->name(), QString::number(size ), storage, dit.current()->file()); newItem->setPixmap(0, Resource::loadPixmap( "opieplayer/musicfile" )); } } } void PlayListWidget::populateVideoView() { videoView->clear(); StorageInfo storageInfo; const QList<FileSystem> &fs = storageInfo.fileSystems(); if(!videoScan ) scanForVideo(); QListIterator<DocLnk> Vdit( vFiles.children() ); QListIterator<FileSystem> it ( fs ); videoView->clear(); QString storage; for ( ; Vdit.current(); ++Vdit ) { for( ; it.current(); ++it ){ const QString name = (*it)->name(); const QString path = (*it)->path(); if( Vdit.current()->file().find(path) != -1 ) storage=name; } QListViewItem * newItem; if ( QFile( Vdit.current()->file()).exists() ) { newItem= /*(void)*/ new QListViewItem( videoView, Vdit.current()->name(), QString::number( QFile( Vdit.current()->file() ).size() ), storage, Vdit.current()->file()); newItem->setPixmap(0, Resource::loadPixmap( "opieplayer/videofile" )); } } } void PlayListWidget::openFile() { QString filename, name; InputDialog *fileDlg; fileDlg = new InputDialog(this,tr("Open file or URL"),TRUE, 0); fileDlg->exec(); if( fileDlg->result() == 1 ) { filename = fileDlg->text(); // qDebug( "Selected filename is " + filename ); DocLnk lnk; Config cfg( "OpiePlayer" ); cfg.setGroup("PlayList"); QString m3uFile; m3uFile = filename; if(filename.left(4) == "http") { if(filename.find(":",8,TRUE) != -1) { //found a port m3uFile = filename; if( m3uFile.right( 1 ).find( '/' ) == -1) { m3uFile += "/"; } filename = m3uFile; } lnk.setName( m3uFile ); //sets name lnk.setFile( filename ); //sets file name lnk.setIcon("opieplayer2/musicfile"); d->selectedFiles->addToSelection( lnk ); writeCurrentM3u(); } else if( filename.right( 3) == "m3u" ) { readm3u( filename ); } else if( filename.right(3) == "pls" ) { readPls( filename ); } else { lnk.setName( fullBaseName ( QFileInfo(filename)) ); //sets name lnk.setFile( filename ); //sets file name d->selectedFiles->addToSelection( lnk); lnk.removeLinkFile(); writeCurrentM3u(); } } if( fileDlg ) { delete fileDlg; } } /* reads m3u and shows files/urls to playlist widget */ void PlayListWidget::readm3u( const QString &filename ) { // qDebug( "read m3u filename " + filename ); Om3u *m3uList; QString s, name; m3uList = new Om3u( filename, IO_ReadOnly ); m3uList->readM3u(); DocLnk lnk; for ( QStringList::ConstIterator it = m3uList->begin(); it != m3uList->end(); ++it ) { s = *it; // qDebug("reading "+ s); if(s.left(4)=="http") { lnk.setName( s ); //sets file name lnk.setIcon("opieplayer2/musicfile"); // if(s.right(4) != '.' || s.right(5) != '.') if(s.right(4) != '.' || s.right(5) != '.' ) if( s.right(1) != "/") lnk.setFile( s+"/"); //if url with no extension else lnk.setFile( s ); //sets file name } else { // if( QFileInfo( s ).exists() ) { lnk.setName( fullBaseName ( QFileInfo(s))); // if(s.right(4) == '.') {//if regular file if(s.left(1) != "/") { // qDebug("set link "+QFileInfo(filename).dirPath()+"/"+s); lnk.setFile( QFileInfo(filename).dirPath()+"/"+s); lnk.setIcon("SoundPlayer"); } else { // qDebug("set link2 "+s); lnk.setFile( s); lnk.setIcon("SoundPlayer"); } } d->selectedFiles->addToSelection( lnk ); } Config config( "OpiePlayer" ); config.setGroup( "PlayList" ); config.writeEntry("CurrentPlaylist",filename); config.write(); currentPlayList=filename; // m3uList->write(); m3uList->close(); if(m3uList) delete m3uList; d->selectedFiles->setSelectedItem( s); setCaption(tr("OpiePlayer: ")+ fullBaseName ( QFileInfo(filename))); } /* reads pls and adds files/urls to playlist */ void PlayListWidget::readPls( const QString &filename ) { // qDebug( "pls filename is " + filename ); Om3u *m3uList; QString s, name; m3uList = new Om3u( filename, IO_ReadOnly ); m3uList->readPls(); for ( QStringList::ConstIterator it = m3uList->begin(); it != m3uList->end(); ++it ) { s = *it; // s.replace( QRegExp( "%20" )," " ); DocLnk lnk( s ); QFileInfo f( s ); QString name = fullBaseName ( f); if( name.left( 4 ) == "http" ) { name = s.right( s.length() - 7); } else { diff --git a/core/pim/addressbook/addressbook.cpp b/core/pim/addressbook/addressbook.cpp index 438c270..406ced6 100644 --- a/core/pim/addressbook/addressbook.cpp +++ b/core/pim/addressbook/addressbook.cpp @@ -1,1061 +1,1061 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** Copyright (C) 2003 Stefan Eilers (eilers.stefan@epost.de) ** ** This file is part of the Open Palmtop Environment (see www.opie.info). ** ** 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. ** ** **********************************************************************/ #define QTOPIA_INTERNAL_FD #include "contacteditor.h" #include "ablabel.h" #include "abview.h" #include "abtable.h" // #include "addresssettings.h" #include "addressbook.h" #include <opie/ofileselector.h> #include <opie/ofiledialog.h> #include <opie/ocontact.h> #include <opie/ocontactaccessbackend_vcard.h> #include <qpe/resource.h> #include <qpe/ir.h> #include <qpe/qpemessagebox.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/qpetoolbar.h> -#include <qpe/qpemenubar.h> +#include <qmenubar.h> // #include <qtoolbar.h> // #include <qmenubar.h> #include <qpe/qpeapplication.h> #include <qpe/config.h> #include <qaction.h> #include <qdialog.h> #include <qdir.h> #include <qfile.h> #include <qimage.h> #include <qlayout.h> #include <qmessagebox.h> #include <qpixmap.h> #include <qpopupmenu.h> #include <qstringlist.h> #include <qtoolbutton.h> #include <qwhatsthis.h> #include <qdatetime.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include "picker.h" #include "configdlg.h" extern QString addressbookPersonalVCardName(); AddressbookWindow::AddressbookWindow( QWidget *parent, const char *name, WFlags f ) : QMainWindow( parent, name, f ), catMenu (0l), abEditor(0l), syncing(FALSE), m_tableViewButton(0l), m_cardViewButton(0l) { isLoading = true; m_config.load(); setCaption( tr("Contacts") ); setIcon( Resource::loadPixmap( "AddressBook" ) ); // Settings for Main Menu // setToolBarsMovable( false ); setToolBarsMovable( !m_config.fixedBars() ); setRightJustification( true ); QPEToolBar *bar = new QPEToolBar( this ); bar->setHorizontalStretchable( TRUE ); - QPEMenuBar *mbList = new QPEMenuBar( bar ); + QMenuBar *mbList = new QMenuBar( bar ); mbList->setMargin( 0 ); QPopupMenu *edit = new QPopupMenu( mbList ); mbList->insertItem( tr( "Contact" ), edit ); // Category Menu catMenu = new QPopupMenu( this ); catMenu->setCheckable( TRUE ); connect( catMenu, SIGNAL(activated(int)), this, SLOT(slotSetCategory(int)) ); mbList->insertItem( tr("View"), catMenu ); // Create Toolbar listTools = new QPEToolBar( this, "list operations" ); listTools->setHorizontalStretchable( true ); addToolBar( listTools ); moveToolBar( listTools, m_config.getToolBarPos() ); // View Icons m_tableViewButton = new QAction( tr( "List" ), Resource::loadPixmap( "addressbook/listview" ), QString::null, 0, this, 0 ); connect( m_tableViewButton, SIGNAL( activated() ), this, SLOT( slotListView() ) ); m_tableViewButton->setToggleAction( true ); m_tableViewButton->addTo( listTools ); m_cardViewButton = new QAction( tr( "Card" ), Resource::loadPixmap( "addressbook/cardview" ), QString::null, 0, this, 0 ); connect( m_cardViewButton, SIGNAL( activated() ), this, SLOT( slotCardView() ) ); m_cardViewButton->setToggleAction( true ); m_cardViewButton->addTo( listTools ); listTools->addSeparator(); // Other Buttons QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 ); actionNew = a; connect( a, SIGNAL( activated() ), this, SLOT( slotListNew() ) ); a->addTo( edit ); a->addTo( listTools ); a = new QAction( tr( "Edit" ), Resource::loadPixmap( "edit" ), QString::null, 0, this, 0 ); actionEdit = a; connect( a, SIGNAL( activated() ), this, SLOT( slotViewEdit() ) ); a->addTo( edit ); a->addTo( listTools ); a = new QAction( tr( "Delete" ), Resource::loadPixmap( "trash" ), QString::null, 0, this, 0 ); actionTrash = a; connect( a, SIGNAL( activated() ), this, SLOT( slotListDelete() ) ); a->addTo( edit ); a->addTo( listTools ); // make it possible to go directly to businesscard via qcop call //#if defined(Q_WS_QWS) // Why this ? (se) #if !defined(QT_NO_COP) QCopChannel *addressChannel = new QCopChannel("QPE/Addressbook" , this ); connect (addressChannel, SIGNAL( received(const QCString &, const QByteArray &)), this, SLOT ( appMessage(const QCString &, const QByteArray &) ) ); #endif // #endif a = new QAction( tr( "Find" ), Resource::loadPixmap( "mag" ), QString::null, 0, this, 0 ); actionFind = a; connect( a, SIGNAL(activated()), this, SLOT( slotFindOpen()) ); a->addTo( edit ); a->addTo( listTools ); // Much better search widget, taken from QTReader.. (se) searchBar = new OFloatBar( "Search", this, QMainWindow::Top, TRUE ); searchBar->setHorizontalStretchable( TRUE ); searchBar->hide(); searchEdit = new QLineEdit( searchBar, "searchEdit" ); // QFont f("unifont", 16 /*, QFont::Bold*/); // searchEdit->setFont( f ); searchBar->setStretchableWidget( searchEdit ); connect( searchEdit, SIGNAL( returnPressed( ) ), this, SLOT( slotFind( ) ) ); a = new QAction( tr( "Start Search" ), Resource::loadPixmap( "enter" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( slotFind() ) ); a->addTo( searchBar ); a = new QAction( tr( "Close Find" ), Resource::loadPixmap( "close" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( slotFindClose() ) ); a->addTo( searchBar ); a = new QAction( tr( "Write Mail To" ), Resource::loadPixmap( "addressbook/sendmail" ), QString::null, 0, this, 0 ); //a->setEnabled( FALSE ); we got support for it now :) zecke actionMail = a; connect( a, SIGNAL( activated() ), this, SLOT( writeMail() ) ); a->addTo( edit ); a->addTo( listTools ); if ( Ir::supported() ) { a = new QAction( tr ("Beam Entry" ), Resource::loadPixmap( "beam" ), QString::null, 0, this, 0 ); actionBeam = a; connect( a, SIGNAL( activated() ), this, SLOT( slotBeam() ) ); a->addTo( edit ); a->addTo( listTools ); } edit->insertSeparator(); a = new QAction( tr("Import vCard"), Resource::loadPixmap( "addressbook/fileimport"), QString::null, 0, this, 0); actionPersonal = a; connect( a, SIGNAL( activated() ), this, SLOT( importvCard() ) ); a->addTo( edit ); a = new QAction( tr("Export vCard"), Resource::loadPixmap( "addressbook/fileexport"), QString::null, 0, this, 0); actionPersonal = a; connect( a, SIGNAL( activated() ), this, SLOT( exportvCard() ) ); a->addTo( edit ); edit->insertSeparator(); a = new QAction( tr("My Personal Details"), Resource::loadPixmap( "addressbook/identity" ), QString::null, 0, this, 0 , TRUE ); actionPersonal = a; connect( a, SIGNAL( activated() ), this, SLOT( slotPersonalView() ) ); a->addTo( edit ); #ifdef __DEBUG_RELEASE // Remove this function for public Release ! This is only // for debug purposes .. a = new QAction( tr( "Save all Data"), QString::null, 0, 0 ); connect( a, SIGNAL( activated() ), this , SLOT( slotSave() ) ); a->addTo( edit ); #endif a = new QAction( tr( "Config" ), Resource::loadPixmap( "SettingsIcon" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( slotConfig() ) ); a->addTo( edit ); // Create Views listContainer = new QWidget( this ); QVBoxLayout *vb = new QVBoxLayout( listContainer ); m_abView = new AbView( listContainer, m_config.orderList() ); vb->addWidget( m_abView ); // abList->setHScrollBarMode( QScrollView::AlwaysOff ); connect( m_abView, SIGNAL( signalViewSwitched ( int ) ), this, SLOT( slotViewSwitched( int ) ) ); QObject::connect( m_abView, SIGNAL(signalNotFound()), this, SLOT(slotNotFound()) ); // m_abView->load(); // Already done by c'tor . // Letter Picker pLabel = new LetterPicker( listContainer ); connect(pLabel, SIGNAL(letterClicked(char)), this, SLOT(slotSetLetter(char))); connect(m_abView, SIGNAL( signalClearLetterPicker() ), pLabel, SLOT( clear() ) ); vb->addWidget( pLabel ); // All Categories into view-menu.. populateCategories(); // Fontsize defaultFont = new QFont( m_abView->font() ); slotSetFont(m_config.fontSize()); m_curFontSize = m_config.fontSize(); setCentralWidget(listContainer); // qDebug("adressbook contrsuction: t=%d", t.elapsed() ); connect( qApp, SIGNAL( flush() ), this, SLOT( flush() ) ); connect( qApp, SIGNAL( reload() ), this, SLOT( reload() ) ); connect( qApp, SIGNAL( appMessage(const QCString &, const QByteArray &) ), this, SLOT( appMessage(const QCString &, const QByteArray &) ) ); isLoading = false; } void AddressbookWindow::slotConfig() { ConfigDlg* dlg = new ConfigDlg( this, "Config" ); dlg -> setConfig( m_config ); dlg -> showMaximized(); if ( dlg -> exec() ) { qWarning ("Config Dialog accepted!"); m_config = dlg -> getConfig(); if ( m_curFontSize != m_config.fontSize() ){ qWarning("Font was changed!"); m_curFontSize = m_config.fontSize(); emit slotSetFont( m_curFontSize ); } m_abView -> setListOrder( m_config.orderList() ); } delete dlg; } void AddressbookWindow::slotSetFont( int size ) { qWarning("void AddressbookWindow::slotSetFont( %d )", size); if (size > 2 || size < 0) size = 1; m_config.setFontSize( size ); QFont *currentFont; switch (size) { case 0: m_abView->setFont( QFont( defaultFont->family(), defaultFont->pointSize() - 2 ) ); currentFont = new QFont (m_abView->font()); // abList->resizeRows(currentFont->pixelSize() + 7); :SX // abList->resizeRows(); break; case 1: m_abView->setFont( *defaultFont ); currentFont = new QFont (m_abView->font()); // // abList->resizeRows(currentFont->pixelSize() + 7); // abList->resizeRows(); break; case 2: m_abView->setFont( QFont( defaultFont->family(), defaultFont->pointSize() + 2 ) ); currentFont = new QFont (m_abView->font()); // //abList->resizeRows(currentFont->pixelSize() + 7); // abList->resizeRows(); break; } } void AddressbookWindow::importvCard() { QString str = OFileDialog::getOpenFileName( 1,"/");//,"", "*", this ); if(!str.isEmpty() ){ setDocument((const QString&) str ); } } void AddressbookWindow::exportvCard() { qWarning(" void AddressbookWindow::exportvCard()"); QString filename = OFileDialog::getSaveFileName( 1,"/home/"); //,"", "*", this ); if( !filename.isEmpty() && ( filename[filename.length()-1] != '/' ) ){ qWarning(" Save to file %s, (%d)", filename.latin1(), filename.length()-1 ); OContact curCont = m_abView->currentEntry(); if ( !curCont.isEmpty() ){ OContactAccessBackend* vcard_backend = new OContactAccessBackend_VCard( QString::null, filename ); OContactAccess* access = new OContactAccess ( "addressbook_exp", QString::null , vcard_backend, true ); if ( access ){ access->add( curCont ); access->save(); } delete access; }else QMessageBox::critical( 0, "Export VCard", QString( tr( "You have to select a contact !") ) ); }else QMessageBox::critical( 0, "Export VCard", QString( tr( "You have to set a filename !") ) ); } void AddressbookWindow::setDocument( const QString &filename ) { qWarning( "void AddressbookWindow::setDocument( %s )", filename.latin1() ); if ( filename.find(".vcf") != int(filename.length()) - 4 ){ switch( QMessageBox::information( this, tr ( "Right file type ?" ), tr( "The selected file \n does not end with \".vcf\".\n Do you really want to open it?" ), tr( "&Yes" ), tr( "&No" ), QString::null, 0, // Enter == button 0 2 ) ) { // Escape == button 2 case 0: qWarning("YES clicked"); break; case 1: qWarning("NO clicked"); return; break; } } OContactAccessBackend* vcard_backend = new OContactAccessBackend_VCard( QString::null, filename ); OContactAccess* access = new OContactAccess ( "addressbook", QString::null , vcard_backend, true ); OContactAccess::List allList = access->allRecords(); qWarning( "Found number of contacts in File: %d", allList.count() ); if ( !allList.count() ) { QMessageBox::information( this, "Import VCard", "It was impossible to import\nthe VCard.\n" "The VCard may be corrupted!" ); } bool doAsk = true; OContactAccess::List::Iterator it; for ( it = allList.begin(); it != allList.end(); ++it ){ qWarning("Adding Contact from: %s", (*it).fullName().latin1() ); if ( doAsk ){ switch( QMessageBox::information( this, tr ( "Add Contact?" ), tr( "Do you really want add contact for \n%1?" ) .arg( (*it).fullName().latin1() ), tr( "&Yes" ), tr( "&No" ), tr( "&All Yes"), 0, // Enter == button 0 2 ) ) { // Escape == button 2 case 0: qWarning("YES clicked"); m_abView->addEntry( *it ); break; case 1: qWarning("NO clicked"); break; case 2: qWarning("YesAll clicked"); doAsk = false; break; } }else m_abView->addEntry( *it ); } delete access; } void AddressbookWindow::resizeEvent( QResizeEvent *e ) { QMainWindow::resizeEvent( e ); } AddressbookWindow::~AddressbookWindow() { ToolBarDock dock; int dummy; bool bDummy; getLocation ( listTools, dock, dummy, bDummy, dummy ); m_config.setToolBarDock( dock ); m_config.save(); } void AddressbookWindow::slotUpdateToolbar() { OContact ce = m_abView->currentEntry(); actionMail->setEnabled( !ce.defaultEmail().isEmpty() ); } void AddressbookWindow::slotListNew() { OContact cnt; if( !syncing ) { editEntry( NewEntry ); } else { QMessageBox::warning(this, tr("Contacts"), tr("Can not edit data, currently syncing")); } } // void AddressbookWindow::slotListView() // { // m_abView -> init( abList->currentEntry() ); // // :SX mView->sync(); // //:SX showView(); // } void AddressbookWindow::slotListDelete() { if(!syncing) { OContact tmpEntry = m_abView ->currentEntry(); // get a name, do the best we can... QString strName = tmpEntry.fullName(); if ( strName.isEmpty() ) { strName = tmpEntry.company(); if ( strName.isEmpty() ) strName = "No Name"; } if ( QPEMessageBox::confirmDelete( this, tr( "Contacts" ), strName ) ) { m_abView->removeEntry( tmpEntry.uid() ); } } else { QMessageBox::warning( this, tr("Contacts"), tr("Can not edit data, currently syncing") ); } } void AddressbookWindow::slotFindOpen() { searchBar->show(); m_abView -> inSearch(); searchEdit->setFocus(); } void AddressbookWindow::slotFindClose() { searchBar->hide(); m_abView -> offSearch(); // m_abView->setFocus(); } void AddressbookWindow::slotFind() { m_abView->slotDoFind( searchEdit->text(), m_config.beCaseSensitive(), m_config.useRegExp(), false); searchEdit->clearFocus(); // m_abView->setFocus(); } void AddressbookWindow::slotViewBack() { // :SX showList(); } void AddressbookWindow::slotViewEdit() { if(!syncing) { if (actionPersonal->isOn()) { editPersonal(); } else { editEntry( EditEntry ); } } else { QMessageBox::warning( this, tr("Contacts"), tr("Can not edit data, currently syncing") ); } } void AddressbookWindow::writeMail() { OContact c = m_abView -> currentEntry(); QString name = c.fileAs(); QString email = c.defaultEmail(); // I prefer the OPIE-Environment variable before the // QPE-one.. QString basepath = QString::fromLatin1( getenv("OPIEDIR") ); if ( basepath.isEmpty() ) basepath = QString::fromLatin1( getenv("QPEDIR") ); // Try to access the preferred. If not possible, try to // switch to the other one.. if ( m_config.useQtMail() ){ qWarning ("Accessing: %s", (basepath + "/bin/qtmail").latin1()); if ( QFile::exists( basepath + "/bin/qtmail" ) ){ qWarning ("QCop"); QCopEnvelope e("QPE/Application/qtmail", "writeMail(QString,QString)"); e << name << email; return; } else m_config.setUseOpieMail( true ); } if ( m_config.useOpieMail() ){ qWarning ("Accessing: %s", (basepath + "/bin/mail").latin1()); if ( QFile::exists( basepath + "/bin/mail" ) ){ qWarning ("QCop"); QCopEnvelope e("QPE/Application/mail", "writeMail(QString,QString)"); e << name << email; return; } else m_config.setUseQtMail( true ); } } static const char * beamfile = "/tmp/obex/contact.vcf"; void AddressbookWindow::slotBeam() { QString beamFilename; OContact c; if ( actionPersonal->isOn() ) { beamFilename = addressbookPersonalVCardName(); if ( !QFile::exists( beamFilename ) ) return; // can't beam a non-existent file OContactAccessBackend* vcard_backend = new OContactAccessBackend_VCard( QString::null, beamFilename ); OContactAccess* access = new OContactAccess ( "addressbook", QString::null , vcard_backend, true ); OContactAccess::List allList = access->allRecords(); OContactAccess::List::Iterator it = allList.begin(); // Just take first c = *it; delete access; } else { unlink( beamfile ); // delete if exists mkdir("/tmp/obex/", 0755); c = m_abView -> currentEntry(); OContactAccessBackend* vcard_backend = new OContactAccessBackend_VCard( QString::null, beamfile ); OContactAccess* access = new OContactAccess ( "addressbook", QString::null , vcard_backend, true ); access->add( c ); access->save(); delete access; beamFilename = beamfile; } qWarning("Beaming: %s", beamFilename.latin1() ); Ir *ir = new Ir( this ); connect( ir, SIGNAL( done( Ir * ) ), this, SLOT( beamDone( Ir * ) ) ); QString description = c.fullName(); ir->send( beamFilename, description, "text/x-vCard" ); } void AddressbookWindow::beamDone( Ir *ir ) { delete ir; unlink( beamfile ); } static void parseName( const QString& name, QString *first, QString *middle, QString * last ) { int comma = name.find ( "," ); QString rest; if ( comma > 0 ) { *last = name.left( comma ); comma++; while ( comma < int(name.length()) && name[comma] == ' ' ) comma++; rest = name.mid( comma ); } else { int space = name.findRev( ' ' ); *last = name.mid( space+1 ); rest = name.left( space ); } int space = rest.find( ' ' ); if ( space <= 0 ) { *first = rest; } else { *first = rest.left( space ); *middle = rest.mid( space+1 ); } } void AddressbookWindow::appMessage(const QCString &msg, const QByteArray &data) { bool needShow = FALSE; qWarning("Receiving QCop-Call with message %s", QString( msg ).latin1() ); if (msg == "editPersonal()") { editPersonal(); } else if (msg == "editPersonalAndClose()") { editPersonal(); close(); } else if ( msg == "addContact(QString,QString)" ) { QDataStream stream(data,IO_ReadOnly); QString name, email; stream >> name >> email; OContact cnt; QString fn, mn, ln; parseName( name, &fn, &mn, &ln ); // qDebug( " %s - %s - %s", fn.latin1(), mn.latin1(), ln.latin1() ); cnt.setFirstName( fn ); cnt.setMiddleName( mn ); cnt.setLastName( ln ); cnt.insertEmails( email ); cnt.setDefaultEmail( email ); cnt.setFileAs(); m_abView -> addEntry( cnt ); // :SXm_abView()->init( cnt ); editEntry( EditEntry ); } else if ( msg == "beamBusinessCard()" ) { QString beamFilename = addressbookPersonalVCardName(); if ( !QFile::exists( beamFilename ) ) return; // can't beam a non-existent file Ir *ir = new Ir( this ); connect( ir, SIGNAL( done( Ir * ) ), this, SLOT( beamDone( Ir * ) ) ); QString description = "mycard.vcf"; ir->send( beamFilename, description, "text/x-vCard" ); } else if ( msg == "show(int)" ) { raise(); QDataStream stream(data,IO_ReadOnly); int uid; stream >> uid; qWarning( "Showing uid: %d" , uid ); // Deactivate Personal View.. if ( actionPersonal->isOn() ){ actionPersonal->setOn( false ); slotPersonalView(); } // Reset category and show as card.. m_abView -> setShowByCategory( QString::null ); m_abView -> setCurrentUid( uid ); slotViewSwitched ( AbView::CardView ); needShow = true; } else if ( msg == "edit(int)" ) { QDataStream stream(data,IO_ReadOnly); int uid; stream >> uid; // Deactivate Personal View.. if ( actionPersonal->isOn() ){ actionPersonal->setOn( false ); slotPersonalView(); } // Reset category and edit.. m_abView -> setShowByCategory( QString::null ); m_abView -> setCurrentUid( uid ); slotViewEdit(); } if (needShow) QPEApplication::setKeepRunning(); } void AddressbookWindow::editEntry( EntryMode entryMode ) { OContact entry; if ( !abEditor ) { abEditor = new ContactEditor( entry, this, "editor" ); } if ( entryMode == EditEntry ) abEditor->setEntry( m_abView -> currentEntry() ); else if ( entryMode == NewEntry ) abEditor->setEntry( entry ); // other things may change the caption. abEditor->setCaption( tr("Edit Address") ); #if defined(Q_WS_QWS) || defined(_WS_QWS_) abEditor->showMaximized(); #endif // fix the foxus... abEditor->setNameFocus(); if ( abEditor->exec() ) { setFocus(); if ( entryMode == NewEntry ) { OContact insertEntry = abEditor->entry(); insertEntry.assignUid(); m_abView -> addEntry( insertEntry ); m_abView -> setCurrentUid( insertEntry.uid() ); } else { OContact replEntry = abEditor->entry(); if ( !replEntry.isValidUid() ) replEntry.assignUid(); m_abView -> replaceEntry( replEntry ); } } // populateCategories(); } void AddressbookWindow::editPersonal() { OContact entry; // Switch to personal view if not selected // but take care of the menu, too if ( ! actionPersonal->isOn() ){ qWarning("*** ++++"); actionPersonal->setOn( true ); slotPersonalView(); } if ( !abEditor ) { abEditor = new ContactEditor( entry, this, "editor" ); } abEditor->setCaption(tr("Edit My Personal Details")); abEditor->setPersonalView( true ); editEntry( EditEntry ); abEditor->setPersonalView( false ); } void AddressbookWindow::slotPersonalView() { qWarning("slotPersonalView()"); if (!actionPersonal->isOn()) { // we just turned it off qWarning("slotPersonalView()-> OFF"); setCaption( tr("Contacts") ); actionNew->setEnabled(TRUE); actionTrash->setEnabled(TRUE); actionFind->setEnabled(TRUE); actionMail->setEnabled(TRUE); // slotUpdateToolbar(); m_abView->showPersonal( false ); return; } qWarning("slotPersonalView()-> ON"); // XXX need to disable some QActions. actionNew->setEnabled(FALSE); actionTrash->setEnabled(FALSE); actionFind->setEnabled(FALSE); actionMail->setEnabled(FALSE); setCaption( tr("Contacts - My Personal Details") ); m_abView->showPersonal( true ); } void AddressbookWindow::listIsEmpty( bool empty ) { if ( !empty ) { deleteButton->setEnabled( TRUE ); } } void AddressbookWindow::reload() { syncing = FALSE; m_abView->clear(); m_abView->reload(); } void AddressbookWindow::flush() { syncing = TRUE; m_abView->save(); } void AddressbookWindow::closeEvent( QCloseEvent *e ) { if(active_view == AbView::CardView){ slotViewSwitched( AbView::TableView ); e->ignore(); return; } if(syncing) { /* shouldn't we save, I hear you say? well its already been set so that an edit can not occur during a sync, and we flushed at the start of the sync, so there is no need to save Saving however itself would cause problems. */ e->accept(); return; } //################## shouldn't always save // True, but the database handles this automatically ! (se) if ( save() ) e->accept(); else e->ignore(); } /* Returns TRUE if it is OK to exit */ bool AddressbookWindow::save() { if ( !m_abView->save() ) { if ( QMessageBox::critical( 0, tr( "Out of space" ), tr("Unable to save information.\n" "Free up some space\n" "and try again.\n" "\nQuit anyway?"), QMessageBox::Yes|QMessageBox::Escape, QMessageBox::No|QMessageBox::Default ) != QMessageBox::No ) return TRUE; else return FALSE; } return TRUE; } #ifdef __DEBUG_RELEASE void AddressbookWindow::slotSave() { save(); } #endif void AddressbookWindow::slotNotFound() { qWarning("Got notfound signal!"); QMessageBox::information( this, tr( "Not Found" ), "<qt>" + tr( "Unable to find a contact for this search pattern!" ) + "</qt>" ); } void AddressbookWindow::slotWrapAround() { qWarning("Got wrap signal!"); // if ( doNotifyWrapAround ) // QMessageBox::information( this, tr( "End of list" ), // tr( "End of list. Wrap around now...!" ) + "\n" ); } void AddressbookWindow::slotSetCategory( int c ) { qWarning( "void AddressbookWindow::slotSetCategory( %d ) from %d", c, catMenu->count() ); QString cat, book; AbView::Views view = AbView::TableView; if ( c <= 0 ) return; // Switch view if ( c < 3 ) for ( unsigned int i = 1; i < 3; i++ ){ if ( catMenu ) catMenu->setItemChecked( i, c == (int)i ); } else // Checkmark Category Menu Item Selected for ( unsigned int i = 3; i < catMenu->count(); i++ ) catMenu->setItemChecked( i, c == (int)i ); // Now switch to the selected category for ( unsigned int i = 1; i < catMenu->count(); i++ ) { if (catMenu->isItemChecked( i )) { if ( i == 1 ){ // default List view book = QString::null; view = AbView::TableView; }else if ( i == 2 ){ book = tr( "Cards" ); view = AbView::CardView; // }else if ( i == 3 ){ // book = tr( "Personal" ); // view = AbView:: PersonalView; }else if ( i == 3 ){ // default All Categories cat = QString::null; }else if ( i == (unsigned int)catMenu->count() - 1 ){ // last menu option (seperator is counted, too) will be Unfiled cat = "Unfiled"; qWarning ("Unfiled selected!"); }else{ cat = m_abView->categories()[i - 4]; } } } // Switch to the selected View slotViewSwitched( view ); // Tell the view about the selected category m_abView -> setShowByCategory( cat ); if ( book.isEmpty() ) book = "List"; if ( cat.isEmpty() ) cat = "All"; setCaption( tr( "Contacts" ) + " - " + book + " - " + tr( cat ) ); } void AddressbookWindow::slotViewSwitched( int view ) { qWarning( "void AddressbookWindow::slotViewSwitched( %d )", view ); int menu = 0; // Switch to selected view switch ( view ){ case AbView::TableView: menu = 1; m_tableViewButton->setOn(true); m_cardViewButton->setOn(false); break; case AbView::CardView: menu = 2; m_tableViewButton->setOn(false); m_cardViewButton->setOn(true); break; } for ( unsigned int i = 1; i < 3; i++ ){ if ( catMenu ) catMenu->setItemChecked( i, menu == (int)i ); } // Tell the view about the selected view m_abView -> setShowToView ( (AbView::Views) view ); active_view = view; } void AddressbookWindow::slotListView() { slotViewSwitched( AbView::TableView ); } void AddressbookWindow::slotCardView() { slotViewSwitched( AbView::CardView ); } void AddressbookWindow::slotSetLetter( char c ) { m_abView->setShowByLetter( c, m_config.letterPickerSearch() ); } void AddressbookWindow::populateCategories() { catMenu->clear(); int id, rememberId; id = 1; rememberId = 0; catMenu->insertItem( Resource::loadPixmap( "addressbook/listview" ), tr( "List" ), id++ ); catMenu->insertItem( Resource::loadPixmap( "addressbook/cardview" ), tr( "Cards" ), id++ ); // catMenu->insertItem( tr( "Personal" ), id++ ); catMenu->insertSeparator(); catMenu->insertItem( tr( "All" ), id++ ); QStringList categories = m_abView->categories(); categories.append( tr( "Unfiled" ) ); for ( QStringList::Iterator it = categories.begin(); it != categories.end(); ++it ) { catMenu->insertItem( *it, id ); if ( *it == m_abView -> showCategory() ) rememberId = id; ++id; } if ( m_abView -> showCategory().isEmpty() ) { slotSetCategory( 3 ); } else { slotSetCategory( rememberId ); } } diff --git a/core/pim/datebook/datebook.cpp b/core/pim/datebook/datebook.cpp index 07d7164..a040d7c 100644 --- a/core/pim/datebook/datebook.cpp +++ b/core/pim/datebook/datebook.cpp @@ -1,1099 +1,1099 @@ /********************************************************************** ** 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. ** ** $Id$ ** **********************************************************************/ #define QTOPIA_INTERNAL_FD #include "datebook.h" #include "datebookday.h" #include "datebooksettings.h" #include "datebookweek.h" #include "datebookweeklst.h" #include "dateentryimpl.h" #include <qpe/datebookmonth.h> #include <qpe/qpeapplication.h> #include <qpe/config.h> #include <qpe/qpedebug.h> #include <qpe/event.h> #include <qpe/finddialog.h> #include <qpe/ir.h> -#include <qpe/qpemenubar.h> +#include <qmenubar.h> #include <qpe/qpemessagebox.h> #include <qpe/resource.h> #include <qpe/sound.h> #include <qpe/timestring.h> #include <qpe/qpetoolbar.h> #include <qpe/tzselect.h> #include <qpe/xmlreader.h> #include <qaction.h> #include <qcopchannel_qws.h> #include <qdatetime.h> #include <qdialog.h> #include <qfile.h> #include <qlabel.h> #include <qlayout.h> #include <qmessagebox.h> #include <qpopupmenu.h> #include <qpushbutton.h> #include <qregexp.h> #include <qtextcodec.h> #include <qtextstream.h> #include <qtimer.h> #include <qtl.h> #include <qwidgetstack.h> #include <qwindowsystem_qws.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> DateBook::DateBook( QWidget *parent, const char *, WFlags f ) : QMainWindow( parent, "datebook", f ), aPreset( FALSE ), presetTime( -1 ), startTime( 8 ), // an acceptable default rowStyle( 0 ), bJumpToCurTime(FALSE), syncing(FALSE), inSearch(FALSE), alarmCounter(0) { bool needEvilHack= false; // if we need an Evil Hack QTime t; t.start(); db = new DateBookDBHack; qDebug("loading db t=%d", t.elapsed() ); loadSettings(); setCaption( tr("Calendar") ); setIcon( Resource::loadPixmap( "datebook_icon" ) ); setToolBarsMovable( FALSE ); views = new QWidgetStack( this ); setCentralWidget( views ); dayView = 0; weekView = 0; weekLstView = 0; monthView = 0; // QPEToolBar *bar = new QPEToolBar( this ); // bar->setHorizontalStretchable( TRUE ); -// QPEMenuBar *mb = new QPEMenuBar( bar ); +// QMenuBar *mb = new QMenuBar( bar ); // mb->setMargin( 0 ); // QPopupMenu *view = new QPopupMenu( this ); // mb->insertItem( tr( "View" ), view ); QPEToolBar *sub_bar = new QPEToolBar(this); sub_bar->setHorizontalStretchable(TRUE); QActionGroup *g = new QActionGroup( this ); g->setExclusive( TRUE ); QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( fileNew() ) ); a->addTo( sub_bar ); sub_bar->addSeparator(); a = new QAction( tr( "Today" ), Resource::loadPixmap( "datebook/to_day" ), QString::null, 0, g, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( slotToday() ) ); a->addTo( sub_bar ); // a->addTo( view ); sub_bar->addSeparator(); a = new QAction( tr( "Day" ), Resource::loadPixmap( "day" ), QString::null, 0, g, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( viewDay() ) ); a->addTo( sub_bar ); // a->addTo( view ); a->setToggleAction( TRUE ); a->setOn( TRUE ); dayAction = a; a = new QAction( tr( "Week" ), Resource::loadPixmap( "week" ), QString::null, 0, g, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( viewWeek() ) ); a->addTo( sub_bar ); // a->addTo( view ); a->setToggleAction( TRUE ); weekAction = a; a = new QAction( tr( "WeekLst" ), Resource::loadPixmap( "datebook/weeklst" ), QString::null, 0, g, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( viewWeekLst() ) ); a->addTo( sub_bar ); // a->addTo( view ); a->setToggleAction( TRUE ); weekLstAction = a; a = new QAction( tr( "Month" ), Resource::loadPixmap( "month" ), QString::null, 0, g, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( viewMonth() ) ); a->addTo( sub_bar ); // a->addTo( view ); a->setToggleAction( TRUE ); monthAction = a; sub_bar->addSeparator(); a = new QAction( tr( "Find" ), Resource::loadPixmap( "mag" ), QString::null, 0, this, 0 ); connect( a, SIGNAL(activated()), this, SLOT(slotFind()) ); a->addTo( sub_bar ); a = new QAction( tr( "Edit..." ), Resource::loadPixmap("SettingsIcon"), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( slotSettings() ) ); a->addTo( sub_bar ); if(defaultView==DAY) viewDay(); if(defaultView==WEEK) needEvilHack=true; // viewWeek(); if(defaultView==WEEKLST) viewWeekLst(); if(defaultView==MONTH) viewMonth(); connect( qApp, SIGNAL(clockChanged(bool)), this, SLOT(changeClock(bool)) ); connect( qApp, SIGNAL(weekChanged(bool)), this, SLOT(changeWeek(bool)) ); #if defined(Q_WS_QWS) && !defined(QT_NO_COP) connect( qApp, SIGNAL(appMessage(const QCString&, const QByteArray&)), this, SLOT(appMessage(const QCString&, const QByteArray&)) ); #endif // listen on QPE/System #if defined(Q_WS_QWS) #if !defined(QT_NO_COP) QCopChannel *channel = new QCopChannel( "QPE/System", this ); connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), this, SLOT(receive(const QCString&, const QByteArray&)) ); channel = new QCopChannel( "QPE/Datebook", this ); connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), this, SLOT(receive(const QCString&, const QByteArray&)) ); qDebug("olle\n"); #endif #endif qDebug("done t=%d", t.elapsed() ); connect( qApp, SIGNAL( flush() ), this, SLOT( flush() ) ); connect( qApp, SIGNAL( reload()), this, SLOT( reload() ) ); /* * Here is a problem description: * When Weekview is the default view * a DateBookWeekView get's created * redraw() get's called. So what? * Remember that we're still in the c'tor * and no final layout has happened? Ok * now all Events get arranged. Their x * position get's determined by a QHeader * position. But the QHeader isn't layouted or * at the right position. redraw() is a slot * so we'll call it then via a singleShot * from view() */ if( needEvilHack ){ QTimer::singleShot( 500, this, SLOT(viewWeek()) ); } } void DateBook::receive( const QCString &msg, const QByteArray &data ) { QDataStream stream( data, IO_ReadOnly ); if ( msg == "timeChange(QString)" ) { // update active view! if ( dayAction->isOn() ) viewDay(); else if ( weekAction->isOn() ) viewWeek(); else if ( monthAction->isOn() ) viewMonth(); } else if (msg == "editEvent(int)") { int uid; stream >> uid; Event e=db->eventByUID(uid); editEvent(e); }else if (msg == "viewDefault(QDate)"){ QDate day; stream >> day; viewDefault(day); } } DateBook::~DateBook() { } void DateBook::slotSettings() { DateBookSettings frmSettings( ampm, this ); frmSettings.setStartTime( startTime ); frmSettings.setAlarmPreset( aPreset, presetTime ); frmSettings.setJumpToCurTime( bJumpToCurTime ); frmSettings.setRowStyle( rowStyle ); frmSettings.comboDefaultView->setCurrentItem(defaultView-1); frmSettings.comboWeekListView->setCurrentItem(weeklistviewconfig); bool found=false; for (int i=0; i<(frmSettings.comboLocation->count()); i++) { if ( frmSettings.comboLocation->text(i) == defaultLocation ) { frmSettings.comboLocation->setCurrentItem(i); found=true; break; } } if(!found) { frmSettings.comboLocation->insertItem(defaultLocation); frmSettings.comboLocation->setCurrentItem(frmSettings.comboLocation->count()-1); } frmSettings.comboCategory->setCategories(defaultCategories,"Calendar", tr("Calendar")); #if defined (Q_WS_QWS) || defined(_WS_QWS_) frmSettings.showMaximized(); #endif if ( frmSettings.exec() ) { aPreset = frmSettings.alarmPreset(); presetTime = frmSettings.presetTime(); startTime = frmSettings.startTime(); bJumpToCurTime = frmSettings.jumpToCurTime(); rowStyle = frmSettings.rowStyle(); defaultView=frmSettings.comboDefaultView->currentItem()+1; weeklistviewconfig=frmSettings.comboWeekListView->currentItem(); defaultLocation=frmSettings.comboLocation->currentText(); defaultCategories=frmSettings.comboCategory->currentCategories(); if ( dayView ) { dayView->setStartViewTime( startTime ); dayView->setJumpToCurTime( bJumpToCurTime ); dayView->setRowStyle( rowStyle ); } if ( weekView ) { weekView->setStartViewTime( startTime ); } saveSettings(); // make the change obvious if ( views->visibleWidget() ) { if ( views->visibleWidget() == dayView ) dayView->redraw(); else if ( views->visibleWidget() == weekView ) weekView->redraw(); else if ( views->visibleWidget() == weekLstView ) weekLstView->redraw(); } } } void DateBook::fileNew() { slotNewEventFromKey(""); } QString DateBook::checkEvent(const Event &e) { /* check if overlaps with itself */ bool checkFailed = FALSE; /* check the next 12 repeats. should catch most problems */ QDate current_date = e.start().date(); Event previous = e; for(int i = 0; i < 12; i++) { QDateTime next; if (!nextOccurance(previous, current_date.addDays(1), next)) { break; // no more repeats } if(next < previous.end()) { checkFailed = TRUE; break; } current_date = next.date(); } if(checkFailed) return tr("Event duration is potentially longer\n" "than interval between repeats."); return QString::null; } QDate DateBook::currentDate() { QDate d = QDate::currentDate(); if ( dayView && views->visibleWidget() == dayView ) { d = dayView->date(); } else if ( weekView && views->visibleWidget() == weekView ) { d = weekView->date(); } else if ( weekLstView && views->visibleWidget() == weekLstView ) { d = weekLstView->date(); } else if ( monthView && views->visibleWidget() == monthView ) { d = monthView->selectedDate(); } return d; } void DateBook::view(int v, const QDate &d) { if (v==DAY) { initDay(); dayAction->setOn( TRUE ); dayView->setDate( d ); views->raiseWidget( dayView ); dayView->redraw(); } else if (v==WEEK) { initWeek(); weekAction->setOn( TRUE ); weekView->setDate( d ); views->raiseWidget( weekView ); weekView->redraw(); } else if (v==WEEKLST) { initWeekLst(); weekLstAction->setOn( TRUE ); weekLstView->setDate(d); views->raiseWidget( weekLstView ); weekLstView->redraw(); } else if (v==MONTH) { initMonth(); monthAction->setOn( TRUE ); monthView->setDate( d.year(), d.month(), d.day() ); views->raiseWidget( monthView ); monthView->redraw(); } } void DateBook::viewDefault(const QDate &d) { view(defaultView,d); } void DateBook::viewDay() { view(DAY,currentDate()); } void DateBook::viewWeek() { view(WEEK,currentDate()); } void DateBook::viewWeekLst() { view(WEEKLST,currentDate()); } void DateBook::viewMonth() { view(MONTH,currentDate()); } void DateBook::insertEvent( const Event &e ) { Event dupEvent=e; if(!dupEvent.isValidUid() ) // tkcRom seems to be different dupEvent.assignUid(); dupEvent.setLocation(defaultLocation); dupEvent.setCategories(defaultCategories); db->addEvent(dupEvent); emit newEvent(); } void DateBook::duplicateEvent( const Event &e ) { qWarning("Hmmm..."); // Alot of code duplication, as this is almost like editEvent(); if (syncing) { QMessageBox::warning( this, tr("Calendar"), tr( "Can not edit data, currently syncing") ); return; } Event dupevent(e); // Make a duplicate. // workaround added for text input. QDialog editDlg( this, 0, TRUE ); DateEntry *entry; editDlg.setCaption( tr("Duplicate Event") ); QVBoxLayout *vb = new QVBoxLayout( &editDlg ); QScrollView *sv = new QScrollView( &editDlg, "scrollview" ); sv->setResizePolicy( QScrollView::AutoOneFit ); // KLUDGE!!! sv->setHScrollBarMode( QScrollView::AlwaysOff ); vb->addWidget( sv ); entry = new DateEntry( onMonday, dupevent, ampm, &editDlg, "editor" ); entry->timezone->setEnabled( FALSE ); sv->addChild( entry ); #if defined(Q_WS_QWS) || defined(_WS_QWS_) editDlg.showMaximized(); #endif while (editDlg.exec() ) { Event newEv = entry->event(); QString error = checkEvent(newEv); if (!error.isNull()) { if (QMessageBox::warning(this, tr("error box"), error, tr("Fix it"), tr("Continue"), 0, 0, 1) == 0) continue; } /* * The problem: * DateBookDB does remove repeating events not by uid but by the time * the recurrence was created * so we need to update that time as well */ Event::RepeatPattern rp = newEv.repeatPattern(); rp.createTime = ::time( NULL ); newEv.setRepeat( TRUE, rp ); // has repeat and repeatPattern... if( newEv.uid() == e.uid() || !newEv.isValidUid() ) newEv.assignUid(); db->addEvent(newEv); emit newEvent(); break; } } void DateBook::editEvent( const Event &e ) { if (syncing) { QMessageBox::warning( this, tr("Calendar"), tr( "Can not edit data, currently syncing") ); return; } // workaround added for text input. QDialog editDlg( this, 0, TRUE ); DateEntry *entry; editDlg.setCaption( tr("Edit Event") ); QVBoxLayout *vb = new QVBoxLayout( &editDlg ); QScrollView *sv = new QScrollView( &editDlg, "scrollview" ); sv->setResizePolicy( QScrollView::AutoOneFit ); // KLUDGE!!! sv->setHScrollBarMode( QScrollView::AlwaysOff ); vb->addWidget( sv ); entry = new DateEntry( onMonday, e, ampm, &editDlg, "editor" ); entry->timezone->setEnabled( FALSE ); sv->addChild( entry ); #if defined(Q_WS_QWS) || defined(_WS_QWS_) editDlg.showMaximized(); #endif while (editDlg.exec() ) { Event newEv = entry->event(); if(newEv.description().isEmpty() && newEv.notes().isEmpty() ) break; newEv.setUid(e.uid()); // FIXME: Hack not to clear uid QString error = checkEvent(newEv); if (!error.isNull()) { if (QMessageBox::warning(this, tr("error box"), error, tr("Fix it"), tr("Continue"), 0, 0, 1) == 0) continue; } db->editEvent(e, newEv); emit newEvent(); break; } } void DateBook::removeEvent( const Event &e ) { if (syncing) { QMessageBox::warning( this, tr("Calendar"), tr( "Can not edit data, currently syncing") ); return; } QString strName = e.description(); if ( !QPEMessageBox::confirmDelete( this, tr( "Calendar" ),strName ) ) return; db->removeEvent( e ); if ( views->visibleWidget() == dayView && dayView ) dayView->redraw(); } void DateBook::addEvent( const Event &e ) { QDate d = e.start().date(); initDay(); dayView->setDate( d ); } void DateBook::showDay( int year, int month, int day ) { QDate d(year, month, day); view(DAY,d); } void DateBook::initDay() { if ( !dayView ) { dayView = new DateBookDay( ampm, onMonday, db, views, "day view" ); views->addWidget( dayView, DAY ); dayView->setJumpToCurTime( bJumpToCurTime ); dayView->setStartViewTime( startTime ); dayView->setRowStyle( rowStyle ); connect( this, SIGNAL( newEvent() ), dayView, SLOT( redraw() ) ); connect( dayView, SIGNAL( newEvent() ), this, SLOT( fileNew() ) ); connect( dayView, SIGNAL( removeEvent( const Event & ) ), this, SLOT( removeEvent( const Event & ) ) ); connect( dayView, SIGNAL( editEvent( const Event & ) ), this, SLOT( editEvent( const Event & ) ) ); connect( dayView, SIGNAL( duplicateEvent( const Event & ) ), this, SLOT( duplicateEvent( const Event & ) ) ); connect( dayView, SIGNAL( beamEvent( const Event & ) ), this, SLOT( beamEvent( const Event & ) ) ); connect( dayView, SIGNAL(sigNewEvent(const QString &)), this, SLOT(slotNewEventFromKey(const QString &)) ); } } void DateBook::initWeek() { if ( !weekView ) { weekView = new DateBookWeek( ampm, onMonday, db, views, "week view" ); weekView->setStartViewTime( startTime ); views->addWidget( weekView, WEEK ); connect( weekView, SIGNAL( showDate( int, int, int ) ), this, SLOT( showDay( int, int, int ) ) ); connect( this, SIGNAL( newEvent() ), weekView, SLOT( redraw() ) ); } //But also get it right: the year that we display can be different //from the year of the current date. So, first find the year //number of the current week. int yearNumber, totWeeks; calcWeek( currentDate(), totWeeks, yearNumber, onMonday ); QDate d = QDate( yearNumber, 12, 31 ); calcWeek( d, totWeeks, yearNumber, onMonday ); while ( totWeeks == 1 ) { d = d.addDays( -1 ); calcWeek( d, totWeeks, yearNumber, onMonday ); } } void DateBook::initWeekLst() { if ( !weekLstView ) { weekLstView = new DateBookWeekLst( ampm, onMonday, db, views, "weeklst view" ); views->addWidget( weekLstView, WEEKLST ); //weekLstView->setStartViewTime( startTime ); connect( weekLstView, SIGNAL( showDate( int, int, int ) ), this, SLOT( showDay( int, int, int ) ) ); connect( weekLstView, SIGNAL( addEvent( const QDateTime &, const QDateTime &, const QString & , const QString &) ), this, SLOT( slotNewEntry( const QDateTime &, const QDateTime &, const QString & , const QString &) ) ); connect( this, SIGNAL( newEvent() ), weekLstView, SLOT( redraw() ) ); connect( weekLstView, SIGNAL( editEvent( const Event & ) ), this, SLOT( editEvent( const Event & ) ) ); } } void DateBook::initMonth() { if ( !monthView ) { monthView = new DateBookMonth( views, "month view", FALSE, db ); views->addWidget( monthView, MONTH ); connect( monthView, SIGNAL( dateClicked( int, int, int ) ), this, SLOT( showDay( int, int, int ) ) ); connect( this, SIGNAL( newEvent() ), monthView, SLOT( redraw() ) ); qApp->processEvents(); } } void DateBook::loadSettings() { Config qpeconfig( "qpe" ); qpeconfig.setGroup("Time"); ampm = qpeconfig.readBoolEntry( "AMPM", TRUE ); onMonday = qpeconfig.readBoolEntry( "MONDAY" ); Config config("DateBook"); config.setGroup("Main"); startTime = config.readNumEntry("startviewtime", 8); aPreset = config.readBoolEntry("alarmpreset"); presetTime = config.readNumEntry("presettime"); bJumpToCurTime = config.readBoolEntry("jumptocurtime"); rowStyle = config.readNumEntry("rowstyle"); defaultView = config.readNumEntry("defaultview",DAY); weeklistviewconfig = config.readNumEntry("weeklistviewconfig",NORMAL); defaultLocation=config.readEntry("defaultLocation"); QString tmpString=config.readEntry("defaultCategories"); QStringList tmpStringList=QStringList::split(",",tmpString); defaultCategories.truncate(0); for( QStringList::Iterator i=tmpStringList.begin(); i!=tmpStringList.end(); i++) { defaultCategories.resize(defaultCategories.count()+1); defaultCategories[defaultCategories.count()-1]=(*i).toInt(); } } void DateBook::saveSettings() { Config config( "qpe" ); Config configDB( "DateBook" ); configDB.setGroup( "Main" ); configDB.writeEntry("startviewtime",startTime); configDB.writeEntry("alarmpreset",aPreset); configDB.writeEntry("presettime",presetTime); configDB.writeEntry("jumptocurtime", bJumpToCurTime); configDB.writeEntry("rowstyle", rowStyle); configDB.writeEntry("defaultview",defaultView); configDB.writeEntry("weeklistviewconfig",weeklistviewconfig); configDB.writeEntry("defaultLocation",defaultLocation); QStringList tmpStringList; for( uint i=0; i<defaultCategories.count(); i++) { tmpStringList << QString::number(defaultCategories[i]); } configDB.writeEntry("defaultCategories",tmpStringList.join(",")); } void DateBook::appMessage(const QCString& msg, const QByteArray& data) { bool needShow = FALSE; if ( msg == "alarm(QDateTime,int)" ) { QDataStream ds(data,IO_ReadOnly); QDateTime when; int warn; ds >> when >> warn; // check to make it's okay to continue, // this is the case that the time was set ahead, and // we are forced given a stale alarm... QDateTime current = QDateTime::currentDateTime(); if ( current.time().hour() != when.time().hour() && current.time().minute() != when.time().minute() ) return; QValueList<EffectiveEvent> list = db->getEffectiveEvents(when.addSecs(warn*60)); if ( list.count() > 0 ) { QString msg; bool bSound = FALSE; int stopTimer = 0; bool found = FALSE; for ( QValueList<EffectiveEvent>::ConstIterator it=list.begin(); it!=list.end(); ++it ) { if ( (*it).event().hasAlarm() ) { found = TRUE; msg += "<CENTER><B>" + (*it).description() + "</B>" + "<BR>" + (*it).location() + "<BR>" + TimeString::dateString((*it).event().start(),ampm) + (warn ? tr(" (in " + QString::number(warn) + tr(" minutes)")) : QString("")) + "<BR>" + (*it).notes() + "</CENTER>"; if ( (*it).event().alarmSound() != Event::Silent ) { bSound = TRUE; } } } if ( found ) { if ( bSound ) { Sound::soundAlarm(); alarmCounter = 0; stopTimer = startTimer( 5000 ); } QDialog dlg( this, 0, TRUE ); QVBoxLayout *vb = new QVBoxLayout( &dlg ); QScrollView *view = new QScrollView( &dlg, "scrollView"); view->setResizePolicy( QScrollView::AutoOneFit ); vb->addWidget( view ); QLabel *lblMsg = new QLabel( msg, &dlg ); view->addChild( lblMsg ); QPushButton *cmdOk = new QPushButton( tr("OK"), &dlg ); connect( cmdOk, SIGNAL(clicked()), &dlg, SLOT(accept()) ); vb->addWidget( cmdOk ); #if defined(Q_WS_QWS) || defined(_WS_QWS_) dlg.showMaximized(); #endif needShow = dlg.exec(); if ( bSound ) killTimer( stopTimer ); } } } else if ( msg == "nextView()" ) { needShow = true; if ( !qApp-> activeWindow ( )) { needShow = TRUE; } else { QWidget* cur = views->visibleWidget(); if ( cur ) { if ( cur == dayView ) viewWeek(); else if ( cur == weekView ) viewWeekLst(); else if ( cur == weekLstView ) viewMonth(); else if ( cur == monthView ) viewDay(); needShow = TRUE; } } } else if (msg == "editEvent(int)") { /* simple copy from receive */ QDataStream stream(data,IO_ReadOnly); int uid; stream >> uid; Event e=db->eventByUID(uid); editEvent(e); } else if (msg == "viewDefault(QDate)"){ /* simple copy from receive */ QDataStream stream(data,IO_ReadOnly); QDate day; stream >> day; viewDefault(day); needShow = true; } if ( needShow ) { #if defined(Q_WS_QWS) || defined(_WS_QWS_) // showMaximized(); #else // show(); #endif // raise(); QPEApplication::setKeepRunning(); // setActiveWindow(); } } void DateBook::reload() { db->reload(); if ( dayAction->isOn() ) viewDay(); else if ( weekAction->isOn() ) viewWeek(); else if ( monthAction->isOn() ) viewMonth(); syncing = FALSE; } void DateBook::flush() { syncing = TRUE; db->save(); } void DateBook::timerEvent( QTimerEvent *e ) { if ( alarmCounter < 10 ) { alarmCounter++; Sound::soundAlarm(); } else { killTimer( e->timerId() ); } } void DateBook::changeClock( bool newClock ) { ampm = newClock; // repaint the affected objects... if (dayView) dayView->redraw(); if (weekView) weekView->redraw(); if (weekLstView) weekLstView->redraw(); } void DateBook::changeWeek( bool m ) { /* no need to redraw, each widget catches. Do need to store though for widgets we haven't made yet */ onMonday = m; } void DateBook::slotToday() { // we need to view today using default view view(defaultView,QDate::currentDate()); } void DateBook::closeEvent( QCloseEvent *e ) { if(syncing) { /* no need to save, did that at flush */ e->accept(); return; } // save settings will generate it's own error messages, no // need to do checking ourselves. saveSettings(); if ( db->save() ) { e->accept(); } else { if ( QMessageBox::critical( this, tr( "Out of space" ), tr("Calendar was unable to save\n" "your changes.\n" "Free up some space and try again.\n" "\nQuit anyway?"), QMessageBox::Yes|QMessageBox::Escape, QMessageBox::No|QMessageBox::Default ) != QMessageBox::No ) e->accept(); else e->ignore(); } } // Entering directly from the "keyboard" void DateBook::slotNewEventFromKey( const QString &str ) { if (syncing) { QMessageBox::warning( this, tr("Calendar"), tr( "Can not edit data, currently syncing") ); return; } // We get to here from a key pressed in the Day View // So we can assume some things. We want the string // passed in to be part of the description. QDateTime start, end; if ( views->visibleWidget() == dayView ) { dayView->selectedDates( start, end ); } else if ( views->visibleWidget() == monthView ) { QDate d = monthView->selectedDate(); start = end = d; start.setTime( QTime( 10, 0 ) ); end.setTime( QTime( 12, 0 ) ); } else if ( views->visibleWidget() == weekView ) { QDate d = weekView->date(); start = end = d; start.setTime( QTime( 10, 0 ) ); end.setTime( QTime( 12, 0 ) ); } else if ( views->visibleWidget() == weekLstView ) { QDate d = weekLstView->date(); start = end = d; start.setTime( QTime( 10, 0 ) ); end.setTime( QTime( 12, 0 ) ); } slotNewEntry(start, end, str); } void DateBook::slotNewEntry(const QDateTime &start, const QDateTime &end, const QString &str, const QString &location) { // argh! This really needs to be encapsulated in a class // or function. QDialog newDlg( this, 0, TRUE ); newDlg.setCaption( DateEntryBase::tr("New Event") ); DateEntry *e; QVBoxLayout *vb = new QVBoxLayout( &newDlg ); QScrollView *sv = new QScrollView( &newDlg ); sv->setResizePolicy( QScrollView::AutoOneFit ); sv->setFrameStyle( QFrame::NoFrame ); sv->setHScrollBarMode( QScrollView::AlwaysOff ); vb->addWidget( sv ); Event ev; ev.setDescription( str ); // When the new gui comes in, change this... if(location==0) { if(defaultLocation.isEmpty()) { ev.setLocation(tr("(Unknown)")); } else { ev.setLocation( defaultLocation ); } } else { ev.setLocation(location); } ev.setCategories(defaultCategories); ev.setStart( start ); ev.setEnd( end ); e = new DateEntry( onMonday, ev, ampm, &newDlg ); e->setAlarmEnabled( aPreset, presetTime, Event::Loud ); sv->addChild( e ); #if defined(Q_WS_QWS) || defined(_WS_QWS_) newDlg.showMaximized(); #endif while (newDlg.exec()) { ev = e->event(); ev.assignUid(); QString error = checkEvent( ev ); if ( !error.isNull() ) { if ( QMessageBox::warning( this, tr("Error!"), error, tr("Fix it"), tr("Continue"), 0, 0, 1 ) == 0 ) continue; } db->addEvent( ev ); emit newEvent(); break; } } void DateBook::setDocument( const QString &filename ) { if ( filename.find(".vcs") != int(filename.length()) - 4 ) return; QValueList<Event> tl = Event::readVCalendar( filename ); for( QValueList<Event>::Iterator it = tl.begin(); it != tl.end(); ++it ) { db->addEvent( *it ); } } static const char * beamfile = "/tmp/obex/event.vcs"; void DateBook::beamEvent( const Event &e ) { qDebug("trying to beamn"); unlink( beamfile ); // delete if exists mkdir("/tmp/obex/", 0755); Event::writeVCalendar( beamfile, e ); Ir *ir = new Ir( this ); connect( ir, SIGNAL( done( Ir * ) ), this, SLOT( beamDone( Ir * ) ) ); QString description = e.description(); ir->send( beamfile, description, "text/x-vCalendar" ); } void DateBook::beamDone( Ir *ir ) { delete ir; unlink( beamfile ); } void DateBook::slotFind() { // move it to the day view... viewDay(); FindDialog frmFind( "Calendar", this ); // no tr needed frmFind.setUseDate( true ); frmFind.setDate( currentDate() ); QObject::connect( &frmFind, SIGNAL(signalFindClicked(const QString&, const QDate&, bool, bool, int)), this, SLOT(slotDoFind(const QString&, const QDate&, bool, bool, int)) ); QObject::connect( this, SIGNAL(signalNotFound()), &frmFind, SLOT(slotNotFound()) ); QObject::connect( this, SIGNAL(signalWrapAround()), &frmFind, SLOT(slotWrapAround()) ); frmFind.move(0,0); frmFind.exec(); inSearch = false; } bool catComp( QArray<int> cats, int category ) { bool returnMe; int i, count; count = int(cats.count()); returnMe = false; if ( (category == -1 && count == 0) || category == -2 ) returnMe = true; else { for ( i = 0; i < count; i++ ) { if ( category == cats[i] ) { returnMe = true; break; } } } return returnMe; } void DateBook::slotDoFind( const QString& txt, const QDate &dt, bool caseSensitive, bool /*backwards*/, int category ) { QDateTime dtEnd( QDate(3001, 1, 1), QTime(0, 0, 0) ), next; QRegExp r( txt ); r.setCaseSensitive( caseSensitive ); static Event rev, nonrev; if ( !inSearch ) { rev.setStart( QDateTime(QDate(1960, 1, 1), QTime(0, 0, 0)) ); nonrev.setStart( rev.start() ); inSearch = true; } static QDate searchDate = dt; static bool wrapAround = true; bool candidtate; candidtate = false; QValueList<Event> repeats = db->getRawRepeats(); // find the candidate for the first repeat that matches... QValueListConstIterator<Event> it; QDate start = dt; for ( it = repeats.begin(); it != repeats.end(); ++it ) { if ( catComp( (*it).categories(), category ) ) { while ( nextOccurance( *it, start, next ) ) { if ( next < dtEnd ) { if ( (*it).match( r ) && !(next <= rev.start()) ) { rev = *it; dtEnd = next; rev.setStart( next ); candidtate = true; wrapAround = true; start = dt; break; } else start = next.date().addDays( 1 ); } } } } // now the for first non repeat... QValueList<Event> nonRepeats = db->getNonRepeatingEvents( dt, dtEnd.date() ); qHeapSort( nonRepeats.begin(), nonRepeats.end() ); for ( it = nonRepeats.begin(); it != nonRepeats.end(); ++it ) { if ( catComp( (*it).categories(), category ) ) { if ( (*it).start() < dtEnd ) { if ( (*it).match( r ) && !(*it <= nonrev) ) { nonrev = *it; dtEnd = nonrev.start(); candidtate = true; wrapAround = true; break; } } } } if ( candidtate ) { dayView->setStartViewTime( dtEnd.time().hour() ); dayView->setDate( dtEnd.date().year(), dtEnd.date().month(), dtEnd.date().day() ); } else { if ( wrapAround ) { emit signalWrapAround(); rev.setStart( QDateTime(QDate(1960, 1, 1), QTime(0, 0, 0)) ); nonrev.setStart( rev.start() ); } else emit signalNotFound(); wrapAround = !wrapAround; } } Event DateBookDBHack::eventByUID(int uid) { // FIXME: Dirty Hacks to get hold of the private event lists QDate start; QDate end=start.addDays(-1); QValueList<Event> myEventList=getNonRepeatingEvents(start,end); QValueList<Event> myRepeatEvents=getRawRepeats(); QValueList<Event>::ConstIterator it; for (it = myEventList.begin(); it != myEventList.end(); it++) { if ((*it).uid() == uid) return *it; } for (it = myRepeatEvents.begin(); it != myRepeatEvents.end(); it++) { if ((*it).uid() == uid) return *it; } qDebug("Event not found: uid=%d\n", uid); Event ev; return ev; // return at least } diff --git a/core/pim/datebook2/mainwindow.cpp b/core/pim/datebook2/mainwindow.cpp index 68525b3..7d436ae 100644 --- a/core/pim/datebook2/mainwindow.cpp +++ b/core/pim/datebook2/mainwindow.cpp @@ -1,305 +1,305 @@ #include <qcopchannel_qws.h> #include <qwidgetstack.h> #include <qlabel.h> #include <qaction.h> #include <qpopupmenu.h> #include <qtimer.h> #include <qpe/qpeapplication.h> #include <qpe/ir.h> -#include <qpe/qpemenubar.h> +#include <qmenubar.h> #include <qpe/qpetoolbar.h> #include <qpe/qpemessagebox.h> #include <qpe/resource.h> #include "editor.h" #include "show.h" #include "templatemanager.h" #include "bookmanager.h" #include "mainwindow.h" using namespace Datebook; MainWindow::MainWindow() : OPimMainWindow( "Datebook", 0, 0 ), m_descMan( "Descriptions" ), m_locMan( "Locations" ) { setIcon( Resource::loadPixmap( "datebook_icon" ) ); initUI(); initManagers(); initView(); initConfig(); QTimer::singleShot(0, this, SLOT(populate() ) ); QCopChannel* chan = new QCopChannel( "QPE/System", this ); connect( chan, SIGNAL( received(const QCString&, const QByteArray& ) ), this, SLOT( slotReceive( const QCString&, const QByteArray& ) ) ); chan = new QCopChannel( "QPE/Datebook", this ); connect( chan, SIGNAL( received(const QCString&, const QByteArray& ) ), this, SLOT( slotReceive( const QCString&, const QByteArray& ) ) ); } MainWindow::~MainWindow() { m_tempMan.save(); m_locMan.save(); m_descMan.save(); manager()->save(); delete m_manager; } void MainWindow::doSetDocument( const QString& str ) { } void MainWindow::flush() { manager()->save(); } void MainWindow::reload() { manager()->reload(); } int MainWindow::create() { return 0; } bool MainWindow::remove( int uid ) { manager()->remove( uid ); return true; } void MainWindow::beam( int uid ) { } void MainWindow::show( int uid ) { eventShow()->show( manager()->event( uid ) ); } void MainWindow::add( const OPimRecord& ad) { manager()->add( ad ); } void MainWindow::edit() { edit ( currentView()->currentItem() ); } void MainWindow::edit( int uid ) { } /* * init tool bars layout and so on */ void MainWindow::initUI() { setToolBarsMovable( false ); m_stack = new QWidgetStack( this ); setCentralWidget( m_stack ); m_toolBar = new QPEToolBar( this ); m_toolBar->setHorizontalStretchable( TRUE ); - QPEMenuBar* mb = new QPEMenuBar( m_toolBar ); + QMenuBar* mb = new QMenuBar( m_toolBar ); m_popView = new QPopupMenu( this ); m_popSetting = new QPopupMenu( this ); mb->insertItem( tr("View"), m_popView ); mb->insertItem( tr("Settings" ), m_popSetting ); m_popTemplate = new QPopupMenu( this ); m_popTemplate->setCheckable( TRUE ); connect( m_popTemplate, SIGNAL(activated(int) ), this, SLOT(slotNewFromTemplate(int) ) ); m_popView->insertItem(tr("New from template"), m_popTemplate, -1, 0); QAction* a = new QAction( tr("New Event"), Resource::loadPixmap("new"), QString::null, 0, this, 0 ); a->addTo( m_toolBar ); a->addTo( m_popView ); connect(a, SIGNAL( activated() ), this, SLOT( create() ) ); a = new QAction( tr("Edit Event"), Resource::loadPixmap("edit"), QString::null, 0, this, 0 ); a->addTo( m_popView ); connect(a, SIGNAL( activated() ), this, SLOT( edit() ) ); a = new QAction( tr("Today" ), Resource::loadPixmap( "datebook/to_day"), QString::null, 0, this, 0 ); a->addTo( m_toolBar ); connect(a, SIGNAL( activated() ), this, SLOT( slotGoToNow() ) ); a = new QAction( tr("Find"), Resource::loadPixmap( "mag" ), QString::null, 0, this, 0 ); a->addTo( m_toolBar ); connect(a, SIGNAL( activated() ), this, SLOT( slotFind() ) ); a = new QAction( tr("Configure"), QString::null, 0, 0 ); a->addTo( m_popSetting ); connect(a, SIGNAL( activated() ), this, SLOT( slotConfigure() ) ); a = new QAction( tr("Configure Locations"), QString::null, 0, 0 ); a->addTo( m_popSetting ); connect(a, SIGNAL( activated() ), this, SLOT( slotConfigureLocs() ) ); a = new QAction( tr("Configure Descriptions"), QString::null, 0, 0 ); a->addTo( m_popSetting ); connect(a, SIGNAL( activated() ), this, SLOT(slotConfigureDesc() ) ); a = new QAction( tr("Configure Templates"), QString::null, 0, 0 ); a->addTo( m_popSetting ); connect(a, SIGNAL( activated() ), this, SLOT(slotConfigureTemp() ) ); connect( qApp, SIGNAL(clockChanged(bool) ), this, SLOT(slotClockChanged(bool) ) ); connect( qApp, SIGNAL(weekChanged(bool) ), this, SLOT(slotWeekChanged(bool) ) ); connect( qApp, SIGNAL(appMessage(const QCString&, const QByteArray& ) ), this, SLOT(slotAppMessage( const QCString&, const QByteArray& ) ) ); } void MainWindow::initConfig() { } void MainWindow::initView() { } void MainWindow::initManagers() { m_manager = new BookManager; m_tempMan.load(); m_locMan.load(); m_descMan.load(); setTemplateMenu(); } void MainWindow::raiseCurrentView() { } /* * populate the view */ void MainWindow::populate() { if (!manager()->isLoaded() ) manager()->load(); } void MainWindow::slotGoToNow() { } View* MainWindow::currentView() { } void MainWindow::slotFind() { } void MainWindow::slotConfigure() { } void MainWindow::slotClockChanged( bool ) { } void MainWindow::slotWeekChanged(bool ) { } void MainWindow::slotAppMessage( const QCString&, const QByteArray& ) { } void MainWindow::slotReceive( const QCString&, const QByteArray& ) { } BookManager* MainWindow::manager() { return m_manager; } TemplateManager MainWindow::templateManager() { return m_tempMan; } LocationManager MainWindow::locationManager() { return m_locMan; } DescriptionManager MainWindow::descriptionManager() { return m_descMan; } void MainWindow::setLocationManager( const LocationManager& loc) { m_locMan = loc; } void MainWindow::setDescriptionManager( const DescriptionManager& dsc ) { m_descMan = dsc; } Show* MainWindow::eventShow() { return m_show; } void MainWindow::slotAction( QAction* act ) { } void MainWindow::slotConfigureLocs() { LocationManagerDialog dlg( locationManager() ); dlg.setCaption( tr("Configure Locations") ); dlg.showMaximized(); if (dlg.exec() == QDialog::Accepted ) { setLocationManager( dlg.manager() ); } } void MainWindow::slotConfigureDesc() { DescriptionManagerDialog dlg( descriptionManager() ); dlg.setCaption( tr("Configure Descriptions") ); dlg.showMaximized(); if (dlg.exec() == QDialog::Accepted ) { setDescriptionManager( dlg.manager() ); } } void MainWindow::slotConfigureTemp() { TemplateDialog dlg( templateManager(), editor() ); dlg.setCaption( tr("Configure Templates") ); dlg.showMaximized(); if ( dlg.exec() == QDialog::Accepted ) { m_tempMan = dlg.manager(); setTemplateMenu(); } } void MainWindow::hideShow() { } void MainWindow::viewPopup(int ) { } void MainWindow::viewAdd(const QDate& ) { } void MainWindow::viewAdd( const QDateTime&, const QDateTime& ) { } bool MainWindow::viewAP()const{ } bool MainWindow::viewStartMonday()const { } void MainWindow::setTemplateMenu() { m_popTemplate->clear(); QStringList list = templateManager().names(); for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) { m_popTemplate->insertItem( (*it) ); } } /* * get the name of the item with the id id * then ask for an OEvent from the manager */ void MainWindow::slotNewFromTemplate(int id ) { QString name = m_popTemplate->text( id ); OEvent ev = templateManager().value( name ); if ( editor()->edit( ev ) ) { ev = editor()->event(); ev.setUid( -1 ); manager()->add( ev ); /* * no we'll find out if the current view * should show the new event * and then we will ask it to refresh * FIXME for now we'll call a refresh */ currentView()->reschedule(); raiseCurrentView(); } } Editor* MainWindow::editor() { return m_edit; } diff --git a/core/pim/osearch/mainwindow.cpp b/core/pim/osearch/mainwindow.cpp index f768d81..80738df 100644 --- a/core/pim/osearch/mainwindow.cpp +++ b/core/pim/osearch/mainwindow.cpp @@ -1,277 +1,277 @@ /*************************************************************************** * * * 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. * * * ***************************************************************************/ // (c) 2002 Patrick S. Vogt <tille@handhelds.org> #include <qaction.h> #include <qmessagebox.h> #include <qpopupmenu.h> #include <qtoolbutton.h> #include <qstring.h> #include <qlabel.h> #include <qfile.h> #include <qhbuttongroup.h> #include <qhbox.h> #include <qpushbutton.h> #include <qintdict.h> #include <qlayout.h> #include <qlineedit.h> #include <qsignalmapper.h> #include <qtextbrowser.h> #include <qregexp.h> #include <qwhatsthis.h> -#include <qpe/qpemenubar.h> +#include <qmenubar.h> #include <qpe/qpemessagebox.h> #include <qpe/resource.h> #include <qpe/config.h> #include <qpe/qpetoolbar.h> #include <qpe/qpeapplication.h> #include <qpe/config.h> #include <qpe/global.h> #include <opie/owait.h> #include "olistview.h" #include "olistviewitem.h" #include "resultitem.h" #include "adresssearch.h" #include "todosearch.h" #include "datebooksearch.h" #include "applnksearch.h" #include "doclnksearch.h" #include "mainwindow.h" MainWindow::MainWindow( QWidget *parent, const char *name, WFlags f ) : QMainWindow( parent, name, f ), _currentItem(0) { setCaption( tr("OSearch") ); setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); QFrame *mainFrame = new QFrame( this, "mainFrame" ); mainFrame->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); mainLayout = new QVBoxLayout( mainFrame ); mainLayout->setSpacing( 0 ); mainLayout->setMargin( 0 ); resultsList = new OListView( mainFrame ); resultsList->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); mainLayout->addWidget( resultsList ); detailsFrame = new QFrame( mainFrame, "detailsFrame" ); QVBoxLayout *detailsLayout = new QVBoxLayout( detailsFrame ); richEdit = new QTextView( detailsFrame ); QWhatsThis::add( richEdit, tr("The details of the current result") ); richEdit->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); detailsLayout->addWidget( richEdit ); buttonBox = new QHBox( mainFrame, "Button Box" ); _buttonCount = 0; mainLayout->addWidget( detailsFrame ); mainLayout->addWidget( buttonBox ); detailsFrame->hide(); buttonBox->hide(); searches.append( new AppLnkSearch( resultsList, tr("Applications") ) ); searches.append( new DocLnkSearch( resultsList, tr("Documents") ) ); searches.append( new TodoSearch( resultsList, tr("Todo List") ) ); searches.append( new DatebookSearch( resultsList, tr("Calendar") ) ); searches.append( new AdressSearch( resultsList, tr("Contacts") ) ); setCentralWidget( mainFrame ); popupTimer = new QTimer(); searchTimer = new QTimer(); connect(popupTimer, SIGNAL(timeout()), SLOT(showPopup())); connect(searchTimer, SIGNAL(timeout()), SLOT(searchStringChanged())); connect(resultsList, SIGNAL(pressed(QListViewItem*)), SLOT(setCurrent(QListViewItem*))); connect(resultsList, SIGNAL(clicked(QListViewItem*)), SLOT(stopTimer(QListViewItem*))); signalMapper = new QSignalMapper( this ); connect(signalMapper, SIGNAL(mapped(int)), SLOT( slotAction(int) ) ); makeMenu(); Config cfg( "osearch", Config::User ); cfg.setGroup( "search_settings" ); actionCaseSensitiv->setOn( cfg.readBoolEntry( "caseSensitiv", false ) ); actionWildcards->setOn( cfg.readBoolEntry( "wildcards", false ) ); // actionWholeWordsOnly->setOn( cfg.readBoolEntry( "whole_words_only", false ) ); } void MainWindow::makeMenu() { QPEToolBar *toolBar = new QPEToolBar( this ); QPEToolBar *searchBar = new QPEToolBar(this); - QPEMenuBar *menuBar = new QPEMenuBar( toolBar ); + QMenuBar *menuBar = new QMenuBar( toolBar ); QPopupMenu *searchMenu = new QPopupMenu( menuBar ); // QPopupMenu *viewMenu = new QPopupMenu( menuBar ); QPopupMenu *cfgMenu = new QPopupMenu( menuBar ); QPopupMenu *searchOptions = new QPopupMenu( cfgMenu ); setToolBarsMovable( false ); toolBar->setHorizontalStretchable( true ); menuBar->insertItem( tr( "Search" ), searchMenu ); menuBar->insertItem( tr( "Settings" ), cfgMenu ); //SETTINGS MENU cfgMenu->insertItem( tr( "Search" ), searchOptions ); QPopupMenu *pop; for (SearchGroup *s = searches.first(); s != 0; s = searches.next() ){ pop = s->popupMenu(); if (pop){ cfgMenu->insertItem( s->text(0), pop ); } } //SEARCH SearchAllAction = new QAction( tr("Search all"),QString::null, 0, this, 0 ); SearchAllAction->setIconSet( Resource::loadIconSet( "find" ) ); // QWhatsThis::add( SearchAllAction, tr("Search everything...") ); connect( SearchAllAction, SIGNAL(activated()), this, SLOT(searchAll()) ); SearchAllAction->addTo( searchMenu ); searchMenu->insertItem( tr( "Options" ), searchOptions ); //SEARCH OPTIONS //actionWholeWordsOnly = new QAction( tr("Whole words only"),QString::null, 0, this, 0, true ); //actionWholeWordsOnly->addTo( searchOptions ); actionCaseSensitiv = new QAction( tr("Case sensitiv"),QString::null, 0, this, 0, true ); actionCaseSensitiv->addTo( searchOptions ); actionWildcards = new QAction( tr("Use wildcards"),QString::null, 0, this, 0, true ); actionWildcards->addTo( searchOptions ); //SEARCH BAR addToolBar( searchBar, "Search", QMainWindow::Top, TRUE ); QLineEdit *searchEdit = new QLineEdit( searchBar, "seachEdit" ); QWhatsThis::add( searchEdit, tr("Enter your search terms here") ); searchEdit->setFocus(); searchBar->setHorizontalStretchable( TRUE ); searchBar->setStretchableWidget( searchEdit ); SearchAllAction->addTo( searchBar ); connect( searchEdit, SIGNAL( textChanged( const QString & ) ), this, SLOT( setSearch( const QString & ) ) ); } MainWindow::~MainWindow() { Config cfg( "osearch", Config::User ); cfg.setGroup( "search_settings" ); cfg.writeEntry( "caseSensitiv", actionCaseSensitiv->isOn() ); cfg.writeEntry( "wildcards", actionWildcards->isOn() ); //cfg.writeEntry( "whole_words_only", actionWholeWordsOnly->isOn() ); } void MainWindow::setCurrent(QListViewItem *item) { if (!item) return; _currentItem = (OListViewItem*)item; // _currentItem = dynamic_cast<OListViewItem*>(item); if (_currentItem->rtti() == OListViewItem::Result){ ResultItem *res = (ResultItem*)item; // ResultItem *res = dynamic_cast<ResultItem*>(item); richEdit->setText( res->toRichText() ); QIntDict<QString> acts = res->actions(); QButton *button; for (uint i = 0; i < acts.count(); i++){ button = buttonMap[i]; if (!button) { qWarning(" no button for %s", (*acts[i]).latin1() ); button = new QPushButton( buttonBox ); buttonMap.insert( i, button ); signalMapper->setMapping(button, i ); connect(button, SIGNAL(clicked() ), signalMapper, SLOT(map() ) ); } button->setText( *acts[i] ); button->show(); } for (uint i = acts.count(); i < _buttonCount; i++){ button = buttonMap[i]; if (button) button->hide(); } _buttonCount = acts.count(); detailsFrame->show(); buttonBox->show(); }else { detailsFrame->hide(); buttonBox->hide(); } popupTimer->start( 300, true ); } void MainWindow::stopTimer(QListViewItem*) { popupTimer->stop(); } void MainWindow::showPopup() { popupTimer->stop(); if (!_currentItem) return; QPopupMenu *pop = _currentItem->popupMenu(); if (pop) pop->popup( QCursor::pos() ); } void MainWindow::setSearch( const QString &key ) { searchTimer->stop(); _searchString = key; searchTimer->start( 300 ); } void MainWindow::searchStringChanged() { #ifdef NEW_OWAIT OWait("setting search string"); #endif searchTimer->stop(); QString ss = _searchString; //ss = Global::stringQuote( _searchString ); // if (actionWholeWordsOnly->isOn()) // ss = "\\s"+_searchString+"\\s"; // qDebug(" set searchString >%s<",ss.latin1()); QRegExp re( ss ); re.setCaseSensitive( actionCaseSensitiv->isOn() ); re.setWildcard( actionWildcards->isOn() ); for (SearchGroup *s = searches.first(); s != 0; s = searches.next() ) s->setSearch( re ); } void MainWindow::searchAll() { #ifdef NEW_OWAIT OWait("searching..."); #endif for (SearchGroup *s = searches.first(); s != 0; s = searches.next() ){ s->doSearch(); //resultsList->repaint(); } } void MainWindow::slotAction( int act ) { if ( _currentItem && _currentItem->rtti() == OListViewItem::Result){ ResultItem *res = (ResultItem*)_currentItem; // ResultItem *res = dynamic_cast<ResultItem*>(item); res->action(act); } } void MainWindow::optionChanged(int ) { searchStringChanged(); } diff --git a/noncore/applets/brightnessapplet/.cvsignore b/noncore/applets/brightnessapplet/.cvsignore new file mode 100644 index 0000000..51d12e8 --- a/dev/null +++ b/noncore/applets/brightnessapplet/.cvsignore @@ -0,0 +1,4 @@ +Makefile* +advancedconfigbase.cpp +advancedconfigbase.h +moc_* diff --git a/noncore/apps/checkbook/mainwindow.cpp b/noncore/apps/checkbook/mainwindow.cpp index bf00102..25f9910 100644 --- a/noncore/apps/checkbook/mainwindow.cpp +++ b/noncore/apps/checkbook/mainwindow.cpp @@ -1,365 +1,365 @@ /* This file is part of the OPIE Project =. .=l. Copyright (c) 2002 Dan Williams <drw@handhelds.org> .>+-= _;:, .> :=|. This file is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This file is distributed in the hope that + . -:. = it will be useful, but WITHOUT ANY WARRANTY; : .. .:, . . . without even the implied warranty of =_ + =;=|` MERCHANTABILITY or FITNESS FOR A _.=:. : :=>`: PARTICULAR PURPOSE. See the GNU General ..}^=.= = ; Public License for more details. ++= -. .` .: : = ...= . :.=- You should have received a copy of the GNU -. .:....=;==+<; General Public License along with this file; -_. . . )=. = see the file COPYING. If not, write to the -- :-=` Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "mainwindow.h" #include "cbinfo.h" #include "configuration.h" #include "password.h" #include "checkbook.h" #include "listedit.h" #include <qpe/config.h> #include <qpe/global.h> #include <qpe/qpeapplication.h> #include <qpe/qpemenubar.h> #include <qpe/qpemessagebox.h> #include <qpe/qpetoolbar.h> #include <qpe/resource.h> #include <qaction.h> #include <qcheckbox.h> #include <qdir.h> #include <qlineedit.h> #include <qwhatsthis.h> MainWindow::MainWindow( QWidget* parent, const char* name, WFlags fl ) : QMainWindow( parent, name, fl || WStyle_ContextHelp ) { setCaption( tr( "Checkbook" ) ); cbDir = Global::applicationFileName( "checkbook", "" ); lockIcon = Resource::loadPixmap( "locked" ); // Load configuration options Config config( "checkbook" ); _cfg.readConfig( config ); // Build menu and tool bars setToolBarsMovable( FALSE ); QPEToolBar *bar = new QPEToolBar( this ); bar->setHorizontalStretchable( TRUE ); - QPEMenuBar *mb = new QPEMenuBar( bar ); + QMenuBar *mb = new QMenuBar( bar ); mb->setMargin( 0 ); QPopupMenu *popup = new QPopupMenu( this ); bar = new QPEToolBar( this ); QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 ); a->setWhatsThis( tr( "Click here to create a new checkbook.\n\nYou also can select New from the Checkbook menu." ) ); connect( a, SIGNAL( activated() ), this, SLOT( slotNew() ) ); a->addTo( popup ); a->addTo( bar ); actionOpen = new QAction( tr( "Edit" ), Resource::loadPixmap( "edit" ), QString::null, 0, this, 0 ); actionOpen->setWhatsThis( tr( "Select a checkbook and then click here to edit it.\n\nYou also can select Edit from the Checkbook menu, or click and hold on a checkbook name." ) ); connect( actionOpen, SIGNAL( activated() ), this, SLOT( slotEdit() ) ); actionOpen->addTo( popup ); actionOpen->addTo( bar ); actionDelete = new QAction( tr( "Delete" ), Resource::loadPixmap( "trash" ), QString::null, 0, this, 0 ); actionDelete->setWhatsThis( tr( "Select a checkbook and then click here delete it.\n\nYou also can select Delete from the Checkbook menu." ) ); connect( actionDelete, SIGNAL( activated() ), this, SLOT( slotDelete() ) ); actionDelete->addTo( popup ); actionDelete->addTo( bar ); popup->insertSeparator(); a = new QAction( tr( "Configure" ), Resource::loadPixmap( "SettingsIcon" ), QString::null, 0, this, 0 ); a->setWhatsThis( tr( "Click here to configure this app." ) ); connect( a, SIGNAL( activated() ), this, SLOT( slotConfigure() ) ); a->addTo( popup ); a->addTo( bar ); mb->insertItem( tr( "Checkbook" ), popup ); // Load Checkbook selection list checkbooks = new CBInfoList(); QDir checkdir( cbDir ); if (checkdir.exists() == true) { QStringList cblist = checkdir.entryList( "*.qcb", QDir::Files|QDir::Readable|QDir::Writable, QDir::Time ); CBInfo *cb = 0x0; QString filename; for ( QStringList::Iterator it = cblist.begin(); it != cblist.end(); it++ ) { filename = cbDir; filename.append( (*it) ); cb = new CBInfo( (*it).remove( (*it).find('.'), (*it).length() ), filename ); checkbooks->inSort( cb ); } } // Build Checkbook selection list control cbList = 0x0; buildList(); // open last book? if( _cfg.isOpenLastBook() ) { this->show(); this->showMaximized(); QListViewItem *itm=cbList->firstChild(); while( itm ) { if( itm->text(posName)==_cfg.getLastBook() ) { openBook( itm ); break; } itm=itm->nextSibling(); } } } // --- ~MainWindow ------------------------------------------------------------ MainWindow::~MainWindow() { writeConfig(); } // --- buildList -------------------------------------------------------------- void MainWindow::buildList() { if ( cbList ) delete cbList; cbList = new QListView( this ); QWhatsThis::add( cbList, tr( "This is a listing of all checkbooks currently available." ) ); if ( _cfg.getShowLocks() ) { cbList->addColumn( Resource::loadIconSet( "locked" ), "", 24 ); posName = 1; } else { posName = 0; } cbList->addColumn( tr( "Checkbook Name" ) ); if ( _cfg.getShowBalances() ) { int colnum = cbList->addColumn( tr( "Balance" ) ); cbList->setColumnAlignment( colnum, Qt::AlignRight ); } cbList->setAllColumnsShowFocus( TRUE ); cbList->setSorting( posName ); QPEApplication::setStylusOperation( cbList->viewport(), QPEApplication::RightOnHold ); connect( cbList, SIGNAL( rightButtonPressed( QListViewItem *, const QPoint &, int ) ), this, SLOT( slotEdit() ) ); setCentralWidget( cbList ); for ( CBInfo *cb = checkbooks->first(); cb; cb = checkbooks->next() ) { addCheckbook( cb ); } } void MainWindow::addCheckbook( CBInfo *cb ) { QListViewItem *lvi = new QListViewItem( cbList ); if ( _cfg.getShowLocks() && !cb->password().isNull() ) { lvi->setPixmap( 0, lockIcon ); } lvi->setText( posName, cb->name() ); if ( _cfg.getShowBalances() ) { QString balance; balance.sprintf( "%s%.2f", _cfg.getCurrencySymbol().latin1(), cb->balance() ); lvi->setText( posName + 1, balance ); } } void MainWindow::buildFilename( const QString &name ) { tempFilename = cbDir; tempFilename.append( name ); tempFilename.append( ".qcb" ); } void MainWindow::slotNew() { CBInfo *cb = new CBInfo(); Checkbook *currcb = new Checkbook( this, cb, &_cfg ); currcb->showMaximized(); if ( currcb->exec() == QDialog::Accepted ) { // Save new checkbook buildFilename( cb->name() ); _cfg.setLastBook( cb->name() ); cb->setFilename( tempFilename ); cb->write(); // Add to listbox checkbooks->inSort( cb ); addCheckbook( cb ); } delete currcb; } // --- slotEdit --------------------------------------------------------------- void MainWindow::slotEdit() { // get name and open it QListViewItem *curritem = cbList->currentItem(); if ( !curritem ) return; openBook( curritem ); } // --- openBook --------------------------------------------------------------- void MainWindow::openBook(QListViewItem *curritem) { // find book in List QString currname=curritem->text(posName); CBInfo *cb = checkbooks->first(); while ( cb ) { if ( cb->name() == currname ) break; cb = checkbooks->next(); } if ( !cb ) return; // buildFilename( currname ); float currbalance = cb->balance(); bool currlock = !cb->password().isNull(); if ( currlock ) { Password *pw = new Password( this, tr( "Enter password" ), tr( "Please enter your password:" ) ); if ( pw->exec() != QDialog::Accepted || pw->password != cb->password() ) { delete pw; return; } delete pw; } _cfg.setLastBook( currname ); Checkbook *currcb = new Checkbook( this, cb, &_cfg ); currcb->showMaximized(); if ( currcb->exec() == QDialog::Accepted ) { QString newname = cb->name(); if ( currname != newname ) { // Update name if changed if( curritem ) { curritem->setText( posName, newname ); cbList->sort(); } _cfg.setLastBook( newname ); // Remove old file QFile f( tempFilename ); if ( f.exists() ) f.remove(); // Get new filename buildFilename( newname ); cb->setFilename( tempFilename ); } cb->write(); // Update lock if changed if ( _cfg.getShowLocks() && !cb->password().isNull() != currlock ) { if ( !cb->password().isNull() ) curritem->setPixmap( 0, lockIcon ); else curritem->setPixmap( 0, nullIcon ); } // Update balance if changed if ( _cfg.getShowBalances() && cb->balance() != currbalance ) { QString tempstr; tempstr.sprintf( "%s%.2f", _cfg.getCurrencySymbol().latin1(), cb->balance() ); curritem->setText( posName + 1, tempstr ); } // write config, if needed if( _cfg.isDirty() ) { Config config("checkbook"); _cfg.writeConfig( config ); } } delete currcb; } // --- slotDelete ------------------------------------------------------------- void MainWindow::slotDelete() { QString currname = cbList->currentItem()->text( posName ); if ( QPEMessageBox::confirmDelete ( this, tr( "Delete checkbook" ), currname ) ) { buildFilename( currname ); QFile f( tempFilename ); if ( f.exists() ) { f.remove(); } delete cbList->currentItem(); } } // --- slotConfigure ---------------------------------------------------------- void MainWindow::slotConfigure() { Configuration *cfgdlg = new Configuration( this, _cfg ); cfgdlg->showMaximized(); if ( cfgdlg->exec() == QDialog::Accepted ) { // read data from config dialog & save it cfgdlg->saveConfig( _cfg ); writeConfig(); buildList(); } delete cfgdlg; } // --- writeConfig -------------------------------------------------------------- void MainWindow::writeConfig() { Config config("checkbook"); _cfg.writeConfig( config ); } diff --git a/noncore/apps/confedit/mainwindow.cpp b/noncore/apps/confedit/mainwindow.cpp index 58538af..4fe45ba 100644 --- a/noncore/apps/confedit/mainwindow.cpp +++ b/noncore/apps/confedit/mainwindow.cpp @@ -1,204 +1,198 @@ /*************************************************************************** * * * 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. * * * ***************************************************************************/ // (c) 2002 Patrick S. Vogt <tille@handhelds.org> #include "mainwindow.h" -#include <opie2/omenubar.h> -#include <opie2/omessagebox.h> -#include <opie2/oresource.h> -#include <opie2/oconfig.h> -#include <opie2/otoolbar.h> -#include <opie2/oapplication.h> #include <qaction.h> #include <qmessagebox.h> #include <qpopupmenu.h> #include <qtoolbutton.h> #include <qstring.h> #include <qlabel.h> #include <qfile.h> #include <qpushbutton.h> #include <qlayout.h> #include <qlineedit.h> #include <qcursor.h> #include "listviewconfdir.h" #include "listviewitemconf.h" #include "listviewitemconfigentry.h" MainWindow::MainWindow( QWidget *parent, const char *name, WFlags f ) : QMainWindow( parent, name, f ), _currentItem(0), _fileItem(0) { setCaption( tr("Conf File Editor") ); // setBaseSize( qApp->globalStrut() ); setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding));//, sizePolicy().hasHeightForWidth() ) ); mainLayout = new QVBoxLayout( this ); mainLayout->setSpacing( 0 ); mainLayout->setMargin( 0 ); qDebug("creating settingList"); settingList = new ListViewConfDir( QDir::homeDirPath() + "/Settings", this, "settingslist"); settingList->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding));//, sizePolicy().hasHeightForWidth() ) ); mainLayout->addWidget( settingList, 0); qDebug("creating editor"); editor = new EditWidget(this); editor->setSizePolicy( QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Maximum));//, sizePolicy().hasHeightForWidth() ) ); mainLayout->addWidget( editor, 1 ); editor->layoutType( ListViewItemConf::File ); makeMenu(); connect(settingList, SIGNAL( pressed(QListViewItem*) ), this, SLOT(setCurrent(QListViewItem*))); connect( settingList, SIGNAL( clicked( QListViewItem* ) ), this, SLOT( stopTimer( QListViewItem* ) ) ); connect( editor->LineEditGroup, SIGNAL( textChanged(const QString&) ), SLOT( groupChanged(const QString&) ) ); connect( editor->LineEditKey, SIGNAL( textChanged(const QString&) ), SLOT( keyChanged(const QString&) ) ); connect( editor->LineEditValue, SIGNAL( textChanged(const QString&) ), SLOT( valueChanged(const QString&) ) ); setCurrent(0); editor->layoutType(EditWidget::File); } void MainWindow::makeMenu() { popupTimer = new QTimer(this); popupMenuFile = new QPopupMenu(this); popupMenuEntry = new QPopupMenu(this); popupActionSave = new QAction( tr("Save"),QString::null, 0, this, 0 ); popupActionSave->addTo( popupMenuFile ); // popupActionSave->addTo( popupMenuEntry ); connect( popupActionSave, SIGNAL( activated() ), this , SLOT( saveConfFile() ) ); popupActionRevert = new QAction( tr("Revert"),QString::null, 0, this, 0 ); popupActionRevert->addTo( popupMenuFile ); popupActionRevert->addTo( popupMenuEntry ); connect( popupActionRevert, SIGNAL( activated() ), this , SLOT( revertConfFile() ) ); popupActionDelete = new QAction( tr("Delete"),QString::null, 0, this, 0 ); popupActionDelete->addTo( popupMenuFile ); popupActionDelete->addTo( popupMenuEntry ); connect( popupActionDelete, SIGNAL( activated() ), this , SLOT( removeConfFile() ) ); connect( popupTimer, SIGNAL(timeout()), this, SLOT(showPopup()) ); } MainWindow::~MainWindow() { } void MainWindow::setCurrent(QListViewItem *item) { // qDebug("MainWindow::setCurrent"); if (!item) return; _item = (ListViewItemConf*) item; if (!_item) return; popupTimer->start( 750, true ); if (_item->getType() == ListViewItemConf::File) { editor->layoutType(EditWidget::File); _currentItem=0; _fileItem = (ListViewItemConfFile*)item; return; } _fileItem = 0; _currentItem = (ListViewItemConfigEntry*)item; if (!_currentItem) return; QString file = _currentItem->getFile(); QString group = _currentItem->getGroup(); QString key = _currentItem->getKey(); QString val = _currentItem->getValue(); editor->TextFileName->setText(file); editor->LineEditGroup->setText(group); if (!key.isEmpty()) { editor->layoutType(EditWidget::Entry); editor->LineEditKey->setText(key); editor->LineEditValue->setText(val); }else{ editor->layoutType(EditWidget::Group); } } void MainWindow::groupChanged(const QString &g) { if (!_currentItem) return; _currentItem->setGroup(g); } void MainWindow::keyChanged(const QString &k) { if (!_currentItem) return; _currentItem->keyChanged(k); } void MainWindow::valueChanged(const QString &v) { if (!_currentItem) return; _currentItem->valueChanged(v); } void MainWindow::stopTimer( QListViewItem* ) { popupTimer->stop(); } void MainWindow::saveConfFile() { if (!_fileItem) return; _fileItem->save(); } void MainWindow::revertConfFile() { if (!_item) return; _item->revert(); } void MainWindow::removeConfFile() { if (!_item) return; _item->remove(); } void MainWindow::showPopup() { qDebug("showPopup"); if (!_item) return; popupActionRevert->setEnabled(_item->revertable()); popupActionSave->setEnabled(_item->isChanged()); if (_fileItem) { popupActionSave->setEnabled(_fileItem->isChanged()); popupMenuFile->popup( QCursor::pos() ); }else if(_currentItem) { popupMenuEntry->popup( QCursor::pos() ); } } diff --git a/noncore/apps/opie-bartender/bartender.cpp b/noncore/apps/opie-bartender/bartender.cpp index 5661ad5..3a0d8d1 100644 --- a/noncore/apps/opie-bartender/bartender.cpp +++ b/noncore/apps/opie-bartender/bartender.cpp @@ -1,447 +1,447 @@ /**************************************************************************** ** ** Created: Sat Jul 20 08:10:53 2002 ** by: L.J. Potter <ljp@llornkcor.com> ** copyright : (C) 2002 by ljp email : ljp@llornkcor.com * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #include "bartender.h" #include "newdrinks.h" #include "showdrinks.h" #include "inputDialog.h" #include "searchresults.h" #include "bac.h" #include <qpe/qpetoolbar.h> #include <qpe/qpemenubar.h> #include <opie/colorpopupmenu.h> #include <qpe/qpeapplication.h> #include <qpe/resource.h> #include <qcstring.h> #include <qlineedit.h> #include <qdir.h> #include <qpushbutton.h> #include <qlistbox.h> #include <qstringlist.h> #include <qmultilineedit.h> #include <qmessagebox.h> #include <qfile.h> #include <qtextstream.h> #include <qfile.h> #include <qaction.h> #include <qheader.h> #include <qlistview.h> #include <qwidget.h> #include <qlayout.h> #include <qvariant.h> #include <qtooltip.h> #include <qwhatsthis.h> #include <qimage.h> #include <qpixmap.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> Bartender::Bartender( QWidget* parent, const char* name, WFlags fl ) : QMainWindow( parent, name, fl ) { if ( !name ) setName( "Bartender" ); QGridLayout *layout = new QGridLayout( this ); layout->setSpacing( 2); layout->setMargin( 2); connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); setCaption( tr( "Bartender" ) ); ToolBar1 = new QPEToolBar( this, "ToolBar1" ); ToolBar1->setFixedHeight(22); layout->addMultiCellWidget( ToolBar1, 0, 0, 0, 4 ); - QPEMenuBar *menuBar = new QPEMenuBar( ToolBar1 ); + QMenuBar *menuBar = new QMenuBar( ToolBar1 ); QPopupMenu *fileMenu; fileMenu = new QPopupMenu( this); menuBar->insertItem( tr("File"), fileMenu ); fileMenu->insertItem(tr("New Drink")); fileMenu->insertItem(tr("Open Drink")); fileMenu->insertItem(tr("Find by Drink Name")); fileMenu->insertItem(tr("Find by Alcohol")); QPopupMenu *editMenu; editMenu = new QPopupMenu( this); menuBar->insertItem( tr("Edit"), editMenu ); editMenu->insertItem(tr("edit")); connect( fileMenu, SIGNAL( activated(int) ), this, SLOT( fileMenuActivated(int) )); connect( editMenu, SIGNAL( activated(int) ), this, SLOT( editMenuActivated(int) )); QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), "New", 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( fileNew() ) ); a->addTo( ToolBar1 ); a = new QAction( tr( "Open" ), Resource::loadPixmap( "bartender/bartender_sm" ), "open", 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( openCurrentDrink() ) ); a->addTo( ToolBar1 ); a = new QAction( tr( "Find" ), Resource::loadPixmap( "find" ), "Find", 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( askSearch() ) ); a->addTo( ToolBar1 ); a = new QAction( tr( "Edit" ), Resource::loadPixmap( "edit" ),"Edit", 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( doEdit() ) ); a->addTo( ToolBar1 ); QPushButton *t; t= new QPushButton( "BAC", ToolBar1, "bacButtin"); connect( t, SIGNAL( clicked() ), this, SLOT( doBac() ) ); DrinkView = new QListView( this, "DrinkView" ); DrinkView->addColumn( tr( "Name of Drink" ) ); // DrinkView->setRootIsDecorated( TRUE ); DrinkView->header()->hide(); QPEApplication::setStylusOperation( DrinkView->viewport(),QPEApplication::RightOnHold); connect(DrinkView, SIGNAL( doubleClicked(QListViewItem*)),this,SLOT(showDrink( QListViewItem*))); connect(DrinkView, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int)), this,SLOT( showDrink(int, QListViewItem *, const QPoint&, int))); layout->addMultiCellWidget( DrinkView, 1, 2, 0, 4 ); if(QDir("db").exists()) { dbFile.setName( "db/drinkdb.txt"); } else dbFile.setName( QPEApplication::qpeDir()+"/etc/bartender/drinkdb.txt"); initDrinkDb(); } Bartender::~Bartender() { } /* this happens right before exit */ void Bartender::cleanUp() { dbFile.close(); } void Bartender::initDrinkDb() { if(!dbFile.isOpen()) if ( !dbFile.open( IO_ReadOnly)) { QMessageBox::message( (tr("Note")), (tr("Drink database not opened sucessfully.\n")) ); return; } fillList(); } void Bartender::fillList() { dbFile.at(1); DrinkView->clear(); int i=0; QListViewItem * item ; QTextStream t( &dbFile); QString s; while ( !t.eof()) { s = t.readLine(); if(s.find("#",0,TRUE) != -1) { // qDebug(s.right(s.length()-2)); item= new QListViewItem( DrinkView, 0 ); item->setText( 0, s.right(s.length()-2)); i++; } } qDebug("there are currently %d of drinks", i); } void Bartender::fileNew() { New_Drink *newDrinks; newDrinks = new New_Drink(this,"New Drink....", TRUE); QString newName, newIng; newDrinks->showMaximized(); newDrinks->exec(); newName = newDrinks->LineEdit1->text(); newIng= newDrinks->MultiLineEdit1->text(); if(dbFile.isOpen()) dbFile.close(); if ( !dbFile.open( IO_WriteOnly| IO_Append)) { QMessageBox::message( (tr("Note")), (tr("Drink database not opened sucessfully.\n")) ); return; } if(newDrinks ->result() == 1 ) { QString newDrink="\n# "+newName+"\n"; newDrink.append(newIng+"\n"); qDebug("writing "+newDrink); dbFile.writeBlock( newDrink.latin1(), newDrink.length()); clearList(); dbFile.close(); initDrinkDb(); } delete newDrinks; } void Bartender::showDrink(int mouse, QListViewItem * item, const QPoint&, int) { switch (mouse) { case 1: // showDrink(item); break; case 2: showDrink(item); break; } } void Bartender::showDrink( QListViewItem *item) { if(item==NULL) return; dbFile.at(0); Show_Drink *showDrinks; QString myDrink=item->text(0); showDrinks = new Show_Drink(this, myDrink, TRUE); QTextStream t( &dbFile); QString s, s2; while ( !t.eof()) { s = t.readLine(); if(s.find( myDrink, 0, TRUE) != -1) { for(int i=0;s2.find( "#", 0, TRUE) == -1;i++) { s2 = t.readLine(); if(s2.find("#",0,TRUE) == -1 || dbFile.atEnd() ) { // qDebug(s2); showDrinks->MultiLineEdit1->append(s2); } if( dbFile.atEnd() ) break; } } } showDrinks->showMaximized(); showDrinks->exec(); if(showDrinks ->result() ==0) { doEdit(); } delete showDrinks; } void Bartender::askSearch() { switch ( QMessageBox::warning(this,tr("Find"),tr("Search by drink name\n")+ "\nor alcohol ?" ,tr("Drink Name"),tr("Alcohol"),0,0,1) ) { case 0: doSearchByName(); break; case 1: doSearchByDrink(); break; }; } /* search by name */ void Bartender::doSearchByName() { // if( DrinkView->currentItem() == NULL) return; QStringList searchList; QString searchForDrinkName; InputDialog *fileDlg; fileDlg = new InputDialog(this,tr("Find by Drink Name"),TRUE, 0); fileDlg->exec(); if( fileDlg->result() == 1 ) { searchForDrinkName = fileDlg->LineEdit1->text(); QListViewItemIterator it( DrinkView ); for ( ; it.current(); ++it ) { if ( it.current()->text(0).find( searchForDrinkName, 0, TRUE) != -1 ) { // qDebug( it.current()->text(0)); searchList.append(it.current()->text(0)); } } if(searchList.count() >0) showSearchResult(searchList); else QMessageBox::message(tr("Search"),tr("Sorry no results for\n")+searchForDrinkName); }//end Inputdialog delete fileDlg; } void Bartender::doSearchByDrink() { // if( DrinkView->currentItem() == NULL) return; QStringList searchList; QString searchForDrinkName, lastDrinkName, tempName; InputDialog *fileDlg; fileDlg = new InputDialog(this,tr("Find by Alcohol"),TRUE, 0); fileDlg->exec(); if( fileDlg->result() == 1 ) { searchForDrinkName = fileDlg->LineEdit1->text(); dbFile.at(0); QTextStream t( &dbFile); QString s, s2; while ( !t.eof()) { s = t.readLine(); if(s.find("#",0,TRUE) != -1) { lastDrinkName=s.right(s.length()-2); // qDebug("last drink name "+lastDrinkName); } else if( s.find( searchForDrinkName ,0, FALSE) != -1 && lastDrinkName != tempName ) { // qDebug("appending "+lastDrinkName); searchList.append( lastDrinkName); tempName=lastDrinkName; } // if( dbFile.atEnd() ) break; } //oef if(searchList.count() >0) showSearchResult(searchList); else QMessageBox::message(tr("Search"),tr("Sorry no results for\n")+ searchForDrinkName); } delete fileDlg; } void Bartender::showSearchResult(QStringList &searchList) { QString result; Search_Results *searchDlg; searchList.sort(); searchDlg = new Search_Results(this, "Search Results", TRUE); searchDlg->showMaximized(); searchDlg->ListBox1->insertStringList( searchList,-1); searchDlg->exec(); if( searchDlg->result() == 1 ) { result= searchDlg->ListBox1->currentText(); } QListViewItemIterator it2( DrinkView ); for ( ; it2.current(); ++it2 ) { if ( it2.current()->text(0)== result ) { // qDebug( it2.current()->text(0)); showDrink(it2.current()); } } delete searchDlg; } void Bartender::doEdit() { if(DrinkView->currentItem() == NULL) { fileNew(); } QString myDrink; myDrink= DrinkView->currentItem()->text(0); dbFile.at(0); int foundAt=0; New_Drink *newDrinks; newDrinks = new New_Drink(this,"Edit Drink....", TRUE); QString newName, newIng; newDrinks->showMaximized(); QTextStream t( &dbFile); QString s, s2; while ( !t.eof()) { s = t.readLine(); if(s.find( myDrink, 0, TRUE) != -1) { foundAt = dbFile.at() - (s.length()+1); for(int i=0;s2.find( "#", 0, TRUE) == -1;i++) { s2 = t.readLine(); if(s2.find("#",0,TRUE) == -1 || dbFile.atEnd() ) { // qDebug(s2); newDrinks->MultiLineEdit1->append(s2); newDrinks->LineEdit1->setText(myDrink); } if( dbFile.atEnd() ) break; } } } newDrinks->exec(); newName = newDrinks->LineEdit1->text(); newIng= newDrinks->MultiLineEdit1->text(); if( newDrinks ->result() == 1 ) { if(dbFile.isOpen()) dbFile.close(); if ( !dbFile.open( IO_ReadWrite )) { QMessageBox::message( (tr("Note")), (tr("Drink database not opened sucessfully.\n")) ); return; } int fd = dbFile.handle(); lseek( fd, foundAt, SEEK_SET); // dbFile.at( foundAt); #warning FIXME problems with editing drinks db ////////// FIXME write to user file QString newDrink="# "+newName+"\n"; newDrink.append(newIng+"\n"); qDebug("writing "+newDrink); dbFile.writeBlock( newDrink.latin1(), newDrink.length()); clearList(); dbFile.flush(); initDrinkDb(); } } void Bartender::clearList() { DrinkView->clear(); } void Bartender::doBac() { BacDialog *bacDlg; bacDlg = new BacDialog(this,"BAC",TRUE); bacDlg->showMaximized(); bacDlg->exec(); delete bacDlg; } void Bartender::openCurrentDrink() { if(DrinkView->currentItem() == NULL) return; showDrink(DrinkView->currentItem()); } void Bartender::fileMenuActivated( int item) { qDebug("Item %d", item); switch(item) { case -3: // new -3 fileNew(); break; case -4:// open -4 openCurrentDrink(); break; case -5:// drink -5 doSearchByName(); break; case -6:// alcohol -6 doSearchByDrink(); break; } } void Bartender::editMenuActivated(int item) { qDebug("Item %d", item); /* edit -8 */ switch(item) { case -8: doEdit() ; break; } } diff --git a/noncore/apps/opie-reader/QTReaderApp.cpp b/noncore/apps/opie-reader/QTReaderApp.cpp index 087ce00..8c0d138 100644 --- a/noncore/apps/opie-reader/QTReaderApp.cpp +++ b/noncore/apps/opie-reader/QTReaderApp.cpp @@ -1,1309 +1,1309 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. Allrights reserved. ** ** This file is part of Qt Palmtop 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 "useqpe.h" #include <qregexp.h> #include <qclipboard.h> #include <qwidgetstack.h> #ifdef USEQPE #include <qpe/qpemenubar.h> #include <qpe/qpetoolbar.h> #endif #include <qmenubar.h> #include <qtoolbar.h> #ifdef USEQPE #include <qpe/menubutton.h> #include <qpe/fontdatabase.h> #endif #include <qcombobox.h> #include <qpopupmenu.h> #include <qaction.h> #include <qapplication.h> #include <qlineedit.h> #include <qtoolbutton.h> #include <qspinbox.h> #include <qobjectlist.h> #ifdef USEQPE #include <qpe/global.h> #include <qpe/applnk.h> #endif #include <qfileinfo.h> #include <stdlib.h> //getenv #include <qprogressbar.h> #ifdef USEQPE #include <qpe/config.h> #endif #include <qbuttongroup.h> #include <qradiobutton.h> #ifdef USEQPE #include <qpe/qcopenvelope_qws.h> #endif #include "QTReader.h" #include "GraphicWin.h" #include "Bkmks.h" #include "cbkmkselector.h" #include "infowin.h" #include "ToolbarPrefs.h" #include "Prefs.h" #include "CAnnoEdit.h" #include "QFloatBar.h" #include "FixedFont.h" #include "URLDialog.h" //#include <qpe/fontdatabase.h> #ifdef USEQPE #include <qpe/resource.h> #include <qpe/qpeapplication.h> #include "fileBrowser.h" #else #include "qfiledialog.h" #endif #include "QTReaderApp.h" #include "CDrawBuffer.h" #include "Filedata.h" #include "opie.h" #include "useqpe.h" #include "names.h" #include "CEncoding_tables.h" #include "CloseDialog.h" bool CheckVersion(int&, int&, char&); #ifdef _WINDOWS #define PICDIR "c:\\uqtreader\\pics\\" #else #ifdef USEQPE #define PICDIR "opie-reader/" #else #define PICDIR "/home/tim/uqtreader/pics/" #endif #endif unsigned long QTReaderApp::m_uid = 0; void QTReaderApp::setScrollState(bool _b) { m_scrollButton->setOn(_b); } #ifdef USEQPE #define geticon(iconname) Resource::loadPixmap( iconname ) #define getmyicon(iconname) Resource::loadPixmap( PICDIR iconname ) #else #define geticon(iconname) QPixmap(PICDIR iconname ".png") #define getmyicon(iconname) geticon(iconname) //#define geticon(iconname) QIconSet( QPixmap(PICDIR iconname) ) #endif #ifndef _WINDOWS #include <unistd.h> #endif #include <stddef.h> #ifndef _WINDOWS #include <dirent.h> #endif void QTReaderApp::listBkmkFiles() { bkmkselector->clear(); bkmkselector->setText("Cancel"); #ifndef USEQPE int cnt = 0; QDir d = QDir::home(); // "/" if ( !d.cd(APPDIR) ) { // "/tmp" qWarning( "Cannot find the \"~/" APPDIR "\" directory" ); d = QDir::home(); d.mkdir(APPDIR); d.cd(APPDIR); } d.setFilter( QDir::Files | QDir::NoSymLinks ); // d.setSorting( QDir::Size | QDir::Reversed ); const QFileInfoList *list = d.entryInfoList(); QFileInfoListIterator it( *list ); // create list iterator QFileInfo *fi; // pointer for traversing while ( (fi=it.current()) ) { // for each file... bkmkselector->insertItem(fi->fileName()); cnt++; //qDebug( "%10li %s", fi->size(), fi->fileName().data() ); ++it; // goto next list element } #else /* USEQPE */ int cnt = 0; DIR *d; d = opendir((const char *)Global::applicationFileName(APPDIR,"")); while(1) { struct dirent* de; struct stat buf; de = readdir(d); if (de == NULL) break; if (lstat((const char *)Global::applicationFileName(APPDIR,de->d_name),&buf) == 0 && S_ISREG(buf.st_mode)) { bkmkselector->insertItem(de->d_name); cnt++; } } closedir(d); #endif if (cnt > 0) { //tjw menu->hide(); editorStack->raiseWidget( bkmkselector ); hidetoolbars(); m_nBkmkAction = cRmBkmkFile; } else QMessageBox::information(this, PROGNAME, "No bookmark files"); } void QTReaderApp::hidetoolbars() { menubar->hide(); if (fileBar != NULL) fileBar->hide(); if (viewBar != NULL) viewBar->hide(); if (navBar != NULL) navBar->hide(); if (markBar != NULL) markBar->hide(); if (m_fontVisible) m_fontBar->hide(); if (regVisible) { #ifdef USEQPE Global::hideInputMethod(); #endif regBar->hide(); } if (searchVisible) { #ifdef USEQPE Global::hideInputMethod(); #endif searchBar->hide(); } } QTReaderApp::QTReaderApp( QWidget *parent, const char *name, WFlags f ) : QMainWindow( parent, name, f ), bFromDocView( FALSE ), m_dontSave(false), fileBar(NULL), navBar(NULL), viewBar(NULL), markBar(NULL) { m_url_clipboard = false; m_url_localfile = false; m_url_globalfile = false; ftime(&m_lastkeytime); //// qDebug("Application directory = %s", (const tchar *)QPEApplication::documentDir()); //// qDebug("Application directory = %s", (const tchar *)Global::applicationFileName("uqtreader","bkmks.xml")); m_bcloseDisabled = true; m_disableesckey = false; pBkmklist = NULL; pOpenlist = NULL; // doc = 0; m_fBkmksChanged = false; QString lang = getenv( "LANG" ); QString rot = getenv( "QWS_DISPLAY" ); /* int m_rot = 0; if (rot.contains("Rot90")) { m_rot = 90; } else if (rot.contains("Rot180")) { m_rot = 180; } else if (rot.contains("Rot270")) { m_rot = 270; } // qDebug("Initial Rotation(%d):%s", m_rot, (const char*)rot); */ m_autogenstr = "^ *[A-Z].*[a-z] *$"; #ifdef USEQPE setIcon( Resource::loadPixmap( PICDIR "uqtreader") ); #else setIcon( QPixmap (PICDIR "uqtreader.png") ); #endif /* USEQPE */ // QPEToolBar *bar = new QPEToolBar( this ); // menubar = new QPEToolBar( this ); #ifdef USEQPE Config config( APPDIR ); #else QDir d = QDir::home(); // "/" if ( !d.cd(APPDIR) ) { // "/tmp" qWarning( "Cannot find the \"~/" APPDIR "\" directory" ); d = QDir::home(); d.mkdir(APPDIR); d.cd(APPDIR); } QFileInfo fi(d, INIFILE); // qDebug("Path:%s", (const char*)fi.absFilePath()); Config config(fi.absFilePath()); #endif config.setGroup("Toolbar"); m_tbmovesave = m_tbmove = config.readBoolEntry("Movable", false); m_tbpolsave = m_tbpol = (ToolbarPolicy)config.readNumEntry("Policy", 1); m_tbposition = (ToolBarDock)config.readNumEntry("Position", 2); menubar = new QToolBar("Menus", this, m_tbposition); // fileBar = new QToolBar("File", this); // QToolBar* viewBar = new QToolBar("File", this); // QToolBar* navBar = new QToolBar("File", this); // QToolBar* markBar = new QToolBar("File", this); #ifdef USEQPE - mb = new QPEMenuBar( menubar ); + mb = new QMenuBar( menubar ); #else mb = new QMenuBar( menubar ); #endif //#ifdef USEQPE QPopupMenu* tmp = new QPopupMenu(mb); mb->insertItem( geticon( "AppsIcon" ), tmp ); //#else // QMenuBar* tmp = mb; //#endif QPopupMenu *file = new QPopupMenu( mb ); tmp->insertItem( tr( "File" ), file ); QPopupMenu *navigation = new QPopupMenu(mb); tmp->insertItem( tr( "Navigation" ), navigation ); QPopupMenu *view = new QPopupMenu( mb ); tmp->insertItem( tr( "View" ), view ); QPopupMenu *marks = new QPopupMenu( this ); tmp->insertItem( tr( "Marks" ), marks ); QPopupMenu *settings = new QPopupMenu( this ); tmp->insertItem( tr( "Settings" ), settings ); // addToolBar(menubar, "Menus",QMainWindow::Top); // addToolBar(fileBar, "Toolbar",QMainWindow::Top); // QPopupMenu *edit = new QPopupMenu( this ); /* 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 ); */ editorStack = new QWidgetStack( this ); setCentralWidget( editorStack ); searchVisible = FALSE; regVisible = FALSE; m_fontVisible = false; m_annoWin = new CAnnoEdit(editorStack); editorStack->addWidget(m_annoWin, get_unique_id()); connect( m_annoWin, SIGNAL( finished(const QString&, const QString&) ), this, SLOT( addAnno(const QString&, const QString&) ) ); connect( m_annoWin, SIGNAL( cancelled() ), this, SLOT( infoClose() ) ); m_infoWin = new infowin(editorStack); editorStack->addWidget(m_infoWin, get_unique_id()); connect( m_infoWin, SIGNAL( Close() ), this, SLOT( infoClose() ) ); m_graphicwin = new GraphicWin(editorStack); editorStack->addWidget(m_graphicwin, get_unique_id()); connect( m_graphicwin, SIGNAL( Closed() ), this, SLOT( infoClose() ) ); // bkmkselector = new QListBox(editorStack, "Bookmarks"); bkmkselector = new CBkmkSelector(editorStack, "Bookmarks"); // connect(bkmkselector, SIGNAL( selected(const QString&) ), this, SLOT( gotobkmk(const QString&) ) ); connect(bkmkselector, SIGNAL( selected(int) ), this, SLOT( gotobkmk(int) ) ); connect(bkmkselector, SIGNAL( cancelled() ), this, SLOT( cancelbkmk() ) ); editorStack->addWidget( bkmkselector, get_unique_id() ); /* importSelector = new FileSelector( "*", editorStack, "importselector", false ); connect( importSelector, SIGNAL( fileSelected( const DocLnk &) ), this, SLOT( importFile( const DocLnk & ) ) ); editorStack->addWidget( importSelector, get_unique_id() ); // don't need the close visible, it is redundant... importSelector->setCloseVisible( FALSE ); */ // qDebug("Reading file list"); readfilelist(); reader = new QTReader( editorStack ); reader->bDoUpdates = false; #ifdef USEQPE ((QPEApplication*)qApp)->setStylusOperation(reader, QPEApplication::RightOnHold); #endif // qDebug("Reading config"); // Config config( APPDIR ); config.setGroup( "View" ); m_debounce = config.readNumEntry("Debounce", 0); #ifdef USEQPE m_bFloatingDialog = config.readBoolEntry("FloatDialogs", false); #else m_bFloatingDialog = config.readBoolEntry("FloatDialogs", true); #endif reader->bstripcr = config.readBoolEntry( "StripCr", true ); reader->bfulljust = config.readBoolEntry( "FullJust", false ); reader->setextraspace(config.readNumEntry( "ExtraSpace", 0 )); reader->setlead(config.readNumEntry( "ExtraLead", 0 )); reader->btextfmt = config.readBoolEntry( "TextFmt", false ); reader->bautofmt = config.readBoolEntry( "AutoFmt", true ); reader->bstriphtml = config.readBoolEntry( "StripHtml", false ); reader->bpeanut = config.readBoolEntry( "Peanut", false ); reader->bdehyphen = config.readBoolEntry( "Dehyphen", false ); reader->bdepluck = config.readBoolEntry( "Depluck", false ); reader->bdejpluck = config.readBoolEntry( "Dejpluck", false ); reader->bonespace = config.readBoolEntry( "OneSpace", false ); reader->bunindent = config.readBoolEntry( "Unindent", false ); reader->brepara = config.readBoolEntry( "Repara", false ); reader->bdblspce = config.readBoolEntry( "DoubleSpace", false ); reader->bindenter = config.readNumEntry( "Indent", 0 ); reader->m_textsize = config.readNumEntry( "FontSize", 12 ); reader->m_delay = config.readNumEntry( "ScrollDelay", 5184); reader->m_lastfile = config.readEntry( "LastFile", QString::null ); reader->m_lastposn = config.readNumEntry( "LastPosn", 0 ); reader->m_bpagemode = config.readBoolEntry( "PageMode", true ); reader->m_bMonoSpaced = config.readBoolEntry( "MonoSpaced", false); reader->m_swapmouse = config.readBoolEntry( "SwapMouse", false); reader->m_fontname = config.readEntry( "Fontname", "helvetica" ); reader->m_encd = config.readNumEntry( "Encoding", 0 ); reader->m_charpc = config.readNumEntry( "CharSpacing", 100 ); reader->m_overlap = config.readNumEntry( "Overlap", 0 ); reader->m_border = config.readNumEntry( "Margin", 6 ); #ifdef REPALM reader->brepalm = config.readBoolEntry( "Repalm", true ); #endif reader->bremap = config.readBoolEntry( "Remap", true ); reader->bmakebold = config.readBoolEntry( "MakeBold", false ); reader->setContinuous(config.readBoolEntry( "Continuous", true )); m_targetapp = config.readEntry( "TargetApp", QString::null ); m_targetmsg = config.readEntry( "TargetMsg", QString::null ); #ifdef _SCROLLPIPE reader->m_pipetarget = config.readEntry( "PipeTarget", QString::null ); reader->m_pauseAfterEachPara = config.readBoolEntry( "PauseAfterPara", true ); #endif m_twoTouch = config.readBoolEntry( "TwoTouch", false); m_doAnnotation = config.readBoolEntry( "Annotation", false); m_doDictionary = config.readBoolEntry( "Dictionary", false); m_doClipboard = config.readBoolEntry( "Clipboard", false); m_spaceTarget = (ActionTypes)config.readNumEntry("SpaceTarget", cesAutoScroll); m_escapeTarget = (ActionTypes)config.readNumEntry("EscapeTarget", cesNone); m_returnTarget = (ActionTypes)config.readNumEntry("ReturnTarget", cesFullScreen); m_leftTarget = (ActionTypes)config.readNumEntry("LeftTarget", cesZoomOut); m_rightTarget = (ActionTypes)config.readNumEntry("RightTarget", cesZoomIn); m_upTarget = (ActionTypes)config.readNumEntry("UpTarget", cesPageUp); m_downTarget = (ActionTypes)config.readNumEntry("DownTarget", cesPageDown); m_leftScroll = config.readBoolEntry("LeftScroll", false); m_rightScroll = config.readBoolEntry("RightScroll", false); m_upScroll = config.readBoolEntry("UpScroll", true); m_downScroll = config.readBoolEntry("DownScroll", true); m_propogatefontchange = config.readBoolEntry( "RequestorFontChange", false); reader->setBaseSize(config.readNumEntry( "Basesize", 10 )); #ifndef USEQPE config.setGroup( "Geometry" ); setGeometry(0,0, config.readNumEntry( "width", QApplication::desktop()->width()/2 ), config.readNumEntry( "height", QApplication::desktop()->height()/2 )); move( config.readNumEntry( "x", 20 ), config.readNumEntry( "y", 20 )); #endif setTwoTouch(m_twoTouch); connect( reader, SIGNAL( OnShowPicture(QImage&) ), this, SLOT( showgraphic(QImage&) ) ); connect( reader, SIGNAL( OnRedraw() ), this, SLOT( OnRedraw() ) ); connect( reader, SIGNAL( OnWordSelected(const QString&, size_t, const QString&) ), this, SLOT( OnWordSelected(const QString&, size_t, const QString&) ) ); connect( reader, SIGNAL( OnURLSelected(const QString&) ), this, SLOT( OnURLSelected(const QString&) ) ); editorStack->addWidget( reader, get_unique_id() ); m_preferences_action = new QAction( tr( "Configuration" ), geticon( "SettingsIcon" ), QString::null, 0, this, NULL); connect( m_preferences_action, SIGNAL( activated() ), this, SLOT( showprefs() ) ); m_preferences_action->addTo( settings ); m_saveconfig_action = new QAction( tr( "Save Config" ), QString::null, 0, this, NULL); connect( m_saveconfig_action, SIGNAL( activated() ), this, SLOT( SaveConfig() ) ); m_saveconfig_action->addTo( settings ); m_loadconfig_action = new QAction( tr( "Load Config" ), QString::null, 0, this, NULL); connect( m_loadconfig_action, SIGNAL( activated() ), this, SLOT( LoadConfig() ) ); m_loadconfig_action->addTo( settings ); m_tidyconfig_action = new QAction( tr( "Delete Config" ), QString::null, 0, this, NULL); connect( m_tidyconfig_action, SIGNAL( activated() ), this, SLOT( TidyConfig() ) ); m_tidyconfig_action->addTo( settings ); settings->insertSeparator(); m_toolbarprefs_action = new QAction( tr( "Toolbars" ), QString::null, 0, this, NULL); connect( m_toolbarprefs_action, SIGNAL( activated() ), this, SLOT( showtoolbarprefs() ) ); m_toolbarprefs_action->addTo( settings ); m_open_action = new QAction( tr( "Open" ), geticon( "fileopen" ), QString::null, 0, this, 0 ); connect( m_open_action, SIGNAL( activated() ), this, SLOT( fileOpen() ) ); m_open_action->addTo( file ); m_close_action = new QAction( tr( "Close" ), geticon( "close" ), QString::null, 0, this, 0 ); connect( m_close_action, SIGNAL( activated() ), this, SLOT( fileClose() ) ); m_close_action->addTo( file ); #ifdef _SCRIPT a = new QAction( tr( "Run Script" ), QString::null, 0, this, NULL); connect( a, SIGNAL( activated() ), this, SLOT( RunScript() ) ); a->addTo( file ); #endif /* a = new QAction( tr( "Revert" ), geticon( "close" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( fileRevert() ) ); a->addTo( file ); a = new QAction( tr( "Cut" ), geticon( "cut" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editCut() ) ); a->addTo( filebar() ); a->addTo( edit ); */ m_info_action = new QAction( tr( "Info" ), geticon( "UtilsIcon" ), QString::null, 0, this, NULL); connect( m_info_action, SIGNAL( activated() ), this, SLOT( showinfo() ) ); m_info_action->addTo( file ); m_touch_action = new QAction( tr( "Two/One Touch" ), geticon( "1to1" ), QString::null, 0, this, NULL, true ); connect( m_touch_action, SIGNAL( toggled(bool) ), this, SLOT( setTwoTouch(bool) ) ); m_touch_action->setOn(m_twoTouch); m_touch_action->addTo( file ); m_find_action = new QAction( tr( "Find..." ), geticon( "find" ), QString::null, 0, this, NULL); connect( m_find_action, SIGNAL( activated() ), this, SLOT( editFind() ) ); file->insertSeparator(); // a->addTo( bar ); m_find_action->addTo( file ); m_exportlinks_action = new QAction( tr( "Export Links" ), QString::null, 0, this, NULL); connect( m_exportlinks_action, SIGNAL( activated() ), this, SLOT( ExportLinks() ) ); m_exportlinks_action->addTo( file ); m_scrollButton = new QAction( tr( "Scroll" ), getmyicon( "panel-arrow-down" ), QString::null, 0, this, 0, true ); connect( m_scrollButton, SIGNAL( toggled(bool) ), this, SLOT( autoScroll(bool) ) ); m_scrollButton->addTo(navigation); m_scrollButton->setOn(false); m_start_action = new QAction( tr( "Goto Start" ), geticon( "start" ), QString::null, 0, this, NULL); connect( m_start_action, SIGNAL( activated() ), this, SLOT( gotoStart() ) ); m_start_action->addTo(navigation); m_end_action = new QAction( tr( "Goto End" ), geticon( "finish" ), QString::null, 0, this, NULL); connect( m_end_action, SIGNAL( activated() ), this, SLOT( gotoEnd() ) ); m_end_action->addTo(navigation); m_jump_action = new QAction( tr( "Jump" ), geticon( "rotate" ), QString::null, 0, this, NULL); connect( m_jump_action, SIGNAL( activated() ), this, SLOT( jump() ) ); m_jump_action->addTo(navigation); m_pageline_action = new QAction( tr( "Page/Line Scroll" ), geticon( "pass" ), QString::null, 0, this, NULL, true ); connect( m_pageline_action, SIGNAL( toggled(bool) ), this, SLOT( pagemode(bool) ) ); m_pageline_action->addTo(navigation); m_pageline_action->setOn(reader->m_bpagemode); m_pageup_action = new QAction( tr( "Up" ), geticon( "up" ), QString::null, 0, this, 0 ); connect( m_pageup_action, SIGNAL( activated() ), this, SLOT( pageup() ) ); m_pageup_action->addTo( navigation ); m_pagedn_action = new QAction( tr( "Down" ), geticon( "down" ), QString::null, 0, this, 0 ); connect( m_pagedn_action, SIGNAL( activated() ), this, SLOT( pagedn() ) ); m_pagedn_action->addTo( navigation ); m_back_action = new QAction( tr( "Back" ), geticon( "back" ), QString::null, 0, this, 0 ); connect( m_back_action, SIGNAL( activated() ), reader, SLOT( goBack() ) ); m_back_action->addTo( navigation ); m_home_action = new QAction( tr( "Home" ), geticon( "home" ), QString::null, 0, this, 0 ); connect( m_home_action, SIGNAL( activated() ), reader, SLOT( goHome() ) ); m_home_action->addTo( navigation ); m_forward_action = new QAction( tr( "Forward" ), geticon( "forward" ), QString::null, 0, this, 0 ); connect( m_forward_action, SIGNAL( activated() ), reader, SLOT( goForward() ) ); m_forward_action->addTo( navigation ); /* a = new QAction( tr( "Find" ), QString::null, 0, this, NULL, true ); // connect( a, SIGNAL( activated() ), this, SLOT( pagedn() ) ); a->addTo( file ); a = new QAction( tr( "Find Again" ), QString::null, 0, this, NULL, true ); // connect( a, SIGNAL( activated() ), this, SLOT( pagedn() ) ); a->addTo( file ); */ // file->insertSeparator(); #ifdef _SCROLLPIPE QActionGroup* ag = new QActionGroup(this); ag->setExclusive(false); spacemenu = new QPopupMenu(this); file->insertItem( tr( "Scrolling" ), spacemenu ); a = new QAction( tr( "Set Target" ), QString::null, 0, ag, NULL); connect( a, SIGNAL( activated() ), this, SLOT( setpipetarget() ) ); a = new QAction( tr( "Pause Paras" ), QString::null, 0, ag, NULL, true ); connect( a, SIGNAL( toggled(bool) ), this, SLOT( setpause(bool) ) ); a->setOn(reader->m_pauseAfterEachPara); ag->addTo(spacemenu); // file->insertSeparator(); #endif /* a = new QAction( tr( "Import" ), QString::null, 0, this, NULL ); connect( a, SIGNAL( activated() ), this, SLOT( importFiles() ) ); a->addTo( file ); */ /* a = new QAction( tr( "Paste" ), geticon( "paste" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editPaste() ) ); a->addTo( fileBar ); a->addTo( edit ); */ // a = new QAction( tr( "Find..." ), geticon( "find" ), QString::null, 0, this, 0 ); m_fullscreen = false; m_actFullscreen = new QAction( tr( "Fullscreen" ), geticon( "fullscreen" ), QString::null, 0, this, NULL, true ); connect( m_actFullscreen, SIGNAL( toggled(bool) ), this, SLOT( setfullscreen(bool) ) ); m_actFullscreen->setOn(m_fullscreen); m_actFullscreen->addTo( view ); view->insertSeparator(); m_zoomin_action = new QAction( tr( "Zoom In" ), geticon( "zoom" ), QString::null, 0, this); connect( m_zoomin_action, SIGNAL( activated() ), this, SLOT( zoomin() ) ); m_zoomin_action->addTo( view ); m_zoomout_action = new QAction( tr( "Zoom Out" ), geticon( "mag" ), QString::null, 0, this); connect( m_zoomout_action, SIGNAL( activated() ), this, SLOT( zoomout() ) ); m_zoomout_action->addTo( view ); view->insertSeparator(); m_setfont_action = new QAction( tr( "Set Font" ), getmyicon( "font" ), QString::null, 0, this); connect( m_setfont_action, SIGNAL( activated() ), this, SLOT( setfont() ) ); m_setfont_action->addTo( view ); view->insertSeparator(); m_setenc_action = new QAction( tr( "Set Encoding" ), getmyicon( "charset" ), QString::null, 0, this); connect( m_setenc_action, SIGNAL( activated() ), this, SLOT( chooseencoding() ) ); m_setenc_action->addTo( view ); m_setmono_action = new QAction( tr( "Ideogram" ), getmyicon( "ideogram" ), QString::null, 0, this, NULL, true); connect( m_setmono_action, SIGNAL( toggled(bool) ), this, SLOT( monospace(bool) ) ); m_setmono_action->addTo( view ); m_setmono_action->setOn(reader->m_bMonoSpaced); // a = new QAction( tr( "Zoom" ), QString::null, 0, this, NULL, true ); // a = new QAction( tr( "Zoom" ), geticon( "mag" ), QString::null, 0, this, 0 ); // a->addTo( filebar() ); // view->insertSeparator(); /* a = new QAction( tr( "Ideogram/Word" ), QString::null, 0, this, NULL, true ); connect( a, SIGNAL( toggled(bool) ), this, SLOT( monospace(bool) ) ); a->setOn(reader->m_bMonoSpaced); a->addTo( view ); */ /* a = new QAction( tr( "Set Width" ), QString::null, 0, this, NULL); connect( a, SIGNAL( activated() ), this, SLOT( setspacing() ) ); a->addTo( view ); */ m_mark_action = new QAction( tr( "Bookmark" ), getmyicon( "bookmark" ), QString::null, 0, this, NULL); connect( m_mark_action, SIGNAL( activated() ), this, SLOT( addbkmk() ) ); m_mark_action->addTo( marks ); m_annotate_action = new QAction( tr( "Annotate" ), getmyicon( "annotate" ), QString::null, 0, this, NULL); connect( m_annotate_action, SIGNAL( activated() ), this, SLOT( addanno() ) ); m_annotate_action->addTo( marks ); m_goto_action = new QAction( tr( "Goto" ), getmyicon( "bookmark_goto" ), QString::null, 0, this, NULL, false ); connect( m_goto_action, SIGNAL( activated() ), this, SLOT( do_gotomark() ) ); m_goto_action->addTo( marks ); m_delete_action = new QAction( tr( "Delete" ), getmyicon( "bookmark_delete" ), QString::null, 0, this, NULL); connect( m_delete_action, SIGNAL( activated() ), this, SLOT( do_delmark() ) ); m_delete_action->addTo( marks ); m_autogen_action = new QAction( tr( "Autogen" ), geticon( "exec" ), QString::null, 0, this, NULL, false ); connect( m_autogen_action, SIGNAL( activated() ), this, SLOT( do_autogen() ) ); marks->insertSeparator(); m_autogen_action->addTo( marks ); m_clear_action = new QAction( tr( "Clear" ), getmyicon( "bookmark_clear" ), QString::null, 0, this, NULL); connect( m_clear_action, SIGNAL( activated() ), this, SLOT( clearBkmkList() ) ); m_clear_action->addTo( marks ); m_save_action = new QAction( tr( "Save" ), getmyicon( "bookmark_save" ), QString::null, 0, this, NULL ); connect( m_save_action, SIGNAL( activated() ), this, SLOT( savebkmks() ) ); m_save_action->addTo( marks ); m_tidy_action = new QAction( tr( "Tidy" ), getmyicon( "bookmark_tidy" ), QString::null, 0, this, NULL); connect( m_tidy_action, SIGNAL( activated() ), this, SLOT( listBkmkFiles() ) ); marks->insertSeparator(); m_tidy_action->addTo( marks ); m_startBlock_action = new QAction( tr( "Start Block" ), geticon( "new" ), QString::null, 0, this, NULL); connect( m_startBlock_action, SIGNAL( activated() ), this, SLOT( editMark() ) ); marks->insertSeparator(); m_startBlock_action->addTo( marks ); m_endBlock_action = new QAction( tr( "Copy Block" ), geticon( "copy" ), QString::null, 0, this, NULL); connect( m_endBlock_action, SIGNAL( activated() ), this, SLOT( editCopy() ) ); m_endBlock_action->addTo( marks ); m_bkmkAvail = NULL; setToolBarsMovable(m_tbmove); addtoolbars(&config); pbar = new QProgressBar(this); pbar->hide(); searchBar = new QFloatBar( "Search", this, QMainWindow::Top, TRUE ); searchBar->setHorizontalStretchable( TRUE ); connect(searchBar, SIGNAL( OnHide() ), this, SLOT( restoreFocus() )); searchEdit = new QLineEdit( searchBar, "searchEdit" ); // QFont f("unifont", 16 /*, QFont::Bold*/); // searchEdit->setFont( f ); searchBar->setStretchableWidget( searchEdit ); #ifdef __ISEARCH connect( searchEdit, SIGNAL( textChanged( const QString & ) ), this, SLOT( search( const QString& ) ) ); #else connect( searchEdit, SIGNAL( returnPressed( ) ), this, SLOT( search( ) ) ); #endif QAction*a = new QAction( tr( "Find Next" ), geticon( "next" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( findNext() ) ); a->addTo( searchBar ); a = new QAction( tr( "Close Find" ), geticon( "close" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( findClose() ) ); a->addTo( searchBar ); searchBar->hide(); regBar = new QFloatBar( "Autogen", this, QMainWindow::Top, TRUE ); connect(regBar, SIGNAL( OnHide() ), this, SLOT( restoreFocus() )); regBar->setHorizontalStretchable( TRUE ); regEdit = new QLineEdit( regBar, "regEdit" ); // regEdit->setFont( f ); regBar->setStretchableWidget( regEdit ); connect( regEdit, SIGNAL( returnPressed( ) ), this, SLOT( do_regaction() ) ); a = new QAction( tr( "Do Reg" ), geticon( "enter" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( do_regaction() ) ); a->addTo( regBar ); a = new QAction( tr( "Close Edit" ), geticon( "close" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( regClose() ) ); a->addTo( regBar ); regBar->hide(); m_fontBar = new QToolBar( "Autogen", this, QMainWindow::Top, TRUE ); m_fontBar->setHorizontalStretchable( TRUE ); // qDebug("Font selector"); m_fontSelector = new QComboBox(false, m_fontBar); m_fontBar->setStretchableWidget( m_fontSelector ); { #ifndef USEQPE QFontDatabase f; #else FontDatabase f; #endif QStringList flist = f.families(); bool realfont = false; for (QStringList::Iterator nm = flist.begin(); nm != flist.end(); nm++) { if (reader->m_fontname == *nm) { realfont = true; } if ((*nm).contains(FIXEDFONT,false)) reader->m_fontControl.hasCourier(true, *nm); } if (!realfont) reader->m_fontname = flist[0]; } // delete the FontDatabase!!! connect( m_fontSelector, SIGNAL( activated(const QString& ) ), this, SLOT( do_setfont(const QString&) ) ); connect( m_fontSelector, SIGNAL( activated(int ) ), this, SLOT( do_setencoding(int) ) ); m_fontBar->hide(); m_fontVisible = false; #ifdef USEMSGS connect(qApp, SIGNAL( appMessage(const QCString&, const QByteArray& ) ), this, SLOT( msgHandler(const QCString&, const QByteArray&) ) ); #endif // qDebug("Initing"); reader->init(); // qDebug("Inited"); // m_buttonAction[m_spaceTarget]->setOn(true); // qDebug("fonting"); do_setfont(reader->m_fontname); if (!reader->m_lastfile.isEmpty()) { // qDebug("doclnk"); // doc = new DocLnk(reader->m_lastfile); // qDebug("doclnk done"); if (pOpenlist != NULL) { /* int ind = 0; Bkmk* p = (*pOpenlist)[ind]; while (p != NULL && toQString(CFiledata(p->anno()).name()) != reader->m_lastfile) { p = (*pOpenlist)[++ind]; } */ Bkmk* p = NULL; for (CList<Bkmk>::iterator iter = pOpenlist->begin(); iter != pOpenlist->end(); iter++) { p = iter.pContent(); if (toQString(CFiledata(p->anno()).name()) == reader->m_lastfile) { break; } // qDebug("Item:%s", (const char*)toQString(CFiledata(p->anno()).name())); p = NULL; } if (p != NULL) { // qDebug("openfrombkmk"); if (!openfrombkmk(p)) showEditTools(); } else { // qDebug("openfile"); openFile( reader->m_lastfile ); } } else { // qDebug("Openfile 2"); if (!reader->m_lastfile.isEmpty()) openFile( reader->m_lastfile ); } } else { showEditTools(); } // qApp->processEvents(); reader->bDoUpdates = true; reader->update(); config.setGroup("Version"); int major = config.readNumEntry("Major", 0); int bkmktype = config.readNumEntry("BkmkType", 0); char minor = config.readNumEntry("Minor", 0); if (CheckVersion(major, bkmktype, minor)) { config.writeEntry("Major", major); config.writeEntry("BkmkType", bkmktype); config.writeEntry("Minor", (int)minor); } // qDebug("finished update"); } void QTReaderApp::addtoolbars(Config* config) { config->setGroup("Toolbar"); if (fileBar != NULL) { if (fileBar != menubar) { fileBar->clear(); } else { m_preferences_action->removeFrom( filebar() ); m_open_action->removeFrom( filebar() ); m_close_action->removeFrom( filebar() ); m_info_action->removeFrom( filebar() ); m_touch_action->removeFrom( filebar() ); m_find_action->removeFrom( filebar() ); } } m_preferences_action->addTo( filebar() ); addfilebar(config, "Open", m_open_action); addfilebar(config, "Close", m_close_action); addfilebar(config, "Info", m_info_action); addfilebar(config, "Two/One Touch", m_touch_action); addfilebar(config, "Find", m_find_action); if (navBar != NULL) { if ((navBar == fileBar) && (fileBar == menubar)) { m_scrollButton->removeFrom( navbar() ); m_start_action->removeFrom( navbar() ); m_end_action->removeFrom( navbar() ); m_jump_action->removeFrom( navbar() ); m_pageline_action->removeFrom( navbar() ); m_pageup_action->removeFrom( navbar() ); m_pagedn_action->removeFrom( navbar() ); m_back_action->removeFrom( navbar() ); m_home_action->removeFrom( navbar() ); m_forward_action->removeFrom( navbar() ); } else if (navBar != fileBar) { navBar->clear(); } } addnavbar(config, "Scroll", m_scrollButton); addnavbar(config, "Goto Start", m_start_action); addnavbar(config, "Goto End", m_end_action); addnavbar(config, "Jump", m_jump_action); addnavbar(config, "Page/Line Scroll", m_pageline_action); addnavbar(config, "Page Up", m_pageup_action); addnavbar(config, "Page Down", m_pagedn_action); addnavbar(config, "Back", m_back_action); addnavbar(config, "Home", m_home_action); addnavbar(config, "Forward", m_forward_action); if (viewBar != NULL) { if ((viewBar == fileBar) && (fileBar == menubar)) { m_actFullscreen->removeFrom( filebar() ); m_zoomin_action->removeFrom( viewbar() ); m_zoomout_action->removeFrom( viewbar() ); m_setfont_action->removeFrom( viewbar() ); m_setenc_action->removeFrom( viewbar() ); m_setmono_action->removeFrom( viewbar() ); } else if (viewBar != fileBar) { viewBar->clear(); } } addviewbar(config, "Fullscreen", m_actFullscreen); addviewbar(config, "Zoom In", m_zoomin_action); addviewbar(config, "Zoom Out", m_zoomout_action); addviewbar(config, "Set Font", m_setfont_action); addviewbar(config, "Encoding Select", m_setenc_action); addviewbar(config, "Ideogram Mode", m_setmono_action); if (markBar != NULL) { if ((markBar == fileBar) && (fileBar == menubar)) { m_mark_action->removeFrom( markbar() ); m_annotate_action->removeFrom( markbar()); m_goto_action->removeFrom( markbar() ); m_delete_action->removeFrom( markbar() ); m_autogen_action->removeFrom( markbar() ); m_clear_action->removeFrom( markbar() ); m_save_action->removeFrom( markbar() ); m_tidy_action->removeFrom( markbar() ); m_startBlock_action->removeFrom( markbar() ); m_endBlock_action->removeFrom( markbar() ); } else if (markBar != fileBar) { markBar->clear(); } } addmarkbar(config, "Mark", m_mark_action); addmarkbar(config, "Annotate", m_annotate_action); addmarkbar(config, "Goto", m_goto_action); addmarkbar(config, "Delete", m_delete_action); addmarkbar(config, "Autogen", m_autogen_action); addmarkbar(config, "Clear", m_clear_action); addmarkbar(config, "Save", m_save_action); addmarkbar(config, "Tidy", m_tidy_action); addmarkbar(config, "Start Block", m_startBlock_action); addmarkbar(config, "Copy Block", m_endBlock_action); if (checkbar(config, "Annotation indicator")) { if (m_bkmkAvail == NULL) { m_bkmkAvail = new QAction( tr( "Annotation" ), geticon( "find" ), QString::null, 0, this, 0 ); connect( m_bkmkAvail, SIGNAL( activated() ), this, SLOT( showAnnotation() ) ); m_bkmkAvail->setEnabled(false); } QLabel *spacer = new QLabel(markBar, ""); markbar()->setStretchableWidget(spacer); m_bkmkAvail->removeFrom( markbar() ); m_bkmkAvail->addTo( markbar() ); } else { if (m_bkmkAvail != NULL) { m_bkmkAvail->removeFrom( markbar() ); delete m_bkmkAvail; m_bkmkAvail = NULL; } } } bool QTReaderApp::checkbar(Config* _config, const QString& key) { return _config->readBoolEntry(key, false); } QToolBar* QTReaderApp::filebar() { if (fileBar == NULL) { switch (m_tbpol) { case cesSingle: // qDebug("Setting filebar to menubar"); fileBar = menubar; break; default: qDebug("Incorrect toolbar policy set"); case cesMenuTool: case cesMultiple: // qDebug("Creating new file bar"); fileBar = new QToolBar("File", this, m_tbposition); break; } // fileBar->setHorizontalStretchable( true ); } return fileBar; } QToolBar* QTReaderApp::viewbar() { if (viewBar == NULL) { switch (m_tbpol) { case cesMultiple: viewBar = new QToolBar("View", this, m_tbposition); break; default: qDebug("Incorrect toolbar policy set"); case cesSingle: case cesMenuTool: viewBar = fileBar; break; } } return viewBar; } QToolBar* QTReaderApp::navbar() { if (navBar == NULL) { switch (m_tbpol) { case cesMultiple: // qDebug("Creating new nav bar"); navBar = new QToolBar("Navigation", this, m_tbposition); break; default: qDebug("Incorrect toolbar policy set"); case cesSingle: case cesMenuTool: navBar = fileBar; // qDebug("Setting navbar to filebar"); break; } } return navBar; } QToolBar* QTReaderApp::markbar() { if (markBar == NULL) { switch (m_tbpol) { case cesMultiple: markBar = new QToolBar("Marks", this, m_tbposition); break; default: qDebug("Incorrect toolbar policy set"); case cesSingle: case cesMenuTool: markBar = fileBar; break; } } return markBar; } void QTReaderApp::addfilebar(Config* _config, const QString& key, QAction* a) { if (_config->readBoolEntry(key, false)) a->addTo( filebar() ); } void QTReaderApp::addnavbar(Config* _config, const QString& key, QAction* a) { if (_config->readBoolEntry(key, false)) a->addTo( navbar() ); } void QTReaderApp::addmarkbar(Config* _config, const QString& key, QAction* a) { if (_config->readBoolEntry(key, false)) a->addTo( markbar() ); } void QTReaderApp::addviewbar(Config* _config, const QString& key, QAction* a) { if (_config->readBoolEntry(key, false)) a->addTo( viewbar() ); } void QTReaderApp::suspend() { reader->suspend(); } #ifdef USEMSGS void QTReaderApp::msgHandler(const QCString& _msg, const QByteArray& _data) { QString msg = QString::fromUtf8(_msg); //// qDebug("Received:%s", (const char*)msg); QDataStream stream( _data, IO_ReadOnly ); if ( msg == "info(QString)" ) { QString info; stream >> info; QMessageBox::information(this, PROGNAME, info); } else if ( msg == "Update(int)" ) { int info; stream >> info; if (info) { reader->bDoUpdates = true; reader->refresh(); } else { reader->bDoUpdates = false; } } else if ( msg == "warn(QString)" ) { QString info; stream >> info; QMessageBox::warning(this, PROGNAME, info); } else if ( msg == "exit()" ) { m_dontSave = true; close(); } else if ( msg == "pageDown()" ) { reader->dopagedn(); } else if ( msg == "pageUp()" ) { reader->dopageup(); } else if ( msg == "lineDown()" ) { reader->lineDown(); } else if ( msg == "lineUp()" ) { reader->lineUp(); } else if ( msg == "showText()" ) { showEditTools(); } else if ( msg == "home()" ) { reader->goHome(); } else if ( msg == "back()" ) { reader->goBack(); } else if ( msg == "forward()" ) { reader->goForward(); } else if ( msg == "File/Open(QString)" ) { QString info; stream >> info; openFile( info ); } else if ( msg == "File/Info()" ) { showinfo(); } else if ( msg == "File/Action(QString)" ) { QString info; stream >> info; m_spaceTarget = ActNameToInt(info); } else if ( msg == "Navigation/Scroll(int)" ) { int info; stream >> info; autoScroll(info); } else if ( msg == "Navigation/GotoStart()" ) { gotoStart(); } else if ( msg == "Navigation/GotoEnd()" ) { gotoEnd(); } else if ( msg == "Navigation/Jump(int)" ) { int info; stream >> info; reader->locate(info); } else if ( msg == "Navigation/Page/LineScroll(int)" ) { int info; stream >> info; pagemode(info); } else if ( msg == "Navigation/SetOverlap(int)" ) { int info; stream >> info; reader->m_overlap = info; } else if ( msg == "Navigation/SetMargin(int)" ) { int info; stream >> info; do_margin(info); } else if ( msg == "File/SetDictionary(QString)" ) { QString info; stream >> info; do_settarget(info); } #ifdef _SCROLLPIPE else if ( msg == "File/SetScrollTarget(QString)" ) { QString info; stream >> info; reader->m_pipetarget = info; } #endif else if ( msg == "File/Two/OneTouch(int)" ) { int info; stream >> info; setTwoTouch(info); } else if ( msg == "Target/Annotation(int)" ) { int info; stream >> info; OnAnnotation(info); } else if ( msg == "Target/Dictionary(int)" ) { int info; stream >> info; OnDictionary(info); } else if ( msg == "Target/Clipboard(int)" ) { int info; stream >> info; OnClipboard(info); } else if ( msg == "File/Find(QString)" ) { QString info; stream >> info; QRegExp arg(info); size_t pos = reader->pagelocate(); size_t start = pos; CDrawBuffer test(&(reader->m_fontControl)); reader->getline(&test); while (arg.match(toQString(test.data())) == -1) { pos = reader->locate(); if (!reader->getline(&test)) { QMessageBox::information(this, PROGNAME, QString("Can't find\n")+info); pos = start; break; } } reader->locate(pos); diff --git a/noncore/apps/opie-reader/QTReaderApp.h b/noncore/apps/opie-reader/QTReaderApp.h index 2765d47..86c14b1 100644 --- a/noncore/apps/opie-reader/QTReaderApp.h +++ b/noncore/apps/opie-reader/QTReaderApp.h @@ -1,442 +1,442 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qt Palmtop 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 __QTREADERAPP_H #define __QTREADERAPP_H //#define _SCROLLPIPE //#define __ISEARCH //#define MAX_ENCODING 6 #define MAX_ACTIONS 5 #include "useqpe.h" #include <sys/timeb.h> #include <qmainwindow.h> #include "CExpander.h" #include "CEncoding.h" #include <qlist.h> //#include <qpe/filemanager.h> #include <qmap.h> #include <qlineedit.h> #include <qstack.h> #include <qlistbox.h> //#include "Queue.h" class QWidgetStack; class QToolButton; class QPopupMenu; class QToolBar; #ifdef USEQPE
class QPEToolBar; -class QPEMenuBar;
+class QMenuBar;
#endif class CBkmkSelector; class QProgressBar; class QAction; class CAnnoEdit; class QFloatBar; class CDrawBuffer; class QTReader; class QImage; class Config; enum ActionTypes { cesNone = 0, cesOpenFile, cesAutoScroll, cesActionMark, cesActionAnno, cesFullScreen, cesZoomIn, cesZoomOut, cesBack, cesForward, cesHome, cesPageUp, cesPageDown, cesLineUp, cesLineDown, cesStartDoc, cesEndDoc }; /* *m_preferences_action, *m_close_action *m_info_action, *m_touch_action, *m_find_action, *m_jump_action, *m_setfont_action *m_goto_action, *m_delete_action; *m_autogen_action, *m_clear_action, *m_save_action; *m_tidy_action, *m_startBlock_action, *m_endBlock_action; *m_setenc_action, *m_setmono_action; */ enum ToolbarPolicy { cesSingle = 0, cesMenuTool, cesMultiple }; enum regedit_type { cAutoGen, cAddBkmk, cJump, cMonoSpace, cSetTarget, #ifdef _SCROLLPIPE cSetPipeTarget, #endif cSetConfigName, cMargin, cExtraSpace, cExtraLead }; enum bkmk_action { cOpenFile, cGotoBkmk, cDelBkmk, cRmBkmkFile, cLdConfig, cRmConfig, cExportLinks }; enum fontselector_action { cChooseFont, cChooseEncoding }; #ifdef __ISEARCH struct searchrecord { QString s; size_t pos; searchrecord(const QString& _s, size_t _pos) : s(_s), pos(_pos) {} }; #endif class infowin; class GraphicWin; class QTReaderApp : public QMainWindow { Q_OBJECT unsigned long m_savedpos; int m_debounce; timeb m_lastkeytime; bool m_annoIsEditing; bool m_propogatefontchange, m_bFloatingDialog; bool m_url_clipboard, m_url_localfile, m_url_globalfile; fontselector_action m_fontAction; void doAction(ActionTypes a, QKeyEvent* e); public: QTReaderApp( QWidget *parent = 0, const char *name = 0, WFlags f = 0 ); ~QTReaderApp(); void handlekey(QKeyEvent* e); void hideEvent(QHideEvent*) { suspend(); } void suspend(); void openFile( const QString & ); void setScrollState(bool _b); protected: void setfontHelper(const QString& lcn, int size = 0); QAction* m_bkmkAvail, *m_actFullscreen; CAnnoEdit* m_annoWin; Bkmk* m_anno; // void resizeEvent(QResizeEvent* e); void closeEvent( QCloseEvent *e ); void readbkmks(); void do_mono(const QString&); void do_jump(const QString&); void do_settarget(const QString&); #ifdef _SCROLLPIPE // void do_setpipetarget(const QString&); #endif void do_saveconfig(const QString&, bool); bool readconfig(const QString&, bool); bool PopulateConfig(const char*); ActionTypes ActNameToInt(const QString&); bool m_doAnnotation; bool m_doDictionary; bool m_doClipboard; bool m_fullscreen; bool m_loadedconfig; public: void saveprefs(); public slots: void setDocument(const QString&); private slots: #ifdef _SCRIPT // void RunScript(); #endif void SaveConfig(); void LoadConfig(); void TidyConfig(); void ExportLinks(); void zoomin(); void zoomout(); void chooseencoding(); void setfullscreen(bool sfs); // void setcontinuous(bool sfs); void setTwoTouch(bool _b); void restoreFocus(); void OnAnnotation(bool _b) { m_doAnnotation = _b; } void OnDictionary(bool _b) { m_doDictionary = _b; } void OnClipboard(bool _b) { m_doClipboard = _b; } void OnWordSelected(const QString&, size_t, const QString&); void OnURLSelected(const QString& href); void showgraphic(QImage&); void addAnno(const QString&, const QString&, size_t); void addAnno(const QString&, const QString&); void addanno(); void showAnnotation(); void do_setencoding(int i); void do_setfont(const QString&); void buttonActionSelected(QAction*); // void msgHandler(const QCString&, const QByteArray&); void monospace(bool); void jump(); void settarget(); #ifdef _SCROLLPIPE // void setpipetarget(); // void setpause(bool); #endif // void setspacing(); void setfont(); void clearBkmkList(); void listBkmkFiles(); void editMark(); void autoScroll(bool); void addbkmk(); void savebkmks(); // void importFiles(); void showprefs(); void showtoolbarprefs(); void infoClose(); // void oldFile(); void showinfo(); // void indentplus(); // void indentminus(); void fileOpen(); void fileClose(); void editCopy(); void editFind(); void gotoStart(); void gotoEnd(); void pageup(); void pagedn(); void findNext(); void findClose(); void regClose(); #ifdef __ISEARCH // void search( const QString& ); #else void search(); #endif void showEditTools(); // void stripcr(bool); // void setfulljust(bool); // void onespace(bool); #ifdef REPALM // void repalm(bool); #endif // void peanut(bool _b); // void remap(bool); // void embolden(bool); // void autofmt(bool); // void textfmt(bool); // void striphtml(bool); // void dehyphen(bool); // void depluck(bool); // void dejpluck(bool); // void unindent(bool); // void repara(bool); // void dblspce(bool); void pagemode(bool); // void gotobkmk(const QString& bm); void gotobkmk(int); void cancelbkmk(); void do_gotomark(); void do_delmark(); void do_autogen(); void do_regaction(); void OnRedraw(); private: void writeUrl(const QString& file, const QString& href); QAction *m_preferences_action, *m_open_action, *m_close_action; QAction *m_info_action, *m_touch_action, *m_find_action, *m_start_action; QAction *m_end_action, *m_jump_action, *m_pageline_action; QAction *m_pageup_action, *m_pagedn_action, *m_back_action; QAction *m_home_action, *m_forward_action, *m_zoomin_action; QAction *m_zoomout_action, *m_setfont_action, *m_mark_action; QAction *m_annotate_action, *m_goto_action, *m_delete_action; QAction *m_autogen_action, *m_clear_action, *m_save_action; QAction *m_tidy_action, *m_startBlock_action, *m_endBlock_action; QAction *m_setenc_action, *m_setmono_action, *m_saveconfig_action; QAction *m_loadconfig_action, *m_toolbarprefs_action, *m_tidyconfig_action; QAction *m_exportlinks_action; void addtoolbars(Config* config); ToolbarPolicy m_tbpol, m_tbpolsave; ToolBarDock m_tbposition; bool m_tbmove, m_tbmovesave; QToolBar* filebar(); QToolBar* viewbar(); QToolBar* navbar(); QToolBar* markbar(); void hidetoolbars(); void addfilebar(Config* _config, const QString& key, QAction* a); void addviewbar(Config* _config, const QString& key, QAction* a); void addnavbar(Config* _config, const QString& key, QAction* a); void addmarkbar(Config* _config, const QString& key, QAction* a); bool checkbar(Config* _config, const QString& key); #ifdef _SCRIPT void SaveScript(const char* sname); #endif /* void setstate(unsigned char* _sd, unsigned short _sdlen); void getstate(unsigned char*& data, unsigned short& len); */ void fileOpen2(); void readfilelist(); void savefilelist(); void updatefileinfo(); bool openfrombkmk(Bkmk*); QString m_targetapp, m_targetmsg; bool listbkmk(CList<Bkmk>*, const QString& _lab = QString::null); QString usefilebrowser(); void do_regedit(); void colorChanged( const QColor &c ); void clear(); void updateCaption(); void do_autogen(const QString&); void do_addbkmk(const QString&); bool findNextBookmark(size_t start); private: QAction* m_scrollButton; QAction* m_buttonAction[MAX_ACTIONS]; CBkmkSelector* bkmkselector; ActionTypes m_spaceTarget, m_escapeTarget, m_returnTarget, m_leftTarget, m_rightTarget, m_upTarget, m_downTarget; bool m_leftScroll, m_rightScroll, m_upScroll, m_downScroll; bool m_bcloseDisabled, m_disableesckey; size_t searchStart; #ifdef __ISEARCH QStack<searchrecord>* searchStack; bool dosearch(size_t start, CDrawBuffer& test, const QString& arg); #else bool dosearch(size_t start, CDrawBuffer& test, const QRegExp& arg); #endif QWidgetStack *editorStack; QTReader* reader; QComboBox* m_fontSelector; // QPEToolBar /* *menu,*/ *fileBar; QToolBar *menubar, *fileBar, *navBar, *viewBar, *markBar; #ifdef USEQPE
- QPEMenuBar *mb;
+ QMenuBar *mb;
#else
QMenuBar *mb;
#endif
QFloatBar *searchBar, *regBar/*, *m_fontBar*/; QToolBar /* *searchBar, *regBar,*/ *m_fontBar; QLineEdit *searchEdit, *regEdit; bool searchVisible; bool regVisible; bool m_fontVisible, m_twoTouch; bool bFromDocView; static unsigned long m_uid; long unsigned get_unique_id() { return m_uid++; } /* void resizeEvent( QResizeEvent * r) { // qDebug("resize:(%u,%u)", r->oldSize().width(), r->oldSize().height()); // qDebug("resize:(%u,%u)", r->size().width(), r->size().height()); // bgroup->move( width()-bgroup->width(), 0 ); } */ CList<Bkmk>* pBkmklist; CList<Bkmk>* pOpenlist; infowin* m_infoWin; GraphicWin* m_graphicwin; QProgressBar* pbar; bool m_fBkmksChanged; // int m_nRegAction; regedit_type m_nRegAction; bkmk_action m_nBkmkAction; QString m_autogenstr; bool m_dontSave; }; //const int cAutoGen = 0; //const int cAddBkmk = 1; //const int cDelBkmk = 2; //const int cGotoBkmk = 3; //const int cRmBkmkFile = 4; //const int cJump = 5; //const int cMonoSpace = 6; //const int cOverlap = 7; //const int cSetTarget = 8; //const int cOpenFile = 9; //const int cSetPipeTarget = 10; //const int cSetConfigName = 11; //const int cMargin = 12; //const int cExtraSpace = 14; //const int cExtraLead = 15; //const int cGfxSize = 16; //const int cChooseFont = 2; //const int cChooseEncoding = 1; #endif diff --git a/noncore/apps/opie-sheet/mainwindow.cpp b/noncore/apps/opie-sheet/mainwindow.cpp index 3915e52..fb2ca79 100644 --- a/noncore/apps/opie-sheet/mainwindow.cpp +++ b/noncore/apps/opie-sheet/mainwindow.cpp @@ -1,835 +1,835 @@ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ /* * Opie Sheet (formerly Sheet/Qt) * by Serdar Ozler <sozler@sitebest.com> */ #include "mainwindow.h" #include <qpe/filemanager.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/resource.h> #include <qmessagebox.h> #include <qfile.h> #include <qtranslator.h> #include <qradiobutton.h> #include "cellformat.h" #include "numberdlg.h" #include "textdlg.h" #include "sortdlg.h" #include "finddlg.h" #include "func-plus.xpm" #include "func-minus.xpm" #include "func-cross.xpm" #include "func-divide.xpm" #include "func-paran-open.xpm" #include "func-paran-close.xpm" #include "func-comma.xpm" #include "func-func.xpm" #include "func-equal.xpm" #include "cell-select.xpm" #define DEFAULT_NUM_ROWS 199 #define DEFAULT_NUM_COLS (26*3) #define DEFAULT_NUM_SHEETS 3 MainWindow::MainWindow(QWidget *parent, const char* n, WFlags fl) :QMainWindow(parent, n, fl) { // initialize variables documentModified=FALSE; // construct objects currentDoc=0; fileSelector=new FileSelector("application/sheet-qt", this, QString::null); connect(fileSelector, SIGNAL(closeMe()), this, SLOT(selectorHide())); connect(fileSelector, SIGNAL(newSelected(const DocLnk &)), this, SLOT(selectorFileNew(const DocLnk &))); connect(fileSelector, SIGNAL(fileSelected(const DocLnk &)), this, SLOT(selectorFileOpen(const DocLnk &))); listSheets.setAutoDelete(TRUE); initActions(); initMenu(); initEditToolbar(); initFunctionsToolbar(); initStandardToolbar(); initSheet(); // set window title setCaption(tr("Opie Sheet")); // create sheets selectorFileNew(DocLnk()); } MainWindow::~MainWindow() { if (currentDoc) delete currentDoc; } void MainWindow::documentSave(DocLnk *lnkDoc) { FileManager fm; QByteArray streamBuffer; QDataStream stream(streamBuffer, IO_WriteOnly); typeSheet *currentSheet=findSheet(sheet->getName()); if (!currentSheet) { QMessageBox::critical(this, tr("Error"), tr("Inconsistency error!")); return; } sheet->copySheetData(¤tSheet->data); stream.writeRawBytes("SQT100", 6); stream << (Q_UINT32)listSheets.count(); for (typeSheet *tempSheet=listSheets.first(); tempSheet; tempSheet=listSheets.next()) { stream << tempSheet->name << (Q_UINT32)tempSheet->data.count(); for (typeCellData *tempCell=tempSheet->data.first(); tempCell; tempCell=tempSheet->data.next()) stream << (Q_UINT32)tempCell->col << (Q_UINT32)tempCell->row << tempCell->borders.right << tempCell->borders.bottom << tempCell->background << (Q_UINT32)tempCell->alignment << tempCell->fontColor << tempCell->font << tempCell->data; } lnkDoc->setType("application/sheet-qt"); if (!fm.saveFile(*lnkDoc, streamBuffer)) { QMessageBox::critical(this, tr("Error"), tr("File cannot be saved!")); return; } documentModified=FALSE; } void MainWindow::documentOpen(const DocLnk &lnkDoc) { FileManager fm; QByteArray streamBuffer; if (!lnkDoc.isValid() || !fm.loadFile(lnkDoc, streamBuffer)) { QMessageBox::critical(this, tr("Error"), tr("File cannot be opened!")); documentModified=FALSE; selectorFileNew(DocLnk()); return; } QDataStream stream(streamBuffer, IO_ReadOnly); Q_UINT32 countSheet, countCell, i, j, row, col, alignment; typeSheet *newSheet; typeCellData *newCell; char fileFormat[7]; stream.readRawBytes(fileFormat, 6); fileFormat[6]=0; if ((QString)fileFormat!="SQT100") { QMessageBox::critical(this, tr("Error"), tr("Invalid file format!")); documentModified=FALSE; selectorFileNew(DocLnk()); return; } stream >> countSheet; for (i=0; i<countSheet; ++i) { newSheet=new typeSheet; newSheet->data.setAutoDelete(TRUE); stream >> newSheet->name >> countCell; comboSheets->insertItem(newSheet->name); for (j=0; j<countCell; ++j) { newCell=new typeCellData; stream >> col >> row >> newCell->borders.right >> newCell->borders.bottom >> newCell->background >> alignment >> newCell->fontColor >> newCell->font >> newCell->data; newCell->col=col; newCell->row=row; newCell->alignment=(Qt::AlignmentFlags)alignment; newSheet->data.append(newCell); } listSheets.append(newSheet); if (i==0) { sheet->setName(newSheet->name); sheet->setSheetData(&newSheet->data); } } } int MainWindow::saveCurrentFile(bool ask) { if (ask) { int result=QMessageBox::information(this, tr("Save File"), tr("Do you want to save the current file?"), QMessageBox::Yes, QMessageBox::No, QMessageBox::Cancel); if (result!=QMessageBox::Yes) return result; } if (!currentDoc->isValid()) { TextDialog dialogText(this); if (dialogText.exec(tr("Save File"), tr("&File Name:"), tr("UnnamedFile"))!=QDialog::Accepted || dialogText.getValue().isEmpty()) return QMessageBox::Cancel; currentDoc->setName(dialogText.getValue()); currentDoc->setFile(QString::null); currentDoc->setLinkFile(QString::null); } documentSave(currentDoc); return QMessageBox::Yes; } void MainWindow::selectorFileNew(const DocLnk &lnkDoc) { selectorHide(); if (documentModified && saveCurrentFile()==QMessageBox::Cancel) return; if (currentDoc) delete currentDoc; currentDoc = new DocLnk(lnkDoc); editData->clear(); listSheets.clear(); comboSheets->clear(); typeSheet *newSheet=createNewSheet(); newSheet->data.setAutoDelete(TRUE); sheet->setName(newSheet->name); sheet->setSheetData(&newSheet->data); for (int i=1; i<DEFAULT_NUM_SHEETS; ++i) createNewSheet(); documentModified=FALSE; } void MainWindow::closeEvent(QCloseEvent *e) { if (documentModified && saveCurrentFile()==QMessageBox::Cancel) e->ignore(); else e->accept(); } void MainWindow::selectorFileOpen(const DocLnk &lnkDoc) { selectorHide(); if (documentModified && saveCurrentFile()==QMessageBox::Cancel) return; if (currentDoc) delete currentDoc; currentDoc = new DocLnk(lnkDoc); listSheets.clear(); comboSheets->clear(); documentOpen(lnkDoc); documentModified=FALSE; } void MainWindow::selectorShow() { sheet->hide(); setCentralWidget(fileSelector); fileSelector->show(); fileSelector->reread(); } void MainWindow::selectorHide() { fileSelector->hide(); setCentralWidget(sheet); sheet->show(); } void MainWindow::slotFileNew() { selectorFileNew(DocLnk()); } void MainWindow::slotFileOpen() { selectorShow(); } void MainWindow::slotFileSave() { saveCurrentFile(FALSE); } void MainWindow::setDocument(const QString &applnk_filename) { selectorFileOpen(DocLnk(applnk_filename)); } void MainWindow::initActions() { fileNew=new QAction(tr("New File"), Resource::loadPixmap( "new" ), tr("&New"), 0, this); connect(fileNew, SIGNAL(activated()), this, SLOT(slotFileNew())); fileOpen=new QAction(tr("Open File"), Resource::loadPixmap( "fileopen" ), tr("&Open"), 0, this); connect(fileOpen, SIGNAL(activated()), this, SLOT(slotFileOpen())); fileSave=new QAction(tr("Save File"),Resource::loadPixmap( "save" ), tr("&Save"), 0, this); connect(fileSave, SIGNAL(activated()), this, SLOT(slotFileSave())); fileSaveAs=new QAction(tr("Save File As"), Resource::loadPixmap( "save" ), tr("Save &As"), 0, this); connect(fileSaveAs, SIGNAL(activated()), this, SLOT(slotFileSaveAs())); //fileQuit=new QAction(tr("Quit"), tr("&Quit"), 0, this); //connect(fileQuit, SIGNAL(activated()), this, SLOT(close())); // helpGeneral=new QAction(tr("General Help"), QPixmap(help_general_xpm), tr("&General"), 0, this); //connect(helpGeneral, SIGNAL(activated()), this, SLOT(slotHelpGeneral())); //helpAbout=new QAction(tr("About Opie Sheet"), tr("&About"), 0, this); //connect(helpAbout, SIGNAL(activated()), this, SLOT(slotHelpAbout())); editAccept=new QAction(tr("Accept"),Resource::loadPixmap( "enter" ) , tr("&Accept"), 0, this); connect(editAccept, SIGNAL(activated()), this, SLOT(slotEditAccept())); editCancel=new QAction(tr("Cancel"), Resource::loadPixmap( "close" ), tr("&Cancel"), 0, this); connect(editCancel, SIGNAL(activated()), this, SLOT(slotEditCancel())); editCellSelect=new QAction(tr("Cell Selector"), QPixmap(cell_select_xpm), tr("Cell &Selector"), 0, this); editCellSelect->setToggleAction(TRUE); connect(editCellSelect, SIGNAL(toggled(bool)), this, SLOT(slotCellSelect(bool))); editCut=new QAction(tr("Cut Cells"), tr("Cu&t"), 0, this); editCopy=new QAction(tr("Copy Cells"), tr("&Copy"), 0, this); editPaste=new QAction(tr("Paste Cells"), tr("&Paste"), 0, this); connect(editPaste, SIGNAL(activated()), this, SLOT(slotEditPaste())); editPasteContents=new QAction(tr("Paste Contents"), tr("Paste Cont&ents"), 0, this); connect(editPasteContents, SIGNAL(activated()), this, SLOT(slotEditPasteContents())); editClear=new QAction(tr("Clear Cells"), tr("C&lear"), 0, this); insertCells=new QAction(tr("Insert Cells"), tr("C&ells"), 0, this); connect(insertCells, SIGNAL(activated()), this, SLOT(slotInsertCells())); insertRows=new QAction(tr("Insert Rows"), tr("&Rows"), 0, this); connect(insertRows, SIGNAL(activated()), this, SLOT(slotInsertRows())); insertCols=new QAction(tr("Insert Columns"), tr("&Columns"), 0, this); connect(insertCols, SIGNAL(activated()), this, SLOT(slotInsertCols())); insertSheets=new QAction(tr("Add Sheets"), tr("&Sheets"), 0, this); connect(insertSheets, SIGNAL(activated()), this, SLOT(slotInsertSheets())); formatCells=new QAction(tr("Cells"), tr("&Cells"), 0, this); connect(formatCells, SIGNAL(activated()), this, SLOT(slotFormatCells())); rowHeight=new QAction(tr("Row Height"), tr("H&eight"), 0, this); connect(rowHeight, SIGNAL(activated()), this, SLOT(slotRowHeight())); rowAdjust=new QAction(tr("Adjust Row"), tr("&Adjust"), 0, this); connect(rowAdjust, SIGNAL(activated()), this, SLOT(slotRowAdjust())); rowShow=new QAction(tr("Show Row"), tr("&Show"), 0, this); connect(rowShow, SIGNAL(activated()), this, SLOT(slotRowShow())); rowHide=new QAction(tr("Hide Row"), tr("&Hide"), 0, this); connect(rowHide, SIGNAL(activated()), this, SLOT(slotRowHide())); colWidth=new QAction(tr("Column Width"), tr("&Width"), 0, this); connect(colWidth, SIGNAL(activated()), this, SLOT(slotColumnWidth())); colAdjust=new QAction(tr("Adjust Column"), tr("&Adjust"), 0, this); connect(colAdjust, SIGNAL(activated()), this, SLOT(slotColumnAdjust())); colShow=new QAction(tr("Show Column"), tr("&Show"), 0, this); connect(colShow, SIGNAL(activated()), this, SLOT(slotColumnShow())); colHide=new QAction(tr("Hide Column"), tr("&Hide"), 0, this); connect(colHide, SIGNAL(activated()), this, SLOT(slotColumnHide())); sheetRename=new QAction(tr("Rename Sheet"), tr("&Rename"), 0, this); connect(sheetRename, SIGNAL(activated()), this, SLOT(slotSheetRename())); sheetRemove=new QAction(tr("Remove Sheet"), tr("R&emove"), 0, this); connect(sheetRemove, SIGNAL(activated()), this, SLOT(slotSheetRemove())); dataSort=new QAction(tr("Sort Data"), tr("&Sort"), 0, this); connect(dataSort, SIGNAL(activated()), this, SLOT(slotDataSort())); dataFindReplace=new QAction(tr("Find && Replace"), tr("&Find && Replace"), 0, this); connect(dataFindReplace, SIGNAL(activated()), this, SLOT(slotDataFindReplace())); funcEqual=new QAction(tr("Equal To"), QPixmap(func_equal_xpm), tr("&Equal To"), 0, this); funcEqual->setToolTip("="); connect(funcEqual, SIGNAL(activated()), this, SLOT(slotFuncOutput())); funcPlus=new QAction(tr("Addition"), QPixmap(func_plus_xpm), tr("&Addition"), 0, this); funcPlus->setToolTip("+"); connect(funcPlus, SIGNAL(activated()), this, SLOT(slotFuncOutput())); funcMinus=new QAction(tr("Subtraction"), QPixmap(func_minus_xpm), tr("&Subtraction"), 0, this); funcMinus->setToolTip("-"); connect(funcMinus, SIGNAL(activated()), this, SLOT(slotFuncOutput())); funcCross=new QAction(tr("Multiplication"), QPixmap(func_cross_xpm), tr("&Multiplication"), 0, this); funcCross->setToolTip("*"); connect(funcCross, SIGNAL(activated()), this, SLOT(slotFuncOutput())); funcDivide=new QAction(tr("Division"), QPixmap(func_divide_xpm), tr("&Division"), 0, this); funcDivide->setToolTip("/"); connect(funcDivide, SIGNAL(activated()), this, SLOT(slotFuncOutput())); funcParanOpen=new QAction(tr("Open ParanthesistempCellData->row+row1, tempCellData->col+col1"), QPixmap(func_paran_open_xpm), tr("&Open Paranthesis"), 0, this); funcParanOpen->setToolTip("("); connect(funcParanOpen, SIGNAL(activated()), this, SLOT(slotFuncOutput())); funcParanClose=new QAction(tr("Close Paranthesis"), QPixmap(func_paran_close_xpm), tr("&Close Paranthesis"), 0, this); funcParanClose->setToolTip(")"); connect(funcParanClose, SIGNAL(activated()), this, SLOT(slotFuncOutput())); funcComma=new QAction(tr("Comma"), QPixmap(func_comma_xpm), tr("&Comma"), 0, this); funcComma->setToolTip(","); connect(funcComma, SIGNAL(activated()), this, SLOT(slotFuncOutput())); } void MainWindow::initMenu() { - menu=new QPEMenuBar(this); + menu=new QMenuBar(this); menuFile=new QPopupMenu; fileNew->addTo(menuFile); fileOpen->addTo(menuFile); fileSave->addTo(menuFile); fileSaveAs->addTo(menuFile); // menuFile->insertSeparator(); // fileQuit->addTo(menuFile); menu->insertItem(tr("&File"), menuFile); menuEdit=new QPopupMenu; editAccept->addTo(menuEdit); editCancel->addTo(menuEdit); editCellSelect->addTo(menuEdit); menuEdit->insertSeparator(); editCut->addTo(menuEdit); editCopy->addTo(menuEdit); editPaste->addTo(menuEdit); editPasteContents->addTo(menuEdit); editClear->addTo(menuEdit); menu->insertItem(tr("&Edit"), menuEdit); menuInsert=new QPopupMenu; menu->insertItem(tr("&Insert"), menuInsert); menuFormat=new QPopupMenu; formatCells->addTo(menuFormat); menu->insertItem(tr("&Format"), menuFormat); menuData=new QPopupMenu; dataSort->addTo(menuData); dataFindReplace->addTo(menuData); menu->insertItem(tr("&Data"), menuData); // menuHelp=new QPopupMenu; // helpGeneral->addTo(menuHelp); // helpAbout->addTo(menuHelp); // menu->insertItem(tr("&Help"), menuHelp); submenuRow=new QPopupMenu; rowHeight->addTo(submenuRow); rowAdjust->addTo(submenuRow); rowShow->addTo(submenuRow); rowHide->addTo(submenuRow); menuFormat->insertItem(tr("&Row"), submenuRow); submenuCol=new QPopupMenu; colWidth->addTo(submenuCol); colAdjust->addTo(submenuCol); colShow->addTo(submenuCol); colHide->addTo(submenuCol); menuFormat->insertItem(tr("Colum&n"), submenuCol); submenuSheet=new QPopupMenu; sheetRename->addTo(submenuSheet); sheetRemove->addTo(submenuSheet); menuFormat->insertItem(tr("&Sheet"), submenuSheet); submenuFunc=new QPopupMenu; menuInsert->insertItem(tr("&Function"), submenuFunc); submenuFuncStd=new QPopupMenu; funcPlus->addTo(submenuFuncStd); funcMinus->addTo(submenuFuncStd); funcCross->addTo(submenuFuncStd); funcDivide->addTo(submenuFuncStd); submenuFunc->insertItem(tr("&Standard"), submenuFuncStd); submenuFuncMath=new QPopupMenu; addFlyAction(tr("Summation"), tr("&Summation"), "SUM(", submenuFuncMath); addFlyAction(tr("Absolute Value"), tr("&Absolute"), "ABS(", submenuFuncMath); submenuFuncMath->insertSeparator(); addFlyAction(tr("Sine"), tr("Si&ne"), "SIN(", submenuFuncMath); addFlyAction(tr("Arc Sine"), tr("A&rc Sine"), "ASIN(", submenuFuncMath); addFlyAction(tr("Cosine"), tr("&Cosine"), "COS(", submenuFuncMath); addFlyAction(tr("ArcCosine"), tr("Arc Cos&ine"), "COS(", submenuFuncMath); addFlyAction(tr("Tangent"), tr("&Tangent"), "TAN(", submenuFuncMath); addFlyAction(tr("Arc Tangent"), tr("Arc Tan&gent"), "ATAN(", submenuFuncMath); addFlyAction(tr("Arc Tangent of Coordinates"), tr("C&oor. Arc Tangent"), "ATAN2(", submenuFuncMath); submenuFuncMath->insertSeparator(); addFlyAction(tr("Exponential"), tr("&Exponential"), "EXP(", submenuFuncMath); addFlyAction(tr("Logarithm"), tr("&Logarithm"), "LOG(", submenuFuncMath); addFlyAction(tr("Power"), tr("&Power"), "POW(", submenuFuncMath); submenuFunc->insertItem(tr("&Mathematical"), submenuFuncMath); submenuFuncStat=new QPopupMenu; addFlyAction(tr("Average"), tr("&Average"), "AVG(", submenuFuncStat); addFlyAction(tr("Maximum"), tr("Ma&ximum"), "MAX(", submenuFuncStat); addFlyAction(tr("Minimum"), tr("&Minimum"), "MIN(", submenuFuncStat); addFlyAction(tr("Count"), tr("&Count"), "COUNT(", submenuFuncStat); submenuFunc->insertItem(tr("&Statistical"), submenuFuncStat); menuInsert->insertSeparator(); insertCells->addTo(menuInsert); insertRows->addTo(menuInsert); insertCols->addTo(menuInsert); insertSheets->addTo(menuInsert); } void MainWindow::initStandardToolbar() { toolbarStandard=new QPEToolBar(this); toolbarStandard->setHorizontalStretchable(TRUE); moveToolBar(toolbarStandard, Top); fileNew->addTo(toolbarStandard); fileOpen->addTo(toolbarStandard); fileSave->addTo(toolbarStandard); comboSheets=new QComboBox(toolbarStandard); toolbarStandard->setStretchableWidget(comboSheets); connect(comboSheets, SIGNAL(activated(const QString &)), this, SLOT(slotSheetChanged(const QString &))); } void MainWindow::initFunctionsToolbar() { toolbarFunctions=new QPEToolBar(this); toolbarFunctions->setHorizontalStretchable(TRUE); moveToolBar(toolbarFunctions, Bottom); funcEqual->addTo(toolbarFunctions); funcPlus->addTo(toolbarFunctions); funcMinus->addTo(toolbarFunctions); funcCross->addTo(toolbarFunctions); funcDivide->addTo(toolbarFunctions); funcParanOpen->addTo(toolbarFunctions); funcParanClose->addTo(toolbarFunctions); funcComma->addTo(toolbarFunctions); toolFunction=new QToolButton(toolbarFunctions); toolFunction->setPixmap(func_func_xpm); toolFunction->setTextLabel(tr("Functions")); toolFunction->setPopup(submenuFunc); toolFunction->setPopupDelay(0); } void MainWindow::initEditToolbar() { toolbarEdit=new QPEToolBar(this); toolbarEdit->setHorizontalStretchable(TRUE); moveToolBar(toolbarEdit, Bottom); editAccept->addTo(toolbarEdit); editCancel->addTo(toolbarEdit); editData=new QLineEdit(toolbarEdit); toolbarEdit->setStretchableWidget(editData); connect(editData, SIGNAL(returnPressed()), this, SLOT(slotEditAccept())); editCellSelect->addTo(toolbarEdit); } void MainWindow::slotHelpAbout() { QDialog dialogAbout(this, 0, TRUE); dialogAbout.resize(width()-40, height()-80); dialogAbout.setCaption(tr("About Opie Sheet")); QLabel label(tr("Opie Sheet\nSpreadsheet Software for Opie\nQWDC Beta Winner (as Sheet/Qt)\n\nDeveloped by: Serdar Ozler\nRelease 1.0.2\nRelease Date: October 08, 2002\n\nThis product is licensed under GPL. It is freely distributable. If you want to get the latest version and also the source code, please visit the web site.\n\nhttp://qtopia.sitebest.com"), &dialogAbout); label.setGeometry(dialogAbout.rect()); label.setAlignment(Qt::AlignCenter | Qt::WordBreak); dialogAbout.exec(); } void MainWindow::initSheet() { sheet=new Sheet(DEFAULT_NUM_ROWS, DEFAULT_NUM_COLS, this); setCentralWidget(sheet); connect(sheet, SIGNAL(currentDataChanged(const QString &)), editData, SLOT(setText(const QString &))); connect(sheet, SIGNAL(cellClicked(const QString &)), this, SLOT(slotCellClicked(const QString &))); connect(sheet, SIGNAL(sheetModified()), this, SLOT(slotDocModified())); connect(editCut, SIGNAL(activated()), sheet, SLOT(editCut())); connect(editCopy, SIGNAL(activated()), sheet, SLOT(editCopy())); connect(editClear, SIGNAL(activated()), sheet, SLOT(editClear())); } void MainWindow::slotEditAccept() { sheet->setData(editData->text()); } void MainWindow::slotEditCancel() { editData->setText(sheet->getData()); } void MainWindow::slotCellSelect(bool lock) { sheet->lockClicks(lock); } void MainWindow::addToData(const QString &data) { editData->setText(editData->text().insert(editData->cursorPosition(), data)); } void MainWindow::slotFuncOutput() { if (sender()->isA("QAction")) addToData(((QAction *)sender())->toolTip()); } void MainWindow::slotInsertRows() { NumberDialog dialogNumber(this); if (dialogNumber.exec(tr("Insert Rows"), tr("&Number of rows:"))==QDialog::Accepted) sheet->insertRows(dialogNumber.getValue()); } void MainWindow::slotInsertCols() { NumberDialog dialogNumber(this); if (dialogNumber.exec(tr("Insert Columns"), tr("&Number of columns:"))==QDialog::Accepted) sheet->insertColumns(dialogNumber.getValue()); } void MainWindow::slotInsertSheets() { NumberDialog dialogNumber(this); if (dialogNumber.exec(tr("Add Sheets"), tr("&Number of sheets:"))==QDialog::Accepted) for (int i=dialogNumber.getValue(); i>0; --i) createNewSheet(); } void MainWindow::slotCellClicked(const QString &cell) { editCellSelect->setOn(FALSE); addToData(cell); } typeSheet *MainWindow::createNewSheet() { typeSheet *newSheet=new typeSheet; int currentNo=1, tempNo; bool ok; for (typeSheet *tempSheet=listSheets.first(); tempSheet; tempSheet=listSheets.next()) if (tempSheet->name.startsWith(tr("Sheet")) && (tempNo=tempSheet->name.mid(tr("Sheet").length()).toInt(&ok))>=currentNo && ok) currentNo=tempNo+1; newSheet->name=tr("Sheet")+QString::number(currentNo); newSheet->data.setAutoDelete(TRUE); comboSheets->insertItem(newSheet->name); listSheets.append(newSheet); return newSheet; } typeSheet *MainWindow::findSheet(const QString &name) { for (typeSheet *tempSheet=listSheets.first(); tempSheet; tempSheet=listSheets.next()) if (tempSheet->name==name) return tempSheet; return NULL; } void MainWindow::slotSheetChanged(const QString &name) { sheet->copySheetData(&findSheet(sheet->getName())->data); sheet->setName(name); sheet->setSheetData(&findSheet(name)->data); } void MainWindow::addFlyAction(const QString &text, const QString &menuText, const QString &tip, QWidget *w) { QAction *action=new QAction(text, menuText, 0, this); action->setToolTip(tip); connect(action, SIGNAL(activated()), this, SLOT(slotFuncOutput())); action->addTo(w); } void MainWindow::slotFormatCells() { CellFormat dialogCellFormat(this); dialogCellFormat.showMaximized(); dialogCellFormat.exec(sheet); } void MainWindow::slotEditPaste() { sheet->editPaste(); } void MainWindow::slotEditPasteContents() { sheet->editPaste(TRUE); } void MainWindow::slotRowHeight() { int row1, row2, col1, col2; sheet->getSelection(&row1, &col1, &row2, &col2); NumberDialog dialogNumber(this); if (dialogNumber.exec(tr("Row Height"), tr("&Height of each row:"), sheet->rowHeight(row1))==QDialog::Accepted) { int newHeight=dialogNumber.getValue(), row; for (row=row1; row<=row2; ++row) sheet->setRowHeight(row, newHeight); } } void MainWindow::slotRowAdjust() { int row1, row2, col1, col2; sheet->getSelection(&row1, &col1, &row2, &col2); for (int row=row1; row<=row2; ++row) sheet->adjustRow(row); } void MainWindow::slotRowShow() { int row1, row2, col1, col2; sheet->getSelection(&row1, &col1, &row2, &col2); for (int row=row1; row<=row2; ++row) sheet->showRow(row); } void MainWindow::slotRowHide() { int row1, row2, col1, col2; sheet->getSelection(&row1, &col1, &row2, &col2); for (int row=row1; row<=row2; ++row) sheet->hideRow(row); } void MainWindow::slotColumnWidth() { int row1, row2, col1, col2; sheet->getSelection(&row1, &col1, &row2, &col2); NumberDialog dialogNumber(this); if (dialogNumber.exec(tr("Column Width"), tr("&Width of each column:"), sheet->columnWidth(col1))==QDialog::Accepted) { int newWidth=dialogNumber.getValue(), col; for (col=col1; col<=col2; ++col) sheet->setColumnWidth(col, newWidth); } } void MainWindow::slotColumnAdjust() { int row1, row2, col1, col2; sheet->getSelection(&row1, &col1, &row2, &col2); for (int col=col1; col<=col2; ++col) sheet->adjustColumn(col); } void MainWindow::slotColumnShow() { int row1, row2, col1, col2; sheet->getSelection(&row1, &col1, &row2, &col2); for (int col=col1; col<=col2; ++col) sheet->showColumn(col); } void MainWindow::slotColumnHide() { int row1, row2, col1, col2; sheet->getSelection(&row1, &col1, &row2, &col2); for (int col=col1; col<=col2; ++col) sheet->hideColumn(col); } void MainWindow::slotFileSaveAs() { TextDialog dialogText(this); if (dialogText.exec(tr("Save File As"), tr("&File Name:"), currentDoc->name())!=QDialog::Accepted || dialogText.getValue().isEmpty()) return; currentDoc->setName(dialogText.getValue()); currentDoc->setFile(QString::null); currentDoc->setLinkFile(QString::null); documentSave(currentDoc); } void MainWindow::slotSheetRename() { TextDialog dialogText(this); if (dialogText.exec(tr("Rename Sheet"), tr("&Sheet Name:"), sheet->getName())!=QDialog::Accepted || dialogText.getValue().isEmpty()) return; QString newName=dialogText.getValue(); typeSheet *tempSheet=findSheet(newName); if (tempSheet) { QMessageBox::critical(this, tr("Error"), tr("There is already a sheet named '"+newName+'\'')); return; } tempSheet=findSheet(sheet->getName()); for (int i=0; i<comboSheets->count(); ++i) if (comboSheets->text(i)==tempSheet->name) { comboSheets->changeItem(newName, i); break; } tempSheet->name=newName; sheet->setName(newName); } void MainWindow::slotSheetRemove() { if (comboSheets->count()<2) { QMessageBox::warning(this, tr("Error"), tr("There is only one sheet!")); return; } if (QMessageBox::information(this, tr("Remove Sheet"), tr("Are you sure?"), QMessageBox::Yes, QMessageBox::No)==QMessageBox::Yes) { typeSheet *tempSheet=findSheet(sheet->getName()); for (int i=0; i<comboSheets->count(); ++i) if (comboSheets->text(i)==tempSheet->name) { comboSheets->removeItem(i); break; } comboSheets->setCurrentItem(0); slotSheetChanged(comboSheets->currentText()); listSheets.remove(tempSheet); } } void MainWindow::slotDataSort() { SortDialog dialogSort(this); dialogSort.showMaximized(); dialogSort.exec(sheet); } void MainWindow::slotDocModified() { documentModified=TRUE; } void MainWindow::slotInsertCells() { QDialog dialogInsert(this, 0, TRUE); dialogInsert.resize(180, 130); dialogInsert.setCaption(tr("Insert Cells")); QVButtonGroup *group=new QVButtonGroup(tr("&Type"), &dialogInsert); group->setGeometry(10, 10, 160, 110); QRadioButton *radio=new QRadioButton(tr("Shift cells &down"), group); radio=new QRadioButton(tr("Shift cells &right"), group); radio=new QRadioButton(tr("Entire ro&w"), group); radio=new QRadioButton(tr("Entire &column"), group); group->setButton(0); if (dialogInsert.exec()==QDialog::Accepted) switch (group->id(group->selected())) { case 0: sheet->insertRows(1, FALSE); break; case 1: sheet->insertColumns(1, FALSE); break; case 2: sheet->insertRows(1, TRUE); break; case 3: sheet->insertColumns(1, TRUE); break; } } void MainWindow::slotDataFindReplace() { FindDialog dialogFind(this); dialogFind.showMaximized(); dialogFind.exec(sheet); } diff --git a/noncore/apps/opie-sheet/mainwindow.h b/noncore/apps/opie-sheet/mainwindow.h index 370d82e..4007f88 100644 --- a/noncore/apps/opie-sheet/mainwindow.h +++ b/noncore/apps/opie-sheet/mainwindow.h @@ -1,133 +1,133 @@ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ /* * Opie Sheet (formerly Sheet/Qt) * by Serdar Ozler <sozler@sitebest.com> */ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <qpe/applnk.h> #include <qpe/fileselector.h> -#include <qpe/qpemenubar.h> +#include <qmenubar.h> #include <qpe/qpetoolbar.h> #include <qmainwindow.h> #include <qaction.h> #include <qlineedit.h> #include <qbutton.h> #include <qcombobox.h> #include <qtoolbutton.h> #include "sheet.h" typedef struct typeSheet { QString name; QList<typeCellData> data; }; class MainWindow: public QMainWindow { Q_OBJECT // QPE objects DocLnk* currentDoc; - QPEMenuBar *menu; + QMenuBar *menu; QPEToolBar *toolbarFunctions, *toolbarEdit, *toolbarStandard; FileSelector *fileSelector; // QT objects QPopupMenu *menuFile, *menuEdit, *menuInsert, *menuFormat, *menuData, *menuHelp, *submenuFunc, *submenuFuncStd, *submenuFuncMath, *submenuFuncStat, *submenuRow, *submenuCol, *submenuSheet; QAction *fileNew, *fileOpen, *fileSave, *fileSaveAs, *fileQuit, *helpAbout, *editAccept, *editCancel, *formatCells, *funcPlus, *funcMinus, *funcCross, *funcDivide, *funcParanOpen, *funcParanClose, *funcComma, *funcEqual, *editCut, *editCopy, *editPaste, *editPasteContents, *editClear, *insertCols, *insertRows, *insertSheets, *insertCells, *rowHeight, *rowShow, *rowHide, *rowAdjust, *colWidth, *colShow, *colHide, *colAdjust, *sheetRename, *sheetRemove, *dataSort, *dataFindReplace, *editCellSelect, *helpGeneral; QLineEdit *editData; QButton *buttonUp, *buttonDown, *buttonLeft, *buttonRight; QComboBox *comboSheets; QToolButton *toolFunction; QList<typeSheet> listSheets; QString helpFile; // Other objects Sheet *sheet; // Variables bool documentModified; // Private functions void initMenu(); void initActions(); void initFunctionsToolbar(); void initEditToolbar(); void initStandardToolbar(); void initSheet(); void addToData(const QString &data); int saveCurrentFile(bool ask=TRUE); void documentOpen(const DocLnk &lnkDoc); void documentSave(DocLnk *lnkDoc); void closeEvent(QCloseEvent *e); void addFlyAction(const QString &text, const QString &menuText, const QString &tip, QWidget *w); typeSheet *createNewSheet(); typeSheet *findSheet(const QString &name); private slots: void slotFileNew(); void slotFileOpen(); void slotFileSave(); void slotFileSaveAs(); void slotHelpAbout(); void slotEditAccept(); void slotEditCancel(); void slotEditPaste(); void slotEditPasteContents(); void slotFormatCells(); void slotInsertCells(); void slotInsertRows(); void slotInsertCols(); void slotInsertSheets(); void slotDataSort(); void slotDataFindReplace(); void slotRowHeight(); void slotRowAdjust(); void slotRowShow(); void slotRowHide(); void slotColumnWidth(); void slotColumnAdjust(); void slotColumnShow(); void slotColumnHide(); void slotSheetRename(); void slotSheetRemove(); void slotFuncOutput(); void slotCellSelect(bool lock); void slotCellClicked(const QString &cell); void slotSheetChanged(const QString &name); void slotDocModified(); void selectorShow(); void selectorHide(); void selectorFileNew(const DocLnk &lnkDoc); void selectorFileOpen(const DocLnk &lnkDoc); public: static QString appName() { return QString::fromLatin1("sheetqt"); } MainWindow(QWidget *p, const char*, WFlags); ~MainWindow(); void setHelpFile(const QString &help_filename) { helpFile=help_filename; } public slots: void setDocument(const QString &applnk_filename); }; #endif diff --git a/noncore/apps/qashmoney/budgetdisplay.cpp b/noncore/apps/qashmoney/budgetdisplay.cpp index afc6a2d..492595a 100755 --- a/noncore/apps/qashmoney/budgetdisplay.cpp +++ b/noncore/apps/qashmoney/budgetdisplay.cpp @@ -1,420 +1,420 @@ #include <qmessagebox.h> #include <qheader.h> #include <qfont.h> #include <sqlite.h> #include "budgetdisplay.h" #include "budget.h" #include "newaccount.h" #include "datepicker.h" #include "preferences.h" #include "transaction.h" extern Preferences *preferences; extern Budget *budget; extern Transaction *transaction; BudgetDisplay::BudgetDisplay ( QWidget *parent ) : QWidget ( parent ) { QFont font = this->font(); font.setWeight ( QFont::Bold ); //set the default date to today newDate = QDate::currentDate (); year = newDate.year(); month = newDate.month(); day = newDate.day(); datelabel = preferences->getDate ( year, month ); setCaption ( "Budget" ); firstline = new QHBox ( this ); firstline->setSpacing ( 2 ); secondline = new QHBox ( this ); secondline->setSpacing ( 10 ); - menu = new QPEMenuBar ( this ); + menu = new QMenuBar ( this ); menu->setFrameStyle ( QFrame::Box | QFrame::Sunken ); budgetmenu = new QPopupMenu ( this ); lineitemsmenu = new QPopupMenu ( this ); datemenu = new QPopupMenu ( this ); menu->insertItem ( "Budget", budgetmenu ); menu->insertItem ( "Line Item", lineitemsmenu ); menu->insertItem ( "Date", datemenu ); budgetmenu->insertItem ( "New", this, SLOT ( newBudget () ), 0, 1 ); budgetmenu->insertItem ( "Edit", this, SLOT ( editBudget () ), 0, 2 ); budgetmenu->insertItem ( "Delete", this, SLOT ( deleteBudget () ), 0, 3 ); lineitemsmenu->insertItem ( "New", this, SLOT ( newLineItem () ), 0, 1 ); lineitemsmenu->insertItem ( "Edit", this, SLOT ( editLineItem () ), 0, 2 ); lineitemsmenu->insertItem ( "Delete", this, SLOT ( deleteLineItem () ), 0, 3 ); datemenu->insertItem ( "Change", this, SLOT ( showCalendar() ) ); budgetbox = new QComboBox ( firstline ); connect ( budgetbox, SIGNAL ( activated ( int ) ), this, SLOT ( setCurrentBudget ( int ) ) ); budgetview = new QComboBox ( firstline ); budgetview->insertItem ( "Month" ); budgetview->insertItem ( "Year" ); connect ( budgetview, SIGNAL ( activated ( int ) ), this, SLOT ( setCurrentView ( int ) ) ); budgeted = new QLabel ( secondline ); budgeted->setFont ( font ); actual = new QLabel ( secondline ); actual->setFont ( font ); date = new QLabel ( secondline ); date->setFont ( font ); listview = new QListView ( this ); listview->setAllColumnsShowFocus ( TRUE ); listview->setShowSortIndicator ( TRUE ); listview->setRootIsDecorated ( TRUE ); listview->setMultiSelection ( FALSE ); listview->addColumn ( "Line Item", preferences->getColumnPreference ( 13 ) ); // column id 13 listview->addColumn ( "Budget", preferences->getColumnPreference ( 14 ) ); // column id 14 listview->addColumn ( "Actual", preferences->getColumnPreference ( 15 ) ); // column id 15 listview->addColumn ( "", 0 ); // line item ids listview->setColumnWidthMode ( 0, QListView::Manual ); listview->setColumnWidthMode ( 1, QListView::Manual ); listview->setColumnWidthMode ( 2, QListView::Manual ); listview->setColumnAlignment ( 1, Qt::AlignRight ); listview->setColumnAlignment ( 2, Qt::AlignRight ); listview->setColumnWidthMode ( 3, QListView::Manual ); listview->header()->setTracking ( FALSE ); connect ( listview->header(), SIGNAL ( sizeChange ( int, int, int ) ), this, SLOT ( saveColumnSize ( int, int, int ) ) ); connect ( listview->header(), SIGNAL ( clicked ( int ) ), this, SLOT ( saveSortingPreference ( int ) ) ); // pull the column sorting preference from the preferences table, and configure the listview accordingly int column = 0; int direction = 0; preferences->getSortingPreference ( 3, &column, &direction ); listview->setSorting ( column, direction ); displayBudgetNames(); layout = new QVBoxLayout ( this, 2, 2 ); layout->setMenuBar ( menu ); layout->addWidget ( firstline ); layout->addWidget ( secondline ); layout->addWidget ( listview ); } void BudgetDisplay::deleteBudget () { listview->clear(); transaction->clearBudgetIDs ( currentbudget ); budget->deleteBudget ( currentbudget ); if ( budgetbox->count() != 0 ) displayBudgetNames(); checkBudgets(); } void BudgetDisplay::saveColumnSize ( int column, int oldsize, int newsize ) { switch ( column ) { case 0: preferences->changeColumnPreference ( 13, newsize ); break; case 1: preferences->changeColumnPreference ( 14, newsize ); break; case 2: preferences->changeColumnPreference ( 15, newsize ); break; } } void BudgetDisplay::saveSortingPreference ( int column ) { preferences->changeSortingPreference ( 3, column ); } int BudgetDisplay::getIDColumn () { int counter; int columns = listview->columns(); for ( counter = 0; counter <= columns; counter++ ) if ( listview->header()->label ( counter ).length() == 0 ) return counter; } void BudgetDisplay::newBudget () { constructBudgetWindow(); int response = nb->exec(); if ( response == 1 ) { // open a new budget object int addedbudget = budget->addBudget ( budgetname->text(), 0, description->text(), currencybox->currencybox->currentText(), day, month, year, day, month, year, 0 ); transaction->clearBudgetIDs ( addedbudget ); displayBudgetNames(); } checkBudgets(); } void BudgetDisplay::constructBudgetWindow () { //construct and format the new budget window nb = new QDialog ( this, 0, TRUE ); nb->setCaption ( "Budget" ); QLabel *namelabel = new QLabel ( "Budget Name", nb ); budgetname = new QLineEdit ( nb ); QLabel *descriptionlabel = new QLabel ( "Description", nb ); description = new QLineEdit ( nb ); currencybox = new Currency ( nb ); QBoxLayout *layout = new QVBoxLayout ( nb, 2, 2 ); layout->addWidget ( namelabel ); layout->addWidget ( budgetname ); layout->addWidget ( descriptionlabel ); layout->addWidget ( description ); layout->addWidget ( currencybox ); } void BudgetDisplay::displayBudgetNames () { budgetbox->clear(); if ( budget->getNumberOfBudgets() != 0 ) { ids = budget->getBudgetIDs(); for ( QStringList::Iterator it = ids->begin(); it != ids->end(); ++it ) { QString flag = "/opt/QtPalmtop/pics/flags/"; flag.append ( budget->getCurrency ( (*it).toInt() ) ); flag.append ( ".png" ); budgetbox->insertItem ( QPixmap ( flag ), budget->getBudgetName ( (*it).toInt() ) ); } setCurrentBudget ( 0 ); } else checkBudgets(); } void BudgetDisplay::setCurrentBudget ( int index ) { currentbudget = ( ids->operator[] ( index ).toInt() ); displayLineItems(); } void BudgetDisplay::setCurrentView ( int index ) { displayLineItems(); } void BudgetDisplay::showCalendar () { // create new calendar object and show it DatePicker *dp = new DatePicker ( QDate ( year, month, day ) ); dp->daylabel->hide(); dp->daybox->hide(); if ( budgetview->currentItem() == 1 ) { dp->monthlabel->hide(); dp->monthbox->hide(); } dp->setMaximumWidth ( ( int ) ( this->size().width() * 0.9 ) ); int response = dp->exec(); if ( response == 1 ) { // Set date integers year = dp->getYear(); if ( budgetview->currentItem() == 0 ) month = dp->getMonth(); else month = newDate.month(); datelabel = preferences->getDate ( year, month ); displayLineItems(); } } void BudgetDisplay::newLineItem () { //construct and format the new line item window constructLineItemWindow (); int response = newlineitem->exec(); if ( response == 1 ) { float amount; if ( lineitemtime->currentItem() == 0 ) amount = lineitemamount->text().toFloat(); else if ( lineitemtime->currentItem() == 1 ) amount = lineitemamount->text().toFloat() * 12; else amount = lineitemamount->text().toFloat() * 52; int lineitemadded = budget->addLineItem ( currentbudget, lineitemname->text(), amount, lineitemtime->currentItem() ); transaction->clearBudgetIDs ( currentbudget, lineitemadded ); displayLineItems(); } checkBudgets(); } void BudgetDisplay::constructLineItemWindow () { //construct and format the new budget window newlineitem = new QDialog ( this, 0, TRUE ); newlineitem->setCaption ( "Line Item" ); QLabel *namelabel = new QLabel ( "Line Item Name", newlineitem ); lineitemname = new QLineEdit ( newlineitem ); QLabel *budgetamountlabel = new QLabel ( "Budget Amount", newlineitem ); lineitemamount = new QLineEdit ( newlineitem ); QLabel *lineitemtimelabel = new QLabel ( "Per:", newlineitem ); lineitemtime = new QComboBox ( newlineitem ); lineitemtime->insertItem ( "Year" ); // type 0 lineitemtime->insertItem ( "Month" ); // type 1 lineitemtime->insertItem ( "Week" ); // type 2 QBoxLayout *layout = new QVBoxLayout ( newlineitem, 2, 2 ); layout->addWidget ( namelabel ); layout->addWidget ( lineitemname ); layout->addWidget ( budgetamountlabel ); layout->addWidget ( lineitemamount ); layout->addWidget ( lineitemtimelabel ); layout->addWidget ( lineitemtime ); } void BudgetDisplay::deleteLineItem () { if ( listview->selectedItem() != 0 ) { int lineitemid = listview->selectedItem()->text ( getIDColumn() ).toInt(); transaction->clearBudgetIDs ( currentbudget, lineitemid ); budget->deleteLineItem ( currentbudget, lineitemid ); displayBudgetNames(); } else QMessageBox::warning ( this, "QashMoney", "Please select a line item to delete." ); checkBudgets(); } void BudgetDisplay::displayLineItems () { listview->clear(); if ( budget->getNumberOfBudgets() != 0 ) { QString budgettable = budgetbox->currentText(); budgettable.append ( QString::number ( currentbudget ) ); budget->displayLineItems ( currentbudget, listview, month, year, budgetview->currentItem() ); totalactual = transaction->getActualTotal ( currentbudget, year, month, budgetview->currentItem() ); totalbudget = budget->getBudgetTotal ( currentbudget, budgetview->currentItem() ); updateBudgetInformation(); } } void BudgetDisplay::checkBudgets () { if ( budget->getNumberOfBudgets() == 0 ) { budgetview->setEnabled ( FALSE ); budgetmenu->setItemEnabled ( 2, FALSE ); budgetmenu->setItemEnabled ( 3, FALSE ); lineitemsmenu->setItemEnabled ( 1, FALSE ); lineitemsmenu->setItemEnabled ( 2, FALSE ); lineitemsmenu->setItemEnabled ( 3, FALSE ); } else { budgetview->setEnabled ( TRUE ); budgetmenu->setItemEnabled ( 2, TRUE ); budgetmenu->setItemEnabled ( 3, TRUE ); lineitemsmenu->setItemEnabled ( 1, TRUE ); lineitemsmenu->setItemEnabled ( 2, FALSE ); lineitemsmenu->setItemEnabled ( 3, FALSE ); if ( budget->getNumberOfLineItems ( currentbudget ) != 0 ) { lineitemsmenu->setItemEnabled ( 2, TRUE ); lineitemsmenu->setItemEnabled ( 3, TRUE ); } } } void BudgetDisplay::updateBudgetInformation () { if ( budgetview->currentItem() == 0 ) { datelabel = preferences->getDate ( year, month ); datelabel.prepend ( "Date: " ); date->setText ( datelabel ); } else date->setText ( QString::number ( year ) ); QString budget = "Budget: "; budget.append ( totalbudget ); budgeted->setText ( budget ); QString actualamount = "Actual: "; actualamount.append ( totalactual ); actual->setText ( actualamount ); } void BudgetDisplay::editBudget () { constructBudgetWindow(); //set the title budgetname->setText ( budget->getBudgetName ( currentbudget ) ); //set the description description->setText ( budget->getBudgetDescription ( currentbudget ) ); // retrieve the two character currency code then // go through the currencty box and find the code //set the currency box to that index number int count = currencybox->currencybox->count(); QString code = budget->getCurrency ( currentbudget ); for ( int counter = 0; count - 1; counter++ ) { if ( QString::compare (currencybox->currencybox->text ( counter ), code ) == 0 ) { currencybox->currencybox->setCurrentItem ( counter ); break; } } int response = nb->exec(); if ( response == 1 ) { budget->updateBudget ( budgetname->text(), description->text(), currencybox->currencybox->currentText(), currentbudget ); displayBudgetNames(); } } void BudgetDisplay::editLineItem () { if ( listview->selectedItem() != 0 ) { constructLineItemWindow(); // set the line item name lineitemname->setText ( listview->selectedItem()->text( 0 ) ); // set the line item time combobox int lineitemtype = budget->getLineItemTime ( currentbudget, listview->selectedItem()->text ( 3 ).toInt() ); lineitemtime->setCurrentItem ( lineitemtype ); // set the line item amount float amount = budget->getLineItemAmount ( currentbudget, listview->selectedItem()->text ( 3 ).toInt() ); if ( lineitemtype == 1 ) amount = amount / 12; else if ( lineitemtype == 2 ) amount = amount / 52; lineitemamount->setText ( QString::number ( amount ) ); int response = newlineitem->exec(); if ( response == 1 ) { float amount; if ( lineitemtime->currentItem() == 0 ) amount = lineitemamount->text().toFloat(); else if ( lineitemtime->currentItem() == 1 ) amount = lineitemamount->text().toFloat() * 12; else amount = lineitemamount->text().toFloat() * 52; budget->updateLineItem ( lineitemname->text(), amount, lineitemtime->currentItem(), currentbudget, listview->selectedItem()->text ( 3 ).toInt() ); displayLineItems(); } } else QMessageBox::warning ( this, "QashMoney", "Please select a line item to edit." ); } diff --git a/noncore/apps/qashmoney/budgetdisplay.h b/noncore/apps/qashmoney/budgetdisplay.h index 3976ce1..a4e806c 100755 --- a/noncore/apps/qashmoney/budgetdisplay.h +++ b/noncore/apps/qashmoney/budgetdisplay.h @@ -1,86 +1,86 @@ #ifndef BUDGETDISPLAY_H #define BUDGETDISPLAY_H #include <qlistview.h> #include <qlineedit.h> #include <qpushbutton.h> #include <qcombobox.h> #include <qlayout.h> #include <qlabel.h> #include <qstringlist.h> #include <qdatetime.h> -#include <qpe/qpemenubar.h> +#include <qmenubar.h> #include <qpopupmenu.h> #include <qhbox.h> #include "currency.h" class BudgetDisplay : public QWidget { Q_OBJECT public: BudgetDisplay ( QWidget *parent ); - QPEMenuBar *menu; + QMenuBar *menu; QPopupMenu *budgetmenu; QPopupMenu *lineitemsmenu; QPopupMenu *datemenu; QHBox *firstline; QHBox *secondline; QLabel *budgeted; QLabel *actual; QLabel *date; QLineEdit *budgetname; QLineEdit *description; Currency *currencybox; QLineEdit *lineitemname; QLineEdit *lineitemamount; QComboBox *lineitemtime; QListView *listview; QComboBox *budgetbox; QComboBox *budgetview; QBoxLayout *layout; int getIDColumn (); public slots: void displayBudgetNames (); void displayLineItems (); void updateBudgetInformation (); private slots: void saveColumnSize ( int column, int oldsize, int newsize ); void newBudget (); void deleteBudget (); void setCurrentBudget ( int ); void setCurrentView ( int ); void showCalendar (); void newLineItem (); void deleteLineItem (); void checkBudgets (); void editBudget (); void editLineItem (); void constructBudgetWindow (); void constructLineItemWindow (); void saveSortingPreference ( int column ); private: QStringList *names; QStringList *ids; int currentbudget, year, month, day; QDate newDate; QString totalbudget, totalactual; QString datelabel; QDialog *nb; QDialog *newlineitem; }; #endif // BUDGETDISPLAY_H diff --git a/noncore/apps/qashmoney/qashmoney.cpp b/noncore/apps/qashmoney/qashmoney.cpp index 20e8d32..e985f0b 100755 --- a/noncore/apps/qashmoney/qashmoney.cpp +++ b/noncore/apps/qashmoney/qashmoney.cpp @@ -1,403 +1,403 @@ #include "qashmoney.h" #include "preferencedialogs.h" #include "memorydialog.h" #include <qheader.h> #include <iostream.h> Budget *budget = new Budget (); Preferences *preferences = new Preferences (); Account *account = new Account (); Transaction *transaction = new Transaction (); Transfer *transfer = new Transfer (); Memory *memory = new Memory (); QashMoney::QashMoney () : QWidget () { preferences->addPreferences (); preferences->initializeColumnPreferences (); preferences->initializeSortingPreferences (); // set the text in the upper part of the frame setCaption ( tr ( "QashMoney" ) ); // Create new menubar for our mainwindow // and add menu items - mainmenu = new QPEMenuBar ( this ); + mainmenu = new QMenuBar ( this ); mainmenu->setFrameStyle ( QFrame::PopupPanel | QFrame::Raised ); preferencesmenu = new QPopupMenu ( this ); utilitiesmenu = new QPopupMenu ( this ); mainmenu->insertItem ( "Preferences", preferencesmenu ); mainmenu->insertItem ( "Utilities", utilitiesmenu ); preferencesmenu->insertItem ( "Date", this, SLOT ( displayDatePreferencesDialog () ) ); preferencesmenu->insertItem ( "Account", this, SLOT ( displayAccountPreferencesDialog () ) ); preferencesmenu->insertItem ( "Transaction", this, SLOT ( displayTransactionPreferencesDialog () ) ); utilitiesmenu->insertItem ( "Memory", this, SLOT ( displayMemoryDialog () ) ); // create the main tabwidget for displaying accounts and transactions maintabs = new QTabWidget ( this ); tab = new QWidget ( this ); tab_2 = new QWidget ( this ); tab_3 = new QWidget ( this ); maintabs->addTab ( tab, "Accounts" ); maintabs->addTab ( tab_2, "Transactions" ); maintabs->addTab ( tab_3, "Budgets" ); tabheight = tab->height(); maintabs->setTabEnabled ( tab_2, FALSE ); // create a new account display object accountdisplay = new AccountDisplay ( maintabs ); accountdisplay->setTabs ( tab_2, maintabs ); connect ( accountdisplay->listview, SIGNAL ( selectionChanged () ), this, SLOT ( setTransactionTab () ) ); // set the connection to disable the one touch account viewing if we are transfering money connect ( accountdisplay->transferbutton, SIGNAL ( toggled ( bool ) ), this, SLOT ( toggleOneTouchViewing ( bool ) ) ); // create a new transactiondisplay object transactiondisplay = new TransactionDisplay ( maintabs ); transactiondisplay->hide(); // create new budgetdisplay object budgetdisplay = new BudgetDisplay ( maintabs ); budgetdisplay->hide(); tabslayout = new QVBoxLayout ( maintabs, 4, 2 ); tabslayout->addSpacing ( tabheight ); tabslayout->addWidget ( accountdisplay ); tabslayout->addWidget ( transactiondisplay ); tabslayout->addWidget ( budgetdisplay ); // connect a change in the maintabs with changing the tab display connect ( maintabs, SIGNAL ( currentChanged ( QWidget * ) ), this, SLOT ( changeTabDisplay () ) ); // create layout that will contain the menubar and the maintabs layout = new QVBoxLayout ( this, 2, 2 ); layout->setMenuBar ( mainmenu ); layout->addWidget ( maintabs ); } QashMoney::~QashMoney () { delete budget; delete preferences; delete account; delete transaction; delete transfer; delete memory; } void QashMoney::changeTabDisplay () { // if the user pressed the transactions tab, hide the account display // object and create a new transaction display if ( maintabs->currentPageIndex() == 1 ) { // initialize variables bool children = FALSE; // hide the account display and define accountid int accountid = accountdisplay->listview->selectedItem()->text ( accountdisplay->getIDColumn() ).toInt(); //remove all the columns from the transactiondisplay int columns = transactiondisplay->listview->columns(); int counter; for ( counter = 0; counter <= columns; counter++ ) transactiondisplay->listview->removeColumn ( 0 ); // set the account name and account balance QString name = account->getAccountName ( accountid ); QString balance = account->getAccountBalance ( accountid ); transactiondisplay->name->setText ( name ); transactiondisplay->balance->setText ( balance ); // clear the limitbox transactiondisplay->limitbox->clear(); // get parent account id int parentaccountid = account->getParentAccountID ( accountid ); // add columns based on which account is selected // this first if determines if we selected a parent with no children or a child // in these cases, we add standard three columns for date, transaction, amount transactiondisplay->listview->addColumn ( "Date", 0 ); transactiondisplay->listview->addColumn ( "Transaction", 0 ); transactiondisplay->listview->addColumn ( "Amt", 0); transactiondisplay->listview->setColumnAlignment ( 2, Qt::AlignRight ); transactiondisplay->listview->addColumn ( "", 0 ); if ( accountdisplay->listview->selectedItem()->parent() == 0 && accountdisplay->listview->selectedItem()->childCount() != 0 ) // we selected a parent with children { // add an extra column for the account name for eac child transaction transactiondisplay->listview->addColumn ( "Acct", 0 ); children = TRUE; // hide the new transaction button transactiondisplay->newtransaction->setEnabled ( FALSE ); } else //we selected a parent without children or a child transactiondisplay->newtransaction->setEnabled ( TRUE ); // disable the transactionid column so it can't be red transactiondisplay->listview->header()->setResizeEnabled ( FALSE, 3 ); // set the accountid and children variables transactiondisplay->setChildren ( children ); transactiondisplay->setAccountID ( accountid ); setTransactionDisplayDate (); // display transactions transactiondisplay->listview->clear(); QString displaytext = "%"; displaytext.prepend ( transactiondisplay->limitbox->text() ); if ( transaction->getNumberOfTransactions() > 0 ) transaction->displayTransactions ( transactiondisplay->listview, accountid, children, displaytext, newdate ); // display transfers transfer->displayTransfers ( transactiondisplay->listview, accountid, children, newdate ); // open a new preferences object and resize the transaction display columns // each column will have a different size based on whether we are looking at a child // account or children through a parent if ( parentaccountid != -1 || accountdisplay->listview->selectedItem()->childCount() == 0 ) // a parent with no children or a child - three columns { transactiondisplay->listview->setColumnWidth ( 0, preferences->getColumnPreference ( 3 ) ); // normal transaction date width transactiondisplay->listview->setColumnWidthMode ( 0, QListView::Manual ); transactiondisplay->listview->setColumnWidth ( 1, preferences->getColumnPreference ( 4 ) ); // normal transaction name width transactiondisplay->listview->setColumnWidthMode ( 1, QListView::Manual ); transactiondisplay->listview->setColumnWidth ( 2, preferences->getColumnPreference ( 5 ) ); // normal transaction amount width transactiondisplay->listview->setColumnWidthMode ( 2, QListView::Manual ); } else { transactiondisplay->listview->setColumnWidth ( 0, preferences->getColumnPreference ( 6 ) ); // extended transaction date width transactiondisplay->listview->setColumnWidthMode ( 0, QListView::Manual ); transactiondisplay->listview->setColumnWidth ( 1, preferences->getColumnPreference ( 7 ) ); // extended transaction name width transactiondisplay->listview->setColumnWidthMode ( 1, QListView::Manual ); transactiondisplay->listview->setColumnWidth ( 2, preferences->getColumnPreference ( 8 ) ); // extended transaction amount width transactiondisplay->listview->setColumnWidthMode ( 2, QListView::Manual ); transactiondisplay->listview->setColumnWidth ( 4, preferences->getColumnPreference ( 9 ) ); // transaction account width transactiondisplay->listview->setColumnWidthMode ( 4, QListView::Manual ); } // pull the column sorting preference from the preferences table, and configure the listview accordingly int column = 0; int direction = 0; preferences->getSortingPreference ( 2, &column, &direction ); transactiondisplay->listview->setSorting ( column, direction ); // show the window transactiondisplay->show(); // hide the account display and define accountid accountdisplay->hide(); // hide the budget display budgetdisplay->hide(); } else if ( maintabs->currentPageIndex() == 0 ) { disableOneTouchViewing(); // clear the account display selection accountdisplay->listview->clearSelection(); // resize the account display columns accountdisplay->listview->setColumnWidth ( 0, preferences->getColumnPreference ( 1 ) ); accountdisplay->listview->setColumnWidth ( 1, preferences->getColumnPreference ( 2 ) ); // set sorting preference on account display columns int column = 0; int direction = 0; preferences->getSortingPreference ( 1, &column, &direction ); accountdisplay->listview->setSorting ( column, direction ); // display the accounts if ( account->getNumberOfAccounts() != 0 ) account->displayAccounts ( accountdisplay->listview ); maintabs->setTabEnabled ( tab_2, FALSE ); // set the toggle button accountdisplay->setToggleButton (); // show the account display accountdisplay->show(); // hide the transaction display transactiondisplay->hide(); // hide the budget display budgetdisplay->hide(); enableOneTouchViewing (); } else { budgetdisplay->displayLineItems(); budgetdisplay->show(); transactiondisplay->hide(); accountdisplay->hide(); } } void QashMoney::setTransactionTab () { if ( accountdisplay->listview->selectedItem() == 0 ) maintabs->setTabEnabled ( tab_2, FALSE ); else maintabs->setTabEnabled ( tab_2, TRUE ); } void QashMoney::displayDatePreferencesDialog () { // this shows a dialog to set preferences for formatting the date DatePreferences *pd = new DatePreferences ( this ); pd->exec (); if ( transactiondisplay->isVisible() ) { // set the account id int accountid = accountdisplay->listview->selectedItem()->text ( accountdisplay->getIDColumn() ).toInt(); // set children so we can let displayTransfers know if there are children for the selected account bool children; if ( accountdisplay->listview->selectedItem()->parent() == 0 && accountdisplay->listview->selectedItem()->childCount() != 0 ) children = TRUE; else children = FALSE; // redisplay transactions if they are visible incorporating // any changes to the date format transactiondisplay->listview->clear(); QString displaytext = "%"; displaytext.prepend ( transactiondisplay->limitbox->text() ); setTransactionDisplayDate(); if ( transaction->getNumberOfTransactions() > 0 ) transaction->displayTransactions ( transactiondisplay->listview, accountid, children, displaytext, newdate ); if ( transfer->getNumberOfTransfers() != 0 ) transfer->displayTransfers ( transactiondisplay->listview, accountid, children, newdate ); } else if ( accountdisplay->isVisible() ) { accountdisplay->listview->clearSelection(); maintabs->setTabEnabled ( tab_2, FALSE ); } else budgetdisplay->updateBudgetInformation(); } void QashMoney::displayTransactionPreferencesDialog () { // display a dialog for setting preferences for transactions TransactionPreferences *td = new TransactionPreferences ( this ); td->exec (); if ( transactiondisplay->isVisible() ) { // set the account id int accountid = accountdisplay->listview->selectedItem()->text ( accountdisplay->getIDColumn() ).toInt(); // set children so we can let displayTransfers know if there are children for the selected account bool children; if ( accountdisplay->listview->selectedItem()->parent() == 0 && accountdisplay->listview->selectedItem()->childCount() != 0 ) children = TRUE; else children = FALSE; // redisplay transactions incorporating any transaction preference changes transactiondisplay->listview->clear(); QString displaytext = "%"; displaytext.prepend ( transactiondisplay->limitbox->text() ); setTransactionDisplayDate(); if ( transaction->getNumberOfTransactions() > 0 ) transaction->displayTransactions ( transactiondisplay->listview, accountid, children, displaytext, newdate ); if ( transfer->getNumberOfTransfers() != 0 ) transfer->displayTransfers ( transactiondisplay->listview, accountid, children, newdate ); } else { accountdisplay->listview->clearSelection(); maintabs->setTabEnabled ( tab_2, FALSE ); } } void QashMoney::displayAccountPreferencesDialog () { // display a dialog for setting preferences for accounts AccountPreferences *ap = new AccountPreferences ( this ); ap->exec (); if ( accountdisplay->isVisible() && account->getNumberOfAccounts() != 0 ) { accountdisplay->listview->clear(); account->displayAccounts ( accountdisplay->listview ); accountdisplay->listview->clearSelection(); maintabs->setTabEnabled ( tab_2, FALSE ); } changeTabDisplay(); } void QashMoney::displayMemoryDialog () { // opens a dialog to add, edit and delete memory items MemoryDialog *md = new MemoryDialog (); md->exec(); } void QashMoney::showTransactions () { maintabs->setCurrentPage ( 1 ); } void QashMoney::enableOneTouchViewing () { if ( preferences->getPreference ( 5 ) == 1 ) connect ( accountdisplay->listview, SIGNAL ( selectionChanged () ), this, SLOT ( showTransactions () ) ); else disconnect ( accountdisplay->listview, SIGNAL ( selectionChanged () ), this, SLOT ( showTransactions () ) ); } void QashMoney::disableOneTouchViewing () { disconnect ( accountdisplay->listview, SIGNAL ( selectionChanged () ), this, SLOT ( showTransactions () ) ); } void QashMoney::toggleOneTouchViewing ( bool state ) { if ( state == TRUE ) disableOneTouchViewing(); else enableOneTouchViewing(); } void QashMoney::setTransactionDisplayDate () { // determine how many days of transactions to show int limittype = preferences->getPreference ( 7 ); if ( limittype != 5 ) // set today's date if we are not showing all transactions { QDate today = QDate::currentDate (); switch ( limittype ) // if we are not showing all transactions { case 0: // viewing two weeks newdate = today.addDays ( -14 ); break; case 1: // viewing one month newdate = today.addDays ( -30 ); break; case 2: // three months newdate = today.addDays ( -90 ); break; case 3: // six months newdate = today.addDays ( -180 ); break; case 4: // one year newdate = today.addDays ( -365 ); break; } } else newdate = QDate ( 1900, 1, 1 ); } diff --git a/noncore/apps/qashmoney/qashmoney.h b/noncore/apps/qashmoney/qashmoney.h index ec2c7ec..f2c456c 100755 --- a/noncore/apps/qashmoney/qashmoney.h +++ b/noncore/apps/qashmoney/qashmoney.h @@ -1,64 +1,64 @@ #ifndef QASHMONEY_H #define QASHMONEY_H -#include <qpe/qpemenubar.h> +#include <qmenubar.h> #include <qpopupmenu.h> #include <qlayout.h> #include <qtabwidget.h> #include <qdatetime.h> #include "accountdisplay.h" #include "transactiondisplay.h" #include "budgetdisplay.h" #include "account.h" #include "preferences.h" #include "transaction.h" #include "transfer.h" #include "memory.h" #include "budget.h" class QashMoney : public QWidget { Q_OBJECT public: QashMoney (); ~QashMoney(); QTabWidget* maintabs; QWidget* tab; QWidget* tab_2; QWidget* tab_3; - QPEMenuBar *mainmenu; + QMenuBar *mainmenu; QPopupMenu *preferencesmenu; QPopupMenu *utilitiesmenu; public slots: void displayDatePreferencesDialog (); void displayTransactionPreferencesDialog (); void displayAccountPreferencesDialog (); void displayMemoryDialog (); void setTransactionTab (); private slots: void changeTabDisplay (); void showTransactions (); void enableOneTouchViewing (); void disableOneTouchViewing (); void toggleOneTouchViewing ( bool ); void setTransactionDisplayDate (); private: QVBoxLayout *layout; QVBoxLayout *tabslayout; AccountDisplay *accountdisplay; TransactionDisplay *transactiondisplay; BudgetDisplay *budgetdisplay; int tabheight; QDate newdate; }; #endif diff --git a/noncore/apps/tableviewer/tableviewer.cpp b/noncore/apps/tableviewer/tableviewer.cpp index fbb5c24..fdf0072 100644 --- a/noncore/apps/tableviewer/tableviewer.cpp +++ b/noncore/apps/tableviewer/tableviewer.cpp @@ -1,481 +1,481 @@ /********************************************************************** ** 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. ** **********************************************************************/ /* local includes */ #include "tableviewer.h" #include "ui/tvbrowseview.h" #include "ui/tvfilterview.h" #include "ui/tvlistview.h" #include "ui/tveditview.h" #include "ui/tvkeyedit.h" #include "db/datacache.h" /* QPE includes */ #include <qpe/fileselector.h> #include <qpe/resource.h> #include <qpe/qpetoolbar.h> /* QTE includes */ #include <qpe/qpemenubar.h> #include <qpe/qpetoolbar.h> #include <qpopupmenu.h> #include <qapplication.h> #include <qwidgetstack.h> #include <qlayout.h> #include <qbuffer.h> /*! \class TableViewerWindow \brief The main window widget of the application This is the main widget of the table viewer application. It is the co-ordination point. */ /*! Constructs a new TableViewerWindow */ TableViewerWindow::TableViewerWindow(QWidget *parent, const char *name, WFlags f) : QMainWindow(parent, name, f) { setCaption(tr("Table Viewer")); /* Build data */ ds = new DBStore(); doc.setType("text/x-xml-tableviewer"); doc.setName("table"); dirty = FALSE; ts.current_column = 0; ts.kRep = ds->getKeys(); /* build menus */ - menu = new QPEMenuBar(this, 0); + menu = new QMenuBar(this, 0); QPopupMenu *file_menu = new QPopupMenu; file_menu->insertItem("New", this, SLOT(newDocument())); file_menu->insertItem("Open", this, SLOT(selectDocument())); file_menu->insertSeparator(); file_menu->insertItem("Properties"); /* later will want to set this up to clean up first via this, SLOT(quit) */ menu->insertItem("Document", file_menu); QPopupMenu *edit_menu = new QPopupMenu; edit_menu->insertItem("Edit Item", this, SLOT(editItemSlot())); edit_menu->insertItem("Edit Keys", this, SLOT(editKeysSlot())); edit_menu->insertItem("Edit filters", this, SLOT(filterViewSlot())); menu->insertItem("Edit", edit_menu); QPopupMenu *view_menu = new QPopupMenu; view_menu->insertItem("Browse View", this, SLOT(browseViewSlot())); view_menu->insertItem("List View", this, SLOT(listViewSlot())); menu->insertItem("View", view_menu); QVBoxLayout *main_layout = new QVBoxLayout; /* Build tool bar */ navigation = new QPEToolBar(this, "navigation"); QToolButton *newItemButton = new QToolButton( QIconSet(Resource::loadPixmap("new")), "New Item", QString::null, this, SLOT(newItemSlot()), navigation, "New Item"); QToolButton *editItemButton = new QToolButton( QIconSet(Resource::loadPixmap("edit")), "Edit Item", QString::null, this, SLOT(editItemSlot()), navigation, "Edit Item"); QToolButton *deleteItemButton = new QToolButton( QIconSet(Resource::loadPixmap("trash")), "Delete Item", QString::null, this, SLOT(deleteItemSlot()), navigation, "Delete Item"); navigation->addSeparator(); QToolButton *firstItemButton = new QToolButton( QIconSet(Resource::loadPixmap("fastback")), "First Item", QString::null, this, SLOT(firstItem()), navigation, "First Item"); QToolButton *previousItemButton = new QToolButton( QIconSet(Resource::loadPixmap("back")), "Previous Item", QString::null, this, SLOT(previousItem()), navigation, "Previous Item"); QToolButton *nextItemButton = new QToolButton( QIconSet(Resource::loadPixmap("forward")), "Next Item", QString::null, this, SLOT(nextItem()), navigation, "Next Item"); QToolButton *lastItemButton = new QToolButton( QIconSet(Resource::loadPixmap("fastforward")), "Last Item", QString::null, this, SLOT(lastItem()), navigation, "Last Item"); navigation->addSeparator(); QToolButton *browseButton = new QToolButton( QIconSet(Resource::loadPixmap("day")), "View Single Item", QString::null, this, SLOT(browseViewSlot()), navigation, "View Single Item"); QToolButton *listButton = new QToolButton( QIconSet(Resource::loadPixmap("month")), "View Multiple Items", QString::null, this, SLOT(listViewSlot()), navigation, "View Multiple Items"); setToolBarsMovable(FALSE); setToolBarsMovable(FALSE); setToolBarsMovable(FALSE); /* Build widgets */ browseView = new TVBrowseView(&ts, this, 0); listView = new TVListView(&ts, this, 0); filterView = new TVFilterView(&ts, this, 0); fileSelector = new FileSelector("text/csv;text/x-xml-tableviewer", this, "fileselector"); fileSelector->setNewVisible(FALSE); fileSelector->setCloseVisible(FALSE); cw = new QWidgetStack(this, 0); cw->addWidget(listView, ListState); cw->addWidget(browseView, BrowseState); cw->addWidget(filterView, FilterState); cw->addWidget(fileSelector, FileState); current_view = FileState; cw->raiseWidget(current_view); fileSelector->reread(); connect(browseView, SIGNAL(searchOnKey(int, TVVariant)), this, SLOT(searchOnKey(int, TVVariant))); connect(browseView, SIGNAL(sortChanged(int)), this, SLOT(setPrimaryKey(int))); connect(fileSelector, SIGNAL(closeMe()), this, SLOT(browseViewSlot())); connect(fileSelector, SIGNAL(fileSelected(const DocLnk &)), this, SLOT(openDocument(const DocLnk &))); main_layout->addWidget(menu); main_layout->addWidget(cw); setCentralWidget(cw); } /*! Destroys the TableViewerWindow */ TableViewerWindow::~TableViewerWindow() { if(dirty) saveDocument(); } /*! Opens a file dialog and loads the file specified by the dialog */ void TableViewerWindow::selectDocument() { if(dirty) saveDocument(); current_view = FileState; cw->raiseWidget(current_view); fileSelector->reread(); } void TableViewerWindow::saveDocument() { if(!dirty) return; FileManager fm; QIODevice *dev = fm.saveFile(doc); if(!ds->saveSource(dev, doc.type())){ qWarning("Save unsuccessful"); return; } dev->close(); dirty = FALSE; } void TableViewerWindow::newDocument() { DocLnk nf; nf.setType("text/x-xml-tableviewer"); nf.setName("table"); delete ds; ds = new DBStore(); ts.current_column = 0; ts.kRep = ds->getKeys(); browseView->reset(); listView->reset(); filterView->reset(); doc = nf; dirty = FALSE; current_view = BrowseState; cw->raiseWidget(current_view); /* now set up for editing the keys */ ts.kRep->addKey("key", TVVariant::String); editKeysSlot(); } void TableViewerWindow::setDocument(const QString &f) { openDocument(DocLnk(f, TRUE)); } void TableViewerWindow::openDocument(const DocLnk &f) { if (!f.isValid()) return; FileManager fm; QIODevice *dev = fm.openFile(f); doc = f; if(ds->openSource(dev, doc.type())) { DataElem *d; browseView->reset(); listView->reset(); filterView->reset(); current_view = BrowseState; cw->raiseWidget(current_view); /* set up new table state and ensure sub widgets have a reference */ ts.current_column = 0; ts.kRep = ds->getKeys(); browseView->rebuildKeys(); listView->rebuildKeys(); filterView->rebuildKeys(); ds->first(); /* set up the list view */ listView->clearItems(); do { d = ds->getCurrentData(); if(d) listView->addItem(d); } while(ds->next()); /* Set up browse view, Will be based of structure of listView */ listView->first(); ts.current_elem = listView->getCurrentData(); browseView->rebuildData(); listView->rebuildData(); QString scratch = "Table Viewer";/* later take from constant */ scratch += " - "; scratch += ds->getName(); setCaption(tr(scratch)); dirty = FALSE; } else { qWarning(tr("could not load Document")); } dev->close(); } /*! Moves to the first item of the current table */ void TableViewerWindow::firstItem() { listView->first(); ts.current_elem = listView->getCurrentData(); browseView->rebuildData(); } /*! Moves to the lat item of the current table */ void TableViewerWindow::lastItem() { listView->last(); ts.current_elem = listView->getCurrentData(); browseView->rebuildData(); } /*! Moves to the next item of the current table */ void TableViewerWindow::nextItem() { listView->next(); ts.current_elem = listView->getCurrentData(); browseView->rebuildData(); } /*! Moves to the previous item of the current table */ void TableViewerWindow::previousItem() { listView->previous(); ts.current_elem = listView->getCurrentData(); browseView->rebuildData(); } /*! Raises the List View. This is a mode change for the application. */ void TableViewerWindow::listViewSlot() { if(current_view == FilterState) applyFilter(); current_view = ListState; cw->raiseWidget(current_view); } void TableViewerWindow::applyFilter() { DataElem *d; listView->clearItems(); ds->first(); do { d = ds->getCurrentData(); if(d) if(filterView->passesFilter(d)) listView->addItem(d); } while(ds->next()); listView->first(); listView->rebuildData(); } /*! Raises the Browse View. This is a mode change for the application. */ void TableViewerWindow::browseViewSlot() { if(current_view == FilterState) applyFilter(); ts.current_elem = listView->getCurrentData(); browseView->rebuildData(); current_view = BrowseState; cw->raiseWidget(current_view); } /*! Raises the List View. This is a mode change for the application. */ void TableViewerWindow::filterViewSlot() { current_view = FilterState; cw->raiseWidget(current_view); } void TableViewerWindow::editItemSlot() { if(TVEditView::openEditItemDialog(&ts, ts.current_elem, this)) { listView->rebuildData(); browseView->rebuildData(); dirty = TRUE; } } void TableViewerWindow::newItemSlot() { DataElem *d = new DataElem(ds); if (TVEditView::openEditItemDialog(&ts, d, this)) { ds->addItem(d); ts.current_elem = d; applyFilter(); listView->rebuildData(); browseView->rebuildData(); dirty = TRUE; } } void TableViewerWindow::deleteItemSlot() { /* delete the actual item, then do a 'filter' */ DataElem *to_remove = ts.current_elem; if(!to_remove) return; listView->removeItem(); ds->removeItem(to_remove); applyFilter(); listView->rebuildData(); browseView->rebuildData(); dirty = TRUE; } void TableViewerWindow::editKeysSlot() { DataElem *d; KeyList *k = TVKeyEdit::openEditKeysDialog(&ts, this); if(k) { /* set as new keys */ ds->setKeys(k); ts.current_column = 0; ts.kRep = k; browseView->reset(); listView->reset(); filterView->reset(); browseView->rebuildKeys(); listView->rebuildKeys(); filterView->rebuildKeys(); ds->first(); /* set up the list view */ listView->clearItems(); do { d = ds->getCurrentData(); if(d) listView->addItem(d); } while(ds->next()); /* Set up browse view, Will be based of structure of listView */ dirty = TRUE; } } /*! A Slot that allows for widgets above to indicate a search should be done on a specified key index for a specified value */ void TableViewerWindow::searchOnKey(int i, TVVariant v) { listView->findItem(i, v); ts.current_elem = listView->getCurrentData(); browseView->rebuildData(); } void TableViewerWindow::setPrimaryKey(int i) { ts.current_column = i; listView->rebuildData(); browseView->rebuildData(); } diff --git a/noncore/games/backgammon/backgammon.cpp b/noncore/games/backgammon/backgammon.cpp index 06523f1..755ed10 100644 --- a/noncore/games/backgammon/backgammon.cpp +++ b/noncore/games/backgammon/backgammon.cpp @@ -1,974 +1,974 @@ #include "backgammon.h" #include "aidialog.h" #include "filedialog.h" #include "playerdialog.h" #include "rulesdialog.h" #include "themedialog.h" #include <qdatetime.h> #include <qfile.h> #include <qlayout.h> #include <qmessagebox.h> #include <qstring.h> #include <qtimer.h> #include <qmainwindow.h> #include <qpe/qpeapplication.h> #include <qpe/config.h> #include <qpe/qpemenubar.h> #include <qpe/resource.h> #include <stdlib.h> BackGammon::BackGammon(QWidget* parent, const char* name, WFlags fl) : QMainWindow(parent, name, fl) { if (!name) setName("BackGammon"); setCaption(tr( "Backgammon") ); setIcon( Resource::loadPixmap( "backgammon" ) ); //general counter varaible int a=0; //the game engine move=new MoveEngine(); //load the default theme Config conf("backgammon"); if(!conf.isValid()) { qDebug("config file does not exist"); conf.setGroup("general"); conf.writeEntry("theme","default"); conf.setGroup("rules"); conf.writeEntry("move_with_pieces_out",false); conf.writeEntry("nice_dice",false); conf.setGroup("display"); conf.writeEntry("small",false); conf.writeEntry("warning",true); conf.setGroup("ai"); conf.writeEntry("rescue",6); conf.writeEntry("eliminate",4); conf.writeEntry("expose",1); conf.writeEntry("protect",5); conf.writeEntry("safe",3); conf.writeEntry("empty",2); } conf.setGroup("general"); theme_name=conf.readEntry("theme","default"); QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme"; //the rules conf.setGroup("rules"); rules.move_with_pieces_out=conf.readBoolEntry("move_with_pieces_out",false); rules.generous_dice=conf.readBoolEntry("nice_dice",false); move->setRules(rules); //get the AI settings AISettings ai; conf.setGroup("ai"); ai.rescue=conf.readNumEntry("rescue",6); ai.eliminate=conf.readNumEntry("eliminate",4); ai.expose=conf.readNumEntry("expose",1); ai.protect=conf.readNumEntry("protect",5); ai.safe=conf.readNumEntry("safe",3); ai.empty=conf.readNumEntry("empty",2); move->setAISettings(ai); //get the theme component names Config theme(theme_file,Config::File); if(!theme.isValid()) { qDebug("theme file does not exist"); theme.setGroup("theme"); theme.writeEntry("board","casino_board_1"); theme.writeEntry("pieces1","casino_pieces_blue"); theme.writeEntry("pieces2","casino_pieces_white"); theme.writeEntry("dice1","casino_dice"); theme.writeEntry("dice2","casino_dice"); theme.writeEntry("table","casino_table_green"); theme.writeEntry("odds","casino_odds"); } theme.setGroup("theme"); board_name=theme.readEntry("board","casino_board_1"); piecesA_name=theme.readEntry("pieces1","casino_pieces_blue"); piecesB_name=theme.readEntry("pieces2","casino_pieces_white"); diceA_name=theme.readEntry("dice1","casino_dice"); diceB_name=theme.readEntry("dice2","casino_dice"); table_name=theme.readEntry("table","casino_table_green"); odds_name=theme.readEntry("odds","casino_odds"); //the menu - QPEMenuBar* menuBar = new QPEMenuBar(this); + QMenuBar* menuBar = new QMenuBar(this); QPopupMenu* gamemenu= new QPopupMenu(this); gamemenu->insertItem(tr( "New" ),this,SLOT(newgame())); gamemenu->insertSeparator(); gamemenu->insertItem(tr( "Load" ),this,SLOT(loadgame())); gamemenu->insertItem(tr( "Save" ),this,SLOT(savegame())); gamemenu->insertSeparator(); gamemenu->insertItem(tr( "Delete" ),this,SLOT(deletegame())); menuBar->insertItem(tr( "Game" ),gamemenu); QPopupMenu* thememenu= new QPopupMenu(this); thememenu->insertItem(tr( "New" ),this,SLOT(newtheme())); thememenu->insertSeparator(); thememenu->insertItem(tr( "Load"),this,SLOT(loadtheme())); thememenu->insertItem(tr( "Save" ),this,SLOT(savetheme())); thememenu->insertSeparator(); thememenu->insertItem(tr( "Default"),this,SLOT(themedefault())); thememenu->insertItem(tr( "Delete" ),this,SLOT(deletetheme())); menuBar->insertItem(tr( "Theme" ),thememenu); QPopupMenu* optionmenu=new QPopupMenu(this); optionmenu->insertItem(tr( "Player" ),this,SLOT(playerselect())); optionmenu->insertSeparator(); optionmenu->insertItem(tr( "AI" ),this,SLOT(modify_AI())); optionmenu->insertItem(tr( "Rules" ),this,SLOT(setrules())); menuBar->insertItem(tr( "Options"),optionmenu); QWidget* mainarea=new QWidget(this); setCentralWidget(mainarea); //the main area QBoxLayout* layout=new QBoxLayout(mainarea,QBoxLayout::TopToBottom); area=new QCanvas(235,235); boardview=new BackGammonView(area,mainarea); boardview->setMaximumHeight(240); layout->addWidget(boardview); connect(boardview,SIGNAL(mouse(int,int)),this,SLOT(mouse(int,int))); //status bar message=new QLabel("<b>Backgammon</b>",mainarea); message->setAlignment(AlignHCenter); layout->addWidget(message); //the marker marker_current=new QCanvasRectangle(area); marker_current->setBrush(QColor(0,0,255)); marker_current->setSize(15,5); marker_current->setZ(1); for(a=0;a<4;a++) { marker_next[a]=new QCanvasRectangle(area); marker_next[a]->setBrush(QColor(0,255,0)); marker_next[a]->setSize(15,5); marker_next[a]->setZ(1); } connect(move,SIGNAL(done_dice1()),this,SLOT(done_dice1())); connect(move,SIGNAL(done_dice2()),this,SLOT(done_dice2())); connect(move,SIGNAL(done_dice3()),this,SLOT(done_dice3())); connect(move,SIGNAL(done_dice4()),this,SLOT(done_dice4())); connect(move,SIGNAL(nomove()),this,SLOT(nomove())); connect(move,SIGNAL(player_finished(int)),this,SLOT(finished(int))); //the pieces p1=new CanvasImageItem*[15]; p1_side=new CanvasImageItem*[15]; QImage piece_1_all(Resource::loadImage("backgammon/pieces/"+piecesA_name)); QImage piece_1_front=piece_1_all.copy(0,0,15,15); QImage piece_1_side=piece_1_all.copy(0,15,15,5); p2=new CanvasImageItem*[15]; p2_side=new CanvasImageItem*[15]; QImage piece_2_all(Resource::loadImage("backgammon/pieces/"+piecesB_name)); QImage piece_2_front=piece_2_all.copy(0,0,15,15); QImage piece_2_side=piece_2_all.copy(0,15,15,5); for(a=0;a<15;a++) { p1[a]=new CanvasImageItem(piece_1_front,area); p1[a]->setSize(15,15); p1_side[a]=new CanvasImageItem(piece_1_side,area); p1_side[a]->setSize(15,5); p2[a]=new CanvasImageItem(piece_2_front,area); p2[a]->setSize(15,15); p2_side[a]=new CanvasImageItem(piece_2_side,area); p2_side[a]->setSize(15,5); } draw(); //the dice QImage dicebgA_all(Resource::loadImage("backgammon/dice/"+diceA_name)); diceA1=new CanvasImageItem*[7]; diceA2=new CanvasImageItem*[7]; QImage dicebgB_all(Resource::loadImage("backgammon/dice/"+diceB_name)); diceB1=new CanvasImageItem*[7]; diceB2=new CanvasImageItem*[7]; QImage oddsbg_all=(Resource::loadImage("backgammon/odds/"+odds_name)); //oddsDice=new CanvasImageItem*[6]; for(a=0;a<7;a++) { QImage dicebgA=dicebgA_all.copy(a*25,0,25,25); diceA1[a]=new CanvasImageItem(dicebgA,area); diceA1[a]->setX(5); diceA1[a]->setY(205-2); diceA1[a]->setZ(1); diceA1[a]->setSize(25,25); diceA2[a]=new CanvasImageItem(dicebgA,area); diceA2[a]->setX(35); diceA2[a]->setY(205-2); diceA2[a]->setZ(1); diceA2[a]->setSize(25,25); QImage dicebgB=dicebgB_all.copy(a*25,0,25,25); diceB1[a]=new CanvasImageItem(dicebgB,area); diceB1[a]->setX(175); diceB1[a]->setY(205-2); diceB1[a]->setZ(1); diceB1[a]->setSize(25,25); diceB2[a]=new CanvasImageItem(dicebgB,area); diceB2[a]->setX(205); diceB2[a]->setY(205-2); diceB2[a]->setZ(1); diceB2[a]->setSize(25,25); /* if(a<6) { QImage oddsbg=oddsbg_all.copy(a*15,0,15,15); oddsDice[a]=new CanvasImageItem(oddsbg,area); oddsDice[a]->setX(110); oddsDice[a]->setY(210-2); oddsDice[a]->setZ(1); oddsDice[a]->setSize(15,15); oddsDice[a]->hide(); } */ } //oddsDice[0]->show(); //set the board QImage boardbg(Resource::loadImage("backgammon/boards/"+board_name)); board=new CanvasImageItem(boardbg,area); board->setX(0); board->setY(0); board->setZ(0); board->setSize(235-2,200-2); board->show(); //the table QImage tablebg(Resource::loadImage("backgammon/table/"+table_name)); table=new CanvasImageItem(tablebg,area); table->setX(0); table->setY(200-2); table->setZ(0); table->setSize(235-2,20); table->show(); //the no move marker QImage nomovebg(Resource::loadImage("backgammon/no_move")); nomove_marker=new CanvasImageItem(nomovebg,area); nomove_marker->setX(0); nomove_marker->setY(200); nomove_marker->setZ(2); nomove_marker->hide(); //default human against computer player1_auto=false; player2_auto=true; //start new game newgame(); } BackGammon::~BackGammon() { //DESTRUCTOR } void BackGammon::newgame() { gameFinished=false; QDateTime now=QDateTime::currentDateTime(); game_name=now.date().toString()+"_"+now.time().toString(); move->reset(); draw(); diceA1_value=7; diceA2_value=7; diceA3_value=7; diceA4_value=7; diceB1_value=7; diceB2_value=7; diceB3_value=7; diceB4_value=7; showdice(); player=2; dice1_played=true; dice2_played=true; dice3_played=true; dice4_played=true; dice_rolled=false; setplayer(); area->update(); } void BackGammon::playerselect() { PlayerDialog* playerdialog=new PlayerDialog(this); playerdialog->setAuto1(player1_auto); playerdialog->setAuto2(player2_auto); if(!playerdialog->exec()) return; player1_auto=playerdialog->getAuto1(); player2_auto=playerdialog->getAuto2(); } void BackGammon::loadgame() { FileDialog* file=new FileDialog(this,"Load Game",".game"); if(!file->exec()) return; game_name=file->filename(); QString game_file=QPEApplication::qpeDir()+"/backgammon/"+game_name+".game"; Config game(game_file,Config::File); game.setGroup("dice"); diceA1_value=game.readNumEntry("diceA1_value"); diceA2_value=game.readNumEntry("diceA2_value"); diceA3_value=game.readNumEntry("diceA3_value"); diceA4_value=game.readNumEntry("diceA4_value"); diceB1_value=game.readNumEntry("diceB1_value"); diceB2_value=game.readNumEntry("diceB2_value"); diceB3_value=game.readNumEntry("diceB3_value"); diceB4_value=game.readNumEntry("diceB4_value"); player=game.readNumEntry("player"); dice1_played=game.readBoolEntry("dice1_played"); dice2_played=game.readBoolEntry("dice2_played"); dice3_played=game.readBoolEntry("dice3_played"); dice4_played=game.readBoolEntry("dice4_played"); dice_rolled=game.readBoolEntry("dice_rolled"); player1_auto=game.readBoolEntry("player1_auto"); player2_auto=game.readBoolEntry("player2_auto"); game.setGroup("pieces"); QString label; LoadSave load; for(int a=0;a<28;a++) { label.setNum(a); load.pop[a].total = game.readNumEntry(label,0); } move->loadGame(load); setplayer(); showdice(); draw(); area->update(); } void BackGammon::savegame() { QString game_file=QPEApplication::qpeDir()+"/backgammon/"+game_name+".game"; Config game(game_file,Config::File); game.setGroup("dice"); game.writeEntry("diceA1_value",diceA1_value); game.writeEntry("diceA2_value",diceA2_value); game.writeEntry("diceA3_value",diceA3_value); game.writeEntry("diceA4_value",diceA4_value); game.writeEntry("diceB1_value",diceB1_value); game.writeEntry("diceB2_value",diceB3_value); game.writeEntry("diceB3_value",diceB4_value); game.writeEntry("diceB4_value",diceB4_value); game.writeEntry("player",player); game.writeEntry("dice1_played",dice1_played); game.writeEntry("dice2_played",dice2_played); game.writeEntry("dice3_played",dice3_played); game.writeEntry("dice4_played",dice4_played); game.writeEntry("dice_rolled",dice_rolled); game.writeEntry("player1_auto",player1_auto); game.writeEntry("player2_auto",player2_auto); game.setGroup("pieces"); QString label; LoadSave save=move->saveGame(); for(int a=0;a<28;a++) { label.setNum(a); game.writeEntry(label,save.pop[a].total); } QMessageBox::information(this,"Backgammon","Game saved","OK"); } void BackGammon::deletegame() { FileDialog* file=new FileDialog(this,"Delete Game",".game"); if(!file->exec()) return; game_name=file->filename(); QString game_file=QPEApplication::qpeDir()+"/backgammon/"+game_name+".game"; if(!QMessageBox::warning(this,"Backgammon","deleted game\n"+game_name+" ?","OK","Cancel")) { QFile(game_file).remove(); } } void BackGammon::newtheme() { ThemeDialog* theme=new ThemeDialog(this); ImageNames names; names.theme=theme_name; names.board=board_name; names.pieces1=piecesA_name; names.pieces2=piecesB_name; names.dice1=diceA_name; names.dice2=diceB_name; names.odds=odds_name; names.table=table_name; theme->setCurrent(names); if(!theme->exec()) return; names=theme->getNames(); theme_name=names.theme; board_name=names.board; piecesA_name=names.pieces1; piecesB_name=names.pieces2; diceA_name=names.dice1; diceB_name=names.dice2; odds_name=names.odds; table_name=names.table; applytheme(); } void BackGammon::loadtheme() { FileDialog* file=new FileDialog(this,"Load Theme",".theme"); if(!file->exec()) return; theme_name=file->filename(); QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme"; Config theme(theme_file,Config::File); theme.setGroup("theme"); board_name=theme.readEntry("board","board_1"); piecesA_name=theme.readEntry("pieces1","pieces_1"); piecesB_name=theme.readEntry("pieces2","pieces_2"); diceA_name=theme.readEntry("dice1","dice_1"); diceB_name=theme.readEntry("dice2","dice_2"); table_name=theme.readEntry("table","table_1"); odds_name=theme.readEntry("odds","odds_1"); applytheme(); } void BackGammon::savetheme() { if(theme_name=="default") { QMessageBox::information(this,"Backgammon","Sorry\nCannot overwrite default.theme","OK"); return; } QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme"; if(QMessageBox::information(this,"Backgammon","Save Theme\n"+theme_name,"Yes","No")) return; Config theme(theme_file,Config::File); theme.setGroup("theme"); theme.writeEntry("board",board_name); theme.writeEntry("pieces1",piecesA_name); theme.writeEntry("pieces2",piecesB_name); theme.writeEntry("dice1",diceA_name); theme.writeEntry("dice2",diceB_name); theme.writeEntry("table",table_name); theme.writeEntry("odds",odds_name); } void BackGammon::themedefault() { if(QMessageBox::information(this,"Backgammon","Make Theme\n"+theme_name+"\nthe default theme","Yes","No")) return; Config conf("backgammon"); conf.setGroup("general"); conf.writeEntry("theme",theme_name); } void BackGammon::deletetheme() { FileDialog* file=new FileDialog(this,"Delete Theme",".theme"); if(!file->exec()) return; theme_name=file->filename(); QString theme_file=QPEApplication::qpeDir()+"/backgammon/"+theme_name+".theme"; if(!QMessageBox::warning(this,tr( "Backgammon" ),tr( "deleted theme %1?").arg(theme_name),tr( "OK" ),tr( "Cancel" ))) { QFile(theme_file).remove(); } } void BackGammon::modify_AI() { AI_Dialog* ai_mod=new AI_Dialog(this,tr( "Load Theme" ),".theme"); ai_mod->setAISettings(move->getAISettings()); if(!ai_mod->exec()) return; //get the AI settings AISettings ai=ai_mod->getAISettings(); move->setAISettings(ai); //write new settings to conf file Config conf("backgammon"); conf.setGroup("ai"); conf.writeEntry("rescue",ai.rescue); conf.writeEntry("eliminate",ai.eliminate); conf.writeEntry("expose",ai.expose); conf.writeEntry("protect",ai.protect); conf.writeEntry("safe",ai.safe); conf.writeEntry("empty",ai.empty); } void BackGammon::setrules() { RulesDialog* rulesdialog=new RulesDialog(this,tr( "Load Theme" ),".theme"); rulesdialog->setRules(rules); if(!rulesdialog->exec()) return; rules=rulesdialog->getRules(); Config conf("backgammon"); conf.setGroup("rules"); conf.writeEntry("move_with_pieces_out",rules.move_with_pieces_out); conf.writeEntry("nice_dice",rules.generous_dice); move->setRules(rules); } void BackGammon::draw() { Pieces pieces; move->position(pieces); for(int a=0;a<15;a++) { if(!pieces.player1[a].side) { p1[a]->setX(pieces.player1[a].x); p1[a]->setY(pieces.player1[a].y); p1[a]->setZ(pieces.player1[a].z); p1[a]->show(); p1_side[a]->hide(); } else { p1_side[a]->setX(pieces.player1[a].x); p1_side[a]->setY(pieces.player1[a].y); p1_side[a]->setZ(pieces.player1[a].z); p1_side[a]->show(); p1[a]->hide(); } if(!pieces.player2[a].side) { p2[a]->setX(pieces.player2[a].x); p2[a]->setY(pieces.player2[a].y); p2[a]->setZ(pieces.player2[a].z); p2[a]->show(); p2_side[a]->hide(); } else { p2_side[a]->setX(pieces.player2[a].x); p2_side[a]->setY(pieces.player2[a].y); p2_side[a]->setZ(pieces.player2[a].z); p2_side[a]->show(); p2[a]->hide(); } } } void BackGammon::mouse(int x,int y) { if(gameFinished) { newgame(); return; } if(y<=200) //move pieces { if((player==1 && player1_auto) || (player==2 && player2_auto)) return; Marker marker; move->boardpressed(x,y,marker); if(marker.visible_current) { marker_current->setX(marker.x_current); marker_current->setY(marker.y_current); marker_current->show(); } else { marker_current->hide(); } for(int a=0;a<4;a++) { if(marker.visible_next[a]) { marker_next[a]->setX(marker.x_next[a]); marker_next[a]->setY(marker.y_next[a]); marker_next[a]->show(); } else { marker_next[a]->hide(); } } area->update(); } else //roll dice { if(x>=10 && x<=65 && player==1 && !dice_rolled) { dice1_played=false; dice2_played=false; dice3_played=false; dice4_played=false; dice_rolled=true; srand(QTime::currentTime().msec()); diceA1_value=1+(int) (6.0*rand()/(RAND_MAX+1.0)); diceA2_value=1+(int) (6.0*rand()/(RAND_MAX+1.0)); if(diceA1_value==diceA2_value) { diceA3_value=diceA1_value; diceA4_value=diceA1_value; } else { diceA3_value=7; dice3_played=true; diceA4_value=7; dice4_played=true; } showdice(); area->update(); move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto); } else if(x>=160 && x<=225 && player==2 && !dice_rolled) { dice1_played=false; dice2_played=false; dice3_played=false; dice4_played=false; dice_rolled=true; srand(QTime::currentTime().msec()); diceB1_value=1+(int) (6.0*rand()/(RAND_MAX+1.0)); diceB2_value=1+(int) (6.0*rand()/(RAND_MAX+1.0)); if(diceB1_value==diceB2_value) { diceB3_value=diceB1_value; diceB4_value=diceB1_value; } else { diceB3_value=7; dice3_played=true; diceB4_value=7; dice4_played=true; } showdice(); area->update(); move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto); } } } void BackGammon::done_dice1() { dice1_played=true; if(player==1) diceA1_value=7; else diceB1_value=7; setplayer(); showdice(); draw(); area->update(); if(!dice2_played || !dice3_played || !dice4_played) { if(player==1) { move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto); } else { move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto); } } } void BackGammon::done_dice2() { dice2_played=true; if(player==1) diceA2_value=7; else diceB2_value=7; setplayer(); showdice(); draw(); area->update(); if(!dice1_played || !dice3_played || !dice4_played) { if(player==1) { move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto); } else { move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto); } } } void BackGammon::done_dice3() { dice3_played=true; if(player==1) diceA3_value=7; else diceB3_value=7; setplayer(); showdice(); draw(); area->update(); if(!dice1_played || !dice2_played || !dice4_played) { if(player==1) { move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto); } else { move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto); } } } void BackGammon::done_dice4() { dice4_played=true; if(player==1) diceA4_value=7; else diceB4_value=7; setplayer(); showdice(); draw(); area->update(); if(!dice1_played || !dice2_played || !dice3_played) { if(player==1) { move->diceroll(1,diceA1_value,diceA2_value,diceA3_value,diceA4_value,player1_auto); } else { move->diceroll(2,diceB1_value,diceB2_value,diceB3_value,diceB4_value,player2_auto); } } } void BackGammon::nomove() { if(player==1) nomove_marker->setX(0); else nomove_marker->setX(170); nomove_marker->show(); message->setText(tr( "<b>no move</b>" )); dice1_played=true; dice2_played=true; dice3_played=true; dice4_played=true; if(player==1) { diceA1_value=7; diceA2_value=7; diceA3_value=7; diceA4_value=7; } else { diceB1_value=7; diceB2_value=7; diceB3_value=7; diceB4_value=7; } area->update(); QTimer::singleShot(2000,this,SLOT(nomove2())); } void BackGammon::nomove2() { nomove_marker->hide(); setplayer(); showdice(); draw(); area->update(); } void BackGammon::finished(int theplayer) { nomove_marker->hide(); if(theplayer==1) message->setText(tr( "<b>Player 1 wins. Click on board for new game.</b>" )); else message->setText(tr( "<b>Player 2 wins. Click on board for new game.</b>" )); diceA1_value=7; diceA2_value=7; diceB1_value=7; diceB2_value=7; player=0; showdice(); draw(); area->update(); gameFinished=true; } void BackGammon::showdice() { int value_diceA1=diceA1_value-1; if(diceA1_value==7 && diceA3_value!=7) value_diceA1=diceA3_value-1; int value_diceA2=diceA2_value-1; if(diceA2_value==7 && diceA4_value!=7) value_diceA2=diceA4_value-1; int value_diceB1=diceB1_value-1; if(diceB1_value==7 && diceB3_value!=7) value_diceB1=diceB3_value-1; int value_diceB2=diceB2_value-1; if(diceB2_value==7 && diceB4_value!=7) value_diceB2=diceB4_value-1; for(int index=0;index<7;index++) { if(value_diceA1==index) diceA1[index]->show(); else diceA1[index]->hide(); if(value_diceA2==index) diceA2[index]->show(); else diceA2[index]->hide(); if(value_diceB1==index) diceB1[index]->show(); else diceB1[index]->hide(); if(value_diceB2==index) diceB2[index]->show(); else diceB2[index]->hide(); } } void BackGammon::setplayer() { if(dice1_played && dice2_played && dice3_played && dice4_played && player==1) { message->setText(tr( "<b>P2 turn</b>", "P means player" )); dice_rolled=false; player=2; if(player2_auto) QTimer::singleShot(2000,this,SLOT(autoroll_dice2())); } else if(dice1_played && dice2_played && dice3_played && dice4_played && player==2) { message->setText(tr( "<b>P1 turn</b>", "P means player" )); dice_rolled=false; player=1; if(player1_auto) QTimer::singleShot(2000,this,SLOT(autoroll_dice1())); } } void BackGammon::autoroll_dice1() { mouse(20,210); } void BackGammon::autoroll_dice2() { mouse(170,210); } void BackGammon::applytheme() { QImage boardbg(Resource::loadImage("backgammon/boards/"+board_name)); board->setImage(boardbg); QImage tablebg(Resource::loadImage("backgammon/table/"+table_name)); table->setImage(tablebg); QImage piece_1_all(Resource::loadImage("backgammon/pieces/"+piecesA_name)); QImage piece_1_front=piece_1_all.copy(0,0,15,15); QImage piece_1_side=piece_1_all.copy(0,15,15,5); QImage piece_2_all(Resource::loadImage("backgammon/pieces/"+piecesB_name)); QImage piece_2_front=piece_2_all.copy(0,0,15,15); QImage piece_2_side=piece_2_all.copy(0,15,15,5); int a=0; for(a=0;a<15;a++) { p1[a]->setImage(piece_1_front); p1_side[a]->setImage(piece_1_side); p2[a]->setImage(piece_2_front); p2_side[a]->setImage(piece_2_side); } draw(); QImage dicebgA_all(Resource::loadImage("backgammon/dice/"+diceA_name)); QImage dicebgB_all(Resource::loadImage("backgammon/dice/"+diceB_name)); QImage oddsbg_all=(Resource::loadImage("backgammon/odds/"+odds_name)); for(a=0;a<7;a++) { QImage dicebgA=dicebgA_all.copy(a*25,0,25,25); diceA1[a]->setImage(dicebgA); diceA2[a]->setImage(dicebgA); QImage dicebgB=dicebgB_all.copy(a*25,0,25,25); diceB1[a]->setImage(dicebgB); diceB2[a]->setImage(dicebgB); /* if(a<6) { QImage oddsbg=oddsbg_all.copy(a*15,0,15,15); oddsDice[a]->setImage(oddsbg); } */ } } diff --git a/noncore/games/fifteen/fifteen.cpp b/noncore/games/fifteen/fifteen.cpp index 293cd65..212f7b1 100644 --- a/noncore/games/fifteen/fifteen.cpp +++ b/noncore/games/fifteen/fifteen.cpp @@ -1,364 +1,364 @@ /********************************************************************** ** 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 "fifteen.h" #include <qpe/resource.h> #include <qpe/config.h> #include <qvbox.h> #include <qaction.h> #include <qlayout.h> #include <qpainter.h> #include <qpopupmenu.h> #include <qmessagebox.h> #include <qpe/qpetoolbar.h> #include <qpe/qpemenubar.h> #include <qstringlist.h> #include <qapplication.h> #include <stdlib.h> #include <time.h> FifteenMainWindow::FifteenMainWindow(QWidget *parent, const char* name) : QMainWindow( parent, name ) { // random seed srand(time(0)); setToolBarsMovable( FALSE ); QVBox *vbox = new QVBox( this ); PiecesTable *table = new PiecesTable( vbox ); setCentralWidget(vbox); QPEToolBar *toolbar = new QPEToolBar(this); toolbar->setHorizontalStretchable( TRUE ); addToolBar(toolbar); - QPEMenuBar *menubar = new QPEMenuBar( toolbar ); + QMenuBar *menubar = new QMenuBar( toolbar ); menubar->setMargin(0); QPopupMenu *game = new QPopupMenu( this ); QWidget *spacer = new QWidget( toolbar ); spacer->setBackgroundMode( PaletteButton ); toolbar->setStretchableWidget( spacer ); QAction *a = new QAction( tr( "Randomize" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), table, SLOT( slotRandomize() ) ); a->addTo( game ); a->addTo( toolbar ); a = new QAction( tr( "Solve" ), Resource::loadPixmap( "repeat" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), table, SLOT( slotReset() ) ); a->addTo( game ); a->addTo( toolbar ); menubar->insertItem( tr( "Game" ), game ); } PiecesTable::PiecesTable(QWidget* parent, const char* name ) : QTableView(parent, name), _menu(0), _randomized(false) { // setup table view setFrameStyle(StyledPanel | Sunken); setBackgroundMode(NoBackground); setMouseTracking(true); setNumRows(4); setNumCols(4); // init arrays initMap(); readConfig(); initColors(); // set font QFont f = font(); f.setPixelSize(18); f.setBold( TRUE ); setFont(f); } PiecesTable::~PiecesTable() { writeConfig(); } void PiecesTable::writeConfig() { Config cfg("Fifteen"); cfg.setGroup("Game"); QStringList map; for (unsigned int i = 0; i < 16; i++) map.append( QString::number( _map[i] ) ); cfg.writeEntry("Map", map, '-'); cfg.writeEntry("Randomized", _randomized ); } void PiecesTable::readConfig() { Config cfg("Fifteen"); cfg.setGroup("Game"); QStringList map = cfg.readListEntry("Map", '-'); _randomized = cfg.readBoolEntry( "Randomized", FALSE ); unsigned int i = 0; for ( QStringList::Iterator it = map.begin(); it != map.end(); ++it ) { _map[i] = (*it).toInt(); i++; if ( i > 15 ) break; } } void PiecesTable::paintCell(QPainter *p, int row, int col) { int w = cellWidth(); int h = cellHeight(); int x2 = w - 1; int y2 = h - 1; int number = _map[col + row * numCols()] + 1; // draw cell background if(number == 16) p->setBrush(colorGroup().background()); else p->setBrush(_colors[number-1]); p->setPen(NoPen); p->drawRect(0, 0, w, h); // draw borders if (height() > 40) { p->setPen(colorGroup().text()); if(col < numCols()-1) p->drawLine(x2, 0, x2, y2); // right border line if(row < numRows()-1) p->drawLine(0, y2, x2, y2); // bottom boder line } // draw number if (number == 16) return; p->setPen(black); p->drawText(0, 0, x2, y2, AlignHCenter | AlignVCenter, QString::number(number)); } void PiecesTable::resizeEvent(QResizeEvent *e) { QTableView::resizeEvent(e); setCellWidth(contentsRect().width()/ numRows()); setCellHeight(contentsRect().height() / numCols()); } void PiecesTable::initColors() { _colors.resize(numRows() * numCols()); for (int r = 0; r < numRows(); r++) for (int c = 0; c < numCols(); c++) _colors[c + r *numCols()] = QColor(255 - 70 * c,255 - 70 * r, 150); } void PiecesTable::initMap() { _map.resize(16); for (unsigned int i = 0; i < 16; i++) _map[i] = i; _randomized = false; } void PiecesTable::randomizeMap() { initMap(); _randomized = true; // find the free position int pos = _map.find(15); int move = 0; while ( move < 333 ) { int frow = pos / numCols(); int fcol = pos - frow * numCols(); // find click position int row = rand()%4; int col = rand()%4; // sanity check if ( row < 0 || row >= numRows() ) continue; if ( col < 0 || col >= numCols() ) continue; if ( row != frow && col != fcol ) continue; move++; // rows match -> shift pieces if(row == frow) { if (col < fcol) { for(int c = fcol; c > col; c--) { _map[c + row * numCols()] = _map[ c-1 + row *numCols()]; } } else if (col > fcol) { for(int c = fcol; c < col; c++) { _map[c + row * numCols()] = _map[ c+1 + row *numCols()]; } } } // cols match -> shift pieces else if (col == fcol) { if (row < frow) { for(int r = frow; r > row; r--) { _map[col + r * numCols()] = _map[ col + (r-1) *numCols()]; } } else if (row > frow) { for(int r = frow; r < row; r++) { _map[col + r * numCols()] = _map[ col + (r+1) *numCols()]; } } } // move free cell to click position _map[pos=(col + row * numCols())] = 15; repaint(); } } void PiecesTable::checkwin() { if(!_randomized) return; int i; for (i = 0; i < 16; i++) if(i != _map[i]) break; if (i == 16) { QMessageBox::information(this, tr("Fifteen Pieces"), tr("Congratulations!\nYou win the game!")); _randomized = FALSE; } } void PiecesTable::slotRandomize() { randomizeMap(); } void PiecesTable::slotReset() { initMap(); repaint(); } void PiecesTable::mousePressEvent(QMouseEvent* e) { QTableView::mousePressEvent(e); if (e->button() == RightButton) { // setup RMB pupup menu if(!_menu) { _menu = new QPopupMenu(this); _menu->insertItem(tr("R&andomize Pieces"), mRandomize); _menu->insertItem(tr("&Reset Pieces"), mReset); _menu->adjustSize(); } // execute RMB popup and check result switch(_menu->exec(mapToGlobal(e->pos()))) { case mRandomize: randomizeMap(); break; case mReset: initMap(); repaint(); break; default: break; } } else { // GAME LOGIC // find the free position int pos = _map.find(15); if(pos < 0) return; int frow = pos / numCols(); int fcol = pos - frow * numCols(); // find click position int row = findRow(e->y()); int col = findCol(e->x()); // sanity check if (row < 0 || row >= numRows()) return; if (col < 0 || col >= numCols()) return; if ( row != frow && col != fcol ) return; // valid move? if(row != frow && col != fcol) return; // rows match -> shift pieces if(row == frow) { if (col < fcol) { for(int c = fcol; c > col; c--) { _map[c + row * numCols()] = _map[ c-1 + row *numCols()]; updateCell(row, c, false); } } else if (col > fcol) { for(int c = fcol; c < col; c++) { _map[c + row * numCols()] = _map[ c+1 + row *numCols()]; updateCell(row, c, false); } } } // cols match -> shift pieces else if (col == fcol) { if (row < frow) { for(int r = frow; r > row; r--) { _map[col + r * numCols()] = _map[ col + (r-1) *numCols()]; updateCell(r, col, false); } } else if (row > frow) { for(int r = frow; r < row; r++) { _map[col + r * numCols()] = _map[ col + (r+1) *numCols()]; updateCell(r, col, false); } } } // move free cell to click position _map[col + row * numCols()] = 15; updateCell(row, col, false); // check if the player wins with this move checkwin(); } } diff --git a/noncore/games/go/gowidget.cpp b/noncore/games/go/gowidget.cpp index 1d38c9f..476f7ce1 100644 --- a/noncore/games/go/gowidget.cpp +++ b/noncore/games/go/gowidget.cpp @@ -1,464 +1,464 @@ /********************************************************************** ** 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 "gowidget.h" #include <qpe/config.h> #include <qpe/resource.h> #include <qpainter.h> #include <qpixmap.h> #include <qpe/qpetoolbar.h> #include <qpe/qpemenubar.h> #include <qpopupmenu.h> #include <qaction.h> #include <qapplication.h> //processEvents() #include <qlabel.h> //#include <stdio.h> #include "amigo.h" #include "goplayutils.h" static const enum bVal computer_color = BLACK; static int current_handicap = 1; static QBrush *goBrush; //static QImage *newBlackStone; //static QImage *blackStone; //static QImage *whiteStone; static QPixmap *newBlackStone; static QPixmap *blackStone; static QPixmap *whiteStone; static bool smallStones = FALSE; GoMainWidget::GoMainWidget( QWidget *parent, const char* name) : QMainWindow( parent, name ) { setToolBarsMovable( FALSE ); GoWidget *go = new GoWidget(this); setCentralWidget(go); toolbar = new QPEToolBar(this); toolbar->setHorizontalStretchable( TRUE ); addToolBar(toolbar); - QPEMenuBar *mb = new QPEMenuBar( toolbar ); + QMenuBar *mb = new QMenuBar( toolbar ); mb->setMargin(0); QPopupMenu *file = new QPopupMenu( this ); QAction *a = new QAction( tr( "New Game" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), go, SLOT( newGame() ) ); a->addTo( file ); a = new QAction( tr( "Pass" ), Resource::loadPixmap( "pass" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), go, SLOT( pass() ) ); a->addTo( file ); a->addTo( toolbar ); a = new QAction( tr( "Resign" ), Resource::loadPixmap( "reset" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), go, SLOT( resign() ) ); a->addTo( file ); a = new QAction( tr( "Two player option" ), QString::null, 0, this, 0 ); a->setToggleAction( TRUE ); connect( a, SIGNAL( toggled(bool) ), go, SLOT( setTwoplayer(bool) ) ); a->addTo( file ); mb->insertItem( tr( "Game" ), file ); QLabel *turnLabel = new QLabel( toolbar ); turnLabel->setBackgroundMode( PaletteButton ); connect( go, SIGNAL(showTurn(const QPixmap&)), turnLabel, SLOT(setPixmap(const QPixmap&)) ); QLabel * scoreLabel = new QLabel( toolbar ); scoreLabel->setBackgroundMode( PaletteButton ); connect( go, SIGNAL(showScore(const QString&)), scoreLabel, SLOT(setText(const QString&)) ); toolbar->setStretchableWidget( scoreLabel ); go->readConfig(); } void GoMainWidget::resizeEvent( QResizeEvent * ) { //### this won't work because of the text label... /* if ( width() > height() ) moveToolBar( toolbar, Left ); else moveToolBar( toolbar, Top ); */ } GoWidget *GoWidget::self = 0; GoWidget::GoWidget( QWidget *parent, const char* name) : QWidget( parent, name ) { if ( self ) fatal( "Only one Go widget allowed" ); self = this; twoplayer = FALSE; d = bx = by = 1; QPixmap pix = Resource::loadPixmap( "go/pine" ); goBrush = new QBrush( black, pix ); /* QString fn = Resource::findPixmap("Go-black"); blackStone = new QImage( fn ); fn = Resource::findPixmap("Go-black-highlight"); newBlackStone = new QImage( fn ); fn = Resource::findPixmap("Go-white"); whiteStone = new QImage( fn ); */ blackStone = new QPixmap(Resource::loadPixmap( "Go-black" )); whiteStone = new QPixmap(Resource::loadPixmap( "Go-white" )); newBlackStone = new QPixmap(Resource::loadPixmap( "Go-black-highlight" )); init(); } GoWidget::~GoWidget() { writeConfig(); } void GoWidget::writeConfig() { Config cfg("Go"); cfg.setGroup("Game"); cfg.writeEntry("TwoPlayer", twoplayer); cfg.writeEntry("CurrentPlayer", currentPlayer); cfg.writeEntry("NPassed", nPassed); QString b; for (int i=0; i<19; i++) for (int j=0; j<19; j++) b += board[i][j] == BLACK ? 'B' : board[i][j] == WHITE ? 'W' : '.'; cfg.writeEntry("Board", b); cfg.writeEntry("LastX", lastX); cfg.writeEntry("LastY", lastY); extern int blackPrisoners, whitePrisoners; cfg.writeEntry("BlackPrisoners", blackPrisoners); cfg.writeEntry("WhitePrisoners", whitePrisoners); } void GoWidget::readConfig() { init(); Config cfg("Go"); cfg.setGroup("Game"); twoplayer = cfg.readBoolEntry("TwoPlayer"); currentPlayer = (bVal)cfg.readNumEntry("CurrentPlayer",1); nPassed = cfg.readNumEntry("NPassed",0); QString b = cfg.readEntry("Board"); if ( b.length() == 19*19 ) for (int i=0; i<19; i++) for (int j=0; j<19; j++) { QChar ch = b[j+19*i]; if ( ch != '.' ) GoPlaceStone( ch == 'B' ? BLACK : WHITE, i, j ); } lastX = cfg.readNumEntry("LastX"); lastY = cfg.readNumEntry("LastY"); extern int blackPrisoners, whitePrisoners; blackPrisoners = cfg.readNumEntry("BlackPrisoners",0); whitePrisoners = cfg.readNumEntry("WhitePrisoners",0); reportPrisoners(blackPrisoners,whitePrisoners); emit showTurn( currentPlayer == WHITE ? *whiteStone : *blackStone ); } void GoWidget::resizeEvent( QResizeEvent * ) { d = QMIN(width(),height())/19; // int r = (d/2-1); bx = (width() - 18*d)/2 ; by = (height() - 18*d)/2 ; if ( d < 10 && !smallStones ) { blackStone->convertFromImage( blackStone->convertToImage().smoothScale(8,8) ); whiteStone->convertFromImage( whiteStone->convertToImage().smoothScale(8,8) ); newBlackStone->convertFromImage( newBlackStone->convertToImage().smoothScale(8,8) ); smallStones = TRUE; } else if ( d >= 10 && smallStones ) { blackStone = new QPixmap(Resource::loadPixmap( "Go-black" )); whiteStone = new QPixmap(Resource::loadPixmap( "Go-white" )); newBlackStone = new QPixmap(Resource::loadPixmap( "Go-black-highlight" )); smallStones = FALSE; } } void GoWidget::init() { lastX = lastY = newX = newY = -1; nPassed = 0; for ( int i = 0; i < 19; i++ ) for ( int j = 0; j < 19; j++ ) board[i][j]=-1; gameActive = TRUE; goRestart(current_handicap); if ( twoplayer ) { currentPlayer = BLACK; } else { doComputerMove(); currentPlayer = WHITE; } emit showTurn( currentPlayer == WHITE ? *whiteStone : *blackStone ); } void GoWidget::paintEvent( QPaintEvent *e ) { int i,j; int r = whiteStone->width()/2; QPainter p(this); p.fillRect( bx - d/2, by - d/2, 19*d, 19*d, *goBrush ); int xMin = QMAX( x2board(e->rect().left()), 0 ); int xMax = QMIN( x2board(e->rect().right()), 18 ); int yMin = QMAX( y2board(e->rect().top()), 0 ); int yMax = QMIN( y2board(e->rect().bottom()), 18 ); QColor pine( 255, 186, 89 ); p.setPen( pine.dark() ); for ( i = xMin; i < xMax+1 ; i ++ ) { p.drawLine( bx+i*d, by, bx+i*d, by+18*d ); } for ( j = yMin; j < yMax+1 ; j ++ ) { p.drawLine( bx, by+j*d, bx+18*d, by+j*d); } // dots are at (3,3), (3,9), (3,15) and so on p.setBrush( black ); for ( i = 3; i < xMax+1; i+=6 ) for ( j = 3; j < yMax+1; j+=6 ) p.drawEllipse( bx+i*d-2, by+j*d-2, 5, 5 ); for ( i = xMin; i < xMax+1; i++ ) for ( j = yMin; j < yMax+1; j++ ) { if ( board[i][j] == WHITE || currentPlayer==WHITE && newX == i && newY == j ) p.drawPixmap( bx+i*d - r, by+j*d - r, *whiteStone ); else if ( i == lastX && j == lastY ) p.drawPixmap( bx+i*d - r, by+j*d - r, *newBlackStone ); else if ( board[i][j] == BLACK || currentPlayer==BLACK && newX == i && newY == j) p.drawPixmap( bx+i*d - r, by+j*d - r, *blackStone ); } } void GoWidget::doMove( int x, int y ) { if ( !GoPlaceStone( currentPlayer, x, y ) ) { //printf( "Illegal move (%d,%d)\n", x, y ); return; } //printf( "you do (%d,%d)\n", x, y ); nPassed = 0; if ( twoplayer ) currentPlayer = (currentPlayer==WHITE) ? BLACK : WHITE; else doComputerMove(); emit showTurn( currentPlayer == WHITE ? *whiteStone : *blackStone ); } void GoWidget::pass() { if ( !gameActive ) return; nPassed++; if ( nPassed >= 2 ) endGame(); else if ( !twoplayer ) doComputerMove(); } void GoWidget::resign() { if ( gameActive ) endGame(); } void GoWidget::newGame() { init(); update(); } void GoWidget::endGame() { gameActive = FALSE; int w,b; CountUp( &w, &b); QString s = tr("White %1, Black %2. ").arg(w).arg(b); if ( w > b ) s += tr("White wins."); else if ( w < b ) s += tr("Black wins."); else s += tr("A draw."); emit showScore( s ); } void GoWidget::doComputerMove() { int ox = lastX; int oy = lastY; lastX = lastY = -1; emit showTurn( *blackStone ); refresh( ox, oy); qApp->processEvents(); short int x,y; if ( genMove( computer_color, &x, &y ) ) { lastX = x; lastY = y; //printf( "I do (%d,%d)\n", x, y ); GoPlaceStone(computer_color,x,y); nPassed = 0; } else { emit showScore( tr("I pass") ); nPassed++; if ( nPassed >= 2 ) endGame(); } } void GoWidget::mousePressEvent( QMouseEvent *me ) { if ( !gameActive ) return; int x = x2board(me->x()); int y = y2board(me->y()); showStone(x,y,currentPlayer); } void GoWidget::mouseMoveEvent( QMouseEvent *me ) { if ( !gameActive ) return; int x = x2board(me->x()); int y = y2board(me->y()); if ( x != newX || y != newY ) showStone(x,y,currentPlayer); } void GoWidget::showStone( int x, int y, enum bVal c ) { if ( newX > -1 ) { refresh( newX, newY ); newY = newX = -1; } if ( x < 0 || x > 18 || y < 0 || y > 18 ) { newX = newY = -1; return; } if ( board[x][y] == -1 && !Suicide( c, x, y ) ) { newX = x; newY = y; refresh(x,y); } } void GoWidget::mouseReleaseEvent( QMouseEvent * ) { if ( gameActive && newX > -1 ) doMove( newX, newY ); newX = newY = -1; } void GoWidget::refresh( int x, int y ) { update( bx+d*x-d/2-1, by+d*y-d/2-1, d+2, d+2 ); } void GoWidget::removeStone(short x, short y) { board[x][y]=-1; refresh( x, y ); } void GoWidget::placeStone (enum bVal c, short x, short y ) { board[x][y]=c; refresh( x, y ); } void GoWidget::reportPrisoners( int blackcnt, int whitecnt ) { QString s = tr( "Prisoners: black %1, white %2" ).arg(blackcnt).arg(whitecnt); emit showScore( s ); } void GoWidget::setTwoplayer( bool b ) { twoplayer = b; } void GoWidget::setHandicap( int h ) { current_handicap = h; } extern "C" { void removestone(short x, short y) { GoWidget::self->removeStone(x,y); } void placestone (enum bVal c, short x, short y ) { GoWidget::self->placeStone(c,x,y); } void intrMoveReport(enum bVal c ,char *coord ,char *reason ) { qDebug( "intrMoveReport colour %d, %s %s", c, coord, reason ); } void intrPrisonerReport( short blackcnt, short whitecnt ) { GoWidget::self->reportPrisoners(blackcnt,whitecnt); } } diff --git a/noncore/games/minesweep/minesweep.cpp b/noncore/games/minesweep/minesweep.cpp index c84fe53..814070b 100644 --- a/noncore/games/minesweep/minesweep.cpp +++ b/noncore/games/minesweep/minesweep.cpp @@ -1,405 +1,405 @@ /********************************************************************** ** 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 "minesweep.h" #include "minefield.h" #include <qpe/resource.h> #include <qpe/config.h> #include <qpe/qpetoolbar.h> #include <qpe/qpemenubar.h> #include <qpopupmenu.h> #include <qpushbutton.h> #include <qlcdnumber.h> #include <qmessagebox.h> #include <qtimer.h> #include <qpalette.h> #include <qapplication.h> #include <qlayout.h> #include <qlabel.h> #include <stdlib.h> #include <time.h> static const char *pix_new[]={ "20 20 3 1", " c None", "# c #00FF00", ". c #000000", " ", " ...... ", " ..######.. ", " .##########. ", " .############. ", " .##############. ", " .##############. ", " .################. ", " .################. ", " .################. ", " .################. ", " .################. ", " .################. ", " .##############. ", " .##############. ", " .############. ", " .##########. ", " ..######.. ", " ...... ", " "}; /* XPM */ static const char * happy_xpm[] = { "20 20 3 1", " c None", ". c #ffff3f ", "# c #000000", " ", " ###### ", " ##......## ", " #..........# ", " #............# ", " #..............# ", " #..............# ", " #....##....##....# ", " #....##....##....# ", " #................# ", " #................# ", " #................# ", " #...#........#...# ", " #.##........##.# ", " #...########...# ", " #...######...# ", " #..........# ", " ##......## ", " ###### ", " "}; /* XPM */ static const char * worried_xpm[] = { "20 20 3 1", " c None", ". c #ffff3f", "# c #000000", " ", " ###### ", " ##......## ", " #..........# ", " #............# ", " #..............# ", " #..............# ", " #....##....##....# ", " #....##....##....# ", " #................# ", " #................# ", " #................# ", " #................# ", " #....######....# ", " #..............# ", " #............# ", " #..........# ", " ##......## ", " ###### ", " "}; /* XPM */ static const char * dead_xpm[] = { "20 20 3 1", " c None", ". c #ffff3f", "# c #000000", " ", " ###### ", " ##......## ", " #..........# ", " #............# ", " #..............# ", " #..#.#...#.#...# ", " #....#.....#.....# ", " #...#.#...#.#....# ", " #................# ", " #................# ", " #................# ", " #......####......# ", " #....# #....# ", " #...#......#...# ", " #............# ", " #..........# ", " ##......## ", " ###### ", " "}; class ResultIndicator : private QLabel { public: static void showResult( QWidget *ref, bool won ); private: ResultIndicator( QWidget *parent, const char *name, WFlags f) :QLabel( parent, name, f ) {} void timerEvent( QTimerEvent *); void center(); bool twoStage; int timerId; }; void ResultIndicator::showResult( QWidget *ref, bool won ) { ResultIndicator *r = new ResultIndicator( ref, 0, WStyle_Customize | WStyle_Tool | WType_TopLevel ); r->setAlignment( AlignCenter ); r->setFrameStyle( Sunken|StyledPanel ); if ( won ) { r->setText( MineSweep::tr("You won!") ); r->center(); r->show(); r->twoStage = FALSE; r->timerId = r->startTimer(1500); } else { QPalette p( red ); r->setPalette( p ); r->setText( MineSweep::tr("You exploded!") ); r->resize( ref->size() ); r->move( ref->mapToGlobal(QPoint(0,0)) ); r->show(); r->twoStage = TRUE; r->timerId =r->startTimer(200); } } void ResultIndicator::center() { QWidget *w = parentWidget(); QPoint pp = w->mapToGlobal( QPoint(0,0) ); QSize s = sizeHint()*3; pp = QPoint( pp.x() + w->width()/2 - s.width()/2, pp.y() + w->height()/ 2 - s.height()/2 ); setGeometry( QRect(pp, s) ); } void ResultIndicator::timerEvent( QTimerEvent *te ) { if ( te->timerId() != timerId ) return; killTimer( timerId ); if ( twoStage ) { center(); twoStage = FALSE; timerId = startTimer( 1000 ); } else { delete this; } } class MineFrame : public QFrame { public: MineFrame( QWidget *parent, const char *name = 0 ) :QFrame( parent, name ) {} void setField( MineField *f ) { field = f; } protected: void resizeEvent( QResizeEvent *e ) { field->setAvailableRect( contentsRect()); QFrame::resizeEvent(e); } private: MineField *field; }; MineSweep::MineSweep( QWidget* parent, const char* name, WFlags f ) : QMainWindow( parent, name, f ) { srand(::time(0)); setCaption( tr("Mine Hunt") ); setIcon( Resource::loadPixmap( "minesweep_icon" ) ); QPEToolBar *toolBar = new QPEToolBar( this ); toolBar->setHorizontalStretchable( TRUE ); - QPEMenuBar *menuBar = new QPEMenuBar( toolBar ); + QMenuBar *menuBar = new QMenuBar( toolBar ); QPopupMenu *gameMenu = new QPopupMenu( this ); gameMenu->insertItem( tr("Beginner"), this, SLOT( beginner() ) ); gameMenu->insertItem( tr("Advanced"), this, SLOT( advanced() ) ); gameMenu->insertItem( tr("Expert"), this, SLOT( expert() ) ); menuBar->insertItem( tr("Game"), gameMenu ); guessLCD = new QLCDNumber( toolBar ); toolBar->setStretchableWidget( guessLCD ); QPalette lcdPal( red ); lcdPal.setColor( QColorGroup::Background, QApplication::palette().active().background() ); lcdPal.setColor( QColorGroup::Button, QApplication::palette().active().button() ); // guessLCD->setPalette( lcdPal ); guessLCD->setSegmentStyle( QLCDNumber::Flat ); guessLCD->setFrameStyle( QFrame::NoFrame ); guessLCD->setNumDigits( 2 ); guessLCD->setBackgroundMode( PaletteButton ); newGameButton = new QPushButton( toolBar ); newGameButton->setPixmap( QPixmap( pix_new ) ); newGameButton->setFocusPolicy(QWidget::NoFocus); connect( newGameButton, SIGNAL(clicked()), this, SLOT(newGame()) ); timeLCD = new QLCDNumber( toolBar ); // timeLCD->setPalette( lcdPal ); timeLCD->setSegmentStyle( QLCDNumber::Flat ); timeLCD->setFrameStyle( QFrame::NoFrame ); timeLCD->setNumDigits( 5 ); // "mm:ss" timeLCD->setBackgroundMode( PaletteButton ); setToolBarsMovable ( FALSE ); addToolBar( toolBar ); MineFrame *mainframe = new MineFrame( this ); mainframe->setFrameShape( QFrame::Box ); mainframe->setFrameShadow( QFrame::Raised ); mainframe->setLineWidth(2); field = new MineField( mainframe ); mainframe->setField( field ); QFont fnt = field->font(); fnt.setBold( TRUE ); field->setFont( QFont( fnt ) ); field->setFocus(); setCentralWidget( mainframe ); connect( field, SIGNAL( gameOver( bool ) ), this, SLOT( gameOver( bool ) ) ); connect( field, SIGNAL( mineCount( int ) ), this, SLOT( setCounter( int ) ) ); connect( field, SIGNAL( gameStarted()), this, SLOT( startPlaying() ) ); timer = new QTimer( this ); connect( timer, SIGNAL( timeout() ), this, SLOT( updateTime() ) ); readConfig(); } MineSweep::~MineSweep() { writeConfig(); } void MineSweep::gameOver( bool won ) { field->showMines(); if ( won ) { newGameButton->setPixmap( QPixmap( happy_xpm ) ); } else { newGameButton->setPixmap( QPixmap( dead_xpm ) ); } ResultIndicator::showResult( this, won ); timer->stop(); } void MineSweep::newGame() { newGame(field->level()); } void MineSweep::newGame(int level) { timeLCD->display( "0:00" ); field->setup( level ); newGameButton->setPixmap( QPixmap( pix_new ) ); timer->stop(); } void MineSweep::startPlaying() { newGameButton->setPixmap( QPixmap( worried_xpm ) ); starttime = QDateTime::currentDateTime(); timer->start( 1000 ); } void MineSweep::beginner() { newGame(1); } void MineSweep::advanced() { newGame(2); } void MineSweep::expert() { newGame(3); } void MineSweep::setCounter( int c ) { if ( !guessLCD ) return; guessLCD->display( c ); } void MineSweep::updateTime() { if ( !timeLCD ) return; int s = starttime.secsTo(QDateTime::currentDateTime()); if ( s/60 > 99 ) timeLCD->display( "-----" ); else timeLCD->display( QString().sprintf("%2d:%02d",s/60,s%60) ); } void MineSweep::writeConfig() const { Config cfg("MineSweep"); cfg.setGroup("Panel"); cfg.writeEntry("Time", timer->isActive() ? starttime.secsTo(QDateTime::currentDateTime()) : -1); field->writeConfig(cfg); } void MineSweep::readConfig() { Config cfg("MineSweep"); field->readConfig(cfg); cfg.setGroup("Panel"); int s = cfg.readNumEntry("Time",-1); if ( s<0 ) { newGame(); } else { startPlaying(); starttime = QDateTime::currentDateTime().addSecs(-s); updateTime(); } } diff --git a/noncore/games/solitaire/canvascardgame.h b/noncore/games/solitaire/canvascardgame.h index d159de6..b93cfbf 100644 --- a/noncore/games/solitaire/canvascardgame.h +++ b/noncore/games/solitaire/canvascardgame.h @@ -1,97 +1,97 @@ /********************************************************************** ** 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 CANVAS_CARD_GAME_H #define CANVAS_CARD_GAME_H #include "cardgame.h" #include "canvasshapes.h" #include "canvascard.h" #include <qpe/resource.h> #include <qpe/config.h> #include <qmainwindow.h> -#include <qpe/qpemenubar.h> +#include <qmenubar.h> #include <qpainter.h> #include <stdlib.h> #include <time.h> class CanvasCardPile; class CanvasCardGame : public QCanvasView, public CardGame { public: CanvasCardGame(QCanvas &c, bool snap, QWidget *parent = 0, int numOfDecks = 1, const char *name = 0, WFlags f = 0) : QCanvasView( &c, parent, name, f ), CardGame(0,numOfDecks), moved(FALSE), moving(NULL), alphaCardPile( NULL ), cardXOff(0), cardYOff(0), snapOn(snap), numberToDraw(1) { } virtual ~CanvasCardGame(); virtual Card *newCard( eValue v, eSuit s, bool f ) { return new CanvasCard( v, s, f, canvas() ); } virtual void readConfig( Config& cfg ) { Q_UNUSED( cfg ); } virtual void writeConfig( Config& cfg ) { Q_UNUSED( cfg ); } virtual void gameWon(); virtual bool haveWeWon() { return FALSE; } virtual bool mousePressCard(Card *card, QPoint p) { Q_UNUSED(card); Q_UNUSED(p); return FALSE; } virtual void mouseReleaseCard(Card *card, QPoint p) { Q_UNUSED(card); Q_UNUSED(p); } void cancelMoving() { moving = NULL; } void toggleSnap() { snapOn = (snapOn == TRUE) ? FALSE : TRUE; } void toggleCardsDrawn() { numberToDraw = (numberToDraw == 1) ? 3 : 1; } int cardsDrawn() { return numberToDraw; } void setNumberToDraw(int numToDraw) { this->numberToDraw = numToDraw; } void readPile( Config& cfg, CardPile *pile, QString name, int& highestZ ); protected: void contentsMousePressEvent(QMouseEvent *e); void contentsMouseReleaseEvent(QMouseEvent *e); void contentsMouseMoveEvent(QMouseEvent *e); virtual void checkUnusable() { } //added for freecell protected: // Mouse event state variables bool moved; CanvasCard *moving; CanvasCardPile *alphaCardPile; int cardXOff, cardYOff; private: bool snapOn; int numberToDraw; }; #endif diff --git a/noncore/games/solitaire/canvascardwindow.cpp b/noncore/games/solitaire/canvascardwindow.cpp index 317a02d..dec5591 100644 --- a/noncore/games/solitaire/canvascardwindow.cpp +++ b/noncore/games/solitaire/canvascardwindow.cpp @@ -1,314 +1,314 @@ /********************************************************************** ** 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 "canvascardwindow.h" #include "patiencecardgame.h" #include "freecellcardgame.h" #include "chicanecardgame.h" #include "harpcardgame.h" #include "teeclubcardgame.h" #include <qpe/resource.h> #include <qmainwindow.h> #include <qpopupmenu.h> #include <qstyle.h> CanvasCardWindow::CanvasCardWindow(QWidget* parent, const char* name, WFlags f) : QMainWindow(parent, name, f), canvas(230, 260), snapOn(TRUE), cardBack(4), gameType(0), cardGame(NULL) { setIcon( Resource::loadPixmap( "cards" ) ); // Create Playing Area for Games if ( QPixmap::defaultDepth() < 12 ) { // canvas.setBackgroundColor(QColor(0x51, 0x74, 0x6B)); // canvas.setBackgroundColor(QColor(0x20, 0xb0, 0x50)); canvas.setBackgroundColor(QColor(0x08, 0x98, 0x2D)); } else { QPixmap bg; bg.convertFromImage( Resource::loadImage( "table_pattern" ), ThresholdDither ); canvas.setBackgroundPixmap(bg); } #if defined( QT_QWS_CASSIOPEIA ) canvas.setAdvancePeriod(70); #else canvas.setAdvancePeriod(30); #endif #ifdef _PATIENCE_USE_ACCELS_ - QPEMenuBar* menu = menuBar(); + QMenuBar* menu = menuBar(); QPopupMenu* file = new QPopupMenu; file->insertItem(tr("Patience"), this, SLOT(initPatience()), CTRL+Key_F); file->insertItem(tr("Freecell"), this, SLOT(initFreecell()), CTRL+Key_F); file->insertItem(tr("Chicane"), this, SLOT(initChicane()), CTRL+Key_F); file->insertItem(tr("Harp"), this, SLOT(initHarp()), CTRL+Key_F); file->insertItem(tr("Teeclub"), this, SLOT(initTeeclub()), CTRL+Key_F); menu->insertItem(tr("&Game"), file); menu->insertSeparator(); settings = new QPopupMenu; settings->insertItem(tr("&Change card backs"), this, SLOT(changeCardBacks()), Key_F2); snap_id = settings->insertItem(tr("&Snap to position"), this, SLOT(snapToggle()), Key_F3); settings->setCheckable(TRUE); menu->insertItem(tr("&Settings"),settings); menu->insertSeparator(); QPopupMenu* help = new QPopupMenu; help->insertItem(tr("&About"), this, SLOT(help()), Key_F1); help->setItemChecked(dbf_id, TRUE); menu->insertItem(tr("&Help"),help); #else QMenuBar* menu = menuBar(); QPopupMenu* file = new QPopupMenu; file->insertItem(tr("Patience"), this, SLOT(initPatience())); file->insertItem(tr("Freecell"), this, SLOT(initFreecell())); file->insertItem(tr("Chicane"), this, SLOT(initChicane())); file->insertItem(tr("Harp"), this, SLOT(initHarp())); file->insertItem(tr("Teeclub"), this, SLOT(initTeeclub())); menu->insertItem(tr("Play"), file); menu->insertSeparator(); settings = new QPopupMenu; settings->setCheckable(TRUE); settings->insertItem(tr("Change card backs"), this, SLOT(changeCardBacks())); snap_id = settings->insertItem(tr("Snap to position"), this, SLOT(snapToggle())); QString m; drawId = settings->insertItem(tr("Turn one card"), this, SLOT(drawnToggle())); menu->insertItem(tr("Settings"),settings); settings->setCheckable(TRUE); #endif menu->show(); Config cfg( "Patience" ); cfg.setGroup( "GlobalSettings" ); snapOn = cfg.readBoolEntry( "SnapOn", TRUE); settings->setItemChecked(snap_id, snapOn); gameType = cfg.readNumEntry( "GameType", -1 ); drawThree = cfg.readBoolEntry( "DrawThree", FALSE); if ( gameType == 0 ) { cardGame = new PatienceCardGame( &canvas, snapOn, this ); cardGame->setNumberToDraw(drawThree ? 3 : 1); setCaption(tr("Patience")); setCentralWidget(cardGame); cardGame->readConfig( cfg ); setCardBacks(); } else if ( gameType == 1 ) { cardGame = new FreecellCardGame( &canvas, snapOn, this ); setCaption(tr("Freecell")); setCentralWidget(cardGame); //cardGame->newGame(); // Until we know how to handle reading freecell config cardGame->readConfig( cfg ); setCardBacks(); } else if ( gameType == 2 ) { cardGame = new ChicaneCardGame( &canvas, snapOn, this ); cardGame->setNumberToDraw(1); setCaption(tr("Chicane")); setCentralWidget(cardGame); cardGame->readConfig( cfg ); setCardBacks(); } else if ( gameType == 3 ) { cardGame = new HarpCardGame( &canvas, snapOn, this ); cardGame->setNumberToDraw(1); setCaption(tr("Harp")); setCentralWidget(cardGame); cardGame->readConfig( cfg ); setCardBacks(); } else if ( gameType == 4 ) { cardGame = new TeeclubCardGame( &canvas, snapOn, this ); cardGame->setNumberToDraw(1); setCaption(tr("Teeclub")); setCentralWidget(cardGame); cardGame->readConfig( cfg ); setCardBacks(); } else { // Probably there isn't a config file or it is broken // Start a new game initPatience(); } updateDraw(); } CanvasCardWindow::~CanvasCardWindow() { if (cardGame) { Config cfg("Patience"); cfg.setGroup( "GlobalSettings" ); cfg.writeEntry( "GameType", gameType ); cfg.writeEntry( "SnapOn", snapOn ); cfg.writeEntry( "DrawThree", drawThree); cfg.write(); cardGame->writeConfig( cfg ); delete cardGame; } } void CanvasCardWindow::resizeEvent(QResizeEvent *) { QSize s = centralWidget()->size(); int fw = style().defaultFrameWidth(); canvas.resize( s.width() - fw - 2, s.height() - fw - 2); } void CanvasCardWindow::initPatience() { // Create New Game if ( cardGame ) delete cardGame; cardGame = new PatienceCardGame( &canvas, snapOn, this ); cardGame->setNumberToDraw(drawThree ? 3 : 1); gameType = 0; setCaption(tr("Patience")); setCentralWidget(cardGame); cardGame->newGame(); setCardBacks(); updateDraw(); } void CanvasCardWindow::initFreecell() { // Create New Game if ( cardGame ) { delete cardGame; } cardGame = new FreecellCardGame( &canvas, snapOn, this ); gameType = 1; setCaption(tr("Freecell")); setCentralWidget(cardGame); cardGame->newGame(); setCardBacks(); } void CanvasCardWindow::initChicane() { // Create New Game if ( cardGame ) { delete cardGame; } cardGame = new ChicaneCardGame( &canvas, snapOn, this ); cardGame->setNumberToDraw(1); gameType = 2; setCaption(tr("Chicane")); setCentralWidget(cardGame); cardGame->newGame(); setCardBacks(); } void CanvasCardWindow::initHarp() { // Create New Game if ( cardGame ) { delete cardGame; } cardGame = new HarpCardGame( &canvas, snapOn, this ); cardGame->setNumberToDraw(1); gameType = 3; setCaption(tr("Harp")); setCentralWidget(cardGame); cardGame->newGame(); setCardBacks(); } void CanvasCardWindow::initTeeclub() { // Create New Game if ( cardGame ) { delete cardGame; } cardGame = new TeeclubCardGame( &canvas, snapOn, this ); cardGame->setNumberToDraw(1); gameType = 4; setCaption(tr("Teeclub")); setCentralWidget(cardGame); cardGame->newGame(); setCardBacks(); } void CanvasCardWindow::snapToggle() { snapOn = !snapOn; settings->setItemChecked(snap_id, snapOn); cardGame->toggleSnap(); } void CanvasCardWindow::drawnToggle() { drawThree=!drawThree; Config cfg( "Patience" ); cfg.setGroup( "GlobalSettings" ); cardGame->toggleCardsDrawn(); updateDraw(); cfg.writeEntry( "DrawThree", drawThree); cfg.write(); } void CanvasCardWindow::updateDraw() { if(cardGame->cardsDrawn() == 3){ settings->changeItem(drawId, tr("Turn one card")); } else { settings->changeItem(drawId, tr("Turn three cards")); } } void CanvasCardWindow::setCardBacks() { QCanvasItemList l = canvas.allItems(); for (QCanvasItemList::Iterator it = l.begin(); it != l.end(); ++it) { if ( (*it)->rtti() == canvasCardId ) ((CanvasCard *)(*it))->setCardBack( cardBack ); } } void CanvasCardWindow::changeCardBacks() { cardBack++; if (cardBack == 5) cardBack = 0; setCardBacks(); } diff --git a/noncore/graphics/drawpad/drawpad.cpp b/noncore/graphics/drawpad/drawpad.cpp index ac08e15..feae237 100644 --- a/noncore/graphics/drawpad/drawpad.cpp +++ b/noncore/graphics/drawpad/drawpad.cpp @@ -1,668 +1,668 @@ /*************************************************************************** * * * DrawPad - a drawing program for Opie Environment * * * * (C) 2002 by S. Prud'homme <prudhomme@laposte.net> * * * * 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 "drawpad.h" #include "drawpadcanvas.h" #include "ellipsetool.h" #include "erasetool.h" #include "exportdialog.h" #include "filledellipsetool.h" #include "filledrectangletool.h" #include "filltool.h" #include "importdialog.h" #include "linetool.h" #include "newpagedialog.h" #include "page.h" #include "pageinformationdialog.h" #include "pointtool.h" #include "rectangletool.h" #include "texttool.h" #include "thumbnailview.h" #include <opie/colordialog.h> #include <opie/colorpopupmenu.h> #include <qpe/applnk.h> #include <qpe/config.h> #include <qpe/global.h> #include <qpe/qpemenubar.h> #include <qpe/qpetoolbar.h> #include <qpe/resource.h> #include <qaction.h> #include <qfile.h> #include <qmessagebox.h> #include <qpainter.h> #include <qspinbox.h> #include <qtoolbutton.h> #include <qtooltip.h> #include <qwhatsthis.h> DrawPad::DrawPad(QWidget* parent, const char* name, WFlags fl ) : QMainWindow(parent, name, WStyle_ContextHelp) { // init members m_pDrawPadCanvas = new DrawPadCanvas(this, this); connect(m_pDrawPadCanvas, SIGNAL(pagesChanged()), this, SLOT(updateView())); setCentralWidget(m_pDrawPadCanvas); // init menu setToolBarsMovable(false); QPEToolBar* menuToolBar = new QPEToolBar(this); - QPEMenuBar* menuBar = new QPEMenuBar(menuToolBar); + QMenuBar* menuBar = new QMenuBar(menuToolBar); QPopupMenu* toolsPopupMenu = new QPopupMenu(menuBar); QAction* deleteAllAction = new QAction(tr("Delete All"), QString::null, 0, this); connect(deleteAllAction, SIGNAL(activated()), this, SLOT(deleteAll())); deleteAllAction->addTo(toolsPopupMenu); toolsPopupMenu->insertSeparator(); QAction* importPageAction = new QAction(tr("Import"), tr("Import..."), 0, this); connect(importPageAction, SIGNAL(activated()), this, SLOT(importPage())); importPageAction->addTo(toolsPopupMenu); QAction* exportPageAction = new QAction(tr("Export"), tr("Export..."), 0, this); connect(exportPageAction, SIGNAL(activated()), this, SLOT(exportPage())); exportPageAction->addTo(toolsPopupMenu); toolsPopupMenu->insertSeparator(); QAction* thumbnailViewAction = new QAction(tr("Thumbnail View"), tr("Thumbnail View..."), 0, this); connect(thumbnailViewAction, SIGNAL(activated()), this, SLOT(thumbnailView())); thumbnailViewAction->addTo(toolsPopupMenu); QAction* pageInformationAction = new QAction(tr("Page Information"), tr("Page Information..."), 0, this); connect(pageInformationAction, SIGNAL(activated()), this, SLOT(pageInformation())); pageInformationAction->addTo(toolsPopupMenu); toolsPopupMenu->insertSeparator(); m_pAntiAliasingAction = new QAction(tr("Anti-Aliasing"), QString::null, 0, this); m_pAntiAliasingAction->setToggleAction(true); m_pAntiAliasingAction->addTo(toolsPopupMenu); menuBar->insertItem(tr("Tools"), toolsPopupMenu); // init page toolbar QPEToolBar* pageToolBar = new QPEToolBar(this); QAction* newPageAction = new QAction(tr("New Page"), Resource::loadPixmap("new"), QString::null, 0, this); connect(newPageAction, SIGNAL(activated()), this, SLOT(newPage())); newPageAction->addTo(pageToolBar); newPageAction->setWhatsThis( tr( "Click here to add a new sheet." ) ); QAction* clearPageAction = new QAction(tr("Clear Page"), Resource::loadPixmap("drawpad/clear"), QString::null, 0, this); connect(clearPageAction, SIGNAL(activated()), this, SLOT(clearPage())); clearPageAction->addTo(pageToolBar); clearPageAction->setWhatsThis( tr( "Click here to erase the current sheet." ) ); QAction* deletePageAction = new QAction(tr("Delete Page"), Resource::loadPixmap("trash"), QString::null, 0, this); connect(deletePageAction, SIGNAL(activated()), this, SLOT(deletePage())); deletePageAction->addTo(pageToolBar); deletePageAction->setWhatsThis( tr( "Click here to remove the current sheet." ) ); QPEToolBar* emptyToolBar = new QPEToolBar(this); emptyToolBar->setHorizontalStretchable(true); // init navigation toolbar QPEToolBar* navigationToolBar = new QPEToolBar(this); m_pUndoAction = new QAction(tr("Undo"), Resource::loadIconSet("undo"), QString::null, 0, this); connect(m_pUndoAction, SIGNAL(activated()), m_pDrawPadCanvas, SLOT(undo())); m_pUndoAction->addTo(navigationToolBar); m_pUndoAction->setWhatsThis( tr( "Click here to undo the last action." ) ); m_pRedoAction = new QAction(tr("Redo"), Resource::loadIconSet("redo"), QString::null, 0, this); connect(m_pRedoAction, SIGNAL(activated()), m_pDrawPadCanvas, SLOT(redo())); m_pRedoAction->addTo(navigationToolBar); m_pRedoAction->setWhatsThis( tr( "Click here to re-perform the last action." ) ); m_pFirstPageAction = new QAction(tr("First Page"), Resource::loadIconSet("fastback"), QString::null, 0, this); connect(m_pFirstPageAction, SIGNAL(activated()), m_pDrawPadCanvas, SLOT(goFirstPage())); m_pFirstPageAction->addTo(navigationToolBar); m_pFirstPageAction->setWhatsThis( tr( "Click here to view the first page." ) ); m_pPreviousPageAction = new QAction(tr("Previous Page"), Resource::loadIconSet("back"), QString::null, 0, this); connect(m_pPreviousPageAction, SIGNAL(activated()), m_pDrawPadCanvas, SLOT(goPreviousPage())); m_pPreviousPageAction->addTo(navigationToolBar); m_pPreviousPageAction->setWhatsThis( tr( "Click here to view the previous page." ) ); m_pNextPageAction = new QAction(tr("Next Page"), Resource::loadIconSet("forward"), QString::null, 0, this); connect(m_pNextPageAction, SIGNAL(activated()), m_pDrawPadCanvas, SLOT(goNextPage())); m_pNextPageAction->addTo(navigationToolBar); m_pNextPageAction->setWhatsThis( tr( "Click here to view the next page." ) ); m_pLastPageAction = new QAction(tr("Last Page"), Resource::loadIconSet("fastforward"), QString::null, 0, this); connect(m_pLastPageAction, SIGNAL(activated()), m_pDrawPadCanvas, SLOT(goLastPage())); m_pLastPageAction->addTo(navigationToolBar); m_pLastPageAction->setWhatsThis( tr( "Click here to view the last page." ) ); // init draw mode toolbar QPEToolBar* drawModeToolBar = new QPEToolBar(this); m_pLineToolButton = new QToolButton(drawModeToolBar); m_pLineToolButton->setToggleButton(true); QWhatsThis::add( m_pLineToolButton, tr( "Click here to select one of the available tools to draw lines." ) ); QPopupMenu* linePopupMenu = new QPopupMenu(m_pLineToolButton); m_pPointToolAction = new QAction(tr("Draw Point"), Resource::loadPixmap("drawpad/point"), "", 0, this); connect(m_pPointToolAction, SIGNAL(activated()), this, SLOT(setPointTool())); m_pPointToolAction->addTo(linePopupMenu); m_pLineToolAction = new QAction(tr("Draw Line"), Resource::loadPixmap("drawpad/line"), "", 0, this); connect(m_pLineToolAction, SIGNAL(activated()), this, SLOT(setLineTool())); m_pLineToolAction->addTo(linePopupMenu); m_pLineToolButton->setPopup(linePopupMenu); m_pLineToolButton->setPopupDelay(0); m_pRectangleToolButton = new QToolButton(drawModeToolBar); m_pRectangleToolButton->setToggleButton(true); QWhatsThis::add( m_pRectangleToolButton, tr( "Click here to select one of the available tools to draw rectangles." ) ); QPopupMenu* rectanglePopupMenu = new QPopupMenu(m_pRectangleToolButton); m_pRectangleToolAction = new QAction(tr("Draw Rectangle"), Resource::loadPixmap("drawpad/rectangle"), "", 0, this); connect(m_pRectangleToolAction, SIGNAL(activated()), this, SLOT(setRectangleTool())); m_pRectangleToolAction->addTo(rectanglePopupMenu); m_pFilledRectangleToolAction = new QAction(tr("Draw Filled Rectangle"), Resource::loadPixmap("drawpad/filledrectangle"), "", 0, this); connect(m_pFilledRectangleToolAction, SIGNAL(activated()), this, SLOT(setFilledRectangleTool())); m_pFilledRectangleToolAction->addTo(rectanglePopupMenu); m_pRectangleToolButton->setPopup(rectanglePopupMenu); m_pRectangleToolButton->setPopupDelay(0); m_pEllipseToolButton = new QToolButton(drawModeToolBar); m_pEllipseToolButton->setToggleButton(true); QWhatsThis::add( m_pEllipseToolButton, tr( "Click here to select one of the available tools to draw ellipses." ) ); QPopupMenu* ellipsePopupMenu = new QPopupMenu(m_pEllipseToolButton); m_pEllipseToolAction = new QAction(tr("Draw Ellipse"), Resource::loadPixmap("drawpad/ellipse"), "", 0, this); connect(m_pEllipseToolAction, SIGNAL(activated()), this, SLOT(setEllipseTool())); m_pEllipseToolAction->addTo(ellipsePopupMenu); m_pFilledEllipseToolAction = new QAction(tr("Draw Filled Ellipse"), Resource::loadPixmap("drawpad/filledellipse"), "", 0, this); connect(m_pFilledEllipseToolAction, SIGNAL(activated()), this, SLOT(setFilledEllipseTool())); m_pFilledEllipseToolAction->addTo(ellipsePopupMenu); m_pEllipseToolButton->setPopup(ellipsePopupMenu); m_pEllipseToolButton->setPopupDelay(0); m_pTextToolAction = new QAction(tr("Insert Text"), Resource::loadPixmap("drawpad/text"), QString::null, 0, this); m_pTextToolAction->setToggleAction(true); connect(m_pTextToolAction, SIGNAL(activated()), this, SLOT(setTextTool())); m_pTextToolAction->addTo(drawModeToolBar); m_pTextToolAction->setWhatsThis( tr( "Click here to select the text drawing tool." ) ); m_pFillToolAction = new QAction(tr("Fill Region"), Resource::loadPixmap("drawpad/fill"), QString::null, 0, this); m_pFillToolAction->setToggleAction(true); connect(m_pFillToolAction, SIGNAL(activated()), this, SLOT(setFillTool())); m_pFillToolAction->addTo(drawModeToolBar); m_pFillToolAction->setWhatsThis( tr( "Click here to select the fill tool." ) ); m_pEraseToolAction = new QAction(tr("Erase Point"), Resource::loadPixmap("drawpad/erase"), QString::null, 0, this); m_pEraseToolAction->setToggleAction(true); connect(m_pEraseToolAction, SIGNAL(activated()), this, SLOT(setEraseTool())); m_pEraseToolAction->addTo(drawModeToolBar); m_pEraseToolAction->setWhatsThis( tr( "Click here to select the eraser tool." ) ); m_pTool = 0; setRectangleTool(); setEllipseTool(); setPointTool(); emptyToolBar = new QPEToolBar(this); emptyToolBar->setHorizontalStretchable(true); emptyToolBar->addSeparator(); // init draw parameters toolbar QPEToolBar* drawParametersToolBar = new QPEToolBar(this); m_pPenWidthSpinBox = new QSpinBox(1, 9, 1, drawParametersToolBar); connect(m_pPenWidthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(changePenWidth(int))); QToolTip::add(m_pPenWidthSpinBox, tr("Pen Width")); m_pPenWidthSpinBox->setValue(1); m_pPenWidthSpinBox->setFocusPolicy(QWidget::NoFocus); QWhatsThis::add( m_pPenWidthSpinBox, tr( "Click here to select the width of the drawing pen." ) ); m_pPenColorToolButton = new QToolButton(drawParametersToolBar); m_pPenColorToolButton->setPixmap(Resource::loadPixmap("drawpad/pencolor")); QWhatsThis::add( m_pPenColorToolButton, tr( "Click here to select the color used when drawing." ) ); OColorPopupMenu* penColorPopupMenu = new OColorPopupMenu(Qt::black, m_pPenColorToolButton); connect(penColorPopupMenu, SIGNAL(colorSelected(const QColor&)), this, SLOT(changePenColor(const QColor&))); QToolTip::add(m_pPenColorToolButton, tr("Pen Color")); m_pPenColorToolButton->setPopup(penColorPopupMenu); m_pPenColorToolButton->setPopupDelay(0); changePenColor(Qt::black); m_pBrushColorToolButton = new QToolButton(drawParametersToolBar); m_pBrushColorToolButton->setPixmap(Resource::loadPixmap("drawpad/brushcolor")); QWhatsThis::add( m_pBrushColorToolButton, tr( "Click here to select the color used when filling in areas." ) ); OColorPopupMenu* brushColorPopupMenu = new OColorPopupMenu(Qt::white, m_pBrushColorToolButton); connect(brushColorPopupMenu, SIGNAL(colorSelected(const QColor&)), this, SLOT(changeBrushColor(const QColor&))); QToolTip::add(m_pBrushColorToolButton, tr("Fill Color")); m_pBrushColorToolButton->setPopup(brushColorPopupMenu); m_pBrushColorToolButton->setPopupDelay(0); changeBrushColor(Qt::white); finishStartup(); } void DrawPad::finishStartup() { // init pages QFile file(Global::applicationFileName("drawpad", "drawpad.xml")); if (file.open(IO_ReadOnly)) { m_pDrawPadCanvas->load(&file); file.close(); } else { m_pDrawPadCanvas->initialPage(); } loadConfig(); } DrawPad::~DrawPad() { saveConfig(); QFile file(Global::applicationFileName("drawpad", "drawpad.xml")); if (file.open(IO_WriteOnly)) { m_pDrawPadCanvas->save(&file); file.close(); } } bool DrawPad::antiAliasing() { return (m_pAntiAliasingAction->isOn()); } void DrawPad::newPage() { QRect rect = m_pDrawPadCanvas->contentsRect(); NewPageDialog newPageDialog(rect.width(), rect.height(), m_pen.color(), m_brush.color(), this); if (newPageDialog.exec() == QDialog::Accepted) { m_pDrawPadCanvas->newPage(newPageDialog.selectedTitle(), newPageDialog.selectedWidth(), newPageDialog.selectedHeight(), newPageDialog.selectedColor()); } } void DrawPad::clearPage() { QMessageBox messageBox(tr("Clear Page"), tr("Do you want to clear\nthe current page?"), QMessageBox::Information, QMessageBox::Yes, QMessageBox::No | QMessageBox::Escape | QMessageBox::Default, QMessageBox::NoButton, this); messageBox.setButtonText(QMessageBox::Yes, tr("Yes")); messageBox.setButtonText(QMessageBox::No, tr("No")); if (messageBox.exec() == QMessageBox::Yes) { m_pDrawPadCanvas->clearPage(); } } void DrawPad::deletePage() { QMessageBox messageBox(tr("Delete Page"), tr("Do you want to delete\nthe current page?"), QMessageBox::Information, QMessageBox::Yes, QMessageBox::No | QMessageBox::Escape | QMessageBox::Default, QMessageBox::NoButton, this); messageBox.setButtonText(QMessageBox::Yes, tr("Yes")); messageBox.setButtonText(QMessageBox::No, tr("No")); if (messageBox.exec() == QMessageBox::Yes) { m_pDrawPadCanvas->deletePage(); } } void DrawPad::setPointTool() { if (m_pTool) { delete m_pTool; } m_pTool = new PointTool(this, m_pDrawPadCanvas); m_pLineToolButton->setIconSet(m_pPointToolAction->iconSet()); QToolTip::add(m_pLineToolButton, m_pPointToolAction->text()); disconnect(m_pLineToolButton, SIGNAL(clicked()), 0, 0); connect(m_pLineToolButton, SIGNAL(clicked()), m_pPointToolAction, SIGNAL(activated())); m_pLineToolButton->setOn(true); m_pRectangleToolButton->setOn(false); m_pEllipseToolButton->setOn(false); m_pTextToolAction->setOn(false); m_pFillToolAction->setOn(false); m_pEraseToolAction->setOn(false); } void DrawPad::setLineTool() { if (m_pTool) { delete m_pTool; } m_pTool = new LineTool(this, m_pDrawPadCanvas); m_pLineToolButton->setIconSet(m_pLineToolAction->iconSet()); QToolTip::add(m_pLineToolButton, m_pLineToolAction->text()); disconnect(m_pLineToolButton, SIGNAL(clicked()), 0, 0); connect(m_pLineToolButton, SIGNAL(clicked()), m_pLineToolAction, SIGNAL(activated())); m_pLineToolButton->setOn(true); m_pRectangleToolButton->setOn(false); m_pEllipseToolButton->setOn(false); m_pTextToolAction->setOn(false); m_pFillToolAction->setOn(false); m_pEraseToolAction->setOn(false); } void DrawPad::setRectangleTool() { if (m_pTool) { delete m_pTool; } m_pTool = new RectangleTool(this, m_pDrawPadCanvas); m_pRectangleToolButton->setIconSet(m_pRectangleToolAction->iconSet()); QToolTip::add(m_pRectangleToolButton, m_pRectangleToolAction->text()); disconnect(m_pRectangleToolButton, SIGNAL(clicked()), 0, 0); connect(m_pRectangleToolButton, SIGNAL(clicked()), m_pRectangleToolAction, SIGNAL(activated())); m_pLineToolButton->setOn(false); m_pRectangleToolButton->setOn(true); m_pEllipseToolButton->setOn(false); m_pTextToolAction->setOn(false); m_pFillToolAction->setOn(false); m_pEraseToolAction->setOn(false); } void DrawPad::setFilledRectangleTool() { if (m_pTool) { delete m_pTool; } m_pTool = new FilledRectangleTool(this, m_pDrawPadCanvas); m_pRectangleToolButton->setIconSet(m_pFilledRectangleToolAction->iconSet()); QToolTip::add(m_pRectangleToolButton, m_pFilledRectangleToolAction->text()); disconnect(m_pRectangleToolButton, SIGNAL(clicked()), 0, 0); connect(m_pRectangleToolButton, SIGNAL(clicked()), m_pFilledRectangleToolAction, SIGNAL(activated())); m_pLineToolButton->setOn(false); m_pRectangleToolButton->setOn(true); m_pEllipseToolButton->setOn(false); m_pTextToolAction->setOn(false); m_pFillToolAction->setOn(false); m_pEraseToolAction->setOn(false); } void DrawPad::setEllipseTool() { if (m_pTool) { delete m_pTool; } m_pTool = new EllipseTool(this, m_pDrawPadCanvas); m_pEllipseToolButton->setIconSet(m_pEllipseToolAction->iconSet()); QToolTip::add(m_pEllipseToolButton, m_pEllipseToolAction->text()); disconnect(m_pEllipseToolButton, SIGNAL(clicked()), 0, 0); connect(m_pEllipseToolButton, SIGNAL(clicked()), m_pEllipseToolAction, SIGNAL(activated())); m_pLineToolButton->setOn(false); m_pRectangleToolButton->setOn(false); m_pEllipseToolButton->setOn(true); m_pTextToolAction->setOn(false); m_pFillToolAction->setOn(false); m_pEraseToolAction->setOn(false); } void DrawPad::setFilledEllipseTool() { if (m_pTool) { delete m_pTool; } m_pTool = new FilledEllipseTool(this, m_pDrawPadCanvas); m_pEllipseToolButton->setIconSet(m_pFilledEllipseToolAction->iconSet()); QToolTip::add(m_pEllipseToolButton, m_pFilledEllipseToolAction->text()); disconnect(m_pEllipseToolButton, SIGNAL(clicked()), 0, 0); connect(m_pEllipseToolButton, SIGNAL(clicked()), m_pFilledEllipseToolAction, SIGNAL(activated())); m_pLineToolButton->setOn(false); m_pRectangleToolButton->setOn(false); m_pEllipseToolButton->setOn(true); m_pTextToolAction->setOn(false); m_pFillToolAction->setOn(false); m_pEraseToolAction->setOn(false); } void DrawPad::setTextTool() { if (m_pTool) { delete m_pTool; } m_pTool = new TextTool(this, m_pDrawPadCanvas); m_pLineToolButton->setOn(false); m_pRectangleToolButton->setOn(false); m_pEllipseToolButton->setOn(false); m_pTextToolAction->setOn(true); m_pFillToolAction->setOn(false); m_pEraseToolAction->setOn(false); } void DrawPad::setFillTool() { if (m_pTool) { delete m_pTool; } m_pTool = new FillTool(this, m_pDrawPadCanvas); m_pLineToolButton->setOn(false); m_pRectangleToolButton->setOn(false); m_pEllipseToolButton->setOn(false); m_pTextToolAction->setOn(false); m_pFillToolAction->setOn(true); m_pEraseToolAction->setOn(false); } void DrawPad::setEraseTool() { if (m_pTool) { delete m_pTool; } m_pTool = new EraseTool(this, m_pDrawPadCanvas); m_pLineToolButton->setOn(false); m_pRectangleToolButton->setOn(false); m_pEllipseToolButton->setOn(false); m_pTextToolAction->setOn(false); m_pFillToolAction->setOn(false); m_pEraseToolAction->setOn(true); } void DrawPad::changePenWidth(int value) { m_pen.setWidth(value); } void DrawPad::changePenColor(const QColor& color) { m_pen.setColor(color); QPainter painter; painter.begin(m_pPenColorToolButton->pixmap()); painter.fillRect(QRect(0, 12, 14, 2), m_pen.color()); painter.end(); m_pPenColorToolButton->popup()->hide(); } void DrawPad::changeBrushColor(const QColor& color) { m_brush = QBrush(color); QPainter painter; painter.begin(m_pBrushColorToolButton->pixmap()); painter.fillRect(QRect(0, 12, 14, 2), m_brush.color()); painter.end(); m_pBrushColorToolButton->popup()->hide(); } void DrawPad::updateView() { uint pagePosition = m_pDrawPadCanvas->pagePosition(); uint pageCount = m_pDrawPadCanvas->pageCount(); setCaption( tr( "DrawPad - Page %1/%2" ).arg( pagePosition ).arg( pageCount ) ); m_pUndoAction->setEnabled(m_pDrawPadCanvas->currentPage()->undoEnabled()); m_pRedoAction->setEnabled(m_pDrawPadCanvas->currentPage()->redoEnabled()); m_pFirstPageAction->setEnabled(m_pDrawPadCanvas->goPreviousPageEnabled()); m_pPreviousPageAction->setEnabled(m_pDrawPadCanvas->goPreviousPageEnabled()); m_pNextPageAction->setEnabled(m_pDrawPadCanvas->goNextPageEnabled()); m_pLastPageAction->setEnabled(m_pDrawPadCanvas->goNextPageEnabled()); } void DrawPad::deleteAll() { QMessageBox messageBox(tr("Delete All"), tr("Do you want to delete\nall the pages?"), QMessageBox::Information, QMessageBox::Yes, QMessageBox::No | QMessageBox::Escape | QMessageBox::Default, QMessageBox::NoButton, this); messageBox.setButtonText(QMessageBox::Yes, tr("Yes")); messageBox.setButtonText(QMessageBox::No, tr("No")); if (messageBox.exec() == QMessageBox::Yes) { m_pDrawPadCanvas->deleteAll(); } } void DrawPad::importPage() { ImportDialog importDialog(this); importDialog.showMaximized(); if (importDialog.exec() == QDialog::Accepted) { const DocLnk* docLnk = importDialog.selected(); if (docLnk) { m_pDrawPadCanvas->importPage(docLnk->file()); delete docLnk; } } } void DrawPad::exportPage() { ExportDialog exportDialog(m_pDrawPadCanvas->pagePosition(), m_pDrawPadCanvas->pageCount(), this); exportDialog.showMaximized(); if (exportDialog.exec() == QDialog::Accepted) { m_pDrawPadCanvas->exportPage(exportDialog.selectedFromPage(), exportDialog.selectedToPage(), exportDialog.selectedName(), exportDialog.selectedFormat()); } } void DrawPad::thumbnailView() { ThumbnailView thumbnailView(this, m_pDrawPadCanvas, this); thumbnailView.showMaximized(); thumbnailView.exec(); } void DrawPad::pageInformation() { PageInformationDialog pageInformationDialog(m_pDrawPadCanvas->currentPage()); if (pageInformationDialog.exec() == QDialog::Accepted) { m_pDrawPadCanvas->currentPage()->setTitle(pageInformationDialog.selectedTitle()); } } void DrawPad::loadConfig() { Config config("drawpad"); config.setGroup("General"); m_pAntiAliasingAction->setOn(config.readBoolEntry("AntiAliasing", false)); m_pPenWidthSpinBox->setValue(config.readNumEntry("PenWidth", 1)); changePenColor(QColor(config.readEntry("PenColor", Qt::black.name()))); changeBrushColor(QColor(config.readEntry("BrushColor", Qt::white.name()))); m_pDrawPadCanvas->selectPage(config.readNumEntry("PagePosition", 1)); } void DrawPad::saveConfig() { Config config("drawpad"); config.setGroup("General"); config.writeEntry("PagePosition", (int)m_pDrawPadCanvas->pagePosition()); config.writeEntry("AntiAliasing", antiAliasing()); config.writeEntry("PenWidth", (int)m_pen.width()); config.writeEntry("PenColor", m_pen.color().name()); config.writeEntry("BrushColor", m_brush.color().name()); } diff --git a/noncore/multimedia/showimg/showimg.cpp b/noncore/multimedia/showimg/showimg.cpp index 56bdecf..b7754f7 100644 --- a/noncore/multimedia/showimg/showimg.cpp +++ b/noncore/multimedia/showimg/showimg.cpp @@ -1,1251 +1,1251 @@ /********************************************************************** ** 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. ** **********************************************************************/ // // Full-screen and rotation options contributed by Robert Wittams <robert@wittams.com> // #include "showimg.h" #include "ImageFileSelector.h" #include "settingsdialog.h" #include <opie/ofiledialog.h> #include <qpe/qpeapplication.h> #include <qpe/config.h> #include <qpe/resource.h> #include <qpe/fileselector.h> #include <qpe/applnk.h> #include <qfileinfo.h> #include <math.h> #include <qpe/qpemenubar.h> #include <qwidgetstack.h> #include <qpe/qpetoolbar.h> #include <qaction.h> #include <qfiledialog.h> #include <qmessagebox.h> #include <qpopupmenu.h> #include <qscrollview.h> #include <qlabel.h> #include <qpainter.h> #include <qkeycode.h> #include <qapplication.h> #include <qclipboard.h> #include <qtimer.h> #include <qspinbox.h> ControlsDialog::ControlsDialog(const QString &caption,QImage image,int *brightness,QWidget *parent) : QDialog(parent,0,true) { setCaption(caption); if ( parent ) { setPalette(parent->palette()); } b=brightness; img=image; setMinimumSize(140,80); QGridLayout *gl= new QGridLayout(this,2,2,4,4); pixmap =new ImageWidget(this);; QPixmap pm; pm.convertFromImage(img); pixmap->setPixmap(pm); pixmap->setMinimumSize(pm.width(),pm.height()); gl->addMultiCellWidget(pixmap,0,0,0,2,AlignCenter); QLabel *l=new QLabel(tr("Brightness")+":",this); gl->addWidget(l,1,0,AlignLeft); spb=new QSpinBox(-100,100,2,this); gl->addWidget(spb,1,1,AlignRight); spb->setValue(0); connect(spb,SIGNAL(valueChanged(int)),this, SLOT(bValueChanged(int))); } void ControlsDialog::bValueChanged(int value) { QImage nImage=img; nImage.detach(); ImageViewer::intensity(nImage, (float)value/100); QPixmap pm; pm.convertFromImage(nImage); pixmap->setPixmap(pm); pixmap->repaint(false); } void ControlsDialog::accept() { *b=spb->value(); done(1); } //=========================================================================== InfoDialog::InfoDialog(const QString &caption, const QStringList text,QWidget *parent) : QDialog(parent,0,true) { setCaption(caption); if ( parent ) { setPalette(parent->palette()); } QString labels[]={ tr("File Name"),tr("Format"),tr("File Size"),tr("Size"),tr("Colors"),tr("Alpha") }; setMinimumSize(180,80); int num=ImageViewer::LAST+1; if ( text[ImageViewer::ALPHA].isEmpty() ) num--; QGridLayout *gl= new QGridLayout(this,num,2,4,2); QLabel *l; int count=0; for ( int i=0;i<num;i++ ) { if ( i==1 ) { QFrame *frm=new QFrame(this); frm->setFrameStyle(QFrame::HLine|QFrame::Sunken); gl->addMultiCellWidget(frm,i,i,0,1); } else { l=new QLabel( tr( labels[count] )+":",this); gl->addWidget(l,i,0,AlignLeft); l=new QLabel(text[count],this); gl->addWidget(l,i,1,AlignRight); count++; } } } void InfoDialog::displayInfo(const QString &caption, const QStringList text, QWidget *parent) { InfoDialog *dlg=new InfoDialog(caption,text,parent); dlg->exec(); delete dlg; } //=========================================================================== ImagePane::ImagePane( QWidget *parent ) : QWidget( parent ) { vb = new QVBoxLayout( this ); image = new QScrollView(this,0,WResizeNoErase|WNorthWestGravity); pic=new ImageWidget(image); image->addChild(pic); connect(pic, SIGNAL( clicked() ), this, SLOT( imageClicked() )); vb->addWidget( image ); } void ImagePane::setPixmap( const QPixmap &pm ) { pic->setPixmap( pm ); pic->resize(pm.width(),pm.height()); image->updateScrollBars (); pic->repaint(false); } void ImagePane::imageClicked() { emit clicked(); } //=========================================================================== /* Draws the portion of the scaled pixmap that needs to be updated */ void ImageWidget::paintEvent( QPaintEvent *e ) { QPainter painter(this); painter.setClipRect(e->rect()); painter.fillRect(0,0,width(),height(),QColor(0,0,0)); if ( pixmap.size() != QSize( 0, 0 ) ) { // is an image loaded? painter.drawPixmap((width() - pixmap.width()) / 2, (height() - pixmap.height()) / 2, pixmap); } } void ImageWidget::mouseReleaseEvent(QMouseEvent *) { emit clicked(); } //=========================================================================== ImageViewer::ImageViewer( QWidget *parent, const char *name, int wFlags ) : QMainWindow( parent, name, WResizeNoErase ), filename( 0 ), bFromDocView( FALSE ) { setCaption( tr("Image Viewer") ); setIcon( Resource::loadPixmap( "ImageViewer" ) ); Config cfg("Image Viewer"); cfg.setGroup("Image Viewer"); showThumbView=cfg.readBoolEntry("ShowThumbnails",false); isSized=cfg.readBoolEntry("SizeToScreen",true); isFullScreen = FALSE; setToolBarsMovable( FALSE ); toolBar = new QPEToolBar( this ); toolBar->setHorizontalStretchable( TRUE ); - menuBar = new QPEMenuBar( toolBar ); + menuBar = new QMenuBar( toolBar ); current=menuBar; fileMenuFile = new QPopupMenu(this); //menuBarmenubarFile->insertItem( tr("File"), fileMenu ); fileMenuFile->insertItem(tr("Open"), this, SLOT(openFile()), 0); viewMenuFile = new QPopupMenu( this ); //menubarFile->insertItem( tr("View"), viewMenu ); viewMenuFile->insertItem( tr("Thumbnail View"), this, SLOT(switchThumbView()), 0, SHOW_THUMBNAILS ); viewMenuFile->setItemChecked ( SHOW_THUMBNAILS, showThumbView ); optionsMenuFile = new QPopupMenu( this); //menubarFile->insertItem( tr("Options"),optionsMenu ); slideAction = new QAction( tr( "Slide show" ), Resource::loadIconSet( "slideshow" ), QString::null, 0, this, 0 ); slideAction->setToggleAction( TRUE ); connect( slideAction, SIGNAL( toggled(bool) ), this, SLOT( slideShow(bool) ) ); slideAction->addTo( optionsMenuFile); // slideAction->addTo( toolBar ); // optionsMenuFile->insertItem( tr("Slideshow") ); optionsMenuFile->insertSeparator(); optionsMenuFile->insertItem( tr("Preferences.."), this, SLOT(settings()), 0); // optionsMenuFile->insertItem( tr("Help"), this, SLOT(help()), 0); QStrList fmt = QImage::outputFormats(); fileMenuView = new QPopupMenu( this ); //menubarView->insertItem( tr("File"),fileMenu ); fileMenuView->insertItem( tr("Image Info ..."),this, SLOT(displayInfoDialog()),0 ); fileMenuView->insertSeparator(); viewMenuView = new QPopupMenu(this ); viewMenuView->setCheckable ( true ); //menubarView->insertItem( tr("View"),viewMenu ); viewMenuView->insertItem(tr("Horizontal flip"), this, SLOT(hFlip()), 0); viewMenuView->insertItem(tr("Vertical flip"), this, SLOT(vFlip()), 0); stack = new QWidgetStack( this ); stack->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ) ); setCentralWidget( stack ); imagePanel = new ImagePane( stack ); connect(imagePanel, SIGNAL(clicked()), this, SLOT(normalView())); ImageFileSelector::CURRENT_VIEW cv; if(showThumbView) cv=ImageFileSelector::THUMBNAIL; else cv=ImageFileSelector::DETAILED; qDebug("cv = %d",cv); fileSelector = new ImageFileSelector( cv,stack, "fs"); //switchThumbView(); //fileSelector = new ImageFileSelector("image/*", stack, "fs"); //fileSelector->setNewVisible(FALSE); //fileSelector->setCloseVisible(FALSE); connect( fileSelector, SIGNAL( closeMe() ), this, SLOT( closeFileSelector() ) ); connect( fileSelector, SIGNAL( fileSelected( const DocLnk &) ), this, SLOT( openFile( const DocLnk & ) ) ); imageList = fileSelector->fileList(); slideAction->setEnabled( imageList.count() != 0); iconToolBar = new QPEToolBar(this); QAction *a; a = new QAction( tr( "Open ..." ), Resource::loadPixmap( "fileopen" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( open() ) ); a->addTo( fileMenuView); a->addTo( iconToolBar ); a = new QAction( tr( "Rotate 90"), Resource::loadPixmap( "rotate90" ), QString::null, 0, this, 0); connect( a, SIGNAL( activated() ), this, SLOT( rot90() ) ); a->addTo( iconToolBar ); a->addTo( viewMenuView ); a = new QAction( tr( "Rotate 180" ), Resource::loadPixmap( "repeat" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( rot180() ) ); a->addTo( iconToolBar ); a->addTo( viewMenuView ); a = new QAction( tr( "Rotate 270"), Resource::loadPixmap( "rotate270" ), QString::null, 0, this, 0); connect( a, SIGNAL( activated() ), this, SLOT( rot270() ) ); //a->addTo( iconToolBar ); a->addTo( viewMenuView ); viewMenuView->insertSeparator(); viewMenuView->insertItem(tr("Brightness ..."), this, SLOT(displayControlsDialog()), 0); viewMenuView->insertItem(tr("Black And White"), this, SLOT(blackAndWhite()), 0,BLACKANDWHITE); viewMenuView->insertSeparator(); sss = new QAction( tr( "Scale to Screen"), Resource::loadPixmap( "scale" ), QString::null, 0, this, 0,true); connect( sss, SIGNAL( activated() ), this, SLOT( switchSizeToScreen() ) ); sss->addTo( iconToolBar ); sss->addTo( viewMenuView ); sss->setOn(isSized); viewMenuView->insertSeparator(); a = new QAction( tr( "Fullscreen" ), Resource::loadPixmap( "fullscreen" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( fullScreen() ) ); a->addTo( iconToolBar ); a->addTo( viewMenuView); a = new QAction( tr( "Stop Slideshow" ), Resource::loadPixmap( "quit_icon" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( stopSlideShow() ) ); a->addTo( iconToolBar ); a->addTo( viewMenuView); Config config( "ImageViewer" ); config.setGroup( "SlideShow" ); slideDelay = config.readNumEntry( "Delay", 2); slideRepeat = config.readBoolEntry( "Repeat", FALSE ); slideReverse = config.readBoolEntry("Reverse", FALSE); config.setGroup("Default"); rotateOnLoad = config.readBoolEntry("Rotate", FALSE); fastLoad = config.readBoolEntry("FastLoad", TRUE); slideTimer = new QTimer( this ); connect( slideTimer, SIGNAL(timeout()), this, SLOT(slideUpdate()) ); switchToFileSelector(); setMouseTracking( TRUE ); } ImageViewer::~ImageViewer() { Config cfg("Image Viewer"); cfg.setGroup("Image Viewer"); cfg.writeEntry("ShowThumbnails",(int)showThumbView); cfg.writeEntry("SizeToScreen",(int)isSized); cfg.setGroup( "SlideShow" ); cfg.writeEntry( "Delay", slideDelay); cfg.writeEntry( "Repeat", slideRepeat ); cfg.writeEntry("Reverse", slideReverse); cfg.setGroup("Default"); cfg.writeEntry("Rotate", rotateOnLoad); cfg.writeEntry("FastLoad", fastLoad); delete imagePanel; // in case it is fullscreen } void ImageViewer::help() { } void ImageViewer::settings() { SettingsDialog dlg( this, 0, TRUE ); dlg.setDelay( slideDelay ); dlg.setRepeat( slideRepeat ); dlg.setReverse( slideReverse ); dlg.setRotate(rotateOnLoad); dlg.setFastLoad(fastLoad); if ( QPEApplication::execDialog(&dlg) == QDialog::Accepted ) { qDebug("<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>"); slideDelay = dlg.delay(); slideRepeat = dlg.repeat(); slideReverse = dlg.reverse(); rotateOnLoad = dlg.rotate(); fastLoad = dlg.fastLoad(); Config config( "ImageViewer" ); config.setGroup( "SlideShow" ); config.writeEntry( "Delay", slideDelay ); config.writeEntry( "Repeat", slideRepeat ); config.writeEntry("Reverse", slideReverse); config.setGroup("Default"); config.writeEntry("Rotate", rotateOnLoad); config.writeEntry("FastLoad", fastLoad); } } void ImageViewer::switchSizeToScreen() { isSized=!isSized; sss->setOn(isSized); updateImage(); } void ImageViewer::updateImage() { if ( isSized ) { imagePanel->setPixmap(pmScaled); } else { imagePanel->setPixmap(pm); } } void ImageViewer::switchThumbView() { showThumbView=!showThumbView; viewMenuFile->setItemChecked ( SHOW_THUMBNAILS, showThumbView ); fileSelector->switchView(); } void ImageViewer::switchToFileSelector() { stack->raiseWidget(fileSelector); menuBar->clear(); menuBar->insertItem( tr("File"), fileMenuFile ); menuBar->insertItem( tr("View"), viewMenuFile ); menuBar->insertItem( tr("Options"), optionsMenuFile ); iconToolBar->hide(); imagePanel->disable(); slideShow(false); } void ImageViewer::switchToImageView() { stack->raiseWidget(imagePanel); menuBar->clear(); menuBar->insertItem( tr("File"), fileMenuView ); menuBar->insertItem( tr("View"), viewMenuView ); viewMenuView->setItemEnabled(BLACKANDWHITE,true); iconToolBar->show(); imagePanel->setPosition(0,0); } void ImageViewer::setDocument(const QString& fileref) { delayLoad = fileref; switchToImageView(); QTimer::singleShot( 0, this, SLOT(doDelayedLoad()) ); } void ImageViewer::doDelayedLoad() { show(delayLoad); } void ImageViewer::show() { normalView(); QMainWindow::show(); } void ImageViewer::show(const QString& fileref) { // qDebug("Show "+fileref); bFromDocView = TRUE; closeFileSelector(); DocLnk link(fileref); if ( link.isValid() ) { openFile(link); } else { filename = fileref; updateCaption( fileref ); loadImage( fileref ); } } void ImageViewer::openFile() { MimeTypes types; QStringList image; image << "image/*"; types.insert("Images", image); QString str = OFileDialog::getOpenFileName( 1,QPEApplication::documentDir(),"", types, 0 ); DocLnk link(str); // if ( link.isValid() ) openFile(link); } void ImageViewer::openFile( const DocLnk &link ) { closeFileSelector(); // DocLnk link(file); qDebug("open "+link.name()); updateCaption( link.name() ); loadImage( link.file() ); if (slideTimer->isActive()) { slideTimer->start(slideDelay * 1000, FALSE); } } void ImageViewer::open() { switchToFileSelector(); } void ImageViewer::closeFileSelector() { switchToImageView(); } void ImageViewer::updateCaption( QString name ) { int sep = name.findRev( '/' ); if ( sep >= 0 ) name = name.mid( sep+1 ); setCaption( name + tr(" - Image Viewer") ); } /* This function loads an image from a file. */ void ImageViewer::loadImage( const char *fileName ) { filename = fileName; if ( filename ) { QApplication::setOverrideCursor( waitCursor ); // this might take time //imagePanel->statusLabel()->setText( tr("Loading image...") ); qApp->processEvents(); bool ok = image.load(filename, 0); if ( ok ) { ok = reconvertImage(); updateImageInfo(filename); } if ( !ok ) { pm.resize(0,0); // couldn't load image update(); } QApplication::restoreOverrideCursor(); // restore original cursor } // fastLoad ? ", Fast" : "", // fastLoad ? QMAX(imagewidth/maxsize, imageheight/maxsize) : 1); // matrix.reset(); rotated90 = FALSE; if (rotateOnLoad) { rotated90 = TRUE; rot90(); // matrix.rotate( -90.0 ); } switchToImageView(); updateImage(); } bool ImageViewer::loadSelected() { bool ok = false; if ( stack->visibleWidget() == fileSelector ) { const DocLnk *link = fileSelector->selected(); if ( link ) { if ( link->file() != filename ) { updateCaption( link->name() ); filename = link->file(); qApp->processEvents(); ok = image.load(filename, 0); if ( ok ) { updateImageInfo(filename); ok = reconvertImage(); } if ( !ok ) pm.resize(0,0); } } } if ( !image.isNull() ) { ok = true; closeFileSelector(); } return ok; } bool ImageViewer::reconvertImage() { bool success = FALSE; if ( image.isNull() ) return FALSE; QApplication::setOverrideCursor( waitCursor ); // this might take time if ( pm.convertFromImage(image /*, conversion_flags */ ) ) { pmScaled = QPixmap(); scale(); success = TRUE; // load successful } else { pm.resize(0,0); // couldn't load image } QApplication::restoreOverrideCursor(); // restore original cursor return success; // TRUE if loaded OK } int ImageViewer::calcHeight() { if ( !isFullScreen ) return imagePanel->paneHeight(); else return qApp->desktop()->height(); } /* This functions scales the pixmap in the member variable "pm" to fit the widget size and puts the resulting pixmap in the member variable "pmScaled". */ void ImageViewer::scale() { int h = calcHeight(); if ( image.isNull() ) return; QApplication::setOverrideCursor( waitCursor ); // this might take time if ( imagePanel->paneWidth() == pm.width() && h == pm.height() ) { // no need to scale if widget pmScaled = pm; // size equals pixmap size } else { double hs = (double)h / (double)image.height(); double ws = (double)imagePanel->paneWidth() / (double)image.width(); double scaleFactor = (hs > ws) ? ws : hs; int smoothW = (int)(scaleFactor * image.width()); int smoothH = (int)(scaleFactor * image.height()); pmScaled.convertFromImage( image.smoothScale( smoothW, smoothH ) /*, conversion_flags */ ); } QApplication::restoreOverrideCursor(); // restore original cursor } /* The resize event handler, if a valid pixmap was loaded it will call scale() to fit the pixmap to the new widget size. */ void ImageViewer::resizeEvent( QResizeEvent * ) { if ( pm.size() == QSize( 0, 0 ) ) // we couldn't load the image return; int h = calcHeight(); if ( imagePanel->paneWidth() != pmScaled.width() || h != pmScaled.height() ) { // if new size, scale(); // scale pmScaled to window } if ( image.hasAlphaBuffer() ) erase(); } void ImageViewer::hFlip() { // matrix.scale( -1.0, 1.0 ); setImage(image.mirror(TRUE,FALSE)); } void ImageViewer::vFlip() { // matrix.scale( 1.0, -1.0 ); setImage(image.mirror(FALSE,TRUE)); } void ImageViewer::rot180() { // matrix.rotate( 180.0 ); setImage(image.mirror(TRUE,TRUE)); } void ImageViewer::rot90() { QImage oldimage; oldimage = image.convertDepth(32); // matrix.rotate( -90.0 ); setImage(rotate(oldimage,Rotate90)); } void ImageViewer::rot270() { QImage oldimage; oldimage = image.convertDepth(32); // matrix.rotate(90.0); setImage(rotate(oldimage,Rotate270)); } void ImageViewer::blackAndWhite() { viewMenuView->setItemEnabled(BLACKANDWHITE,false); setImage(toGray(image,false)); } void ImageViewer::displayControlsDialog() { int w=80; int h=w; QImage small; if ( image.width()<w ||image.height()<h ) small=image.smoothScale(w,h); else small=image.copy(0,0,w,h); int newB=0; ControlsDialog *dlg=new ControlsDialog("Image Viewer",small,&newB,this); dlg->exec(); if ( newB ) { intensity(image,(float)newB/100); setImage(image); } } void ImageViewer::displayInfoDialog() { QStringList ls; for ( int i=0;i<LAST;i++ ) ls.append(imageInfo[i]); InfoDialog::displayInfo("Image Viewer",ls,this); } void ImageViewer::normalView() { if ( !imagePanel->parentWidget() ) { isFullScreen = FALSE; stack->addWidget( imagePanel, 1 ); switchToImageView(); if ( isSized ) scale(); updateImage(); } } void ImageViewer::stopSlideShow() { if (slideTimer->isActive()) slideTimer->stop(); } void ImageViewer::fullScreen() { // Full-screen option // contributed by Robert Wittams <robert@wittams.com> if ( imagePanel->parentWidget() && loadSelected() ) { isFullScreen = TRUE; imagePanel->reparent(0,QPoint(0,0)); imagePanel->resize(qApp->desktop()->width(), qApp->desktop()->height()); if ( isSized ) scale(); updateImage(); imagePanel->showFullScreen(); } } void ImageViewer::setImage(const QImage& newimage) { image = newimage; reconvertImage(); updateImage(); } void ImageViewer::updateImageInfo(QString &filePath) { for ( int i=0;i<LAST;i++ ) { imageInfo[i]=""; } imageInfo[FORMAT]=QImage::imageFormat (filePath ); QFileInfo fi(filePath); imageInfo[PATH]=fi.fileName(); imageInfo[FILE_SIZE]=QString::number(fi.size())+" (bytes)"; QString message("%1x%2"); imageInfo[SIZE]=QString("%1x%2"); imageInfo[SIZE]=imageInfo[SIZE].arg(image.width()).arg(image.height()); if ( image.numColors() > 0 ) { imageInfo[COLORS]=tr("%1 colors").arg(image.numColors()); } else if ( image.depth() >= 16 ) { imageInfo[COLORS]=tr(" True color"); } if ( image.hasAlphaBuffer() ) { if ( image.depth() == 8 ) { int i; bool alpha[256]; int nalpha=0; for ( i=0; i<256; i++ ) alpha[i] = FALSE; for ( i=0; i<image.numColors(); i++ ) { int alevel = image.color(i) >> 24; if ( !alpha[alevel] ) { alpha[alevel] = TRUE; nalpha++; } } imageInfo[ALPHA]=tr("%1 alpha levels").arg(nalpha); } else { imageInfo[ALPHA]=tr("8-bit alpha channel"); } } } void ImageViewer::closeEvent( QCloseEvent *e ) { if ( stack->visibleWidget() == imagePanel && !bFromDocView ) { e->ignore(); open(); } else { bFromDocView = FALSE; e->accept(); } } // Intensity,toGray and rotate code courtesy of KDE project. QImage& ImageViewer::intensity(QImage &image, float percent) { int segColors = image.depth() > 8 ? 256 : image.numColors(); unsigned char *segTbl = new unsigned char[segColors]; int pixels = image.depth() > 8 ? image.width()*image.height() : image.numColors(); unsigned int *data = image.depth() > 8 ? (unsigned int *)image.bits() : (unsigned int *)image.colorTable(); bool brighten = (percent >= 0); if ( percent < 0 ) percent = -percent; if ( brighten ) { // keep overflow check out of loops for ( int i=0; i < segColors; ++i ) { int tmp = (int)(i*percent); if ( tmp > 255 ) tmp = 255; segTbl[i] = tmp; } } else { for ( int i=0; i < segColors; ++i ) { int tmp = (int)(i*percent); if ( tmp < 0 ) tmp = 0; segTbl[i] = tmp; } } if ( brighten ) { // same here for ( int i=0; i < pixels; ++i ) { int r = qRed(data[i]); int g = qGreen(data[i]); int b = qBlue(data[i]); int a = qAlpha(data[i]); r = r + segTbl[r] > 255 ? 255 : r + segTbl[r]; g = g + segTbl[g] > 255 ? 255 : g + segTbl[g]; b = b + segTbl[b] > 255 ? 255 : b + segTbl[b]; data[i] = qRgba(r, g, b,a); } } else { for ( int i=0; i < pixels; ++i ) { int r = qRed(data[i]); int g = qGreen(data[i]); int b = qBlue(data[i]); int a = qAlpha(data[i]); r = r - segTbl[r] < 0 ? 0 : r - segTbl[r]; g = g - segTbl[g] < 0 ? 0 : g - segTbl[g]; b = b - segTbl[b] < 0 ? 0 : b - segTbl[b]; data[i] = qRgba(r, g, b, a); } } delete [] segTbl; return image; } QImage& ImageViewer::toGray(QImage &img, bool fast) { if ( img.width() == 0 || img.height() == 0 ) return img; if ( fast ) { if ( img.depth() == 32 ) { register uchar * r(img.bits()); register uchar * g(img.bits() + 1); register uchar * b(img.bits() + 2); uchar * end(img.bits() + img.numBytes()); while ( r != end ) { *r = *g = *b = (((*r + *g) >> 1) + *b) >> 1; // (r + b + g) / 3 r += 4; g += 4; b += 4; } } else { for ( int i = 0; i < img.numColors(); i++ ) { register uint r = qRed(img.color(i)); register uint g = qGreen(img.color(i)); register uint b = qBlue(img.color(i)); register uint gray = (((r + g) >> 1) + b) >> 1; img.setColor(i, qRgba(gray, gray, gray, qAlpha(img.color(i)))); } } } else { int pixels = img.depth() > 8 ? img.width()*img.height() : img.numColors(); unsigned int *data = img.depth() > 8 ? (unsigned int *)img.bits() : (unsigned int *)img.colorTable(); int val, i; for ( i=0; i < pixels; ++i ) { val = qGray(data[i]); data[i] = qRgba(val, val, val, qAlpha(data[i])); } } return img; } QImage ImageViewer::rotate(QImage &img, RotateDirection r) { QImage dest; int x, y; if ( img.depth() > 8 ) { unsigned int *srcData, *destData; switch ( r ) { case Rotate90: dest.create(img.height(), img.width(), img.depth()); for ( y=0; y < img.height(); ++y ) { srcData = (unsigned int *)img.scanLine(y); for ( x=0; x < img.width(); ++x ) { destData = (unsigned int *)dest.scanLine(x); destData[img.height()-y-1] = srcData[x]; } } break; case Rotate180: dest.create(img.width(), img.height(), img.depth()); for ( y=0; y < img.height(); ++y ) { srcData = (unsigned int *)img.scanLine(y); destData = (unsigned int *)dest.scanLine(img.height()-y-1); for ( x=0; x < img.width(); ++x ) destData[img.width()-x-1] = srcData[x]; } break; case Rotate270: dest.create(img.height(), img.width(), img.depth()); for ( y=0; y < img.height(); ++y ) { srcData = (unsigned int *)img.scanLine(y); for ( x=0; x < img.width(); ++x ) { destData = (unsigned int *)dest.scanLine(img.width()-x-1); destData[y] = srcData[x]; } } break; default: dest = img; break; } } else { unsigned char *srcData, *destData; unsigned int *srcTable, *destTable; switch ( r ) { case Rotate90: dest.create(img.height(), img.width(), img.depth()); dest.setNumColors(img.numColors()); srcTable = (unsigned int *)img.colorTable(); destTable = (unsigned int *)dest.colorTable(); for ( x=0; x < img.numColors(); ++x ) destTable[x] = srcTable[x]; for ( y=0; y < img.height(); ++y ) { srcData = (unsigned char *)img.scanLine(y); for ( x=0; x < img.width(); ++x ) { destData = (unsigned char *)dest.scanLine(x); destData[img.height()-y-1] = srcData[x]; } } break; case Rotate180: dest.create(img.width(), img.height(), img.depth()); dest.setNumColors(img.numColors()); srcTable = (unsigned int *)img.colorTable(); destTable = (unsigned int *)dest.colorTable(); for ( x=0; x < img.numColors(); ++x ) destTable[x] = srcTable[x]; for ( y=0; y < img.height(); ++y ) { srcData = (unsigned char *)img.scanLine(y); destData = (unsigned char *)dest.scanLine(img.height()-y-1); for ( x=0; x < img.width(); ++x ) destData[img.width()-x-1] = srcData[x]; } break; case Rotate270: dest.create(img.height(), img.width(), img.depth()); dest.setNumColors(img.numColors()); srcTable = (unsigned int *)img.colorTable(); destTable = (unsigned int *)dest.colorTable(); for ( x=0; x < img.numColors(); ++x ) destTable[x] = srcTable[x]; for ( y=0; y < img.height(); ++y ) { srcData = (unsigned char *)img.scanLine(y); for ( x=0; x < img.width(); ++x ) { destData = (unsigned char *)dest.scanLine(img.width()-x-1); destData[y] = srcData[x]; } } break; default: dest = img; break; } } return (dest); } void ImageViewer::slideShow( bool on ) { if (on) { if (!imageList.isEmpty()) { slideTimer->start(slideDelay * 1000, FALSE); filename = ""; // force restart slideReverse ? prevImage() : nextImage(); } } else { slideTimer->stop(); slideAction->setOn( false); } } void ImageViewer::slideUpdate() { bool final_image = slideReverse ? prevImage() : nextImage(); if (final_image && !slideRepeat) { slideTimer->stop(); slideAction->setOn(FALSE); } } // // Display the image after the current one in the image list. // Return TRUE if the next call to nextImage() will wrap around to the // first image in the list (ie. we're now viewing the last image in the list). // bool ImageViewer::nextImage(void) { int idx = 0; if (imageList.count() > 0) { idx = imageIndex(); if (idx != -1) { if (idx == int(imageList.count() - 1)) { idx = 0; } else { idx++; } } else { idx = 0; } openFile(imageList[idx]); } return idx == int(imageList.count() - 1) ? TRUE : FALSE; } // // Display the image preceeding the current one in the image list. // Return TRUE if the next call to prevImage() will wrap around to the last // image in the list (ie. we're now viewing the first image in the list). // bool ImageViewer::prevImage(void) { int idx = -1; if (imageList.count() > 0) { idx = imageIndex(); if (idx != -1) { if (idx == 0) { idx = imageList.count() - 1; } else { idx--; } } else { idx = imageList.count() - 1; } openFile(imageList[idx]); } return idx == 0 ? TRUE : FALSE; } // // Return the index into the imageList of the currently viewed // image (ie. ImageViewer::filename in ImageViewer::imageList). // int ImageViewer::imageIndex(void) { QValueListConstIterator<DocLnk> i; int index; if (imageList.count() == 0) { return -1; } for (index = 0, i = imageList.begin(); i != imageList.end(); ++i, index++) { if ((*i).file() == filename) { return index; } } return -1; } diff --git a/noncore/multimedia/showimg/showimg.h b/noncore/multimedia/showimg/showimg.h index abbd976..da4c0b6 100644 --- a/noncore/multimedia/showimg/showimg.h +++ b/noncore/multimedia/showimg/showimg.h @@ -1,289 +1,289 @@ /********************************************************************** ** 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 SHOWIMG_H #define SHOWIMG_H #include <qwidget.h> #include <qmainwindow.h> #include <qimage.h> #include <qlabel.h> #include <qlayout.h> #include <qscrollview.h> #include <qdialog.h> #include <qstringlist.h> #include <qvaluelist.h> #include <qwmatrix.h> class QAction; class QPEToolBar; -class QPEMenuBar; +class QMenuBar; class QPopupMenu; class QWidgetStack; class FileSelector; class DocLnk; class QLabel; class QAction; class QSpinBox; class ImageFileSelector; class QTimer; class ImageWidget : public QWidget { Q_OBJECT public: ImageWidget( QWidget *parent=0 ) : QWidget( parent ) { setBackgroundMode(NoBackground); } ~ImageWidget() { } void setPixmap( const QPixmap &pm ) { pixmap = pm; show(); } signals: void clicked(); protected: void paintEvent( QPaintEvent * ); void mouseReleaseEvent(QMouseEvent* event); private: QPixmap pixmap; }; class InfoDialog:public QDialog { Q_OBJECT public: static void displayInfo(const QString &caption, const QStringList text, QWidget *parent); private: InfoDialog(const QString &caption,const QStringList text, QWidget *parent); }; class ControlsDialog:public QDialog { Q_OBJECT public: ControlsDialog(const QString &caption,const QImage image,int *brightness, QWidget *parent); private slots: void bValueChanged(int); void accept(); private: ImageWidget *pixmap; QSpinBox *spb; QImage img; int *b; }; class ImagePane : public QWidget { Q_OBJECT public: ImagePane( QWidget *parent=0 ); ~ImagePane() { } //void showStatus(); //void hideStatus(); //QLabel *statusLabel() //{ // return status; //} void setPixmap( const QPixmap &pm ); int paneWidth() const { return image->visibleWidth(); } int paneHeight() const { return image->visibleHeight(); } void setPosition(int x, int y) { image->setContentsPos (x,y ); } void disable() { pic->hide(); } signals: void clicked(); private: QScrollView *image; ImageWidget *pic; QVBoxLayout *vb; private slots: void imageClicked(); }; class ImageViewer : public QMainWindow { Q_OBJECT public: static QString appName() { return QString::fromLatin1("showimg"); } ImageViewer( QWidget *parent=0, const char *name=0, int wFlags=0 ); ~ImageViewer(); void loadImage( const char *fileName ); void show(const QString& fileref); void show(); enum INFO_STRINGS { PATH, FORMAT, FILE_SIZE, SIZE, COLORS, ALPHA, LAST }; enum RotateDirection { Rotate90, Rotate180, Rotate270 }; static QImage rotate(QImage &img, RotateDirection r); static QImage& intensity(QImage &image, float percent); static QImage& toGray(QImage &image, bool fast = false); bool showThumbView; // a flag to indicate if FileSelector should be initialized with thumbnail view protected: void resizeEvent( QResizeEvent * ); void closeEvent( QCloseEvent * ); private: int imageIndex(void); void updateCaption( QString name ); bool loadSelected(); void scale(); bool reconvertImage(); int calcHeight(); void setImage(const QImage& newimage); void updateImageInfo(QString &filePath); void switchToFileSelector(); void switchToImageView(); void updateImage(); private slots: void slideShow( bool on ); void help(); void slideUpdate(); bool nextImage(); bool prevImage(); void settings(); void switchThumbView(); void switchSizeToScreen(); void setDocument(const QString& fileref); void doDelayedLoad(); void openFile( const DocLnk &file ); void openFile(); void open(); void closeFileSelector(); void hFlip(); void vFlip(); void rot180(); void rot90(); void rot270(); void normalView(); void fullScreen(); void stopSlideShow(); void blackAndWhite(); void displayInfoDialog(); void displayControlsDialog(); private: QWMatrix matrix; bool rotated90; enum MENU_ITEMS { SHOW_THUMBNAILS, SIZE_TO_SCREEN, BLACKANDWHITE }; QString filename; QString delayLoad; QImage image; // the loaded image QPixmap pm; // the converted pixmap QPixmap pmScaled; // the scaled pixmap QPEToolBar *toolBar; QPEToolBar *iconToolBar; - QPEMenuBar *menuBar; - QPEMenuBar *current; + QMenuBar *menuBar; + QMenuBar *current; QPopupMenu *fileMenuFile; QPopupMenu *viewMenuFile; QPopupMenu *optionsMenuFile; QPopupMenu *fileMenuView; QPopupMenu *viewMenuView; QAction *sss; // scale to screen size QLabel *lab; ImagePane *imagePanel; QWidgetStack *stack; //FileSelector *fileSelector; ImageFileSelector *fileSelector; bool isFullScreen; bool isSized; // true if image is to be resized to fit the window size bool bFromDocView; // a flag to indicate whether or not we were // launched from the document view... int slideDelay; bool slideRepeat; bool slideReverse; // show slideshow in reverse order bool rotateOnLoad; // rotate by 90 degrees on loading bool fastLoad; QTimer *slideTimer; QValueList<DocLnk> imageList; QAction *slideAction; QString imageInfo[LAST]; }; #endif // SHOWIMG_H diff --git a/noncore/net/opieftp/opieftp.cpp b/noncore/net/opieftp/opieftp.cpp index ee7d32f..48629bf 100644 --- a/noncore/net/opieftp/opieftp.cpp +++ b/noncore/net/opieftp/opieftp.cpp @@ -1,1095 +1,1095 @@ /*************************************************************************** opieftp.cpp ------------------- ** Created: Sat Mar 9 23:33:09 2002 copyright : (C) 2002 by ljp email : ljp@llornkcor.com * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ //#define DEVELOPERS_VERSION #include "opieftp.h" extern "C" { #include "../ftplib/ftplib.h" } #include "inputDialog.h" #include <qpe/qpemenubar.h> #include <qpe/qpeapplication.h> #include <qpe/resource.h> #include <qpe/config.h> #include <qpe/mimetype.h> #include <qtextstream.h> #include <qpushbutton.h> #include <qtoolbutton.h> #include <qcombobox.h> #include <qlistview.h> #include <qlabel.h> #include <qprogressbar.h> #include <qspinbox.h> #include <qtabwidget.h> #include <qlayout.h> #include <qmessagebox.h> #include <qlineedit.h> #include <qlistbox.h> #include <unistd.h> #include <stdlib.h> QProgressBar *ProgressBar; static netbuf *conn=NULL; static int log_progress(netbuf *, int xfered, void *) { // int fsz = *(int *)arg; // int pct = (xfered * 100) / fsz; // printf("%3d%%\r", pct); // fflush(stdout); ProgressBar->setProgress(xfered); qApp->processEvents(); return 1; } OpieFtp::OpieFtp( QWidget* parent, const char* name, WFlags fl) : QMainWindow( parent, name, fl ) { setCaption( tr( "OpieFtp" ) ); fuckeduphack=FALSE; QGridLayout *layout = new QGridLayout( this ); layout->setSpacing( 2); layout->setMargin( 2); connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); - QPEMenuBar *menuBar = new QPEMenuBar(this); + QMenuBar *menuBar = new QMenuBar(this); // QPEToolBar *menuBar = new QPEToolBar(this); // menuBar->setHorizontalStretchable( TRUE ); QWMatrix matrix; QPixmap pix(Resource::loadPixmap( "UnknownDocument" )); matrix.scale( .4, .4); unknownXpm = pix.xForm(matrix); connectionMenu = new QPopupMenu( this ); localMenu = new QPopupMenu( this ); remoteMenu = new QPopupMenu( this ); tabMenu = new QPopupMenu( this ); layout->addMultiCellWidget( menuBar, 0, 0, 0, 2 ); menuBar->insertItem( tr( "Connection" ), connectionMenu); // menuBar->insertItem( tr( "Local" ), localMenu); // menuBar->insertItem( tr( "Remote" ), remoteMenu); menuBar->insertItem( tr( "View" ), tabMenu); tabMenu->insertItem( tr( "Local" ), localMenu); tabMenu->insertItem( tr( "Remote" ), remoteMenu); connectionMenu->insertItem( tr( "New" ), this, SLOT( newConnection() )); connectionMenu->insertItem( tr( "Connect" ), this, SLOT( connector() )); connectionMenu->insertItem( tr( "Disconnect" ), this, SLOT( disConnector() )); localMenu->insertItem( tr( "Show Hidden Files" ), this, SLOT( showHidden() )); localMenu->insertSeparator(); localMenu->insertItem( tr( "Upload" ), this, SLOT( localUpload() )); localMenu->insertItem( tr( "Make Directory" ), this, SLOT( localMakDir() )); localMenu->insertItem( tr( "Rename" ), this, SLOT( localRename() )); localMenu->insertSeparator(); localMenu->insertItem( tr( "Delete" ), this, SLOT( localDelete() )); localMenu->setCheckable(TRUE); remoteMenu->insertItem( tr( "Download" ), this, SLOT( remoteDownload() )); remoteMenu->insertItem( tr( "Make Directory" ), this, SLOT( remoteMakDir() )); remoteMenu->insertItem( tr( "Rename" ), this, SLOT( remoteRename() )); remoteMenu->insertSeparator(); remoteMenu->insertItem( tr( "Delete" ), this, SLOT( remoteDelete() )); tabMenu->insertSeparator(); tabMenu->insertItem( tr( "Switch to Local" ), this, SLOT( switchToLocalTab() )); tabMenu->insertItem( tr( "Switch to Remote" ), this, SLOT( switchToRemoteTab() )); tabMenu->insertItem( tr( "Switch to Config" ), this, SLOT( switchToConfigTab() )); tabMenu->insertSeparator(); // tabMenu->insertItem( tr( "About" ), this, SLOT( doAbout() )); tabMenu->setCheckable(TRUE); cdUpButton = new QToolButton( this,"cdUpButton"); cdUpButton->setPixmap(Resource::loadPixmap("up")); cdUpButton ->setFixedSize( QSize( 20, 20 ) ); connect( cdUpButton ,SIGNAL(released()),this,SLOT( upDir()) ); layout->addMultiCellWidget( cdUpButton, 0, 0, 3, 3 ); cdUpButton->hide(); // docButton = new QPushButton(Resource::loadIconSet("DocsIcon"),"",this,"docsButton"); // docButton->setFixedSize( QSize( 20, 20 ) ); // connect( docButton,SIGNAL(released()),this,SLOT( docButtonPushed()) ); // docButton->setFlat(TRUE); // layout->addMultiCellWidget( docButton, 0, 0, 6, 6 ); homeButton = new QToolButton(this,"homeButton"); homeButton->setPixmap( Resource::loadPixmap("home")); homeButton->setFixedSize( QSize( 20, 20 ) ); connect(homeButton,SIGNAL(released()),this,SLOT(homeButtonPushed()) ); layout->addMultiCellWidget( homeButton, 0, 0, 4, 4); homeButton->hide(); TabWidget = new QTabWidget( this, "TabWidget" ); layout->addMultiCellWidget( TabWidget, 1, 1, 0, 4 ); // TabWidget->setTabShape(QTabWidget::Triangular); tab = new QWidget( TabWidget, "tab" ); tabLayout = new QGridLayout( tab ); tabLayout->setSpacing( 2); tabLayout->setMargin( 2); Local_View = new QListView( tab, "Local_View" ); // Local_View->setResizePolicy( QListView::AutoOneFit ); Local_View->addColumn( tr("File"),150); Local_View->addColumn( tr("Date"),-1); Local_View->setColumnAlignment(1,QListView::AlignRight); Local_View->addColumn( tr("Size"),-1); Local_View->setColumnAlignment(2,QListView::AlignRight); Local_View->setAllColumnsShowFocus(TRUE); Local_View->setMultiSelection( TRUE); Local_View->setSelectionMode(QListView::Extended); Local_View->setFocusPolicy(QWidget::ClickFocus); QPEApplication::setStylusOperation( Local_View->viewport(),QPEApplication::RightOnHold); tabLayout->addWidget( Local_View, 0, 0 ); connect( Local_View, SIGNAL( clicked( QListViewItem*)), this,SLOT( localListClicked(QListViewItem *)) ); // connect( Local_View, SIGNAL( doubleClicked( QListViewItem*)), // this,SLOT( localListClicked(QListViewItem *)) ); connect( Local_View, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int)), this,SLOT( ListPressed(int, QListViewItem *, const QPoint&, int)) ); TabWidget->insertTab( tab, tr( "Local" ) ); tab_2 = new QWidget( TabWidget, "tab_2" ); tabLayout_2 = new QGridLayout( tab_2 ); tabLayout_2->setSpacing( 2); tabLayout_2->setMargin( 2); Remote_View = new QListView( tab_2, "Remote_View" ); Remote_View->addColumn( tr("File"),150); Remote_View->addColumn( tr("Date"),-1); // Remote_View->setColumnAlignment(1,QListView::AlignRight); Remote_View->addColumn( tr("Size"),-1); Remote_View->setColumnAlignment(2,QListView::AlignRight); Remote_View->setColumnAlignment(3,QListView::AlignCenter); Remote_View->addColumn( tr("Dir"),-1); Remote_View->setColumnAlignment(4,QListView::AlignRight); Remote_View->setAllColumnsShowFocus(TRUE); Remote_View->setMultiSelection( FALSE); Remote_View->setSelectionMode(QListView::Extended); Remote_View->setFocusPolicy(QWidget::ClickFocus); QPEApplication::setStylusOperation( Remote_View->viewport(),QPEApplication::RightOnHold); connect( Remote_View, SIGNAL( clicked( QListViewItem*)), this,SLOT( remoteListClicked(QListViewItem *)) ); connect( Remote_View, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int)), this,SLOT( RemoteListPressed(int, QListViewItem *, const QPoint&, int)) ); tabLayout_2->addWidget( Remote_View, 0, 0 ); TabWidget->insertTab( tab_2, tr( "Remote" ) ); tab_3 = new QWidget( TabWidget, "tab_3" ); tabLayout_3 = new QGridLayout( tab_3 ); tabLayout_3->setSpacing( 2); tabLayout_3->setMargin( 2); TextLabel1 = new QLabel( tab_3, "TextLabel1" ); TextLabel1->setText( tr( "Username" ) ); tabLayout_3->addMultiCellWidget( TextLabel1, 0, 0, 0, 1 ); UsernameComboBox = new QComboBox( FALSE, tab_3, "UsernameComboBox" ); UsernameComboBox->setEditable(TRUE); tabLayout_3->addMultiCellWidget( UsernameComboBox, 1, 1, 0, 1 ); connect( UsernameComboBox,SIGNAL(textChanged(const QString &)),this, SLOT( UsernameComboBoxEdited(const QString & ) )); TextLabel2 = new QLabel( tab_3, "TextLabel2" ); TextLabel2->setText( tr( "Password" ) ); tabLayout_3->addMultiCellWidget( TextLabel2, 0, 0, 2, 3 ); PasswordEdit = new QLineEdit( "", tab_3, "PasswordComboBox" ); PasswordEdit->setEchoMode(QLineEdit::Password); tabLayout_3->addMultiCellWidget( PasswordEdit, 1, 1, 2, 3 ); connect( PasswordEdit,SIGNAL(textChanged(const QString &)),this, SLOT( PasswordEditEdited(const QString & ) )); //PasswordEdit->setFixedWidth(85); TextLabel3 = new QLabel( tab_3, "TextLabel3" ); TextLabel3->setText( tr( "Remote server" ) ); tabLayout_3->addMultiCellWidget( TextLabel3, 2, 2, 0, 1 ); ServerComboBox = new QComboBox( FALSE, tab_3, "ServerComboBox" ); ServerComboBox->setEditable(TRUE); tabLayout_3->addMultiCellWidget( ServerComboBox, 3, 3, 0, 1 ); connect(ServerComboBox,SIGNAL(activated(int)),this,SLOT(serverComboSelected(int ) )); connect(ServerComboBox,SIGNAL(textChanged(const QString &)),this, SLOT(serverComboEdited(const QString & ) )); QLabel *TextLabel5 = new QLabel( tab_3, "TextLabel5" ); TextLabel5->setText( tr( "Remote path" ) ); tabLayout_3->addMultiCellWidget( TextLabel5, 2, 2, 2, 3 ); remotePath = new QLineEdit( "/", tab_3, "remotePath" ); tabLayout_3->addMultiCellWidget( remotePath, 3, 3, 2, 3 ); TextLabel4 = new QLabel( tab_3, "TextLabel4" ); TextLabel4->setText( tr( "Port" ) ); tabLayout_3->addMultiCellWidget( TextLabel4, 4, 4, 0, 1 ); PortSpinBox = new QSpinBox( tab_3, "PortSpinBox" ); PortSpinBox->setButtonSymbols( QSpinBox::UpDownArrows ); PortSpinBox->setMaxValue(32786); tabLayout_3->addMultiCellWidget( PortSpinBox, 4, 4, 1, 1); serverListView = new QListBox( tab_3, "ServerListView" ); tabLayout_3->addMultiCellWidget( serverListView , 5, 5, 0, 5); connect( serverListView, SIGNAL( highlighted( const QString &)), this,SLOT( serverListClicked( const QString &) ) ); connectServerBtn = new QPushButton( tr("Connect"), tab_3 , "ConnectButton" ); tabLayout_3->addMultiCellWidget( connectServerBtn, 6, 6, 0, 1); connectServerBtn->setToggleButton(TRUE); connect(connectServerBtn,SIGNAL( toggled( bool)),SLOT( connectorBtnToggled(bool) )); newServerButton= new QPushButton( tr("Add"), tab_3 , "NewServerButton" ); tabLayout_3->addMultiCellWidget( newServerButton, 6, 6, 2, 2); connect( newServerButton,SIGNAL( clicked()),SLOT( NewServer() )); QPushButton *deleteServerBtn; deleteServerBtn = new QPushButton( tr("Delete"), tab_3 , "OpenButton" ); tabLayout_3->addMultiCellWidget( deleteServerBtn, 6, 6, 3, 3); connect(deleteServerBtn,SIGNAL(clicked()),SLOT(deleteServer())); QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding ); tabLayout_3->addItem( spacer, 5, 0 ); TabWidget->insertTab( tab_3, tr( "Config" ) ); connect(TabWidget,SIGNAL(currentChanged(QWidget *)), this,SLOT(tabChanged(QWidget*))); currentDir.setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All); currentDir.setPath( QDir::currentDirPath()); // currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst); currentPathCombo = new QComboBox( FALSE, this, "currentPathCombo" ); layout->addMultiCellWidget( currentPathCombo, 3, 3, 0, 4); currentPathCombo ->setFixedWidth(220); currentPathCombo->setEditable(TRUE); currentPathCombo->lineEdit()->setText( currentDir.canonicalPath()); connect( currentPathCombo, SIGNAL( activated( const QString & ) ), this, SLOT( currentPathComboActivated( const QString & ) ) ); connect( currentPathCombo->lineEdit(),SIGNAL(returnPressed()), this,SLOT(currentPathComboChanged())); ProgressBar = new QProgressBar( this, "ProgressBar" ); layout->addMultiCellWidget( ProgressBar, 4, 4, 0, 4); ProgressBar->setMaximumHeight(10); filterStr="*"; b=FALSE; populateLocalView(); readConfig(); // ServerComboBox->setCurrentItem(currentServerConfig); TabWidget->setCurrentPage(2); } OpieFtp::~OpieFtp() { } void OpieFtp::cleanUp() { if(conn) FtpQuit(conn); QString sfile=QDir::homeDirPath(); if(sfile.right(1) != "/") sfile+="/._temp"; else sfile+="._temp"; QFile file( sfile); if(file.exists()) file.remove(); Config cfg("opieftp"); cfg.setGroup("Server"); cfg.writeEntry("currentServer", currentServerConfig); exit(0); } void OpieFtp::tabChanged(QWidget *) { if (TabWidget->currentPageIndex() == 0) { currentPathCombo->lineEdit()->setText( currentDir.canonicalPath()); tabMenu->setItemChecked(tabMenu->idAt(0),TRUE); tabMenu->setItemChecked(tabMenu->idAt(1),FALSE); tabMenu->setItemChecked(tabMenu->idAt(2),FALSE); if(cdUpButton->isHidden()) cdUpButton->show(); if(homeButton->isHidden()) homeButton->show(); } if (TabWidget->currentPageIndex() == 1) { currentPathCombo->lineEdit()->setText( currentRemoteDir ); tabMenu->setItemChecked(tabMenu->idAt(1),TRUE); tabMenu->setItemChecked(tabMenu->idAt(0),FALSE); tabMenu->setItemChecked(tabMenu->idAt(2),FALSE); if(cdUpButton->isHidden()) cdUpButton->show(); homeButton->hide(); } if (TabWidget->currentPageIndex() == 2) { tabMenu->setItemChecked(tabMenu->idAt(2),TRUE); tabMenu->setItemChecked(tabMenu->idAt(0),FALSE); tabMenu->setItemChecked(tabMenu->idAt(1),FALSE); cdUpButton->hide(); homeButton->hide(); } } void OpieFtp::newConnection() { UsernameComboBox->lineEdit()->setText(""); PasswordEdit->setText( "" ); ServerComboBox->lineEdit()->setText( ""); remotePath->setText( currentRemoteDir = "/"); PortSpinBox->setValue( 21); TabWidget->setCurrentPage(2); } void OpieFtp::serverComboEdited(const QString & ) { // if( ServerComboBox->text(currentServerConfig) != edit /*edit.isEmpty() */) { // qDebug("ServerComboEdited"); // // currentServerConfig = -1; // } } void OpieFtp::UsernameComboBoxEdited(const QString &) { // currentServerConfig = -1; } void OpieFtp::PasswordEditEdited(const QString & ) { // currentServerConfig = -1; } void OpieFtp::connectorBtnToggled(bool On) { if(On) { connector(); } else { disConnector(); } } void OpieFtp::connector() { // QCopEnvelope ( "QPE/System", "busy()" ); // qApp->processEvents(); currentRemoteDir=remotePath->text(); if( ServerComboBox->currentText().isEmpty()) { QMessageBox::warning(this,tr("Ftp"),tr("Please set the server info"),tr("Ok"),0,0); TabWidget->setCurrentPage(2); ServerComboBox->setFocus(); connectServerBtn->setOn(FALSE); connectServerBtn->setText( tr("Connect")); return; } FtpInit(); TabWidget->setCurrentPage(1); QString ftp_host = ServerComboBox->currentText(); QString ftp_user = UsernameComboBox->currentText(); QString ftp_pass = PasswordEdit->text(); QString port=PortSpinBox->cleanText(); port.stripWhiteSpace(); Config cfg("opieftp"); cfg.setGroup("Server"); // int current=cfg.readNumEntry("currentServer", 1); // if(ftp_host!= cfg.readEntry(QString::number( current))) // currentServerConfig=-1; // cfg.setGroup(QString::number(current)); // if( ftp_user != cfg.readEntry("Username")) // currentServerConfig=-1; // if(ftp_pass != cfg.readEntry(cfg.readEntry("Username"))) // currentServerConfig=-1; if(ftp_host.find("ftp://",0, TRUE) != -1 ) ftp_host=ftp_host.right(ftp_host.length()-6); ftp_host+=":"+port; if (!FtpConnect( ftp_host.latin1(), &conn)) { QMessageBox::message(tr("Note"),tr("Unable to connect to\n")+ftp_host); connectServerBtn->setOn(FALSE); connectServerBtn->setText( tr("Connect")); return ; } if (!FtpLogin( ftp_user.latin1(), ftp_pass.latin1(),conn )) { QString msg; msg.sprintf(tr("Unable to log in\n")+"%s",FtpLastResponse(conn)); msg.replace(QRegExp(":"),"\n"); QMessageBox::message(tr("Note"),msg); if(conn) FtpQuit(conn); connectServerBtn->setOn(FALSE); connectServerBtn->setText( tr("Connect")); return ; } remoteDirList("/") ; setCaption(ftp_host); if( currentServerConfig == -1) writeConfig(); connectServerBtn->setText( tr("Disconnect")); // QCopEnvelope ( "QPE/System", "notBusy()" ); } void OpieFtp::disConnector() { if(conn) FtpQuit(conn); setCaption("OpieFtp"); currentRemoteDir="/"; Remote_View->clear(); connectServerBtn->setText( tr("Connect")); connectServerBtn->setOn(FALSE); setCaption("OpieFtp"); } void OpieFtp::localUpload() { int fsz; // QCopEnvelope ( "QPE/System", "busy()" ); // qApp->processEvents(); QList<QListViewItem> * getSelectedItems( QListView * Local_View ); QListViewItemIterator it( Local_View ); for ( ; it.current(); ++it ) { if ( it.current()->isSelected() ) { QString strItem = it.current()->text(0); QString localFile = currentDir.canonicalPath()+"/"+strItem; QString remoteFile= currentRemoteDir+strItem; QFileInfo fi(localFile); if( !fi.isDir()) { fsz=fi.size(); ProgressBar->setTotalSteps(fsz); FtpOptions(FTPLIB_CALLBACK, (long) log_progress, conn); FtpOptions(FTPLIB_IDLETIME, (long) 1000, conn); FtpOptions(FTPLIB_CALLBACKARG, (long) &fsz, conn); FtpOptions(FTPLIB_CALLBACKBYTES, (long) fsz/10, conn); qDebug("Put: %s, %s",localFile.latin1(),remoteFile.latin1()); if( !FtpPut( localFile.latin1(), remoteFile.latin1(),FTPLIB_IMAGE, conn ) ) { QString msg; msg.sprintf(tr("Unable to upload\n")+"%s",FtpLastResponse(conn)); msg.replace(QRegExp(":"),"\n"); QMessageBox::message(tr("Note"),msg); } } else { QMessageBox::message(tr("Note"),tr("Cannot upload directories")); } ProgressBar->reset(); nullifyCallBack(); it.current()->setSelected(FALSE); } //end currentSelected } for ( ; it.current(); ++it ) { Local_View->clearSelection(); } Local_View->clearFocus(); TabWidget->setCurrentPage(1); remoteDirList( (const QString &)currentRemoteDir); //this also calls populate // QCopEnvelope ( "QPE/System", "notBusy()" ); } void OpieFtp::nullifyCallBack() { FtpOptions(FTPLIB_CALLBACK, 0, conn); FtpOptions(FTPLIB_IDLETIME, 0, conn); FtpOptions(FTPLIB_CALLBACKARG, 0, conn); FtpOptions(FTPLIB_CALLBACKBYTES, 0, conn); } void OpieFtp::remoteDownload() { // qApp->processEvents(); int fsz; // QCopEnvelope ( "QPE/System", "busy()" ); QList<QListViewItem> * getSelectedItems( QListView * Remote_View ); QListViewItemIterator it( Remote_View ); for ( ; it.current(); ++it ) { if ( it.current()->isSelected() ) { QString strItem = it.current()->text(0); // strItem=strItem.right(strItem.length()-1); QString localFile = currentDir.canonicalPath(); if(localFile.right(1).find("/",0,TRUE) == -1) localFile += "/"; localFile += strItem; // QString localFile = currentDir.canonicalPath()+"/"+strItem; QString remoteFile= currentRemoteDir+strItem; if (!FtpSize( remoteFile.latin1(), &fsz, FTPLIB_ASCII, conn)) fsz = 0; QString temp; temp.sprintf( remoteFile+" "+" %dkb", fsz); ProgressBar->setTotalSteps(fsz); FtpOptions(FTPLIB_CALLBACK, (long) log_progress, conn); FtpOptions(FTPLIB_IDLETIME, (long) 1000, conn); FtpOptions(FTPLIB_CALLBACKARG, (long) &fsz, conn); FtpOptions(FTPLIB_CALLBACKBYTES, (long) fsz/10, conn); qDebug("Get: %s, %s",localFile.latin1(),remoteFile.latin1()); if(!FtpGet( localFile.latin1(), remoteFile.latin1(),FTPLIB_IMAGE, conn ) ) { QString msg; msg.sprintf(tr("Unable to download \n")+"%s",FtpLastResponse(conn)); msg.replace(QRegExp(":"),"\n"); QMessageBox::message(tr("Note"),msg); } ProgressBar->reset(); nullifyCallBack(); it.current()->setSelected(FALSE); } } for ( ; it.current(); ++it ) { Remote_View->clearSelection(); } Remote_View->setFocus(); TabWidget->setCurrentPage(0); populateLocalView(); // QCopEnvelope ( "QPE/System", "notBusy()" ); } bool OpieFtp::remoteDirList(const QString &dir) { QString tmp = QDir::homeDirPath(); if(tmp.right(1) != "/") tmp+="/._temp"; else tmp+="._temp"; // qDebug("Listing remote dir "+tmp); // QCopEnvelope ( "QPE/System", "busy()" ); if (!FtpDir( tmp.latin1(), dir.latin1(), conn) ) { QString msg; msg.sprintf(tr("Unable to list the directory\n")+dir+"\n%s",FtpLastResponse(conn) ); msg.replace(QRegExp(":"),"\n"); QMessageBox::message(tr("Note"),msg); return false; } populateRemoteView() ; // QCopEnvelope ( "QPE/System", "notBusy()" ); return true; } bool OpieFtp::remoteChDir(const QString &dir) { // QCopEnvelope ( "QPE/System", "busy()" ); if (!FtpChdir( dir.latin1(), conn )) { QString msg; msg.sprintf(tr("Unable to change directories\n")+dir+"\n%s",FtpLastResponse(conn)); msg.replace(QRegExp(":"),"\n"); QMessageBox::message(tr("Note"),msg); // qDebug(msg); // QCopEnvelope ( "QPE/System", "notBusy()" ); return FALSE; } // QCopEnvelope ( "QPE/System", "notBusy()" ); return TRUE; } void OpieFtp::populateLocalView() { Local_View->clear(); currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst); currentDir.setMatchAllDirs(TRUE); currentDir.setNameFilter(filterStr); QString fileL, fileS, fileDate; bool isDir=FALSE; const QFileInfoList *list = currentDir.entryInfoList( /*QDir::All*/ /*, QDir::SortByMask*/); QFileInfoListIterator it(*list); QFileInfo *fi; while ( (fi=it.current()) ) { if (fi->isSymLink() ){ QString symLink=fi->readLink(); // qDebug("Symlink detected "+symLink); QFileInfo sym( symLink); fileS.sprintf( "%10i", sym.size() ); fileL.sprintf( "%s -> %s", fi->fileName().data(),sym.absFilePath().data() ); fileDate = sym.lastModified().toString(); } else { // qDebug("Not a dir: "+currentDir.canonicalPath()+fileL); fileS.sprintf( "%10i", fi->size() ); fileL.sprintf( "%s",fi->fileName().data() ); fileDate= fi->lastModified().toString(); if( QDir(QDir::cleanDirPath(currentDir.canonicalPath()+"/"+fileL)).exists() ) { fileL+="/"; isDir=TRUE; // qDebug( fileL); } } if(fileL !="./" && fi->exists()) { item = new QListViewItem( Local_View,fileL, fileDate, fileS ); QPixmap pm; if(isDir || fileL.find("/",0,TRUE) != -1) { if( !QDir( fi->filePath() ).isReadable()) pm = Resource::loadPixmap( "lockedfolder" ); else pm= Resource::loadPixmap( "folder" ); item->setPixmap( 0,pm ); } else { if( !fi->isReadable() ) pm = Resource::loadPixmap( "locked" ); else { MimeType mt(fi->filePath()); pm=mt.pixmap(); //sets the correct pixmap for mimetype if(pm.isNull()) pm = unknownXpm; } } if( fileL.find("->",0,TRUE) != -1) { // overlay link image pm= Resource::loadPixmap( "folder" ); QPixmap lnk = Resource::loadPixmap( "opie/symlink" ); QPainter painter( &pm ); painter.drawPixmap( pm.width()-lnk.width(), pm.height()-lnk.height(), lnk ); pm.setMask( pm.createHeuristicMask( FALSE ) ); } item->setPixmap( 0,pm); } isDir=FALSE; ++it; } Local_View->setSorting( 3,FALSE); currentPathCombo->lineEdit()->setText( currentDir.canonicalPath() ); fillCombo( (const QString &)currentDir); } bool OpieFtp::populateRemoteView( ) { // qDebug("populate remoteview"); QString sfile=QDir::homeDirPath(); if(sfile.right(1) != "/") sfile+="/._temp"; else sfile+="._temp"; QFile file( sfile); Remote_View->clear(); QString s, File_Name; QListViewItem *itemDir=NULL, *itemFile=NULL; QRegExp monthRe(" [JFMASOND][eapuecoe][brynlgptvc] [ 0-9][0-9] [ 0-9][0-9][:0-9][0-9][0-9] "); QString fileL, fileS, fileDate; if ( file.open(IO_ReadOnly)) { QTextStream t( &file ); // use a text stream while ( !t.eof()) { s = t.readLine(); if(s.find("total",0,TRUE) == 0) continue; int len, month = monthRe.match(s, 0, &len); fileDate = s.mid(month + 1, len - 2); // minus spaces fileL = s.right(s.length() - month - len); if(s.left(1) == "d") fileL = fileL+"/"; fileS = s.mid(month - 8, 8); // FIXME fileS = fileS.stripWhiteSpace(); if(s.left(1) == "d" || fileL.find("/",0,TRUE) != -1) { QListViewItem * item = new QListViewItem( Remote_View, fileL, fileDate, fileS,"d"); item->setPixmap( 0, Resource::loadPixmap( "folder" )); // if(itemDir) item->moveItem(itemDir); itemDir=item; } else { QListViewItem * item = new QListViewItem( Remote_View, fileL, fileDate, fileS,"f"); item->setPixmap( 0, Resource::loadPixmap( "fileopen" )); // if(itemFile) item->moveItem(itemDir); item->moveItem(itemFile); itemFile=item; } } QListViewItem * item1 = new QListViewItem( Remote_View, "../"); item1->setPixmap( 0, Resource::loadPixmap( "folder" )); file.close(); if( file.exists()) file. remove(); } else qDebug("temp file not opened successfullly "+sfile); Remote_View->setSorting( 4,TRUE); return true; } void OpieFtp::remoteListClicked(QListViewItem *selectedItem) { if( selectedItem) { // if(selectedItem!= NULL) { // QCopEnvelope ( "QPE/System", "busy()" ); QString oldRemoteCurrentDir = currentRemoteDir; QString strItem=selectedItem->text(0); strItem=strItem.simplifyWhiteSpace(); if(strItem == "../") { // the user wants to go ^ if( FtpCDUp( conn) == 0) { QString msg; msg.sprintf(tr("Unable to cd up\n")+"%s",FtpLastResponse(conn)); msg.replace(QRegExp(":"),"\n"); QMessageBox::message(tr("Note"),msg); // qDebug(msg); } char path[256]; if( FtpPwd( path,sizeof(path),conn) == 0) { //this is easier than fudging the string QString msg; msg.sprintf(tr("Unable to get working dir\n")+"%s",FtpLastResponse(conn)); msg.replace(QRegExp(":"),"\n"); QMessageBox::message(tr("Note"),msg); // qDebug(msg); } currentRemoteDir=path; } else { if(strItem.find("->",0,TRUE) != -1) { //symlink on some servers strItem=strItem.right( strItem.length() - strItem.find("->",0,TRUE) - 2 ); strItem = strItem.stripWhiteSpace(); currentRemoteDir = strItem; if( !remoteChDir( (const QString &)strItem)) { currentRemoteDir = oldRemoteCurrentDir; strItem=""; // qDebug("RemoteCurrentDir1 "+oldRemoteCurrentDir); } } else if(strItem.find("/",0,TRUE) != -1) { // this is a directory if( !remoteChDir( (const QString &)currentRemoteDir + strItem)) { currentRemoteDir = oldRemoteCurrentDir; strItem=""; // qDebug("RemoteCurrentDir1 "+oldRemoteCurrentDir); } else { currentRemoteDir = currentRemoteDir+strItem; } } else { // QCopEnvelope ( "QPE/System", "notBusy()" ); return; } } remoteDirList( (const QString &)currentRemoteDir); //this also calls populate if(currentRemoteDir.right(1) !="/") currentRemoteDir +="/"; currentPathCombo->lineEdit()->setText( currentRemoteDir); fillRemoteCombo( (const QString &)currentRemoteDir); // QCopEnvelope ( "QPE/System", "notBusy()" ); Remote_View->ensureItemVisible(Remote_View->firstChild()); } } void OpieFtp::localListClicked(QListViewItem *selectedItem) { if(selectedItem!= NULL) { QString strItem=selectedItem->text(0); QString strSize=selectedItem->text(1); strSize=strSize.stripWhiteSpace(); if(strItem.find("@",0,TRUE) !=-1 || strItem.find("->",0,TRUE) !=-1 ) { //if symlink // is symlink QString strItem2 = strItem.right( (strItem.length() - strItem.find("->",0,TRUE)) - 4); if(QDir(strItem2).exists() ) { currentDir.cd(strItem2, TRUE); populateLocalView(); } } else { // not a symlink if(strItem.find(". .",0,TRUE) && strItem.find("/",0,TRUE)!=-1 ) { if(QDir(QDir::cleanDirPath(currentDir.canonicalPath()+"/"+strItem)).exists() ) { strItem=QDir::cleanDirPath(currentDir.canonicalPath()+"/"+strItem); currentDir.cd(strItem,FALSE); populateLocalView(); } else { currentDir.cdUp(); populateLocalView(); } if(QDir(strItem).exists()){ currentDir.cd(strItem, TRUE); populateLocalView(); } } else { strItem=QDir::cleanDirPath(currentDir.canonicalPath()+"/"+strItem); if( QFile::exists(strItem ) ) { // qDebug("upload "+strItem); return; } } //end not symlink chdir(strItem.latin1()); } Local_View->ensureItemVisible(Local_View->firstChild()); } } void OpieFtp::doLocalCd() { localListClicked( Local_View->currentItem()); } void OpieFtp:: doRemoteCd() { remoteListClicked( Remote_View->currentItem()); } void OpieFtp::showHidden() { if (!b) { currentDir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All); localMenu->setItemChecked(localMenu->idAt(0),TRUE); // currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst); b=TRUE; } else { currentDir.setFilter( QDir::Files | QDir::Dirs/* | QDir::Hidden*/ | QDir::All); localMenu->setItemChecked(localMenu->idAt(0),FALSE); // currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst); b=FALSE; } populateLocalView(); } void OpieFtp::ListPressed( int mouse, QListViewItem *item, const QPoint &, int) { // if(item) if (mouse == 2) { showLocalMenu(item); } } void OpieFtp::RemoteListPressed( int mouse, QListViewItem *item, const QPoint &, int ) { if(mouse == 2) { showRemoteMenu(item); } } void OpieFtp::showRemoteMenu(QListViewItem * item) { QPopupMenu * m;// = new QPopupMenu( Local_View ); m = new QPopupMenu(this); if(item != NULL ) { if( item->text(0).find("/",0,TRUE) != -1) m->insertItem( tr( "Change Directory" ), this, SLOT( doRemoteCd() )); else m->insertItem( tr( "Download" ), this, SLOT( remoteDownload() )); } m->insertItem( tr( "Make Directory" ), this, SLOT( remoteMakDir() )); m->insertItem( tr("Rescan"), this, SLOT( populateLocalView() )); m->insertItem( tr( "Rename" ), this, SLOT( remoteRename() )); m->insertSeparator(); m->insertItem( tr( "Delete" ), this, SLOT( remoteDelete() )); m->exec( QCursor::pos() ); delete m; } void OpieFtp::showLocalMenu(QListViewItem * item) { QPopupMenu *m; m = new QPopupMenu( this); m->insertItem( tr( "Show Hidden Files" ), this, SLOT( showHidden() )); m->insertSeparator(); if(item != NULL ) { if( item->text(0).find("/",0,TRUE) !=-1) m->insertItem( tr( "Change Directory" ), this, SLOT( doLocalCd() )); else m->insertItem( tr( "Upload" ), this, SLOT( localUpload() )); } m->insertItem( tr( "Make Directory" ), this, SLOT( localMakDir() )); m->insertItem( tr("Rescan"), this, SLOT( populateRemoteView() )); m->insertItem( tr( "Rename" ), this, SLOT( localRename() )); m->insertSeparator(); m->insertItem( tr( "Delete" ), this, SLOT( localDelete() )); m->setCheckable(TRUE); if (b) m->setItemChecked(m->idAt(0),TRUE); else m->setItemChecked(m->idAt(0),FALSE); m->exec( QCursor::pos() ); delete m; } void OpieFtp::localMakDir() { InputDialog *fileDlg; fileDlg = new InputDialog(this,tr("Make Directory"),TRUE, 0); fileDlg->exec(); if( fileDlg->result() == 1 ) { QString filename = fileDlg->LineEdit1->text(); currentDir.mkdir( currentDir.canonicalPath()+"/"+filename); } populateLocalView(); } void OpieFtp::localDelete() { QList<QListViewItem> * getSelectedItems( QListView * Local_View ); QListViewItemIterator it( Local_View ); for ( ; it.current(); ++it ) { if ( it.current()->isSelected() ) { QString f = it.current()->text(0); it.current()->setSelected(FALSE); // QString f = Local_View->currentItem()->text(0); if(QDir(f).exists() ) { switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f+ tr(" ?\nIt must be empty"),tr("Yes"),tr("No"),0,0,1) ) { case 0: { f=currentDir.canonicalPath()+"/"+f; QString cmd="rmdir "+f; system( cmd.latin1()); } break; case 1: // exit break; }; } else { switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f +" ?",tr("Yes"),tr("No"),0,0,1) ) { case 0: { f=currentDir.canonicalPath()+"/"+f; QString cmd="rm "+f; system( cmd.latin1()); } break; case 1: // exit break; }; } } } populateLocalView(); } void OpieFtp::remoteMakDir() { InputDialog *fileDlg; fileDlg = new InputDialog(this,tr("Make Directory"),TRUE, 0); fileDlg->exec(); if( fileDlg->result() == 1 ) { QString filename = fileDlg->LineEdit1->text();//+".playlist"; QString tmp=currentRemoteDir+filename; // QCopEnvelope ( "QPE/System", "busy()" ); if(FtpMkdir( tmp.latin1(), conn) == 0) { QString msg; msg.sprintf(tr("Unable to make directory\n")+"%s",FtpLastResponse(conn)); msg.replace(QRegExp(":"),"\n"); QMessageBox::message(tr("Note"),msg); } // QCopEnvelope ( "QPE/System", "notBusy()" ); remoteDirList( (const QString &)currentRemoteDir); //this also calls populate } } void OpieFtp::remoteDelete() { QList<QListViewItem> * getSelectedItems( QListView * Remote_View ); QListViewItemIterator it( Remote_View ); for ( ; it.current(); ++it ) { if ( it.current()->isSelected() ) { QString f = it.current()->text(0); // QString f = Remote_View->currentItem()->text(0); // QCopEnvelope ( "QPE/System", "busy()" ); if( f.right(1) =="/") { QString path= currentRemoteDir+f; switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f+"?" ,tr("Yes"),tr("No"),0,0,1) ) { case 0: { f=currentDir.canonicalPath()+"/"+f; if(FtpRmdir( path.latin1(), conn) ==0) { QString msg; msg.sprintf(tr("Unable to remove directory\n")+"%s",FtpLastResponse(conn)); msg.replace(QRegExp(":"),"\n"); QMessageBox::message(tr("Note"),msg); } remoteDirList( (const QString &)currentRemoteDir); //this also calls populate } break; }; } else { switch ( QMessageBox::warning(this,tr("Delete"),tr("Do you really want to delete\n")+f+"?" ,tr("Yes"),tr("No"),0,0,1) ) { case 0: { QString path= currentRemoteDir+f; if(FtpDelete( path.latin1(), conn)==0) { QString msg; msg.sprintf(tr("Unable to delete file\n")+"%s",FtpLastResponse(conn)); msg.replace(QRegExp(":"),"\n"); QMessageBox::message(tr("Note"),msg); } remoteDirList( (const QString &)currentRemoteDir); //this also calls populate } break; }; } } } // QCopEnvelope ( "QPE/System", "notBusy()" ); } void OpieFtp::remoteRename() { QString curFile = Remote_View->currentItem()->text(0); InputDialog *fileDlg; fileDlg = new InputDialog(this,tr("Rename"),TRUE, 0); fileDlg->setTextEdit((const QString &)curFile); fileDlg->exec(); if( fileDlg->result() == 1 ) { QString oldName = currentRemoteDir +"/"+ curFile; QString newName = currentRemoteDir +"/"+ fileDlg->LineEdit1->text();//+".playlist"; // QCopEnvelope ( "QPE/System", "busy()" ); if(FtpRename( oldName.latin1(), newName.latin1(),conn) == 0) { QString msg; msg.sprintf(tr("Unable to rename file\n")+"%s",FtpLastResponse(conn)); msg.replace(QRegExp(":"),"\n"); QMessageBox::message(tr("Note"),msg); } // QCopEnvelope ( "QPE/System", "notBusy()" ); remoteDirList( (const QString &)currentRemoteDir); //this also calls populate diff --git a/noncore/net/opieftp/opieftp.h b/noncore/net/opieftp/opieftp.h index 7bd615a..f58778a 100644 --- a/noncore/net/opieftp/opieftp.h +++ b/noncore/net/opieftp/opieftp.h @@ -1,143 +1,143 @@ /*************************************************************************** opieftp.h ------------------- ** Created: Sat Mar 9 23:33:09 2002 copyright : (C) 2002 by ljp email : ljp@llornkcor.com * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #ifndef OPIEFTP_H #define OPIEFTP_H #include <qvariant.h> #include <qdialog.h> #include <qmainwindow.h> #include <qdir.h> #include <qstring.h> #include <qpoint.h> #include <qpixmap.h> class QVBoxLayout; class QHBoxLayout; class QGridLayout; class QComboBox; class QListView; class QListViewItem; class QLabel; class QProgressBar; class QSpinBox; class QTabWidget; class QWidget; class QPEToolBar; -class QPEMenuBar; +class QMenuBar; class QPopupMenu; class QFile; class QLineEdit; class QPushButton; class QToolButton; class QStringList; class QListBox; class QTimer; class OpieFtp : public QMainWindow { Q_OBJECT public: OpieFtp( QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); ~OpieFtp(); static QString appName() { return QString::fromLatin1("opieftp"); } QTabWidget *TabWidget; QWidget *tab, *tab_2, *tab_3; QListView *Local_View, *Remote_View; QListBox *serverListView; QComboBox *UsernameComboBox, *ServerComboBox, *currentPathCombo; QLineEdit *PasswordEdit, *remotePath; QLabel *TextLabel2, *TextLabel1, *TextLabel3, *TextLabel4;; QSpinBox* PortSpinBox; QPopupMenu *connectionMenu, *localMenu, *remoteMenu, *tabMenu, *aboutMenu; QDir currentDir; QString currentRemoteDir; QString filterStr; QListViewItem * item; QPushButton *connectServerBtn, *newServerButton;// QToolButton *cdUpButton, *homeButton, *docButton; bool b; int currentServerConfig; protected slots: void timerOut(); void upDir(); void homeButtonPushed(); void docButtonPushed(); void doAbout(); void serverComboEdited(const QString & ); void UsernameComboBoxEdited(const QString & ); void PasswordEditEdited(const QString & ); void showLocalMenu( QListViewItem *); void showRemoteMenu( QListViewItem *); void doLocalCd(); void doRemoteCd(); void localUpload(); void remoteDownload(); void newConnection(); void connector(); void disConnector(); void populateLocalView(); bool populateRemoteView(); void showHidden(); void writeConfig(); void readConfig(); void localListClicked(QListViewItem *); void remoteListClicked(QListViewItem *); void ListPressed( int, QListViewItem *, const QPoint&, int); void RemoteListPressed( int, QListViewItem *, const QPoint&, int); void localMakDir(); void localDelete(); void remoteMakDir(); void remoteDelete(); bool remoteDirList(const QString &); bool remoteChDir(const QString &); void tabChanged(QWidget*); void cleanUp(); void remoteRename(); void localRename(); void currentPathComboChanged(); void currentPathComboActivated(const QString &); void switchToLocalTab(); void switchToRemoteTab(); void switchToConfigTab(); void fillCombos(); void clearCombos(); void fillRemoteCombo(const QString&); void fillCombo(const QString &); void serverComboSelected(int); void deleteServer(); void connectorBtnToggled(bool); void NewServer(); void serverListClicked( const QString &); protected: QPixmap unknownXpm; bool fuckeduphack; QStringList remoteDirPathStringList, localDirPathStringList; QString newServerName; void nullifyCallBack(); QGridLayout* tabLayout; QGridLayout* tabLayout_2; QGridLayout* tabLayout_3; }; #endif // OPIEFTP_H diff --git a/noncore/net/opieirc/mainwindow.cpp b/noncore/net/opieirc/mainwindow.cpp index 8f76cdd..95fbdcd 100644 --- a/noncore/net/opieirc/mainwindow.cpp +++ b/noncore/net/opieirc/mainwindow.cpp @@ -1,93 +1,93 @@ #include <qpe/qpemenubar.h> #include <qpe/resource.h> #include <qpe/config.h> #include <qpopupmenu.h> #include <qwhatsthis.h> #include "mainwindow.h" #include "ircservertab.h" #include "ircserverlist.h" #include "ircsettings.h" MainWindow::MainWindow(QWidget *parent, const char *name, WFlags) : QMainWindow(parent, name, WStyle_ContextHelp) { setCaption(tr("IRC Client")); m_tabWidget = new IRCTabWidget(this); QWhatsThis::add(m_tabWidget, tr("Server connections, channels, queries and other things will be placed here")); connect(m_tabWidget, SIGNAL(currentChanged(QWidget *)), this, SLOT(selected(QWidget *))); setCentralWidget(m_tabWidget); setToolBarsMovable(FALSE); - QPEMenuBar *menuBar = new QPEMenuBar(this); + QMenuBar *menuBar = new QMenuBar(this); QPopupMenu *irc = new QPopupMenu(this); menuBar->insertItem(tr("IRC"), irc); QAction *a = new QAction(tr("New connection"), Resource::loadPixmap("pass"), QString::null, 0, this, 0); connect(a, SIGNAL(activated()), this, SLOT(newConnection())); a->setWhatsThis(tr("Create a new connection to an IRC server")); a->addTo(irc); a = new QAction(tr("Settings"), Resource::loadPixmap("SettingsIcon"), QString::null, 0, this, 0); a->setWhatsThis(tr("Configure OpieIRC's behavior and appearance")); connect(a, SIGNAL(activated()), this, SLOT(settings())); a->addTo(irc); loadSettings(); } /*IRCTabWidget MainWindow::getTabWidget(){ return m_tabWidget; } */ void MainWindow::loadSettings() { Config config("OpieIRC"); config.setGroup("OpieIRC"); IRCTab::m_backgroundColor = config.readEntry("BackgroundColor", "#FFFFFF"); IRCTab::m_textColor = config.readEntry("TextColor", "#000000"); IRCTab::m_errorColor = config.readEntry("ErrorColor", "#FF0000"); IRCTab::m_selfColor = config.readEntry("SelfColor", "#CC0000"); IRCTab::m_otherColor = config.readEntry("OtherColor", "#0000BB"); IRCTab::m_serverColor = config.readEntry("ServerColor", "#0000FF"); IRCTab::m_notificationColor = config.readEntry("NotificationColor", "#AA3300"); IRCTab::m_maxLines = config.readNumEntry("Lines", 100); } void MainWindow::selected(QWidget *) { m_tabWidget->setTabColor(m_tabWidget->currentPageIndex(), black); emit updateScroll(); } void MainWindow::addTab(IRCTab *tab) { connect(tab, SIGNAL(changed(IRCTab *)), this, SLOT(changeEvent(IRCTab *))); m_tabWidget->addTab(tab, tab->title()); m_tabWidget->showPage(tab); tab->setID(m_tabWidget->currentPageIndex()); m_tabs.append(tab); } void MainWindow::changeEvent(IRCTab *tab) { if (tab->id() != m_tabWidget->currentPageIndex()) m_tabWidget->setTabColor(tab->id(), blue); } void MainWindow::killTab(IRCTab *tab) { m_tabWidget->removePage(tab); m_tabs.remove(tab); /* there might be nicer ways to do this .. */ delete tab; } void MainWindow::newConnection() { IRCServerList list(this, "ServerList", TRUE); if (list.exec() == QDialog::Accepted && list.hasServer()) { IRCServerTab *serverTab = new IRCServerTab(list.server(), this, m_tabWidget); addTab(serverTab); serverTab->doConnect(); } } void MainWindow::settings() { IRCSettings settings(this, "Settings", TRUE); if (settings.exec() == QDialog::Accepted) { QListIterator<IRCTab> it(m_tabs); for (; it.current(); ++it) { /* Inform all tabs about the new settings */ it.current()->settingsChanged(); } } } diff --git a/noncore/net/wellenreiter/TODO b/noncore/net/wellenreiter/TODO index a1d5bee..0336417 100644 --- a/noncore/net/wellenreiter/TODO +++ b/noncore/net/wellenreiter/TODO @@ -1,4 +1,15 @@ -- save configuration settings - beep over headphone / customizable -- autoshow new nets - maybe in other color or more contrast +- identification of probe requests + i.e. other sniffers around + +- decloaking of falsely reported zero-length SSIDs + +- option to run skript on + - new net + - new station + - <whatever> + +- adaptive hopping scheme ! + +- diff --git a/noncore/unsupported/filebrowser/filebrowser.cpp b/noncore/unsupported/filebrowser/filebrowser.cpp index d16e771..114ebfa 100644 --- a/noncore/unsupported/filebrowser/filebrowser.cpp +++ b/noncore/unsupported/filebrowser/filebrowser.cpp @@ -1,1091 +1,1091 @@ /********************************************************************** ** 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 "inlineedit.h" #include "filebrowser.h" #include "filePermissions.h" #include <qpe/resource.h> #include <qpe/global.h> #include <qpe/mimetype.h> #include <qpe/applnk.h> #include <qpe/config.h> #include <qcopchannel_qws.h> #include <qpe/qcopenvelope_qws.h> #include <qmessagebox.h> #include <qdir.h> #include <qregexp.h> #include <qheader.h> #include <qpe/qpetoolbar.h> #include <qpopupmenu.h> -#include <qpe/qpemenubar.h> +#include <qmenubar.h> #include <qaction.h> #include <qstringlist.h> #include <qcursor.h> #include <qmultilineedit.h> #include <qfont.h> #include <qpainter.h> #include <qprogressbar.h> #include <unistd.h> #include <stdlib.h> #include <sys/stat.h> #include <qpe/qpeapplication.h> // // FileItem // FileItem::FileItem( QListView * parent, const QFileInfo & fi ) : QListViewItem( parent ), fileInfo( fi ) { QDate d = fi.lastModified().date(); setText( 0, fi.fileName() ); setText( 1, sizeString( fi.size() ) + " " ); setText( 2, QString().sprintf("%4d-%02d-%02d",d.year(), d.month(), d.day() ) ); MimeType mt(fi.filePath()); if ( fi.isSymLink() ) setText( 3, "symlink" ); else if( fi.isDir() ) setText( 3, "directory" ); else if( isLib() ) setText( 3, "library" ); else setText( 3, mt.description() ); QPixmap pm; if( fi.isDir() ){ if( !QDir( fi.filePath() ).isReadable() ) pm = Resource::loadPixmap( "lockedfolder" ); else pm = Resource::loadPixmap( "folder" ); } else if( !fi.isReadable() ) pm = Resource::loadPixmap( "locked" ); else if( isLib() ) pm = Resource::loadPixmap( "library" ); else if( ((FileView* )parent)->getShowThumbnails() && mt.id().contains(QRegExp("^image/", FALSE, FALSE)) ) pm = drawThumbnail(fi); else pm = mt.pixmap(); if ( pm.isNull() ) pm = Resource::loadPixmap("UnknownDocument-14"); if( fi.isSymLink() ){ // overlay link image QPixmap lnk = Resource::loadPixmap( "filebrowser/symlink" ); QPainter painter( &pm ); painter.drawPixmap( pm.width()-lnk.width(), pm.height()-lnk.height(), lnk ); pm.setMask( pm.createHeuristicMask( FALSE ) ); } setPixmap(0,pm); } QString FileItem::sizeString( unsigned int s ) { double size = s; if ( size > 1024 * 1024 * 1024 ) return QString().sprintf( "%.1f", size / ( 1024 * 1024 * 1024 ) ) + "G"; else if ( size > 1024 * 1024 ) return QString().sprintf( "%.1f", size / ( 1024 * 1024 ) ) + "M"; else if ( size > 1024 ) return QString().sprintf( "%.1f", size / ( 1024 ) ) + "K"; else return QString::number( size ) + "B"; } QString FileItem::key( int column, bool ascending ) const { QString tmp; ascending = ascending; if( (column == 0) && fileInfo.isDir() ){ // Sort by name // We want the directories to appear at the top of the list tmp = (char) 0; return (tmp + text( column ).lower()); } else if( column == 2 ) { // Sort by date QDateTime epoch( QDate( 1980, 1, 1 ) ); tmp.sprintf( "%08d", epoch.secsTo( fileInfo.lastModified() ) ); return tmp; } else if( column == 1 ) { // Sort by size return tmp.sprintf( "%08d", fileInfo.size() ); } return text( column ).lower(); } bool FileItem::isLib() { // This is of course not foolproof if( !qstrncmp("lib", fileInfo.baseName(), 3) && ( fileInfo.extension().contains( "so" ) || fileInfo.extension().contains( "a" ) ) ) return TRUE; else return FALSE; } int FileItem::launch() { DocLnk doc( fileInfo.filePath(), FALSE ); doc.execute(); listView()->clearSelection(); return 1; } bool FileItem::rename( const QString & name ) { QString oldpath, newpath; if ( name.isEmpty() ) return FALSE; if ( name.contains( QRegExp("[/\\$\"\'\\*\\?]") ) ) return FALSE; oldpath = fileInfo.filePath(); newpath = fileInfo.dirPath() + "/" + name; if ( ::rename( (const char *) oldpath, (const char *) newpath ) != 0 ) return FALSE; else return TRUE; } QPixmap FileItem::drawThumbnail(const QFileInfo &file) { /* * this thing is sloooooow, and it also doesn't load * dynamicly (like a web browser). if anyone knows how to * do that, please do! */ QString cacheDir = "/tmp/filebrowserThumbnailCache"; QFileInfo cachedFile (cacheDir + file.filePath()); if (cachedFile.exists() && cachedFile.lastModified() == file.lastModified()) { QPixmap cachedImage (cachedFile.filePath()); return cachedImage; } else { QImage image (file.filePath()); // if inside of cache dir, don't render thumbnails! recursive error! if (image.isNull() || file.filePath().contains(QRegExp("^" + cacheDir))) { DocLnk doc (file.filePath()); return doc.pixmap(); } Config cfg("Filebrowser"); cfg.setGroup("View"); int size; size =cfg.readNumEntry("ThumbSize", 72); QPixmap thumb (size, size); double scale = (double)image.height() / (double)image.width(); int newHeight = int(size * scale); thumb.convertFromImage (image.smoothScale(size, newHeight)); if (!cachedFile.dir().exists()) { QString cmd = "/bin/mkdir -p \"" + cachedFile.dirPath() +"\""; system( (const char *) cmd ); } if (thumb.save(cachedFile.filePath(), QPixmap::imageFormat(file.filePath()), 70)) { // make thumbnail modify time the same as the image QString cmd = "/bin/touch -r \"" + file.filePath() +"\" " + "\"" + cachedFile.filePath() + "\""; system( (const char *) cmd ); } return thumb; } } // // FileView // FileView::FileView( const QString & dir, QWidget * parent, const char * name, bool hidden, bool symlinks, bool thumbnails ) : QListView( parent, name ), menuTimer( this ), le( NULL ), itemToRename( NULL ), showHidden( hidden ), showSymlinks( symlinks ), showThumbnails( thumbnails ), menuKeepsOpen( FALSE ) { addColumn( "Name" ); addColumn( "Size" ); addColumn( "Date" ); addColumn( "Type" ); setMultiSelection( TRUE ); //header()->hide(); setColumnWidthMode( 0, Manual ); setColumnWidthMode( 3, Manual ); // right align yize column setColumnAlignment( 1, AlignRight ); generateDir( dir ); connect( this, SIGNAL( clicked( QListViewItem * )), SLOT( itemClicked( QListViewItem * )) ); connect( this, SIGNAL( doubleClicked( QListViewItem * )), SLOT( itemDblClicked( QListViewItem * )) ); connect( this, SIGNAL( selectionChanged() ), SLOT( cancelMenuTimer() ) ); connect( &menuTimer, SIGNAL( timeout() ), SLOT( showFileMenu() ) ); } void FileView::resizeEvent( QResizeEvent *e ) { setColumnWidth( 0, width() - 2 * lineWidth() - 20 - columnWidth( 1 ) - columnWidth( 2 ) ); // hide type column, we use it for "sort by type" only //setColumnWidth( 3, 0 ); QListView::resizeEvent( e ); } void FileView::updateDir() { generateDir( currentDir ); } void FileView::setDir( const QString & dir ) { if ( dir.startsWith( "/dev" ) ) { QMessageBox::warning( this, tr( "File Manager" ), tr( "Can't show /dev/ directory." ), tr( "&Ok" ) ); return; } dirHistory += currentDir; generateDir( dir ); } void FileView::generateDir( const QString & dir ) { if(menuKeepsOpen){ cancelMenuTimer(); } QDir d( dir ); if( d.exists() && !d.isReadable() ) return; currentDir = d.canonicalPath(); if( !showHidden) d.setFilter( QDir::Dirs | QDir::Files ); else d.setFilter( QDir::Dirs | QDir::Files |QDir::Hidden | QDir::All); d.setSorting( QDir::Name | QDir::DirsFirst | QDir::IgnoreCase | QDir::Reversed ); const QFileInfoList * list = d.entryInfoList(); QFileInfoListIterator it( *list ); QFileInfo *fi; QProgressBar *thumbProgress = 0; if (showThumbnails) { thumbProgress = new QProgressBar(it.count(), this); thumbProgress->show(); } clear(); int fileCount = 1; // used in the thumbnail progress meter while( (fi = it.current()) ){ if( (fi->fileName() == ".") || (fi->fileName() == "..") ){ ++it; continue; } if(!showSymlinks && fi->isSymLink()){ ++it; continue; } // thumbnail progress if (showThumbnails) { thumbProgress->setProgress(fileCount); } (void) new FileItem( (QListView *) this, *fi ); ++it; ++fileCount; } if (showThumbnails) { thumbProgress->close(); } emit dirChanged(); } void FileView::rename() { itemToRename = (FileItem *) currentItem(); const QPixmap * pm; int pmw; if( itemToRename == NULL ) return; if( ( pm = itemToRename->pixmap( 0 ) ) == NULL ) pmw = 0; else pmw = pm->width(); ensureItemVisible( itemToRename ); horizontalScrollBar()->setValue( 0 ); horizontalScrollBar()->setEnabled( FALSE ); verticalScrollBar()->setEnabled( FALSE ); selected = isSelected( itemToRename ); setSelected( itemToRename, FALSE ); if( le == NULL ){ le = new InlineEdit( this ); le->setFrame( FALSE ); connect( le, SIGNAL( lostFocus() ), SLOT( endRenaming() ) ); } QRect r = itemRect( itemToRename ); r.setTop( r.top() + frameWidth() + 1 ); r.setLeft( r.left() + frameWidth() + pmw ); r.setBottom( r.bottom() + frameWidth() ); r.setWidth( columnWidth( 0 ) - pmw ); le->setGeometry( r ); le->setText( itemToRename->text( 0 ) ); le->selectAll(); le->show(); le->setFocus(); } void FileView::endRenaming() { if( le && itemToRename ){ le->hide(); setSelected( itemToRename, selected ); if( !itemToRename->rename( le->text() ) ){ QMessageBox::warning( this, tr( "Rename file" ), tr( "Rename failed!" ), tr( "&Ok" ) ); } else { updateDir(); } itemToRename = NULL; horizontalScrollBar()->setEnabled( TRUE ); verticalScrollBar()->setEnabled( TRUE ); } } void FileView::copy() { // dont keep cut files any longer than necessary // ##### a better inmplementation might be to rename the CUT file // ##### to ".QPE-FILEBROWSER-MOVING" rather than copying it. system ( "rm -rf /tmp/qpemoving" ); FileItem * i; if((i = (FileItem *) firstChild()) == 0) return; flist.clear(); while( i ){ if( i->isSelected() /*&& !i->isDir()*/ ){ flist += i->getFilePath(); } i = (FileItem *) i->nextSibling(); } } void FileView::paste() { int i, err; QString cmd, dest, basename, cd = currentDir; if(cd == "/") cd = ""; for ( QStringList::Iterator it = flist.begin(); it != flist.end(); ++it ) { basename = (*it).mid((*it).findRev("/") + 1, (*it).length()); dest = cd + "/" + basename; if( QFile( dest ).exists() ){ i = 1; dest = cd + "/Copy of " + basename; while( QFile( dest ).exists() ){ dest.sprintf( "%s/Copy (%d) of %s", (const char *) cd, i++, (const char *) basename ); } } // // Copy a directory recursively using the "cp" command - // may have to be changed // if( QFileInfo( (*it) ).isDir() ){ cmd = "/bin/cp -fpR \"" + (*it) +"\" " + "\"" + dest + "\""; err = system( (const char *) cmd ); } else if( !copyFile( dest, (*it) ) ){ err = -1; } else { err = 0; } if ( err != 0 ) { QMessageBox::warning( this, tr("Paste file"), tr("Paste failed!"), tr("Ok") ); break; } else { updateDir(); QListViewItem * i = firstChild(); basename = dest.mid( dest.findRev("/") + 1, dest.length() ); while( i ){ if( i->text(0) == basename ){ setCurrentItem( i ); ensureItemVisible( i ); break; } i = i->nextSibling(); } } } } bool FileView::copyFile( const QString & dest, const QString & src ) { char bf[ 50000 ]; int bytesRead; bool success = TRUE; struct stat status; QFile s( src ); QFile d( dest ); if( s.open( IO_ReadOnly | IO_Raw ) && d.open( IO_WriteOnly | IO_Raw ) ) { while( (bytesRead = s.readBlock( bf, sizeof( bf ) )) == sizeof( bf ) ) { if( d.writeBlock( bf, sizeof( bf ) ) != sizeof( bf ) ){ success = FALSE; break; } } if( success && (bytesRead > 0) ){ d.writeBlock( bf, bytesRead ); } } else { success = FALSE; } // Set file permissions if( stat( (const char *) src, &status ) == 0 ){ chmod( (const char *) dest, status.st_mode ); } return success; } void FileView::cut() { int err; // ##### a better inmplementation might be to rename the CUT file // ##### to ".QPE-FILEBROWSER-MOVING" rather than copying it. QString cmd, dest, basename, cd = "/tmp/qpemoving"; QStringList newflist; newflist.clear(); cmd = "rm -rf " + cd; system ( (const char *) cmd ); cmd = "mkdir " + cd; system( (const char *) cmd ); // get the names of the files to cut FileItem * item; if((item = (FileItem *) firstChild()) == 0) return; flist.clear(); while( item ){ if( item->isSelected() /*&& !item->isDir()*/ ){ flist += item->getFilePath(); } item = (FileItem *) item->nextSibling(); } // move these files into a tmp dir for ( QStringList::Iterator it = flist.begin(); it != flist.end(); ++it ) { basename = (*it).mid((*it).findRev("/") + 1, (*it).length()); dest = cd + "/" + basename; newflist += dest; cmd = "/bin/mv -f \"" + (*it) +"\" " + "\"" + dest + "\""; err = system( (const char *) cmd ); if ( err != 0 ) { QMessageBox::warning( this, tr("Cut file"), tr("Cut failed!"), tr("Ok") ); break; } else { updateDir(); QListViewItem * im = firstChild(); basename = dest.mid( dest.findRev("/") + 1, dest.length() ); while( im ){ if( im->text(0) == basename ){ setCurrentItem( im ); ensureItemVisible( im ); break; } im = im->nextSibling(); } } } // update the filelist to point to tmp dir so paste works nicely flist = newflist; } void FileView::del() { FileItem * i; QStringList fl; QString cmd; int err; if((i = (FileItem *) firstChild()) == 0) return; while( i ){ if( i->isSelected() ){ fl += i->getFilePath(); } i = (FileItem *) i->nextSibling(); } if( fl.count() < 1 ) return; if( QMessageBox::warning( this, tr("Delete"), tr("Are you sure?"), tr("Yes"), tr("No") ) == 0) { // // Dependant upon the "rm" command - will probably have to be replaced // for ( QStringList::Iterator it = fl.begin(); it != fl.end(); ++it ) { cmd = "/bin/rm -rf \"" + (*it) + "\""; err = system( (const char *) cmd ); if ( err != 0 ) { QMessageBox::warning( this, tr("Delete"), tr("Delete failed!"), tr("Ok") ); break; } } updateDir(); } } void FileView::newFolder() { int t = 1; FileItem * i; QString nd = currentDir + "/NewFolder"; while( QFile( nd ).exists() ){ nd.sprintf( "%s/NewFolder (%d)", (const char *) currentDir, t++ ); } if( mkdir( (const char *) nd, 0777 ) != 0){ QMessageBox::warning( this, tr( "New folder" ), tr( "Folder creation failed!" ), tr( "Ok" ) ); return; } updateDir(); if((i = (FileItem *) firstChild()) == 0) return; while( i ){ if( i->isDir() && ( i->getFilePath() == nd ) ){ setCurrentItem( i ); rename(); break; } i = (FileItem *) i->nextSibling(); } } void FileView::viewAsText() { FileItem * i = (FileItem *) currentItem(); QCopEnvelope e("QPE/Application/textedit","setDocument(QString)"); e << i->getFilePath(); // Global::execute( "textedit -f ", i->getFilePath() ); } void FileView::itemClicked( QListViewItem * i) { FileItem * t = (FileItem *) i; if( t == NULL ) return; if( t->isDir() ){ setDir( t->getFilePath() ); } } void FileView::itemDblClicked( QListViewItem * i) { if(menuKeepsOpen){ cancelMenuTimer(); } FileItem * t = (FileItem *) i; if(t == NULL) return; if(t->launch() == -1){ QMessageBox::warning( this, tr( "Launch Application" ), tr( "Launch failed!" ), tr( "Ok" ) ); } } void FileView::parentDir() { setDir( currentDir + "./.." ); } void FileView::lastDir() { if( dirHistory.count() == 0 ) return; QString newDir = dirHistory.last(); dirHistory.remove( dirHistory.last() ); generateDir( newDir ); } void FileView::contentsMousePressEvent( QMouseEvent * e ) { QListView::contentsMousePressEvent( e ); menuTimer.start( 750, TRUE ); } void FileView::contentsMouseReleaseEvent( QMouseEvent * e ) { QListView::contentsMouseReleaseEvent( e ); if(!menuKeepsOpen){ menuTimer.stop(); } } void FileView::cancelMenuTimer() { if( menuTimer.isActive() ) menuTimer.stop(); } void FileView::addToDocuments() { FileItem * i = (FileItem *) currentItem(); DocLnk f; QString n = i->text(0); n.replace(QRegExp("\\..*"),""); f.setName( n ); f.setFile( i->getFilePath() ); f.writeLink(); } void FileView::run() { FileItem * i = (FileItem *) currentItem(); i->launch(); } void FileView::showFileMenu() { FileItem * i = (FileItem *) currentItem(); if ( !i ) return; QPopupMenu * m = new QPopupMenu( this ); if ( !i->isDir() ) { m->insertItem( tr( "Add to Documents" ), this, SLOT( addToDocuments() ) ); m->insertSeparator(); } MimeType mt(i->getFilePath()); const AppLnk* app = mt.application(); if ( !i->isDir() ) { if ( app ) m->insertItem( app->pixmap(), tr( "Open in " + app->name() ), this, SLOT( run() ) ); else if( i->isExecutable() ) m->insertItem( Resource::loadPixmap( i->text( 0 ) ), tr( "Run" ), this, SLOT( run() ) ); m->insertItem( Resource::loadPixmap( "txt" ), tr( "View as text" ), this, SLOT( viewAsText() ) ); m->insertSeparator(); } m->insertItem( tr( "Rename" ), this, SLOT( rename() ) ); m->insertItem( Resource::loadPixmap("cut"), tr( "Cut" ), this, SLOT( cut() ) ); m->insertItem( Resource::loadPixmap("copy"), tr( "Copy" ), this, SLOT( copy() ) ); m->insertItem( Resource::loadPixmap("paste"), tr( "Paste" ), this, SLOT( paste() ) ); m->insertItem( tr( "Change Permissions" ), this, SLOT( chPerm() ) ); m->insertItem(Resource::loadPixmap( "close" ), tr( "Delete" ), this, SLOT( del() ) ); m->insertSeparator(); m->insertItem( tr( "Select all" ), this, SLOT( selectAll() ) ); m->insertItem( tr( "Deselect all" ), this, SLOT( deselectAll() ) ); m->popup( QCursor::pos() ); } // // FileBrowser // void FileView::setShowHidden(bool hidden) { showHidden=hidden; } void FileView::setShowSymlinks(bool symlinks) { showSymlinks=symlinks; } void FileView::setShowThumbnails(bool thumbnails) { showThumbnails=thumbnails; } void FileView::setMenuKeepsOpen(bool keepOpen) { menuKeepsOpen=keepOpen; } FileBrowser::FileBrowser( QWidget * parent, const char * name, WFlags f ) : QMainWindow( parent, name, f ) { init( QDir::current().canonicalPath() ); } FileBrowser::FileBrowser( const QString & dir, QWidget * parent, const char * name, WFlags f ) : QMainWindow( parent, name, f ) { init( dir ); } void FileBrowser::init(const QString & dir) { setCaption( tr("File Manager") ); setIcon( Resource::loadPixmap( "filebrowser_icon" ) ); connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); Config cfg("Filebrowser"); cfg.setGroup("View"); bool showHidden=(cfg.readEntry("Hidden","FALSE") == "TRUE"); bool showSymlinks=(cfg.readEntry("Symlinks","FALSE") == "TRUE"); bool showThumbnails=(cfg.readEntry("Thumbnails","FALSE") == "TRUE"); cfg.setGroup("Menu"); bool menuKeepsOpen=(cfg.readEntry("KeepOpen", "FALSE") == "TRUE"); fileView = new FileView( dir, this, 0, showHidden, showSymlinks, showThumbnails ); fileView->setAllColumnsShowFocus( TRUE ); fileView->setMenuKeepsOpen(menuKeepsOpen); setCentralWidget( fileView ); setToolBarsMovable( FALSE ); QPEToolBar* toolBar = new QPEToolBar( this ); toolBar->setHorizontalStretchable( TRUE ); - QPEMenuBar* menuBar = new QPEMenuBar( toolBar ); + QMenuBar* menuBar = new QMenuBar( toolBar ); dirMenu = new QPopupMenu( this ); menuBar->insertItem( tr( "Dir" ), dirMenu ); sortMenu = new QPopupMenu( this ); menuBar->insertItem( tr( "Sort" ), sortMenu ); sortMenu->insertItem( tr( "by Name "), this, SLOT( sortName() ) ); sortMenu->insertItem( tr( "by Size "), this, SLOT( sortSize() ) ); sortMenu->insertItem( tr( "by Date "), this, SLOT( sortDate() ) ); sortMenu->insertItem( tr( "by Type "), this, SLOT( sortType() ) ); sortMenu->insertSeparator(); sortMenu->insertItem( tr( "Ascending" ), this, SLOT( updateSorting() ) ); sortMenu->setItemChecked( sortMenu->idAt( 5 ), TRUE ); sortMenu->setItemChecked( sortMenu->idAt( 0 ), TRUE ); viewMenu = new QPopupMenu( this); viewMenu->insertItem( tr( "Hidden"), this, SLOT( updateShowHidden() ) ); viewMenu->insertItem( tr( "Symlinks"), this, SLOT( updateShowSymlinks() ) ); viewMenu->insertItem( tr( "Thumbnails"), this, SLOT( updateShowThumbnails() ) ); viewMenu->setItemChecked( viewMenu->idAt( 0 ), showHidden ); viewMenu->setItemChecked( viewMenu->idAt( 1 ), showSymlinks ); viewMenu->setItemChecked( viewMenu->idAt( 2 ), showThumbnails ); menuBar->insertItem( tr("View"), viewMenu ); toolBar = new QPEToolBar( this ); lastAction = new QAction( tr("Previous dir"), Resource::loadIconSet( "back" ), QString::null, 0, this, 0 ); connect( lastAction, SIGNAL( activated() ), fileView, SLOT( lastDir() ) ); lastAction->addTo( toolBar ); lastAction->setEnabled( FALSE ); upAction = new QAction( tr("Parent dir"), Resource::loadIconSet( "up" ), QString::null, 0, this, 0 ); connect( upAction, SIGNAL( activated() ), fileView, SLOT( parentDir() ) ); upAction->addTo( toolBar ); QAction *a = new QAction( tr("New folder"), Resource::loadPixmap( "newfolder" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), fileView, SLOT( newFolder() ) ); a->addTo( toolBar ); a = new QAction( tr("Cut"), Resource::loadPixmap( "cut" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), fileView, SLOT( cut() ) ); a->addTo( toolBar ); a = new QAction( tr("Copy"), Resource::loadPixmap( "copy" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), fileView, SLOT( copy() ) ); a->addTo( toolBar ); pasteAction = new QAction( tr("Paste"), Resource::loadPixmap( "paste" ), QString::null, 0, this, 0 ); connect( pasteAction, SIGNAL( activated() ), fileView, SLOT( paste() ) ); pasteAction->addTo( toolBar ); // dirLabel = new QLabel(this, "DirLabel"); connect( fileView, SIGNAL( dirChanged() ), SLOT( updateDirMenu() ) ); updateDirMenu(); QCopChannel* pcmciaChannel = new QCopChannel( "QPE/Card", this ); connect( pcmciaChannel, SIGNAL(received(const QCString &, const QByteArray &)), this, SLOT(pcmciaMessage( const QCString &, const QByteArray &)) ); } void FileBrowser::pcmciaMessage( const QCString &msg, const QByteArray &) { if ( msg == "mtabChanged()" ) { // ## Only really needed if current dir is on a card fileView->updateDir(); } } void FileBrowser::changeCaption(const QString & dir) { setCaption( dir); } void FileBrowser::dirSelected( int id ) { int i = 0, j; QString dir; // Bulid target dir from menu while( (j = dirMenu->idAt( i )) != id ){ dir += dirMenu->text( j ).stripWhiteSpace(); if( dirMenu->text( j ) != "/" ) dir += "/"; i++; } dir += dirMenu->text( dirMenu->idAt( i ) ).stripWhiteSpace(); fileView->setDir( dir ); } void FileBrowser::updateDirMenu() { QString spc, cd = fileView->cd(); QStringList l = QStringList::split( "/", cd ); int i = 0; dirMenu->clear(); dirMenu->insertItem( tr( "/" ), this, SLOT( dirSelected(int) ) ); for ( QStringList::Iterator it = l.begin(); it != l.end(); ++it ) { spc.fill( ' ', i++); dirMenu->insertItem( spc + (*it), this, SLOT( dirSelected(int) ) ); } dirMenu->setItemChecked( dirMenu->idAt( l.count() ), TRUE ); lastAction->setEnabled( fileView->history().count() != 0 ); upAction->setEnabled( cd != "/" ); } void FileBrowser::sortName() { fileView->setSorting( 0, sortMenu->isItemChecked( sortMenu->idAt( 5 ) ) ); fileView->sort(); sortMenu->setItemChecked( sortMenu->idAt( 0 ), TRUE ); sortMenu->setItemChecked( sortMenu->idAt( 1 ), FALSE ); sortMenu->setItemChecked( sortMenu->idAt( 2 ), FALSE ); sortMenu->setItemChecked( sortMenu->idAt( 3 ), FALSE ); } void FileBrowser::sortSize() { fileView->setSorting( 1, sortMenu->isItemChecked( sortMenu->idAt( 5 ) ) ); fileView->sort(); sortMenu->setItemChecked( sortMenu->idAt( 0 ), FALSE ); sortMenu->setItemChecked( sortMenu->idAt( 1 ), TRUE ); sortMenu->setItemChecked( sortMenu->idAt( 2 ), FALSE ); sortMenu->setItemChecked( sortMenu->idAt( 3 ), FALSE ); } void FileBrowser::sortDate() { fileView->setSorting( 2, sortMenu->isItemChecked( sortMenu->idAt( 5 ) ) ); fileView->sort(); sortMenu->setItemChecked( sortMenu->idAt( 0 ), FALSE ); sortMenu->setItemChecked( sortMenu->idAt( 1 ), FALSE ); sortMenu->setItemChecked( sortMenu->idAt( 2 ), TRUE ); sortMenu->setItemChecked( sortMenu->idAt( 3 ), FALSE ); } void FileBrowser::sortType() { fileView->setSorting( 3, sortMenu->isItemChecked( sortMenu->idAt( 5 ) ) ); fileView->sort(); sortMenu->setItemChecked( sortMenu->idAt( 0 ), FALSE ); sortMenu->setItemChecked( sortMenu->idAt( 1 ), FALSE ); sortMenu->setItemChecked( sortMenu->idAt( 2 ), FALSE ); sortMenu->setItemChecked( sortMenu->idAt( 3 ), TRUE ); } void FileBrowser::updateSorting() { sortMenu->setItemChecked( sortMenu->idAt( 5 ), !sortMenu->isItemChecked( sortMenu->idAt( 5 ) ) ); if ( sortMenu->isItemChecked( sortMenu->idAt( 0 ) ) ) sortName(); else if ( sortMenu->isItemChecked( sortMenu->idAt( 1 ) ) ) sortSize(); else if ( sortMenu->isItemChecked( sortMenu->idAt( 2 ) ) ) sortDate(); else sortType(); } void FileView::chPerm() { FileItem * i; QStringList fl; QString cmd; if((i = (FileItem *) firstChild()) == 0) return; while( i ){ if( i->isSelected() ){ fl += i->getFilePath(); } i = (FileItem *) i->nextSibling(); } if( fl.count() < 1 ) return; if( QMessageBox::warning( this, tr("Change permissions"), tr("Are you sure?"), tr("Yes"), tr("No") ) == 0) { for ( QStringList::Iterator it = fl.begin(); it != fl.end(); ++it ) { filePermissions *filePerm; filePerm = new filePermissions(this, "Permissions",true,0,(const QString &)(*it)); filePerm->exec(); if( filePerm) delete filePerm; break; } updateDir(); } } void FileBrowser::updateShowHidden() { bool valShowHidden=viewMenu->isItemChecked( viewMenu->idAt( 0 ) ); valShowHidden=!valShowHidden; viewMenu->setItemChecked( viewMenu->idAt( 0 ), valShowHidden ); fileView->setShowHidden(valShowHidden); Config cfg("Filebrowser"); cfg.setGroup("View"); cfg.writeEntry("Hidden",valShowHidden?"TRUE":"FALSE"); fileView->updateDir(); } void FileBrowser::updateShowSymlinks() { bool valShowSymlinks=viewMenu->isItemChecked( viewMenu->idAt( 1 ) ); valShowSymlinks=!valShowSymlinks; viewMenu->setItemChecked( viewMenu->idAt( 1 ), valShowSymlinks ); fileView->setShowSymlinks(valShowSymlinks); Config cfg("Filebrowser"); cfg.setGroup("View"); cfg.writeEntry("Symlinks",valShowSymlinks?"TRUE":"FALSE"); fileView->updateDir(); } void FileBrowser::updateShowThumbnails() { bool valShowThumbnails=viewMenu->isItemChecked( viewMenu->idAt( 2 ) ); valShowThumbnails=!valShowThumbnails; viewMenu->setItemChecked( viewMenu->idAt( 2 ), valShowThumbnails ); fileView->setShowThumbnails(valShowThumbnails); Config cfg("Filebrowser"); cfg.setGroup("View"); cfg.writeEntry("Thumbnails",valShowThumbnails?"TRUE":"FALSE"); fileView->updateDir(); } void FileBrowser::cleanUp() { QString cmdr = "rm -rf /tmp/filebrowserThumbnailCache"; // qDebug("exit"); system(cmdr.latin1()); } diff --git a/noncore/unsupported/mail2/composerbase.cpp b/noncore/unsupported/mail2/composerbase.cpp index 6f6ab8e..34d6eb6 100644 --- a/noncore/unsupported/mail2/composerbase.cpp +++ b/noncore/unsupported/mail2/composerbase.cpp @@ -1,205 +1,205 @@ #include <qmultilineedit.h> #include <qpopupmenu.h> #include <qcombobox.h> #include <qlineedit.h> #include <qlayout.h> #include <qaction.h> #include <qlabel.h> #include <qvbox.h> #include <qpe/qpetoolbar.h> #include <qpe/qpemenubar.h> #include <qpe/resource.h> #include "mailstatusbar.h" #include "listviewplus.h" #include "composerbase.h" ComposerBase::ComposerBase(QWidget *parent, const char *name, WFlags fl) : QMainWindow(parent, name, fl) { setCaption(tr("Compose Message")); setToolBarsMovable(false); toolbar = new QPEToolBar(this); - menubar = new QPEMenuBar( toolbar ); + menubar = new QMenuBar( toolbar ); mailmenu = new QPopupMenu( menubar ); menubar->insertItem( tr( "Mail" ), mailmenu ); addToolBar(toolbar); toolbar->setHorizontalStretchable(true); QLabel *spacer = new QLabel(toolbar); spacer->setBackgroundMode(QWidget::PaletteButton); toolbar->setStretchableWidget(spacer); sendmail = new QAction(tr("Send the mail"), QIconSet(Resource::loadPixmap("mail/sendmail")), 0, 0, this); sendmail->addTo(toolbar); sendmail->addTo(mailmenu); queuemail = new QAction(tr("Queue the mail"), QIconSet(Resource::loadPixmap("mail/sendall")), 0, 0, this); queuemail->addTo(toolbar); queuemail->addTo(mailmenu); attachfile = new QAction(tr("Attach a file"), QIconSet(Resource::loadPixmap("mail/attach")), 0, 0, this, 0, true); attachfile->addTo(toolbar); attachfile->addTo(mailmenu); connect(attachfile, SIGNAL(toggled(bool)), SLOT(slotAttachfileChanged(bool))); addressbook = new QAction(tr("Addressbook"), QIconSet(Resource::loadPixmap("mail/addbook")), 0, 0, this); addressbook->addTo(toolbar); addressbook->addTo(mailmenu); QWidget *main = new QWidget(this); setCentralWidget(main); QGridLayout *layout = new QGridLayout(main); fromBox = new QComboBox(main); fromBox->insertItem(tr("From"), POPUP_FROM_FROM); fromBox->insertItem(tr("Reply"), POPUP_FROM_REPLYTO); layout->addWidget(fromBox, 0, 0); connect(fromBox, SIGNAL(activated(int)), SLOT(slotFromMenuChanged(int))); QHBoxLayout *fromLayout = new QHBoxLayout(); layout->addLayout(fromLayout, 0, 1); from = new QComboBox(main); fromLayout->addWidget(from); replyto = new QLineEdit(main); replyto->hide(); fromLayout->addWidget(replyto); receiversBox = new QComboBox(main); receiversBox->insertItem(tr("To"), POPUP_RECV_TO); receiversBox->insertItem(tr("Cc"), POPUP_RECV_CC); receiversBox->insertItem(tr("Bcc"), POPUP_RECV_BCC); layout->addWidget(receiversBox, 1, 0); connect(receiversBox, SIGNAL(activated(int)), SLOT(slotReceiverMenuChanged(int))); QHBoxLayout *receiverLayout = new QHBoxLayout(); layout->addLayout(receiverLayout, 1, 1); to = new QLineEdit(main); receiverLayout->addWidget(to); cc = new QLineEdit(main); cc->hide(); receiverLayout->addWidget(cc); bcc = new QLineEdit(main); bcc->hide(); receiverLayout->addWidget(bcc); subjectBox = new QComboBox(main); subjectBox->insertItem(tr("Subj."), POPUP_SUBJ_SUBJECT); subjectBox->insertItem(tr("Prio."), POPUP_SUBJ_PRIORITY); layout->addWidget(subjectBox, 2, 0); connect(subjectBox, SIGNAL(activated(int)), SLOT(slotSubjectMenuChanged(int))); QHBoxLayout *subjectLayout = new QHBoxLayout(); layout->addLayout(subjectLayout, 2, 1); subject = new QLineEdit(main); subjectLayout->addWidget(subject); priority = new QComboBox(main); priority->insertItem(tr("Low"), POPUP_PRIO_LOW); priority->insertItem(tr("Normal"), POPUP_PRIO_NORMAL); priority->insertItem(tr("High"), POPUP_PRIO_HIGH); priority->setCurrentItem(POPUP_PRIO_NORMAL); priority->hide(); subjectLayout->addWidget(priority); QVBox *view = new QVBox(main); layout->addMultiCellWidget(view, 3, 3, 0, 1); message = new QMultiLineEdit(view); message->setMinimumHeight(30); attachWindow = new QMainWindow(view, 0, 0); attachWindow->setMinimumHeight(80); attachWindow->setMaximumHeight(80); attachWindow->setToolBarsMovable(false); attachWindow->hide(); attachToolbar = new QPEToolBar(attachWindow); attachToolbar->setVerticalStretchable(true); addattach = new QAction(tr("Add an Attachement"), QIconSet(Resource::loadPixmap("mail/newmail")), 0, 0, this); addattach->addTo(attachToolbar); delattach = new QAction(tr("Remove Attachement"), QIconSet(Resource::loadPixmap("mail/delete")), 0, 0, this); delattach->addTo(attachToolbar); QLabel *attachSpacer = new QLabel(attachToolbar); attachSpacer->setBackgroundMode(QWidget::PaletteButton); attachToolbar->setStretchableWidget(attachSpacer); attachWindow->addToolBar(attachToolbar, QMainWindow::Left); attachView = new ListViewPlus(attachWindow); attachView->addColumn(tr("Name"), 80); attachView->addColumn(tr("Description"), 110); attachView->setAllColumnsShowFocus(true); attachWindow->setCentralWidget(attachView); attachPopup = new QPopupMenu(attachView); attachPopup->insertItem(tr("Rename"), POPUP_ATTACH_RENAME); attachPopup->insertItem(tr("Change Description"), POPUP_ATTACH_DESC); attachPopup->insertSeparator(); attachPopup->insertItem(tr("Remove"), POPUP_ATTACH_REMOVE); attachView->setPopup(attachPopup); status = new MailStatusBar(view); } void ComposerBase::slotAttachfileChanged(bool toggled) { if (toggled) { if (attachWindow->isHidden()) attachWindow->show(); } else { if (!attachWindow->isHidden()) attachWindow->hide(); } } void ComposerBase::slotFromMenuChanged(int id) { if (POPUP_FROM_FROM == id) { if (from->isHidden()) from->show(); if (!replyto->isHidden()) replyto->hide(); } else if (POPUP_FROM_REPLYTO == id) { if (!from->isHidden()) from->hide(); if (replyto->isHidden()) replyto->show(); } } void ComposerBase::slotReceiverMenuChanged(int id) { if (POPUP_RECV_TO == id) { if (to->isHidden()) to->show(); if (!cc->isHidden()) cc->hide(); if (!bcc->isHidden()) bcc->hide(); } else if (POPUP_RECV_CC == id) { if (!to->isHidden()) to->hide(); if (cc->isHidden()) cc->show(); if (!bcc->isHidden()) bcc->hide(); } else if (POPUP_RECV_BCC == id) { if (!to->isHidden()) to->hide(); if (!cc->isHidden()) cc->hide(); if (bcc->isHidden()) bcc->show(); } } void ComposerBase::slotSubjectMenuChanged(int id) { if (POPUP_SUBJ_SUBJECT == id) { if (subject->isHidden()) subject->show(); if (!priority->isHidden()) priority->hide(); } else if (POPUP_SUBJ_PRIORITY == id) { if (!subject->isHidden()) subject->hide(); if (priority->isHidden()) priority->show(); } } diff --git a/noncore/unsupported/mail2/composerbase.h b/noncore/unsupported/mail2/composerbase.h index 58f1157..2c832d6 100644 --- a/noncore/unsupported/mail2/composerbase.h +++ b/noncore/unsupported/mail2/composerbase.h @@ -1,61 +1,61 @@ #ifndef COMPOSERBASE_H #define COMPOSERBASE_H #include <qmainwindow.h> class QMultiLineEdit; class MailStatusBar; class ListViewPlus; class QPopupMenu; class QPEToolBar; -class QPEMenuBar; +class QMenuBar; class QPopupMenu; class QComboBox; class QLineEdit; class QAction; class QLabel; class ComposerBase : public QMainWindow { Q_OBJECT public: ComposerBase(QWidget *parent = 0, const char *name = 0, WFlags fl = 0); protected: static const int POPUP_FROM_FROM = 0; static const int POPUP_FROM_REPLYTO = 1; static const int POPUP_RECV_TO = 0; static const int POPUP_RECV_CC = 1; static const int POPUP_RECV_BCC = 2; static const int POPUP_SUBJ_SUBJECT = 0; static const int POPUP_SUBJ_PRIORITY = 1; static const int POPUP_PRIO_LOW = 0; static const int POPUP_PRIO_NORMAL = 1; static const int POPUP_PRIO_HIGH = 2; static const int POPUP_ATTACH_RENAME = 0; static const int POPUP_ATTACH_DESC = 1; static const int POPUP_ATTACH_REMOVE = 2; QMultiLineEdit *message; MailStatusBar *status; ListViewPlus *attachView; QMainWindow *attachWindow; QPopupMenu *attachPopup; QPEToolBar *toolbar, *attachToolbar; - QPEMenuBar *menubar; + QMenuBar *menubar; QPopupMenu *mailmenu; QComboBox *fromBox, *from, *receiversBox, *subjectBox, *priority; QLineEdit *replyto, *to, *cc, *bcc, *subject; QAction *sendmail, *queuemail, *attachfile, *addressbook, *abort, *addattach, *delattach; QLabel *fromLabel; protected slots: void slotAttachfileChanged(bool toggled); void slotFromMenuChanged(int id); void slotReceiverMenuChanged(int id); void slotSubjectMenuChanged(int id); }; #endif diff --git a/noncore/unsupported/mail2/mainwindowbase.cpp b/noncore/unsupported/mail2/mainwindowbase.cpp index e35d489..119acfb 100644 --- a/noncore/unsupported/mail2/mainwindowbase.cpp +++ b/noncore/unsupported/mail2/mainwindowbase.cpp @@ -1,75 +1,75 @@ #include <qpopupmenu.h> #include <qaction.h> #include <qheader.h> #include <qlabel.h> #include <qvbox.h> #include <qpe/qpetoolbar.h> #include <qpe/qpemenubar.h> #include <qpe/resource.h> #include "mainwindowbase.h" #include "mailstatusbar.h" #include "folderwidget.h" #include "mailtable.h" MainWindowBase::MainWindowBase(QWidget *parent, const char *name, WFlags fl) : QMainWindow(parent, name, fl) { setCaption(tr("E-Mail")); setToolBarsMovable(false); toolbar = new QPEToolBar(this); - menubar = new QPEMenuBar( toolbar ); + menubar = new QMenuBar( toolbar ); mailmenu = new QPopupMenu( menubar ); servermenu = new QPopupMenu( menubar ); menubar->insertItem( tr( "Mail" ), mailmenu ); menubar->insertItem( tr( "Servers" ), servermenu ); addToolBar(toolbar); toolbar->setHorizontalStretchable(true); QLabel *spacer = new QLabel(toolbar); spacer->setBackgroundMode(QWidget::PaletteButton); toolbar->setStretchableWidget(spacer); compose = new QAction(tr("Compose new mail"), QIconSet(Resource::loadPixmap("mail/newmail")), 0, 0, this); compose->addTo(toolbar); compose->addTo(mailmenu); sendQueue = new QAction(tr("Send queued mails"), QIconSet(Resource::loadPixmap("mail/sendqueue")), 0, 0, this); sendQueue->addTo(toolbar); sendQueue->addTo(mailmenu); folders = new QAction(tr("Show/hide folders"), QIconSet(Resource::loadPixmap("mail/folder")), 0, 0, this, 0, true); folders->addTo(toolbar); folders->addTo(servermenu); connect(folders, SIGNAL(toggled(bool)), SLOT(slotFoldersToggled(bool))); findmails = new QAction(tr("Search mails"), QIconSet(Resource::loadPixmap("mail/find")), 0, 0, this); findmails->addTo(toolbar); findmails->addTo(mailmenu); configure = new QAction(tr("Configuration"), QIconSet(Resource::loadPixmap("mail/configure")), 0, 0, this); configure->addTo(servermenu); QVBox *view = new QVBox(this); setCentralWidget(view); folderView = new FolderWidget(view); folderView->setMinimumHeight(90); folderView->setMaximumHeight(90); folderView->hide(); mailView = new MailTable(view); mailView->setMinimumHeight(50); status = new MailStatusBar(view); } void MainWindowBase::slotFoldersToggled(bool toggled) { if (folderView->isHidden() && toggled) folderView->show(); if (!folderView->isHidden() && !toggled) folderView->hide(); } diff --git a/noncore/unsupported/mail2/mainwindowbase.h b/noncore/unsupported/mail2/mainwindowbase.h index 11c5ea0..b2e1dc5 100644 --- a/noncore/unsupported/mail2/mainwindowbase.h +++ b/noncore/unsupported/mail2/mainwindowbase.h @@ -1,37 +1,37 @@ #ifndef MAINWINDOWBASE_H #define MAINWINDOWBASE_H #include <qmainwindow.h> class ServerConnection; class MailStatusBar; class FolderWidget; class QPEToolBar; -class QPEMenuBar; +class QMenuBar; class QPopupMenu; class MailTable; class QAction; class MainWindowBase : public QMainWindow { Q_OBJECT public: MainWindowBase(QWidget *parent = 0, const char *name = 0, WFlags fl = 0); protected slots: void slotFoldersToggled(bool toggled); protected: ServerConnection *serverConnection; MailStatusBar *status; FolderWidget *folderView; QPEToolBar *toolbar; - QPEMenuBar *menubar; + QMenuBar *menubar; QPopupMenu *mailmenu, *servermenu; MailTable *mailView; QAction *compose, *sendQueue, *folders, *findmails, *configure; }; #endif diff --git a/noncore/unsupported/mail2/viewmailbase.cpp b/noncore/unsupported/mail2/viewmailbase.cpp index a02f73a..10aa14d 100644 --- a/noncore/unsupported/mail2/viewmailbase.cpp +++ b/noncore/unsupported/mail2/viewmailbase.cpp @@ -1,75 +1,75 @@ #include <qtextbrowser.h> #include <qlistview.h> #include <qaction.h> #include <qlabel.h> #include <qvbox.h> #include <qpopupmenu.h> #include <qpe/qpetoolbar.h> #include <qpe/qpemenubar.h> #include <qpe/resource.h> #include "viewmailbase.h" #include "opendiag.h" ViewMailBase::ViewMailBase(QWidget *parent, const char *name, WFlags fl) : QMainWindow(parent, name, fl) { setCaption(tr("E-Mail by %1")); setToolBarsMovable(false); toolbar = new QPEToolBar(this); - menubar = new QPEMenuBar( toolbar ); + menubar = new QMenuBar( toolbar ); mailmenu = new QPopupMenu( menubar ); menubar->insertItem( tr( "Mail" ), mailmenu ); toolbar->setHorizontalStretchable(true); addToolBar(toolbar); QLabel *spacer = new QLabel(toolbar); spacer->setBackgroundMode(QWidget::PaletteButton); toolbar->setStretchableWidget(spacer); reply = new QAction(tr("Reply"), QIconSet(Resource::loadPixmap("mail/reply")), 0, 0, this); reply->addTo(toolbar); reply->addTo(mailmenu); forward = new QAction(tr("Forward"), QIconSet(Resource::loadPixmap("mail/forward")), 0, 0, this); forward->addTo(toolbar); forward->addTo(mailmenu); attachbutton = new QAction(tr("Attachments"), QIconSet(Resource::loadPixmap("mail/attach")), 0, 0, this, 0, true); attachbutton->addTo(toolbar); attachbutton->addTo(mailmenu); connect(attachbutton, SIGNAL(toggled(bool)), SLOT(slotChangeAttachview(bool))); deleteMail = new QAction(tr("Delete Mail"), QIconSet(Resource::loadPixmap("mail/delete")), 0, 0, this); deleteMail->addTo(toolbar); deleteMail->addTo(mailmenu); QVBox *view = new QVBox(this); setCentralWidget(view); attachments = new QListView(view); attachments->setMinimumHeight(90); attachments->setMaximumHeight(90); attachments->setAllColumnsShowFocus(true); attachments->addColumn("Mime Type", 100); attachments->addColumn("Filename", 100); attachments->addColumn("Description", 100); attachments->hide(); browser = new QTextBrowser(view); openDiag = new OpenDiag(view); openDiag->hide(); } void ViewMailBase::slotChangeAttachview(bool state) { if (state) attachments->show(); else attachments->hide(); } diff --git a/noncore/unsupported/mail2/viewmailbase.h b/noncore/unsupported/mail2/viewmailbase.h index ba82017..6e55021 100644 --- a/noncore/unsupported/mail2/viewmailbase.h +++ b/noncore/unsupported/mail2/viewmailbase.h @@ -1,36 +1,36 @@ #ifndef VIEWMAILBASE_H #define VIEWMAILBASE_H #include <qmainwindow.h> class QAction; class OpenDiag; class QListView; class QPEToolBar; class QTextBrowser; -class QPEMenuBar; +class QMenuBar; class QPopupMenu; class ViewMailBase : public QMainWindow { Q_OBJECT public: ViewMailBase(QWidget *parent = 0, const char *name = 0, WFlags fl = 0); protected: QAction *reply, *forward, *attachbutton, *deleteMail; QListView *attachments; QPEToolBar *toolbar; QTextBrowser *browser; OpenDiag *openDiag; - QPEMenuBar *menubar; + QMenuBar *menubar; QPopupMenu *mailmenu; protected slots: void slotChangeAttachview(bool state); }; #endif diff --git a/noncore/unsupported/oipkg/mainwindow.cpp b/noncore/unsupported/oipkg/mainwindow.cpp index 04362d3..6930d60 100644 --- a/noncore/unsupported/oipkg/mainwindow.cpp +++ b/noncore/unsupported/oipkg/mainwindow.cpp @@ -1,515 +1,515 @@ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ // Copyright (C) 2000 Trolltech AS. // adadpted form qpe/qipkg // (c) 2002 Patrick S. Vogt <tille@handhelds.org> #include "mainwindow.h" -#include <qpe/qpemenubar.h> +#include <qmenubar.h> #include <qpe/qpemessagebox.h> #include <qpe/resource.h> #include <qpe/config.h> #include <qpe/qpetoolbar.h> #include <qpe/qcopenvelope_qws.h> #include <qaction.h> #include <qmessagebox.h> #include <qpopupmenu.h> #include <qtoolbutton.h> #include <qstring.h> #include <qlabel.h> #include <qfile.h> #include <qlistview.h> #include <qtextview.h> #include <qcheckbox.h> #include <qlineedit.h> #include <qtabwidget.h> #include <qcombobox.h> #include <qmessagebox.h> #include <qpushbutton.h> #include <qlayout.h> #include "pksettingsbase.h" #include "utils.h" #include "packagelistitem.h" MainWindow::MainWindow( QWidget *parent, const char *name, WFlags f ) : QMainWindow( parent, name, f ) // packageListServers( QObject(parent), name ), // packageListSearch( parent, name ), // packageListDocLnk( parent, name ) { setCaption( tr("Package Manager") ); settings = new PackageManagerSettings(this,0,TRUE); listViewPackages = new PackageListView( this,"listViewPackages",settings ); setCentralWidget( listViewPackages ); listViewPackages->addList( tr("feeds"), &packageListServers ); listViewPackages->addList( tr("ipkgfind&killefiz"), &packageListSearch ); listViewPackages->addList( tr("documents"), &packageListDocLnk ); ipkg = new PmIpkg( settings, this ); packageListServers.setSettings( settings ); packageListSearch.setSettings( settings ); packageListDocLnk.setSettings( settings ); pvDebug(9,"packageListServers.update"); packageListServers.update(); pvDebug(9,"packageListDocLnk.update"); packageListDocLnk.update(); pvDebug(9,"makeMenu"); makeMenu(); makeChannel(); connect( section, SIGNAL(activated(int)), SLOT(sectionChanged()) ); connect( subsection, SIGNAL(activated(int)), SLOT(subSectionChanged()) ); connect( settings->removeLinksButton, SIGNAL( clicked()), SLOT(removeLinks()) ); connect( settings->createLinksButton, SIGNAL( clicked()), SLOT(createLinks()) ); pvDebug(9,"displayList"); displayList(); } void MainWindow::makeMenu() { QPEToolBar *toolBar = new QPEToolBar( this ); - QPEMenuBar *menuBar = new QPEMenuBar( toolBar ); + QMenuBar *menuBar = new QMenuBar( toolBar ); QPopupMenu *srvMenu = new QPopupMenu( menuBar ); QPopupMenu *viewMenu = new QPopupMenu( menuBar ); QPopupMenu *cfgMenu = new QPopupMenu( menuBar ); QPopupMenu *helpMenu = new QPopupMenu( menuBar ); setToolBarsMovable( false ); toolBar->setHorizontalStretchable( true ); menuBar->insertItem( tr( "Package" ), srvMenu ); menuBar->insertItem( tr( "View" ), viewMenu ); menuBar->insertItem( tr( "Settings" ), cfgMenu ); menuBar->insertItem( tr( "Help" ), helpMenu ); // QLabel *spacer; // spacer = new QLabel( "", toolBar ); // spacer->setBackgroundColor( toolBar->backgroundColor() ); // toolBar->setStretchableWidget( spacer ); runAction = new QAction( tr( "Apply" ), Resource::loadPixmap( "oipkg/install" ), QString::null, 0, this, 0 ); connect( runAction, SIGNAL( activated() ), this, SLOT( runIpkg() ) ); runAction->addTo( toolBar ); runAction->addTo( srvMenu ); srvMenu->insertSeparator(); updateAction = new QAction( tr( "Update" ), Resource::loadIconSet( "oipkg/update" ), QString::null, 0, this, 0 ); connect( updateAction, SIGNAL( activated() ), this , SLOT( updateList() ) ); updateAction->addTo( toolBar ); updateAction->addTo( srvMenu ); QAction *cfgact; cfgact = new QAction( tr( "Setups" ), QString::null, 0, this, 0 ); connect( cfgact, SIGNAL( activated() ), SLOT( showSettingsSetup() ) ); cfgact->addTo( cfgMenu ); cfgact = new QAction( tr( "Servers" ), QString::null, 0, this, 0 ); connect( cfgact, SIGNAL( activated() ), SLOT( showSettingsSrv() ) ); cfgact->addTo( cfgMenu ); cfgact = new QAction( tr( "Destinations" ), QString::null, 0, this, 0 ); connect( cfgact, SIGNAL( activated() ), SLOT( showSettingsDst() ) ); cfgact->addTo( cfgMenu ); QAction *a; // SECTIONS sectionBar = new QPEToolBar( this ); addToolBar( sectionBar, "Section", QMainWindow::Top, TRUE ); sectionBar->setHorizontalStretchable( true ); QLabel *label = new QLabel( sectionBar, "section" ); // label->setBackgroundMode( NoBackground ); label->font().setPointSize( 8 ); label->setText( tr( "Section:" ) ); sectionBar->setStretchableWidget( label ); section = new QComboBox( false, sectionBar ); section->font().setPointSize( 8 ); label = new QLabel( " / ", sectionBar ); label->font().setPointSize( 8 ); // label->setBackgroundMode( PaletteForeground ); subsection = new QComboBox( false, sectionBar ); subsection->font().setPointSize( 8 ); a = new QAction( tr( "Close Section" ), Resource::loadPixmap( "close" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( sectionClose() ) ); a->addTo( sectionBar ); setSections(); setSubSections(); sectionAction = new QAction( tr( "Sections" ), QString::null, 0, this, 0 ); connect( sectionAction, SIGNAL( toggled(bool) ), this, SLOT( sectionShow(bool) ) ); sectionAction->setToggleAction( true ); sectionAction->addTo( viewMenu ); // sectionBar->setStretchableWidget( section ); //FIND findBar = new QPEToolBar(this); addToolBar( findBar, "Filter", QMainWindow::Top, TRUE ); label = new QLabel( tr("Filter: "), findBar ); // label->setBackgroundMode( PaletteForeground ); findBar->setHorizontalStretchable( TRUE ); findEdit = new QLineEdit( findBar, "findEdit" ); findBar->setStretchableWidget( findEdit ); connect( findEdit, SIGNAL( textChanged( const QString & ) ), this, SLOT( displayList() ) ); a = new QAction( tr( "Clear Find" ), Resource::loadPixmap( "back" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), findEdit, SLOT( clear() ) ); a->addTo( findBar ); a = new QAction( tr( "Close Find" ), Resource::loadPixmap( "close" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( findClose() ) ); a->addTo( findBar ); findAction = new QAction( tr( "Filter" ), QString::null, 0, this, 0 ); connect( findAction, SIGNAL( toggled(bool) ), this, SLOT( findShow(bool) ) ); findAction->setToggleAction( true ); findAction->addTo( viewMenu ); //SEARCH searchBar = new QPEToolBar(this); addToolBar( searchBar, "Search", QMainWindow::Top, TRUE ); label = new QLabel( tr("Search: "), searchBar ); // label->setBackgroundMode( PaletteForeground ); searchBar->setHorizontalStretchable( TRUE ); searchEdit = new QLineEdit( searchBar, "seachEdit" ); searchBar->setStretchableWidget( searchEdit ); // connect( searchEdit, SIGNAL( textChanged( const QString & ) ), // this, SLOT( displayList() ) ); a = new QAction( tr( "Clear Search" ), Resource::loadPixmap( "back" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), searchEdit, SLOT( clear() ) ); a->addTo( searchBar ); searchCommit = new QAction( tr( "Do Search" ), Resource::loadPixmap( "find" ), QString::null, 0, this, 0 ); connect( searchCommit, SIGNAL( activated() ), SLOT( remotePackageQuery() ) ); searchCommit->addTo( searchBar ); a = new QAction( tr( "Close Find" ), Resource::loadPixmap( "close" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( searchClose() ) ); a->addTo( searchBar ); searchAction = new QAction( tr( "Search" ), QString::null, 0, this, 0 ); connect( searchAction, SIGNAL( toggled(bool) ), this, SLOT( searchShow(bool) ) ); searchAction->setToggleAction( true ); searchAction->addTo( viewMenu ); //DEST destBar = new QPEToolBar(this); addToolBar( destBar, "Destination", QMainWindow::Top, TRUE ); label = new QLabel( tr("Destination: "), destBar ); // label->setBackgroundMode( PaletteForeground ); destBar->setHorizontalStretchable( TRUE ); destination = new QComboBox( false, destBar ); destination->insertStringList( settings->getDestinationNames() ); setComboName(destination,settings->getDestinationName()); connect( destination, SIGNAL(activated(int)), settings, SLOT(activeDestinationChange(int)) ); // space->setBackgroundMode( PaletteForeground ); CheckBoxLink = new QCheckBox( tr("Link"), destBar); // CheckBoxLink->setBackgroundMode( PaletteForeground ); CheckBoxLink->setChecked( settings->createLinks() ); connect( CheckBoxLink, SIGNAL(toggled(bool)), settings, SLOT(linkEnabled(bool)) ); destAction = new QAction( tr( "Destinations" ), QString::null, 0, this, 0 ); connect( destAction, SIGNAL( toggled(bool) ), SLOT( destShow(bool) ) ); a = new QAction( tr( "Close Destinations" ), Resource::loadPixmap( "close" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), SLOT( destClose() ) ); a->addTo( destBar ); destBar->setStretchableWidget( CheckBoxLink ); destAction->setToggleAction( true ); destAction->addTo( viewMenu ); // helpMenu helpMenu->insertSeparator(); a = new QAction( tr( "Package Actions" ), QString::null, 0, this, 0 ); a->addTo( helpMenu ); helpMenu->insertSeparator(); a = new QAction( tr( "Install" ), Resource::loadPixmap( "oipkg/install" ), QString::null, 0, this, 0 ); a->addTo( helpMenu ); a = new QAction( tr( "Remove" ), Resource::loadPixmap( "oipkg/uninstall" ), QString::null, 0, this, 0 ); a->addTo( helpMenu ); helpMenu->insertSeparator(); a = new QAction( tr( "Package Status" ), QString::null, 0, this, 0 ); a->addTo( helpMenu ); helpMenu->insertSeparator(); a = new QAction( tr( "New version, installed" ), Resource::loadPixmap( "oipkg/installed" ), QString::null, 0, this, 0 ); a->addTo( helpMenu ); a = new QAction( tr( "New version, not installed" ), Resource::loadPixmap( "oipkg/uninstalled" ), QString::null, 0, this, 0 ); a->addTo( helpMenu ); a = new QAction( tr( "Old version, installed" ), Resource::loadPixmap( "oipkg/installedOld" ), QString::null, 0, this, 0 ); a->addTo( helpMenu ); a = new QAction( tr( "Old version, not installed" ), Resource::loadPixmap( "oipkg/uninstalledOld" ), QString::null, 0, this, 0 ); a->addTo( helpMenu ); a = new QAction( tr( "Old version, new version installed" ), Resource::loadPixmap( "oipkg/uninstalledOldinstalledNew" ), QString::null, 0, this, 0 ); a->addTo( helpMenu ); a = new QAction( tr( "New version, old version installed" ), Resource::loadPixmap( "oipkg/uninstalledInstalledOld" ), QString::null, 0, this, 0 ); a->addTo( helpMenu ); // a = new QAction( tr( "" ), // Resource::loadPixmap( "oipkg/" ), QString::null, 0, this, 0 ); // a->addTo( helpMenu ); // configure the menus Config cfg( "oipkg", Config::User ); cfg.setGroup( "gui" ); findShow( cfg.readBoolEntry( "findBar", true ) ); searchShow( cfg.readBoolEntry( "searchBar", true ) ); sectionShow( cfg.readBoolEntry( "sectionBar", true ) ); destShow( cfg.readBoolEntry( "destBar", false ) ); setComboName(section,cfg.readEntry("default_section")); sectionChanged(); } MainWindow::~MainWindow() { Config cfg( "oipkg", Config::User ); cfg.setGroup( "gui" ); cfg.writeEntry( "findBar", !findBar->isHidden() ); cfg.writeEntry( "searchBar", !searchBar->isHidden() ); cfg.writeEntry( "sectionBar", !sectionBar->isHidden() ); cfg.writeEntry( "destBar", !destBar->isHidden() ); cfg.writeEntry( "default_section", section->currentText() ); } void MainWindow::runIpkg() { packageListServers.allPackages(); ipkg->loadList( &packageListSearch ); ipkg->loadList( &packageListDocLnk ); ipkg->loadList( &packageListServers ); ipkg->commit(); ipkg->clearLists(); // ##### If we looked in the list of files, we could send out accurate // ##### messages. But we don't bother yet, and just do an "all". QCopEnvelope e("QPE/System", "linkChanged(QString)"); QString lf = QString::null; e << lf; displayList(); } void MainWindow::updateList() { packageListServers.clear(); packageListSearch.clear(); packageListDocLnk.clear(); ipkg->update(); packageListServers.update(); packageListSearch.update(); packageListDocLnk.update(); } void MainWindow::filterList() { QString f = ""; if ( findAction->isOn() ) f = findEdit->text(); packageListServers.filterPackages( f ); } void MainWindow::displayList() { filterList(); listViewPackages->display(); } void MainWindow::sectionChanged() { disconnect( section, SIGNAL( activated(int) ), this, SLOT( sectionChanged() ) ); disconnect( subsection, SIGNAL(activated(int) ), this, SLOT( subSectionChanged() ) ); subsection->clear(); packageListServers.setSection( section->currentText() ); setSubSections(); connect( section, SIGNAL( activated(int) ), this, SLOT( sectionChanged() ) ); connect( subsection, SIGNAL(activated(int) ), this, SLOT( subSectionChanged() ) ); displayList(); } void MainWindow::subSectionChanged() { disconnect( section, SIGNAL( activated(int) ), this, SLOT( sectionChanged() ) ); disconnect( subsection, SIGNAL(activated(int) ), this, SLOT( subSectionChanged() ) ); packageListServers.setSubSection( subsection->currentText() ); connect( section, SIGNAL( activated(int) ), this, SLOT( sectionChanged() ) ); connect( subsection, SIGNAL(activated(int) ), this, SLOT( subSectionChanged() ) ); displayList(); } void MainWindow::setSections() { section->clear(); section->insertStringList( packageListServers.getSections() ); } void MainWindow::setSubSections() { subsection->clear(); subsection->insertStringList( packageListServers.getSubSections() ); } void MainWindow::showSettings(int i) { if ( settings->showDialog( i ) ) { updateList(); } setComboName(destination,settings->getDestinationName()); CheckBoxLink->setChecked( settings->createLinks() ); } void MainWindow::showSettingsSetup() { showSettings(0); } void MainWindow::showSettingsSrv() { showSettings(1); } void MainWindow::showSettingsDst() { showSettings(2); } void MainWindow::sectionShow(bool b) { if (b) sectionBar->show(); else sectionBar->hide(); sectionAction->setOn( b ); } void MainWindow::sectionClose() { sectionAction->setOn( false ); } void MainWindow::findShow(bool b) { if (b) findBar->show(); else findBar->hide(); findAction->setOn( b ); } void MainWindow::findClose() { findAction->setOn( false ); } void MainWindow::searchShow(bool b) { if (b) searchBar->show(); else searchBar->hide(); searchAction->setOn( b ); } void MainWindow::searchClose() { searchAction->setOn( false ); } void MainWindow::destShow(bool b) { if (b) destBar->show(); else destBar->hide(); destAction->setOn( b ); } void MainWindow::destClose() { destAction->setOn( false ); } void MainWindow::setDocument(const QString &fileName) { if ( !QFile::exists( fileName ) ) return; ipkg->installFile( fileName ); QCopEnvelope e("QPE/System", "linkChanged(QString)"); QString lf = QString::null; e << lf; } void MainWindow::makeChannel() { channel = new QCopChannel( "QPE/Application/oipkg", this ); connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), this, SLOT(receive(const QCString&, const QByteArray&)) ); } void MainWindow::receive(const QCString &msg, const QByteArray &arg) { pvDebug(3, "QCop "+msg+" "+QCString(arg)); if ( msg == "installFile(QString)" ) { ipkg->installFile( QString(arg) ); }else if( msg == "removeFile(QString)" ) { ipkg->removeFile( QString(arg) ); }else if( msg == "createLinks(QString)" ) { ipkg->createLinks( QString(arg) ); }else if( msg == "removeLinks(QString)" ) { ipkg->removeLinks( QString(arg) ); }else{ pvDebug(2,"Huh what do ya want") } } void MainWindow::createLinks() { pvDebug(2,"creating links..."); ipkg->createLinks( settings->destinationurl->text() ); } void MainWindow::removeLinks() { pvDebug(2,"removing links..."); ipkg->removeLinks( settings->destinationurl->text() ); } void MainWindow::remotePackageQuery() { packageListSearch.query( searchEdit->text() ); packageListSearch.update(); displayList(); } |